file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
./partial_match/1/0x98b7893C5717aF41d3e351c6e3445Be02a062A90/sources/contracts/MapleLoan.sol
Clears all state variables to end a loan, but keep borrower and lender withdrawal functionality intact.
function _clearLoanAccounting() internal { _refinanceCommitment = bytes32(0); _gracePeriod = uint256(0); _paymentInterval = uint256(0); _interestRate = uint256(0); _closingRate = uint256(0); _lateFeeRate = uint256(0); _lateInterestPremiumRate = uint256(0); _endingPrincipal = uint256(0); _nextPaymentDueDate = uint256(0); _paymentsRemaining = uint256(0); _principal = uint256(0); _refinanceInterest = uint256(0); _originalNextPaymentDueDate = uint256(0); }
3,924,822
// <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary pragma solidity ^0.4.18; contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns (bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } contract usingOraclize { uint constant day = 60 * 60 * 24; uint constant week = 60 * 60 * 24 * 7; uint constant month = 60 * 60 * 24 * 30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if ((address(OAR) == 0) || (getCodeSize(address(OAR)) == 0)) oraclize_setNetwork(networkID_auto); if (address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns (bool){ return oraclize_setNetwork(); networkID; // silence the warning and remain backwards compatible } function oraclize_setNetwork() internal returns (bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed) > 0) {//mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1) > 0) {//ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e) > 0) {//kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48) > 0) {//rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475) > 0) {//ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF) > 0) {//ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA) > 0) {//browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; // Silence compiler warnings } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice * 200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice * 200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice * gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice * gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice * 200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice * 200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice * gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice * gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice * 200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice * 200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice * gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice * gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice * 200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice * 200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice * gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice * gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns (uint _size) { assembly { _size := extcodesize(_addr) } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i = 0; i < bresult.length; i++) { if ((bresult[i] >= 48) && (bresult[i] <= 57)) { if (decimals) { if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10 ** _b; return mint; } function stra2cbor(string[] arr) internal pure returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1) / 23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1) / 23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes[3] memory args = [unonce, nbytes, sessionKeyHash]; bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit); oraclize_randomDS_setCommitment(queryId, keccak256(bytes8(_delay), args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32 => bytes32) oraclize_randomDS_args; mapping(bytes32 => bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4 + (uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset + (uint(dersig[offset - 1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset + 1]) + 2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3 + 1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1 + 65 + 32); tosign2[0] = byte(1); //role copyBytes(proof, sig2offset - 65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1 + 65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1 + 65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3 + 65 + 1]) + 2); copyBytes(proof, 3 + 65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L") || (_proof[1] != "P") || (_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix) internal pure returns (bool){ bool match_ = true; for (uint256 i = 0; i < prefix.length; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ bool checkok; // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3 + 65 + (uint(proof[3 + 65 + 1]) + 2) + 32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); checkok = (keccak256(keyhash) == keccak256(sha256(context_name, queryId))); if (checkok == false) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength + (32 + 8 + 1 + 32) + 1]) + 2); copyBytes(proof, ledgerProofLength + (32 + 8 + 1 + 32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) checkok = matchBytes32Prefix(sha256(sig1), result); if (checkok == false) return false; // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8 + 1 + 32); copyBytes(proof, ledgerProofLength + 32, 8 + 1 + 32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength + 32 + (8 + 1 + 32) + sig1.length + 65; copyBytes(proof, sig2offset - 64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)) {//unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32 + 8 + 1 + 32); copyBytes(proof, ledgerProofLength, 32 + 8 + 1 + 32, tosign1, 0); checkok = verifySig(sha256(tosign1), sig1, sessionPubkey); if (checkok == false) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false) { oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // Should be a better way? // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } } // </ORACLIZE_API> /* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> */ pragma solidity ^0.4.14; library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } function toSlice(string self) internal returns (slice) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } function copy(slice self) internal returns (slice) { return slice(self._len, self._ptr); } function toString(slice self) internal returns (string) { var ret = new string(self._len); uint retptr; assembly {retptr := add(ret, 32)} memcpy(retptr, self._ptr, self._len); return ret; } function beyond(slice self, slice needle) internal returns (slice) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, length), sha3(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } function until(slice self, slice needle) internal returns (slice) { if (self._len < needle._len) { return self; } var selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; } return self; } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { uint ptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { // Optimized assembly for 68 gas per byte on short strings assembly { let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) let needledata := and(mload(needleptr), mask) let end := add(selfptr, sub(selflen, needlelen)) ptr := selfptr loop : jumpi(exit, eq(and(mload(ptr), mask), needledata)) ptr := add(ptr, 1) jumpi(loop, lt(sub(ptr, 1), end)) ptr := add(selfptr, selflen) exit : } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly {hash := sha3(needleptr, needlelen)} ptr = selfptr; for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly {testHash := sha3(ptr, needlelen)} if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } function split(slice self, slice needle, slice token) internal returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } function split(slice self, slice needle) internal returns (slice token) { split(self, needle, token); } } contract CryptoLotto is usingOraclize { using strings for *; address Owner; uint public constant lottoPrice = 10 finney; uint public constant duration = 1 days; uint8 public constant lottoLength = 6; uint8 public constant lottoLowestNumber = 1; uint8 public constant lottoHighestNumber = 15; uint8 public constant sixMatchPayoutInPercent = 77; uint8 public constant bonusMatchPayoutInPercent = 11; uint8 public constant fiveMatchPayoutInPercent = 11; uint8 public constant ownerShareInPercent = 1; uint8 public constant numTurnsToRevolve = 10; string constant oraclizedQuery = "Sort[randomsample [range [1, 15], 7]], randomsample [range [0, 6], 1]"; string constant oraclizedQuerySource = "WolframAlpha"; bool public isLottoStarted = false; uint32 public turn = 0; uint32 public gasForOraclizedQuery = 600000; uint256 public raisedAmount = 0; uint8[] lottoNumbers = new uint8[](lottoLength); uint8 bonusNumber; enum lottoRank {NONCE, FIVE_MATCH, BONUS_MATCH, SIX_MATCH, DEFAULT} uint256 public finishWhen; uint256[] bettings; uint256[] accNumBettings; mapping(address => mapping(uint32 => uint64[])) tickets; uint256[] public raisedAmounts; uint256[] public untakenPrizeAmounts; uint32[] encodedLottoResults; uint32[] numFiveMatchWinners; uint32[] numBonusMatchWinners; uint32[] numSixMatchWinners; uint32[] nonces; uint64[] public timestamps; bytes32 oracleCallbackId; event LottoStart(uint32 turn); event FundRaised(address buyer, uint256 value, uint256 raisedAmount); event LottoNumbersAnnounced(uint8[] lottoNumbers, uint8 bonusNumber, uint256 raisedAmount, uint32 numFiveMatchWinners, uint32 numBonusMatchWinners, uint32 numSixMatchWinners); event SixMatchPrizeTaken(address winner, uint256 prizeAmount); event BonusMatchPrizeTaken(address winner, uint256 prizeAmount); event FiveMatchPrizeTaken(address winner, uint256 prizeAmount); modifier onlyOwner { require(msg.sender == Owner); _; } modifier onlyOracle { require(msg.sender == oraclize_cbAddress()); _; } modifier onlyWhenLottoNotStarted { require(isLottoStarted == false); _; } modifier onlyWhenLottoStarted { require(isLottoStarted == true); _; } function CryptoLotto() { Owner = msg.sender; } function launchLotto() onlyOwner { oracleCallbackId = oraclize_query(oraclizedQuerySource, oraclizedQuery, gasForOraclizedQuery); } // Emergency function to call only when the turn missed oraclized_query becaused of gas management failure and no chance to resume by itself. function resumeLotto() onlyOwner { require(finishWhen < now); oracleCallbackId = oraclize_query(oraclizedQuerySource, oraclizedQuery, gasForOraclizedQuery); } function setGasForOraclizedQuery(uint32 _gasLimit) onlyOwner { gasForOraclizedQuery = _gasLimit; } function __callback(bytes32 myid, string result) onlyOracle { require(myid == oracleCallbackId); if (turn > 0) _finishLotto(); _setLottoNumbers(result); _startLotto(); } function _startLotto() onlyWhenLottoNotStarted internal { turn++; finishWhen = now + duration; oracleCallbackId = oraclize_query(duration, oraclizedQuerySource, oraclizedQuery, gasForOraclizedQuery); isLottoStarted = true; numFiveMatchWinners.push(0); numBonusMatchWinners.push(0); numSixMatchWinners.push(0); nonces.push(0); LottoStart(turn); } function _finishLotto() onlyWhenLottoStarted internal { isLottoStarted = false; _saveLottoResult(); LottoNumbersAnnounced(lottoNumbers, bonusNumber, raisedAmounts[turn - 1], numFiveMatchWinners[turn - 1], numBonusMatchWinners[turn - 1], numSixMatchWinners[turn - 1]); } function _setLottoNumbers(string _strData) onlyWhenLottoNotStarted internal { uint8[] memory _lottoNumbers = new uint8[](lottoLength); uint8 _bonusNumber; var slicedString = _strData.toSlice(); slicedString.beyond("{{".toSlice()).until("}".toSlice()); var _strLottoNumbers = slicedString.split('}, {'.toSlice()); var _bonusNumberIndex = uint8(parseInt(slicedString.toString())); uint8 _lottoLowestNumber = lottoLowestNumber; uint8 _lottoHighestNumber = lottoHighestNumber; uint8 _nonce = 0; for (uint8 _index = 0; _index < lottoLength + 1; _index++) { var splited = _strLottoNumbers.split(', '.toSlice()); if (_index == _bonusNumberIndex) { bonusNumber = uint8(parseInt(splited.toString())); _nonce = 1; continue; } _lottoNumbers[_index - _nonce] = uint8(parseInt(splited.toString())); require(_lottoNumbers[_index - _nonce] >= _lottoLowestNumber && _lottoNumbers[_index - _nonce] <= _lottoHighestNumber); if (_index - _nonce > 0) require(_lottoNumbers[_index - _nonce - 1] < _lottoNumbers[_index - _nonce]); lottoNumbers[_index - _nonce] = _lottoNumbers[_index - _nonce]; } } function _saveLottoResult() onlyWhenLottoNotStarted internal { uint32 _encodedLottoResult = 0; var _raisedAmount = raisedAmount; // lottoNumbers[6] 24 bits [0..23] for (uint8 _index = 0; _index < lottoNumbers.length; _index++) { _encodedLottoResult |= uint32(lottoNumbers[_index]) << (_index * 4); } // bonusNumber 4 bits [24..27] _encodedLottoResult |= uint32(bonusNumber) << (24); uint256 _totalPrizeAmount = 0; if (numFiveMatchWinners[turn - 1] > 0) _totalPrizeAmount += _raisedAmount * fiveMatchPayoutInPercent / 100; if (numBonusMatchWinners[turn - 1] > 0) _totalPrizeAmount += _raisedAmount * bonusMatchPayoutInPercent / 100; if (numSixMatchWinners[turn - 1] > 0) _totalPrizeAmount += _raisedAmount * sixMatchPayoutInPercent / 100; raisedAmounts.push(_raisedAmount); untakenPrizeAmounts.push(_totalPrizeAmount); encodedLottoResults.push(_encodedLottoResult); accNumBettings.push(bettings.length); timestamps.push(uint64(now)); var _ownerShare = _raisedAmount * ownerShareInPercent / 100; Owner.transfer(_ownerShare); uint32 _numTurnsToRevolve = uint32(numTurnsToRevolve); uint256 _amountToCarryOver = 0; if (turn > _numTurnsToRevolve) _amountToCarryOver = untakenPrizeAmounts[turn - _numTurnsToRevolve - 1]; raisedAmount = _raisedAmount - _totalPrizeAmount - _ownerShare + _amountToCarryOver; } function getLottoResult(uint256 _turn) constant returns (uint256, uint256, uint32, uint32, uint32) { require(_turn < turn && _turn > 0); return (raisedAmounts[_turn - 1], untakenPrizeAmounts[_turn - 1], numFiveMatchWinners[_turn - 1], numBonusMatchWinners[_turn - 1], numSixMatchWinners[_turn - 1]); } function getLottoNumbers(uint256 _turn) constant returns (uint8[], uint8) { require(_turn < turn && _turn > 0); var _encodedLottoResult = encodedLottoResults[_turn - 1]; uint8[] memory _lottoNumbers = new uint8[](lottoLength); uint8 _bonusNumber; for (uint8 _index = 0; _index < _lottoNumbers.length; _index++) { _lottoNumbers[_index] = uint8((_encodedLottoResult >> (_index * 4)) & (2 ** 4 - 1)); } _bonusNumber = uint8((_encodedLottoResult >> 24) & (2 ** 4 - 1)); return (_lottoNumbers, _bonusNumber); } function buyTickets(uint _numTickets, uint8[] _betNumbersList, bool _isAutoGenerated) payable onlyWhenLottoStarted { require(finishWhen > now); var _lottoLength = lottoLength; require(_betNumbersList.length == _numTickets * _lottoLength); uint _totalPrice = _numTickets * lottoPrice; require(msg.value >= _totalPrice); for (uint j = 0; j < _numTickets; j++) { require(_betNumbersList[j * _lottoLength] >= lottoLowestNumber && _betNumbersList[(j + 1) * _lottoLength - 1] <= lottoHighestNumber); for (uint _index = 0; _index < _lottoLength - 1; _index++) { require(_betNumbersList[_index + j * _lottoLength] < _betNumbersList[_index + 1 + j * _lottoLength]); } } uint8[] memory _betNumbers = new uint8[](lottoLength); for (j = 0; j < _numTickets; j++) { for (_index = 0; _index < _lottoLength - 1; _index++) { _betNumbers[_index] = _betNumbersList[_index + j * _lottoLength]; } _betNumbers[_index] = _betNumbersList[_index + j * _lottoLength]; _saveBettingAndTicket(_betNumbers, _isAutoGenerated); } raisedAmount += _totalPrice; Owner.transfer(msg.value - _totalPrice); FundRaised(msg.sender, msg.value, raisedAmount); } function _getLottoRank(uint8[] _betNumbers) internal constant returns (lottoRank) { uint8 _lottoLength = lottoLength; uint8[] memory _lottoNumbers = new uint8[](_lottoLength); uint8 _indexLotto = 0; uint8 _indexBet = 0; uint8 _numMatch = 0; for (uint8 i = 0; i < _lottoLength; i++) { _lottoNumbers[i] = lottoNumbers[i]; } while (_indexLotto < _lottoLength && _indexBet < _lottoLength) { if (_betNumbers[_indexBet] == _lottoNumbers[_indexLotto]) { _numMatch++; _indexBet++; _indexLotto++; if (_numMatch > 4) for (uint8 _burner = 0; _burner < 6; _burner++) {} continue; } else if (_betNumbers[_indexBet] < _lottoNumbers[_indexLotto]) { _indexBet++; continue; } else { _indexLotto++; continue; } } if (_numMatch == _lottoLength - 1) { uint8 _bonusNumber = bonusNumber; for (uint8 _index = 0; _index < lottoLength; _index++) { if (_betNumbers[_index] == _bonusNumber) { for (_burner = 0; _burner < 6; _burner++) {} return lottoRank.BONUS_MATCH; } } return lottoRank.FIVE_MATCH; } else if (_numMatch == _lottoLength) { for (_burner = 0; _burner < 12; _burner++) {} return lottoRank.SIX_MATCH; } return lottoRank.DEFAULT; } function _saveBettingAndTicket(uint8[] _betNumbers, bool _isAutoGenerated) internal onlyWhenLottoStarted { require(_betNumbers.length == 6 && lottoHighestNumber <= 16); uint256 _encodedBetting = 0; uint64 _encodedTicket = 0; uint256 _nonce256 = 0; uint64 _nonce64 = 0; // isTaken 1 bit betting[0] ticket[0] // isAutoGenerated 1 bit betting[1] ticket[1] // betNumbers[6] 24 bits betting[2..25] ticket[2..25] // lottoRank.FIVE_MATCH 1 bit betting[26] ticket[26] // lottoRank.BONUS_MATCH 1 bit betting[27] ticket[27] // lottoRank.SIX_MATCH 1 bit betting[28] ticket[28] // sender address 160 bits betting[29..188] // timestamp 36 bits betting[189..224] ticket[29..64] // isAutoGenerated if (_isAutoGenerated) { _encodedBetting |= uint256(1) << 1; _encodedTicket |= uint64(1) << 1; } // betNumbers[6] for (uint8 _index = 0; _index < _betNumbers.length; _index++) { uint256 _betNumber = uint256(_betNumbers[_index]) << (_index * 4 + 2); _encodedBetting |= _betNumber; _encodedTicket |= uint64(_betNumber); } // lottoRank.FIVE_MATCH, lottoRank.BONUS_MATCH, lottoRank.SIX_MATCH lottoRank _lottoRank = _getLottoRank(_betNumbers); if (_lottoRank == lottoRank.FIVE_MATCH) { numFiveMatchWinners[turn - 1]++; _encodedBetting |= uint256(1) << 26; _encodedTicket |= uint64(1) << 26; } else if (_lottoRank == lottoRank.BONUS_MATCH) { numBonusMatchWinners[turn - 1]++; _encodedBetting |= uint256(1) << 27; _encodedTicket |= uint64(1) << 27; } else if (_lottoRank == lottoRank.SIX_MATCH) { numSixMatchWinners[turn - 1]++; _encodedBetting |= uint256(1) << 28; _encodedTicket |= uint64(1) << 28; } else { nonces[turn - 1]++; _nonce256 |= uint256(1) << 29; _nonce64 |= uint64(1) << 29; } // sender address _encodedBetting |= uint256(msg.sender) << 29; // timestamp _encodedBetting |= now << 189; _encodedTicket |= uint64(now) << 29; // push ticket tickets[msg.sender][turn].push(_encodedTicket); // push betting bettings.push(_encodedBetting); } function getNumBettings() constant returns (uint256) { return bettings.length; } function getTurn(uint256 _bettingId) constant returns (uint32) { uint32 _turn = turn; require(_turn > 0); require(_bettingId < bettings.length); if (_turn == 1 || _bettingId < accNumBettings[0]) return 1; if (_bettingId >= accNumBettings[_turn - 2]) return _turn; uint32 i = 0; uint32 j = _turn - 1; uint32 mid = 0; while (i < j) { mid = (i + j) / 2; if (accNumBettings[mid] == _bettingId) return mid + 2; if (_bettingId < accNumBettings[mid]) { if (mid > 0 && _bettingId > accNumBettings[mid - 1]) return mid + 1; j = mid; } else { if (mid < _turn - 2 && _bettingId < accNumBettings[mid + 1]) return mid + 2; i = mid + 1; } } return mid + 2; } function getBetting(uint256 i) constant returns (bool, bool, uint8[], lottoRank, uint32){ require(i < bettings.length); uint256 _betting = bettings[i]; // isTaken 1 bit [0] bool _isTaken; if (_betting & 1 == 1) _isTaken = true; else _isAutoGenerated = false; // _isAutoGenerated 1 bit [1] bool _isAutoGenerated; if ((_betting >> 1) & 1 == 1) _isAutoGenerated = true; else _isAutoGenerated = false; // 6 betNumbers 24 bits [2..25] uint8[] memory _betNumbers = new uint8[](lottoLength); for (uint8 _index = 0; _index < lottoLength; _index++) { _betNumbers[_index] = uint8((_betting >> (_index * 4 + 2)) & (2 ** 4 - 1)); } // _timestamp bits [189..255] uint128 _timestamp; _timestamp = uint128((_betting >> 189) & (2 ** 67 - 1)); uint32 _turn = getTurn(i); if (_turn == turn && isLottoStarted) return (_isTaken, _isAutoGenerated, _betNumbers, lottoRank.NONCE, _turn); // return lottoRank only when the turn is finished // lottoRank 3 bits [26..28] lottoRank _lottoRank = lottoRank.DEFAULT; if ((_betting >> 26) & 1 == 1) _lottoRank = lottoRank.FIVE_MATCH; if ((_betting >> 27) & 1 == 1) _lottoRank = lottoRank.BONUS_MATCH; if ((_betting >> 28) & 1 == 1) _lottoRank = lottoRank.SIX_MATCH; return (_isTaken, _isAutoGenerated, _betNumbers, _lottoRank, _turn); } function getBettingExtra(uint256 i) constant returns (address, uint128){ require(i < bettings.length); uint256 _betting = bettings[i]; uint128 _timestamp = uint128((_betting >> 189) & (2 ** 67 - 1)); address _beneficiary = address((_betting >> 29) & (2 ** 160 - 1)); return (_beneficiary, _timestamp); } function getMyResult(uint32 _turn) constant returns (uint256, uint32, uint32, uint32, uint256) { require(_turn > 0); if (_turn == turn) require(!isLottoStarted); else require(_turn < turn); uint256 _numMyTickets = tickets[msg.sender][_turn].length; uint256 _totalPrizeAmount = 0; uint64 _ticket; uint32 _numSixMatchPrizes = 0; uint32 _numBonusMatchPrizes = 0; uint32 _numFiveMatchPrizes = 0; if (_numMyTickets == 0) { return (0, 0, 0, 0, 0); } for (uint256 _index = 0; _index < _numMyTickets; _index++) { _ticket = tickets[msg.sender][_turn][_index]; if ((_ticket >> 26) & 1 == 1) { _numFiveMatchPrizes++; _totalPrizeAmount += _getFiveMatchPrizeAmount(_turn); } else if ((_ticket >> 27) & 1 == 1) { _numBonusMatchPrizes++; _totalPrizeAmount += _getBonusMatchPrizeAmount(_turn); } else if ((_ticket >> 28) & 1 == 1) { _numSixMatchPrizes++; _totalPrizeAmount += _getSixMatchPrizeAmount(_turn); } } return (_numMyTickets, _numSixMatchPrizes, _numBonusMatchPrizes, _numFiveMatchPrizes, _totalPrizeAmount); } function getNumMyTickets(uint32 _turn) constant returns (uint256) { require(_turn > 0 && _turn <= turn); return tickets[msg.sender][_turn].length; } function getMyTicket(uint32 _turn, uint256 i) constant returns (bool, bool, uint8[], lottoRank, uint64){ require(_turn <= turn); require(i < tickets[msg.sender][_turn].length); uint64 _ticket = tickets[msg.sender][_turn][i]; // isTaken 1 bit ticket[0] bool _isTaken = false; if ((_ticket & 1) == 1) _isTaken = true; // isAutoGenerated 1 bit ticket[1] bool _isAutoGenerated = false; if ((_ticket >> 1) & 1 == 1) _isAutoGenerated = true; // betNumbers[6] 24 bits ticket[2..25] uint8[] memory _betNumbers = new uint8[](lottoLength); for (uint8 _index = 0; _index < lottoLength; _index++) { _betNumbers[_index] = uint8((_ticket >> (_index * 4 + 2)) & (2 ** 4 - 1)); } // timestamp 36 bits ticket[29..64] uint64 _timestamp = uint64((_ticket >> 29) & (2 ** 36 - 1)); if (_turn == turn) return (_isTaken, _isAutoGenerated, _betNumbers, lottoRank.NONCE, _timestamp); // return lottoRank only when the turn is finished // lottoRank.FIVE_MATCH 1 bit ticket[26] // lottoRank.BONUS_MATCH 1 bit ticket[27] // lottoRank.SIX_MATCH 1 bit ticket[28] lottoRank _lottoRank = lottoRank.DEFAULT; if ((_ticket >> 26) & 1 == 1) _lottoRank = lottoRank.FIVE_MATCH; if ((_ticket >> 27) & 1 == 1) _lottoRank = lottoRank.BONUS_MATCH; if ((_ticket >> 28) & 1 == 1) _lottoRank = lottoRank.SIX_MATCH; return (_isTaken, _isAutoGenerated, _betNumbers, _lottoRank, _timestamp); } function getMyUntakenPrizes(uint32 _turn) constant returns (uint32[]) { require(_turn > 0 && _turn < turn); uint256 _numMyTickets = tickets[msg.sender][_turn].length; uint32[] memory _prizes = new uint32[](50); uint256 _indexPrizes = 0; for (uint16 _index; _index < _numMyTickets; _index++) { uint64 _ticket = tickets[msg.sender][_turn][_index]; if (((_ticket >> 26) & 1 == 1) && (_ticket & 1 == 0)) _prizes[_indexPrizes++] = _index; else if (((_ticket >> 27) & 1 == 1) && (_ticket & 1 == 0)) _prizes[_indexPrizes++] = _index; else if (((_ticket >> 28) & 1 == 1) && (_ticket & 1 == 0)) _prizes[_indexPrizes++] = _index; if (_indexPrizes >= 50) { break; } } uint32[] memory _retPrizes = new uint32[](_indexPrizes); for (_index = 0; _index < _indexPrizes; _index++) { _retPrizes[_index] = _prizes[_index]; } return (_retPrizes); } function takePrize(uint32 _turn, uint256 i) { require(_turn > 0 && _turn < turn); if (turn > numTurnsToRevolve) require(_turn >= turn - numTurnsToRevolve); require(i < tickets[msg.sender][_turn].length); var _ticket = tickets[msg.sender][_turn][i]; // isTaken must be false require((_ticket & 1) == 0); // lottoRank.FIVE_MATCH 1 bit [26] // lottoRank.BONUS_MATCH 1 bit [27] // lottoRank.SIX_MATCH 1 bit [28] if ((_ticket >> 26) & 1 == 1) { uint256 _prizeAmount = _getFiveMatchPrizeAmount(_turn); require(_prizeAmount > 0); msg.sender.transfer(_prizeAmount); FiveMatchPrizeTaken(msg.sender, _prizeAmount); tickets[msg.sender][_turn][i] |= 1; untakenPrizeAmounts[_turn - 1] -= _prizeAmount; } else if ((_ticket >> 27) & 1 == 1) { _prizeAmount = _getBonusMatchPrizeAmount(_turn); require(_prizeAmount > 0); msg.sender.transfer(_prizeAmount); BonusMatchPrizeTaken(msg.sender, _prizeAmount); tickets[msg.sender][_turn][i] |= 1; untakenPrizeAmounts[_turn - 1] -= _prizeAmount; } else if ((_ticket >> 28) & 1 == 1) { _prizeAmount = _getSixMatchPrizeAmount(_turn); require(_prizeAmount > 0); msg.sender.transfer(_prizeAmount); SixMatchPrizeTaken(msg.sender, _prizeAmount); tickets[msg.sender][_turn][i] |= 1; untakenPrizeAmounts[_turn - 1] -= _prizeAmount; } } function _getFiveMatchPrizeAmount(uint256 _turn) internal constant returns (uint256) { require(_turn > 0 && _turn < turn); uint256 _numFiveMatchWinners = uint256(numFiveMatchWinners[_turn - 1]); if (_numFiveMatchWinners == 0) return 0; return raisedAmounts[_turn - 1] * fiveMatchPayoutInPercent / 100 / _numFiveMatchWinners; } function _getBonusMatchPrizeAmount(uint256 _turn) internal constant returns (uint256) { require(_turn > 0 && _turn < turn); uint256 _numBonusMatchWinners = uint256(numBonusMatchWinners[_turn - 1]); if (_numBonusMatchWinners == 0) return 0; return raisedAmounts[_turn - 1] * bonusMatchPayoutInPercent / 100 / _numBonusMatchWinners; } function _getSixMatchPrizeAmount(uint256 _turn) internal constant returns (uint256) { require(_turn > 0 && _turn < turn); uint256 _numSixMatchWinners = uint256(numSixMatchWinners[_turn - 1]); if (_numSixMatchWinners == 0) return 0; return raisedAmounts[_turn - 1] * sixMatchPayoutInPercent / 100 / _numSixMatchWinners; } function() payable { } }
Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. This is to verify that the computed args match with the ones specified in the query.
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ bool checkok; uint ledgerProofLength = 3 + 65 + (uint(proof[3 + 65 + 1]) + 2) + 32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); checkok = (keccak256(keyhash) == keccak256(sha256(context_name, queryId))); if (checkok == false) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength + (32 + 8 + 1 + 32) + 1]) + 2); copyBytes(proof, ledgerProofLength + (32 + 8 + 1 + 32), sig1.length, sig1, 0); checkok = matchBytes32Prefix(sha256(sig1), result); if (checkok == false) return false; bytes memory commitmentSlice1 = new bytes(8 + 1 + 32); copyBytes(proof, ledgerProofLength + 32, 8 + 1 + 32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength + 32 + (8 + 1 + 32) + sig1.length + 65; copyBytes(proof, sig2offset - 64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); delete oraclize_randomDS_args[queryId]; } else return false;
7,323,302
/** *Submitted for verification at Etherscan.io on 2021-07-04 */ //SPDX-License-Identifier: SourceLibre /** * Elysium * Powered by Diemlibre. * A SourceLibre Product. * DApp for buying Diemlibre $DLB. * * This file includes: * 1) interface IERC20. * 2) library SafeMath. * 3) contract BuyDiemlibre. * * Note: Token is in its smallet unit with respect to its decimal value. */ pragma solidity 0.8.1; /** * ERC Interface for Diemlibre Token. */ 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); function decimals() external view returns (uint8); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * Safe Math Library. */ library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } 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; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } /** * BuyDiemlibre Contract. * * Default Attribues: * - `owner` -> The owner of the contract. * - `rate` -> The rate of the exchange in WEI, to be set by the `owner`. * - `token` -> The ERC20 token handle. * - `holder` -> The address of the holder of coins which this contract will be spending on its behave. * - `self` -> The address of this contract. To be set by the owner after deployment. * - `fees` -> The fees per transaction to be set by the owner. */ contract BuyDiemlibre { using SafeMath for uint256; address owner; uint256 rate; // Rate is in WEI per Diemlibre IERC20 token; uint256 tokenDecimalsValue; address holder; address self; uint256 fees; /** * * Method Name: constructor * Initialises the contract. * Set most of the default attribues. * * Parameters: * - `address _tokenAddress` -> non zero address of the token contract. * - `address _holderAddress` -> non zero address of the holder of the tokens which has tokens. * - the caller is recommeded to be the owner or has some admin control of the token contract. * */ constructor(address _tokenAddress, address _holderAddress) { require(_tokenAddress != address(0), "Error! Invalid Token Address."); require(_holderAddress != address(0), "Error! Invalid Holder Address."); require(_tokenAddress != _holderAddress, "Token Address and Spender Address cann't be the same."); token = IERC20(_tokenAddress); holder = _holderAddress; owner = msg.sender; rate = 1000000000000000000; // in WEI fees = 0; tokenDecimalsValue = 10**token.decimals(); } /** * * Method Name: withdrawETHToOwner, private * Withdraw ETH to the owner. * * Parameters: * - `uint256 _amount` -> non zero amount of ETH to be sent to the owner. * * Returns: * Boolean if the transaction was successfull or not. * */ function withdrawETHToOwner(uint256 _amount) private returns(bool) { payable(owner).transfer(_amount); return true; } function getRate() external view returns(uint256) { return rate; } function getSelf() external view returns(address) { return self; } function getFees() external view returns(uint256) { return fees; } /** * * Method Name: currentETHValue, external view * Gets the current ETH value of 1 Token. * * Parameters: * - `uint256 _tokenAmount` -> non zero amount of tokens to get its equivilence in ETH. * * Returns: * The amount in ETH. * */ function currentETHValue(uint256 _tokenAmount) external view returns(uint256) { return _tokenAmount.mul(rate).div(tokenDecimalsValue); } /** * * Method Name: currentTokenValue, external view * Gets the current token value of 1 ETH. * * Parameters: * - `uint256 _WEIETHAmount` -> non zero amount of ETH in WEI to get its equivilence in token. * * Returns: * The amount in token. * */ function currentTokenValue(uint256 _WEIETHAmount) external view returns(uint256) { return _WEIETHAmount.mul(tokenDecimalsValue).div(rate); } /** * * Method Name: _buy, private * Payable the sends equivilent tokens calculated based on the rate to the msg.sender. * * Parameters: * - `address _msgSender` -> non zero address of the Message sender. * - `uint256 _msgValue` -> non zero amount of ETH in WEI the sender sent. * * Returns: * The total amount of tokens the sender has. * */ function _buy(address _msgSender, uint256 _msgValue) private returns(uint256) { require(_msgValue > 0, "Error! Invalid or Insufficient Amount."); require(self != address(0), "Error! Uninitialized self."); uint256 tokenAmount = _msgValue.mul(tokenDecimalsValue).div(rate); uint256 tokenAllowance = token.allowance(holder, self); require(tokenAmount > 0 && tokenAmount <= tokenAllowance, "Insufficient Liquidity"); withdrawETHToOwner(_msgValue); require(token.transferFrom(holder, _msgSender, tokenAmount), "Oops... Could not complete Transaction. Please try again later."); return token.balanceOf(_msgSender); } /** * * Method: _buyFor, private * Payable the sends equivilent tokens calculated based on the rate to the _receiver set by msg.sender. * * Parameters: * - `address _receiver` -> non zero address of the receiver of the tokens. * - `uint256 _msgValue` -> non zero amount of ETH in WEI the sender sent. * * Returns: * The total amount of tokens the _receiver has. * */ function _buyFor(address _receiver, uint256 _msgValue) private returns(uint256) { require(_msgValue > 0, "Error! Invalid or Insufficient Amount."); require(self != address(0), "Error! Uninitialized self."); uint256 tokenAmount = _msgValue.mul(tokenDecimalsValue).div(rate); uint256 tokenAllowance = token.allowance(holder, self); require(tokenAmount > 0 && tokenAmount <= tokenAllowance, "Insufficient Liquidity"); withdrawETHToOwner(_msgValue); require(token.transferFrom(holder, _receiver, tokenAmount), "Oops... Could not complete Transaction. Please try again later."); return token.balanceOf(_receiver); } /** * * Method: buy, external payable * External implementation of _buy() * */ function buy() external payable returns(uint256) { return _buy(msg.sender, msg.value); } /** * * Method: buyFor, external payable * External implementation of _buyFor() * */ function buyFor(address _receiver) external payable returns(uint256) { return _buyFor(_receiver, msg.value); } /** * * Fancy names for Web3.js Providers to read method names. * */ // Buy function buyDLB() external payable returns(uint256) { return _buy(msg.sender, msg.value); } function buyDlb() external payable returns(uint256) { return _buy(msg.sender, msg.value); } function buyDiemlibre() external payable returns(uint256) { return _buy(msg.sender, msg.value); } // BuyFor function buyDLBFor(address _receiver) external payable returns(uint256) { return _buyFor(_receiver, msg.value); } function buyDlbFor(address _receiver) external payable returns(uint256) { return _buyFor(_receiver, msg.value); } function buyDiemlibreFor(address _receiver) external payable returns(uint256) { return _buyFor(_receiver, msg.value); } /** * * Methods to be ran only by the owner * */ function getHolder() external view returns(address) { require(msg.sender == owner, "Error! Unauthorized access."); return holder; } function setHolder(address _newHolder) external returns(address) { require(msg.sender == owner, "Error! Unauthorized access."); require(_newHolder != address(0), "Error! Invalid New Holder Address."); holder = _newHolder; return holder; } function withdrawETH(address _receiver, uint256 _amount) external returns(bool) { require(msg.sender == owner, "Error! Unauthorized access."); require(_receiver != address(0), "Error! Invalid Receiver Address."); payable(_receiver).transfer(_amount); return true; } function setRate(uint256 _newRate) external returns(uint256) { require(msg.sender == owner, "Error! Unauthorized access."); rate = _newRate; return rate; } function setFees(uint256 _newFees) external returns(uint256) { require(msg.sender == owner, "Error! Unauthorized access."); fees = _newFees; return fees; } function setSelf(address _selfAddress) external returns(address) { require(msg.sender == owner, "Error! Unauthorized access."); require(_selfAddress != address(0), "Error! Invalid Self Address."); self = _selfAddress; return self; } }
ERC Interface for Diemlibre Token./
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); function decimals() external view returns (uint8); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); pragma solidity 0.8.1; }
10,710,575
pragma solidity 0.5.16; import "../base/Owned.sol"; /** * @title Timelock * @author Authereum Labs, Inc. * @dev Used to make changes to contracts with a known time lock. * @dev The goal of this contract is to make the public aware of contract changes made * @dev by the contract owners. This will keep the owners honest and will allow the * @dev users of the contracts to remove any funds if they suspect any foul play. */ contract Timelock is Owned { uint256 public timelock; uint256 public timelockExpire; enum ChangeState {Uninitialized, Pending, Changeable, Expired} struct ContractChangeTime{ uint256 unlockTime; uint256 unlockExpireTime; } event TimelockUpdated(uint256 indexed newTimelock); event TimelockExpireUpdated(uint256 indexed newTimelockExpire); event ChangeInitiated(bytes data, address indexed changeAddress, uint256 changeTime); event ChangeExecuted(bytes data, address indexed changeAddress, uint256 changeTime); event ChangeCancelled(bytes data, address indexed changeAddress, uint256 changeTime); mapping(bytes => mapping(address => ContractChangeTime)) public changes; modifier onlyThisContract { require(msg.sender == address(this), "T: Only this contract can call this function"); _; } /// @param _timelock Amount of time that a pending change is locked for /// @param _timelockExpire Amoutn of time AFTER timelock that data is changeable before expiring constructor(uint256 _timelock, uint256 _timelockExpire) public { timelock = _timelock; timelockExpire = _timelockExpire; emit TimelockUpdated(timelock); emit TimelockExpireUpdated(timelockExpire); } /** * Getters */ /// @dev Get unlock time of change /// @param _data Data that will be the change /// @param _changeAddress Address that will receive the data /// @return The unlock time of the transaction function getUnlockTime(bytes memory _data, address _changeAddress) public view returns (uint256) { return changes[_data][_changeAddress].unlockTime; } /// @dev Get the expiration time of change /// @param _data Data that will be the change /// @param _changeAddress Address that will receive the data /// @return The unlock expire time of the transaction function getUnlockExpireTime(bytes memory _data, address _changeAddress) public view returns (uint256) { return changes[_data][_changeAddress].unlockExpireTime; } /// @dev Get remaining time until change can be made /// @param _data Data that will be the change /// @param _changeAddress Address that will receive the data /// @return The remaining unlock time of the transaction function getRemainingUnlockTime(bytes memory _data, address _changeAddress) public view returns (uint256) { uint256 unlockTime = changes[_data][_changeAddress].unlockTime; if (unlockTime <= block.timestamp) { return 0; } return unlockTime - block.timestamp; } /// @dev Get remaining time until change will expire /// @param _data Data that will be the change /// @param _changeAddress Address that will receive the data /// @return The remaining unlock expire time of the transaction function getRemainingUnlockExpireTime(bytes memory _data, address _changeAddress) public view returns (uint256) { uint256 unlockTime = changes[_data][_changeAddress].unlockTime; if (unlockTime <= block.timestamp) { return 0; } return unlockTime - block.timestamp; } /// @dev Get the current state of some data /// @param _data Data that will be the change /// @param _changeAddress Address that will receive the data /// @return The change state of the transaction function getCurrentChangeState(bytes memory _data, address _changeAddress) public view returns (ChangeState) { uint256 unlockTime = changes[_data][_changeAddress].unlockTime; uint256 unlockExpireTime = changes[_data][_changeAddress].unlockExpireTime; if (unlockTime == 0) { return ChangeState.Uninitialized; } else if (block.timestamp < unlockTime) { return ChangeState.Pending; } else if (unlockTime <= block.timestamp && block.timestamp < unlockExpireTime) { return ChangeState.Changeable; } else if (unlockExpireTime <= block.timestamp) { return ChangeState.Expired; } } /** * Setters */ /// @dev Sets a new timelock /// @notice Can only be called by self /// @param _timelock New timelock time function setTimelock(uint256 _timelock) public onlyThisContract { timelock = _timelock; emit TimelockUpdated(timelock); } /// @dev Sets a new timelock exipration /// @notice Can only be called by self /// @param _timelockExpire New timelock time function setTimelockExpire(uint256 _timelockExpire) public onlyThisContract { timelockExpire = _timelockExpire; emit TimelockExpireUpdated(timelockExpire); } /** * Public functions */ /// @dev Initiate change /// @param _data Data that will be the change /// @param _changeAddress Address that will receive the data function initiateChange(bytes memory _data, address _changeAddress) public onlyOwner { require(getCurrentChangeState(_data, _changeAddress) == ChangeState.Uninitialized, "T: Change not able to be initiated"); changes[_data][_changeAddress].unlockTime = timelock + block.timestamp; changes[_data][_changeAddress].unlockExpireTime = changes[_data][_changeAddress].unlockTime + timelockExpire; emit ChangeInitiated(_data, _changeAddress, block.timestamp); } /// @dev Execute change /// @param _data Data that will be the change /// @param _changeAddress Address that will receive the data function executeChange(bytes memory _data, address _changeAddress) public payable onlyOwner { require(getCurrentChangeState(_data, _changeAddress) == ChangeState.Changeable, "T: Change not able to be made"); delete changes[_data][_changeAddress]; _changeAddress.call.value(msg.value)(_data); emit ChangeExecuted(_data, _changeAddress, block.timestamp); } /// @dev Cancel change /// @param _data Data that will be cancelled /// @param _changeAddress Address that will receive the data function cancelChange(bytes memory _data, address _changeAddress) public onlyOwner { delete changes[_data][_changeAddress]; emit ChangeCancelled(_data, _changeAddress, block.timestamp); } }
Initiate change _data Data that will be the change _changeAddress Address that will receive the data
function initiateChange(bytes memory _data, address _changeAddress) public onlyOwner { require(getCurrentChangeState(_data, _changeAddress) == ChangeState.Uninitialized, "T: Change not able to be initiated"); changes[_data][_changeAddress].unlockTime = timelock + block.timestamp; changes[_data][_changeAddress].unlockExpireTime = changes[_data][_changeAddress].unlockTime + timelockExpire; emit ChangeInitiated(_data, _changeAddress, block.timestamp); }
12,724,787
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; pragma abicoder v2; import './interfaces/IUniswapV3Staker.sol'; import './libraries/IncentiveId.sol'; import './libraries/RewardMath.sol'; import './libraries/NFTPositionInfo.sol'; import './libraries/TransferHelperExtended.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import '@uniswap/v3-core/contracts/interfaces/IERC20Minimal.sol'; import '@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol'; import '@uniswap/v3-periphery/contracts/base/Multicall.sol'; /// @title Uniswap V3 canonical staking interface contract UniswapV3Staker is IUniswapV3Staker, Multicall { /// @notice Represents a staking incentive struct Incentive { uint256 totalRewardUnclaimed; uint160 totalSecondsClaimedX128; uint96 numberOfStakes; } /// @notice Represents the deposit of a liquidity NFT struct Deposit { address owner; uint48 numberOfStakes; int24 tickLower; int24 tickUpper; } /// @notice Represents a staked liquidity NFT struct Stake { uint160 secondsPerLiquidityInsideInitialX128; uint96 liquidityNoOverflow; uint128 liquidityIfOverflow; } /// @inheritdoc IUniswapV3Staker IUniswapV3Factory public immutable override factory; /// @inheritdoc IUniswapV3Staker INonfungiblePositionManager public immutable override nonfungiblePositionManager; /// @inheritdoc IUniswapV3Staker uint256 public immutable override maxIncentiveStartLeadTime; /// @inheritdoc IUniswapV3Staker uint256 public immutable override maxIncentiveDuration; /// @dev bytes32 refers to the return value of IncentiveId.compute mapping(bytes32 => Incentive) public override incentives; /// @dev deposits[tokenId] => Deposit mapping(uint256 => Deposit) public override deposits; /// @dev stakes[tokenId][incentiveHash] => Stake mapping(uint256 => mapping(bytes32 => Stake)) private _stakes; /// @inheritdoc IUniswapV3Staker function stakes(uint256 tokenId, bytes32 incentiveId) public view override returns (uint160 secondsPerLiquidityInsideInitialX128, uint128 liquidity) { Stake storage stake = _stakes[tokenId][incentiveId]; secondsPerLiquidityInsideInitialX128 = stake.secondsPerLiquidityInsideInitialX128; liquidity = stake.liquidityNoOverflow; if (liquidity == type(uint96).max) { liquidity = stake.liquidityIfOverflow; } } /// @dev rewards[rewardToken][owner] => uint256 /// @inheritdoc IUniswapV3Staker mapping(IERC20Minimal => mapping(address => uint256)) public override rewards; /// @param _factory the Uniswap V3 factory /// @param _nonfungiblePositionManager the NFT position manager contract address /// @param _maxIncentiveStartLeadTime the max duration of an incentive in seconds /// @param _maxIncentiveDuration the max amount of seconds into the future the incentive startTime can be set constructor( IUniswapV3Factory _factory, INonfungiblePositionManager _nonfungiblePositionManager, uint256 _maxIncentiveStartLeadTime, uint256 _maxIncentiveDuration ) { factory = _factory; nonfungiblePositionManager = _nonfungiblePositionManager; maxIncentiveStartLeadTime = _maxIncentiveStartLeadTime; maxIncentiveDuration = _maxIncentiveDuration; } /// @inheritdoc IUniswapV3Staker function createIncentive(IncentiveKey memory key, uint256 reward) external override { require(reward > 0, 'UniswapV3Staker::createIncentive: reward must be positive'); require( block.timestamp <= key.startTime, 'UniswapV3Staker::createIncentive: start time must be now or in the future' ); require( key.startTime - block.timestamp <= maxIncentiveStartLeadTime, 'UniswapV3Staker::createIncentive: start time too far into future' ); require(key.startTime < key.endTime, 'UniswapV3Staker::createIncentive: start time must be before end time'); require( key.endTime - key.startTime <= maxIncentiveDuration, 'UniswapV3Staker::createIncentive: incentive duration is too long' ); bytes32 incentiveId = IncentiveId.compute(key); incentives[incentiveId].totalRewardUnclaimed += reward; TransferHelperExtended.safeTransferFrom(address(key.rewardToken), msg.sender, address(this), reward); emit IncentiveCreated(key.rewardToken, key.pool, key.startTime, key.endTime, key.refundee, reward); } /// @inheritdoc IUniswapV3Staker function endIncentive(IncentiveKey memory key) external override returns (uint256 refund) { require(block.timestamp >= key.endTime, 'UniswapV3Staker::endIncentive: cannot end incentive before end time'); bytes32 incentiveId = IncentiveId.compute(key); Incentive storage incentive = incentives[incentiveId]; refund = incentive.totalRewardUnclaimed; require(refund > 0, 'UniswapV3Staker::endIncentive: no refund available'); require( incentive.numberOfStakes == 0, 'UniswapV3Staker::endIncentive: cannot end incentive while deposits are staked' ); // issue the refund incentive.totalRewardUnclaimed = 0; TransferHelperExtended.safeTransfer(address(key.rewardToken), key.refundee, refund); // note we never clear totalSecondsClaimedX128 emit IncentiveEnded(incentiveId, refund); } /// @notice Upon receiving a Uniswap V3 ERC721, creates the token deposit setting owner to `from`. Also stakes token /// in one or more incentives if properly formatted `data` has a length > 0. /// @inheritdoc IERC721Receiver function onERC721Received( address, address from, uint256 tokenId, bytes calldata data ) external override returns (bytes4) { require( msg.sender == address(nonfungiblePositionManager), 'UniswapV3Staker::onERC721Received: not a univ3 nft' ); (, , , , , int24 tickLower, int24 tickUpper, , , , , ) = nonfungiblePositionManager.positions(tokenId); deposits[tokenId] = Deposit({owner: from, numberOfStakes: 0, tickLower: tickLower, tickUpper: tickUpper}); emit DepositTransferred(tokenId, address(0), from); if (data.length > 0) { if (data.length == 160) { _stakeToken(abi.decode(data, (IncentiveKey)), tokenId); } else { IncentiveKey[] memory keys = abi.decode(data, (IncentiveKey[])); for (uint256 i = 0; i < keys.length; i++) { _stakeToken(keys[i], tokenId); } } } return this.onERC721Received.selector; } /// @inheritdoc IUniswapV3Staker function transferDeposit(uint256 tokenId, address to) external override { require(to != address(0), 'UniswapV3Staker::transferDeposit: invalid transfer recipient'); address owner = deposits[tokenId].owner; require(owner == msg.sender, 'UniswapV3Staker::transferDeposit: can only be called by deposit owner'); deposits[tokenId].owner = to; emit DepositTransferred(tokenId, owner, to); } /// @inheritdoc IUniswapV3Staker function withdrawToken( uint256 tokenId, address to, bytes memory data ) external override { require(to != address(this), 'UniswapV3Staker::withdrawToken: cannot withdraw to staker'); Deposit memory deposit = deposits[tokenId]; require(deposit.numberOfStakes == 0, 'UniswapV3Staker::withdrawToken: cannot withdraw token while staked'); require(deposit.owner == msg.sender, 'UniswapV3Staker::withdrawToken: only owner can withdraw token'); delete deposits[tokenId]; emit DepositTransferred(tokenId, deposit.owner, address(0)); nonfungiblePositionManager.safeTransferFrom(address(this), to, tokenId, data); } /// @inheritdoc IUniswapV3Staker function stakeToken(IncentiveKey memory key, uint256 tokenId) external override { require(deposits[tokenId].owner == msg.sender, 'UniswapV3Staker::stakeToken: only owner can stake token'); _stakeToken(key, tokenId); } /// @inheritdoc IUniswapV3Staker function unstakeToken(IncentiveKey memory key, uint256 tokenId) external override { Deposit memory deposit = deposits[tokenId]; // anyone can call unstakeToken if the block time is after the end time of the incentive if (block.timestamp < key.endTime) { require( deposit.owner == msg.sender, 'UniswapV3Staker::unstakeToken: only owner can withdraw token before incentive end time' ); } bytes32 incentiveId = IncentiveId.compute(key); (uint160 secondsPerLiquidityInsideInitialX128, uint128 liquidity) = stakes(tokenId, incentiveId); require(liquidity != 0, 'UniswapV3Staker::unstakeToken: stake does not exist'); Incentive storage incentive = incentives[incentiveId]; deposits[tokenId].numberOfStakes--; incentive.numberOfStakes--; (, uint160 secondsPerLiquidityInsideX128, ) = key.pool.snapshotCumulativesInside(deposit.tickLower, deposit.tickUpper); (uint256 reward, uint160 secondsInsideX128) = RewardMath.computeRewardAmount( incentive.totalRewardUnclaimed, incentive.totalSecondsClaimedX128, key.startTime, key.endTime, liquidity, secondsPerLiquidityInsideInitialX128, secondsPerLiquidityInsideX128, block.timestamp ); // if this overflows, e.g. after 2^32-1 full liquidity seconds have been claimed, // reward rate will fall drastically so it's safe incentive.totalSecondsClaimedX128 += secondsInsideX128; // reward is never greater than total reward unclaimed incentive.totalRewardUnclaimed -= reward; // this only overflows if a token has a total supply greater than type(uint256).max rewards[key.rewardToken][deposit.owner] += reward; Stake storage stake = _stakes[tokenId][incentiveId]; delete stake.secondsPerLiquidityInsideInitialX128; delete stake.liquidityNoOverflow; if (liquidity >= type(uint96).max) delete stake.liquidityIfOverflow; emit TokenUnstaked(tokenId, incentiveId); } /// @inheritdoc IUniswapV3Staker function claimReward( IERC20Minimal rewardToken, address to, uint256 amountRequested ) external override returns (uint256 reward) { reward = rewards[rewardToken][msg.sender]; if (amountRequested != 0 && amountRequested < reward) { reward = amountRequested; } rewards[rewardToken][msg.sender] -= reward; TransferHelperExtended.safeTransfer(address(rewardToken), to, reward); emit RewardClaimed(to, reward); } /// @inheritdoc IUniswapV3Staker function getRewardInfo(IncentiveKey memory key, uint256 tokenId) external view override returns (uint256 reward, uint160 secondsInsideX128) { bytes32 incentiveId = IncentiveId.compute(key); (uint160 secondsPerLiquidityInsideInitialX128, uint128 liquidity) = stakes(tokenId, incentiveId); require(liquidity > 0, 'UniswapV3Staker::getRewardInfo: stake does not exist'); Deposit memory deposit = deposits[tokenId]; Incentive memory incentive = incentives[incentiveId]; (, uint160 secondsPerLiquidityInsideX128, ) = key.pool.snapshotCumulativesInside(deposit.tickLower, deposit.tickUpper); (reward, secondsInsideX128) = RewardMath.computeRewardAmount( incentive.totalRewardUnclaimed, incentive.totalSecondsClaimedX128, key.startTime, key.endTime, liquidity, secondsPerLiquidityInsideInitialX128, secondsPerLiquidityInsideX128, block.timestamp ); } /// @dev Stakes a deposited token without doing an ownership check function _stakeToken(IncentiveKey memory key, uint256 tokenId) private { require(block.timestamp >= key.startTime, 'UniswapV3Staker::stakeToken: incentive not started'); require(block.timestamp < key.endTime, 'UniswapV3Staker::stakeToken: incentive ended'); bytes32 incentiveId = IncentiveId.compute(key); require( incentives[incentiveId].totalRewardUnclaimed > 0, 'UniswapV3Staker::stakeToken: non-existent incentive' ); require( _stakes[tokenId][incentiveId].liquidityNoOverflow == 0, 'UniswapV3Staker::stakeToken: token already staked' ); (IUniswapV3Pool pool, int24 tickLower, int24 tickUpper, uint128 liquidity) = NFTPositionInfo.getPositionInfo(factory, nonfungiblePositionManager, tokenId); require(pool == key.pool, 'UniswapV3Staker::stakeToken: token pool is not the incentive pool'); require(liquidity > 0, 'UniswapV3Staker::stakeToken: cannot stake token with 0 liquidity'); deposits[tokenId].numberOfStakes++; incentives[incentiveId].numberOfStakes++; (, uint160 secondsPerLiquidityInsideX128, ) = pool.snapshotCumulativesInside(tickLower, tickUpper); if (liquidity >= type(uint96).max) { _stakes[tokenId][incentiveId] = Stake({ secondsPerLiquidityInsideInitialX128: secondsPerLiquidityInsideX128, liquidityNoOverflow: type(uint96).max, liquidityIfOverflow: liquidity }); } else { Stake storage stake = _stakes[tokenId][incentiveId]; stake.secondsPerLiquidityInsideInitialX128 = secondsPerLiquidityInsideX128; stake.liquidityNoOverflow = uint96(liquidity); } emit TokenStaked(tokenId, incentiveId, liquidity); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; pragma abicoder v2; import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import '@uniswap/v3-core/contracts/interfaces/IERC20Minimal.sol'; import '@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol'; import '@uniswap/v3-periphery/contracts/interfaces/IMulticall.sol'; /// @title Uniswap V3 Staker Interface /// @notice Allows staking nonfungible liquidity tokens in exchange for reward tokens interface IUniswapV3Staker is IERC721Receiver, IMulticall { /// @param rewardToken The token being distributed as a reward /// @param pool The Uniswap V3 pool /// @param startTime The time when the incentive program begins /// @param endTime The time when rewards stop accruing /// @param refundee The address which receives any remaining reward tokens when the incentive is ended struct IncentiveKey { IERC20Minimal rewardToken; IUniswapV3Pool pool; uint256 startTime; uint256 endTime; address refundee; } /// @notice The Uniswap V3 Factory function factory() external view returns (IUniswapV3Factory); /// @notice The nonfungible position manager with which this staking contract is compatible function nonfungiblePositionManager() external view returns (INonfungiblePositionManager); /// @notice The max duration of an incentive in seconds function maxIncentiveDuration() external view returns (uint256); /// @notice The max amount of seconds into the future the incentive startTime can be set function maxIncentiveStartLeadTime() external view returns (uint256); /// @notice Represents a staking incentive /// @param incentiveId The ID of the incentive computed from its parameters /// @return totalRewardUnclaimed The amount of reward token not yet claimed by users /// @return totalSecondsClaimedX128 Total liquidity-seconds claimed, represented as a UQ32.128 /// @return numberOfStakes The count of deposits that are currently staked for the incentive function incentives(bytes32 incentiveId) external view returns ( uint256 totalRewardUnclaimed, uint160 totalSecondsClaimedX128, uint96 numberOfStakes ); /// @notice Returns information about a deposited NFT /// @return owner The owner of the deposited NFT /// @return numberOfStakes Counter of how many incentives for which the liquidity is staked /// @return tickLower The lower tick of the range /// @return tickUpper The upper tick of the range function deposits(uint256 tokenId) external view returns ( address owner, uint48 numberOfStakes, int24 tickLower, int24 tickUpper ); /// @notice Returns information about a staked liquidity NFT /// @param tokenId The ID of the staked token /// @param incentiveId The ID of the incentive for which the token is staked /// @return secondsPerLiquidityInsideInitialX128 secondsPerLiquidity represented as a UQ32.128 /// @return liquidity The amount of liquidity in the NFT as of the last time the rewards were computed function stakes(uint256 tokenId, bytes32 incentiveId) external view returns (uint160 secondsPerLiquidityInsideInitialX128, uint128 liquidity); /// @notice Returns amounts of reward tokens owed to a given address according to the last time all stakes were updated /// @param rewardToken The token for which to check rewards /// @param owner The owner for which the rewards owed are checked /// @return rewardsOwed The amount of the reward token claimable by the owner function rewards(IERC20Minimal rewardToken, address owner) external view returns (uint256 rewardsOwed); /// @notice Creates a new liquidity mining incentive program /// @param key Details of the incentive to create /// @param reward The amount of reward tokens to be distributed function createIncentive(IncentiveKey memory key, uint256 reward) external; /// @notice Ends an incentive after the incentive end time has passed and all stakes have been withdrawn /// @param key Details of the incentive to end /// @return refund The remaining reward tokens when the incentive is ended function endIncentive(IncentiveKey memory key) external returns (uint256 refund); /// @notice Transfers ownership of a deposit from the sender to the given recipient /// @param tokenId The ID of the token (and the deposit) to transfer /// @param to The new owner of the deposit function transferDeposit(uint256 tokenId, address to) external; /// @notice Withdraws a Uniswap V3 LP token `tokenId` from this contract to the recipient `to` /// @param tokenId The unique identifier of an Uniswap V3 LP token /// @param to The address where the LP token will be sent /// @param data An optional data array that will be passed along to the `to` address via the NFT safeTransferFrom function withdrawToken( uint256 tokenId, address to, bytes memory data ) external; /// @notice Stakes a Uniswap V3 LP token /// @param key The key of the incentive for which to stake the NFT /// @param tokenId The ID of the token to stake function stakeToken(IncentiveKey memory key, uint256 tokenId) external; /// @notice Unstakes a Uniswap V3 LP token /// @param key The key of the incentive for which to unstake the NFT /// @param tokenId The ID of the token to unstake function unstakeToken(IncentiveKey memory key, uint256 tokenId) external; /// @notice Transfers `amountRequested` of accrued `rewardToken` rewards from the contract to the recipient `to` /// @param rewardToken The token being distributed as a reward /// @param to The address where claimed rewards will be sent to /// @param amountRequested The amount of reward tokens to claim. Claims entire reward amount if set to 0. /// @return reward The amount of reward tokens claimed function claimReward( IERC20Minimal rewardToken, address to, uint256 amountRequested ) external returns (uint256 reward); /// @notice Calculates the reward amount that will be received for the given stake /// @param key The key of the incentive /// @param tokenId The ID of the token /// @return reward The reward accrued to the NFT for the given incentive thus far function getRewardInfo(IncentiveKey memory key, uint256 tokenId) external returns (uint256 reward, uint160 secondsInsideX128); /// @notice Event emitted when a liquidity mining incentive has been created /// @param rewardToken The token being distributed as a reward /// @param pool The Uniswap V3 pool /// @param startTime The time when the incentive program begins /// @param endTime The time when rewards stop accruing /// @param refundee The address which receives any remaining reward tokens after the end time /// @param reward The amount of reward tokens to be distributed event IncentiveCreated( IERC20Minimal indexed rewardToken, IUniswapV3Pool indexed pool, uint256 startTime, uint256 endTime, address refundee, uint256 reward ); /// @notice Event that can be emitted when a liquidity mining incentive has ended /// @param incentiveId The incentive which is ending /// @param refund The amount of reward tokens refunded event IncentiveEnded(bytes32 indexed incentiveId, uint256 refund); /// @notice Emitted when ownership of a deposit changes /// @param tokenId The ID of the deposit (and token) that is being transferred /// @param oldOwner The owner before the deposit was transferred /// @param newOwner The owner after the deposit was transferred event DepositTransferred(uint256 indexed tokenId, address indexed oldOwner, address indexed newOwner); /// @notice Event emitted when a Uniswap V3 LP token has been staked /// @param tokenId The unique identifier of an Uniswap V3 LP token /// @param liquidity The amount of liquidity staked /// @param incentiveId The incentive in which the token is staking event TokenStaked(uint256 indexed tokenId, bytes32 indexed incentiveId, uint128 liquidity); /// @notice Event emitted when a Uniswap V3 LP token has been unstaked /// @param tokenId The unique identifier of an Uniswap V3 LP token /// @param incentiveId The incentive in which the token is staking event TokenUnstaked(uint256 indexed tokenId, bytes32 indexed incentiveId); /// @notice Event emitted when a reward token has been claimed /// @param to The address where claimed rewards were sent to /// @param reward The amount of reward tokens claimed event RewardClaimed(address indexed to, uint256 reward); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; pragma abicoder v2; import '../interfaces/IUniswapV3Staker.sol'; library IncentiveId { /// @notice Calculate the key for a staking incentive /// @param key The components used to compute the incentive identifier /// @return incentiveId The identifier for the incentive function compute(IUniswapV3Staker.IncentiveKey memory key) internal pure returns (bytes32 incentiveId) { return keccak256(abi.encode(key)); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; import '@openzeppelin/contracts/math/Math.sol'; /// @title Math for computing rewards /// @notice Allows computing rewards given some parameters of stakes and incentives library RewardMath { /// @notice Compute the amount of rewards owed given parameters of the incentive and stake /// @param totalRewardUnclaimed The total amount of unclaimed rewards left for an incentive /// @param totalSecondsClaimedX128 How many full liquidity-seconds have been already claimed for the incentive /// @param startTime When the incentive rewards began in epoch seconds /// @param endTime When rewards are no longer being dripped out in epoch seconds /// @param liquidity The amount of liquidity, assumed to be constant over the period over which the snapshots are measured /// @param secondsPerLiquidityInsideInitialX128 The seconds per liquidity of the liquidity tick range as of the beginning of the period /// @param secondsPerLiquidityInsideX128 The seconds per liquidity of the liquidity tick range as of the current block timestamp /// @param currentTime The current block timestamp, which must be greater than or equal to the start time /// @return reward The amount of rewards owed /// @return secondsInsideX128 The total liquidity seconds inside the position's range for the duration of the stake function computeRewardAmount( uint256 totalRewardUnclaimed, uint160 totalSecondsClaimedX128, uint256 startTime, uint256 endTime, uint128 liquidity, uint160 secondsPerLiquidityInsideInitialX128, uint160 secondsPerLiquidityInsideX128, uint256 currentTime ) internal pure returns (uint256 reward, uint160 secondsInsideX128) { // this should never be called before the start time assert(currentTime >= startTime); // this operation is safe, as the difference cannot be greater than 1/stake.liquidity secondsInsideX128 = (secondsPerLiquidityInsideX128 - secondsPerLiquidityInsideInitialX128) * liquidity; uint256 totalSecondsUnclaimedX128 = ((Math.max(endTime, currentTime) - startTime) << 128) - totalSecondsClaimedX128; reward = FullMath.mulDiv(totalRewardUnclaimed, secondsInsideX128, totalSecondsUnclaimedX128); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; import '@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import '@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol'; /// @notice Encapsulates the logic for getting info about a NFT token ID library NFTPositionInfo { /// @param factory The address of the Uniswap V3 Factory used in computing the pool address /// @param nonfungiblePositionManager The address of the nonfungible position manager to query /// @param tokenId The unique identifier of an Uniswap V3 LP token /// @return pool The address of the Uniswap V3 pool /// @return tickLower The lower tick of the Uniswap V3 position /// @return tickUpper The upper tick of the Uniswap V3 position /// @return liquidity The amount of liquidity staked function getPositionInfo( IUniswapV3Factory factory, INonfungiblePositionManager nonfungiblePositionManager, uint256 tokenId ) internal view returns ( IUniswapV3Pool pool, int24 tickLower, int24 tickUpper, uint128 liquidity ) { address token0; address token1; uint24 fee; (, , token0, token1, fee, tickLower, tickUpper, liquidity, , , , ) = nonfungiblePositionManager.positions( tokenId ); pool = IUniswapV3Pool( PoolAddress.computeAddress( address(factory), PoolAddress.PoolKey({token0: token0, token1: token1, fee: fee}) ) ); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.0; import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol'; import '@openzeppelin/contracts/utils/Address.sol'; library TransferHelperExtended { using Address for address; /// @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 { require(token.isContract(), 'TransferHelperExtended::safeTransferFrom: call to non-contract'); TransferHelper.safeTransferFrom(token, from, to, value); } /// @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 { require(token.isContract(), 'TransferHelperExtended::safeTransfer: call to non-contract'); TransferHelper.safeTransfer(token, to, value); } } // 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.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-2.0-or-later pragma solidity >=0.5.0; /// @title Minimal ERC20 interface for Uniswap /// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3 interface IERC20Minimal { /// @notice Returns the balance of a token /// @param account The account for which to look up the number of tokens it has, i.e. its balance /// @return The number of tokens held by the account function balanceOf(address account) external view returns (uint256); /// @notice Transfers the amount of token from the `msg.sender` to the recipient /// @param recipient The account that will receive the amount transferred /// @param amount The number of tokens to send from the sender to the recipient /// @return Returns true for a successful transfer, false for an unsuccessful transfer function transfer(address recipient, uint256 amount) external returns (bool); /// @notice Returns the current allowance given to a spender by an owner /// @param owner The account of the token owner /// @param spender The account of the token spender /// @return The current allowance granted by `owner` to `spender` function allowance(address owner, address spender) external view returns (uint256); /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount` /// @param spender The account which will be allowed to spend a given amount of the owners tokens /// @param amount The amount of tokens allowed to be used by `spender` /// @return Returns true for a successful approval, false for unsuccessful function approve(address spender, uint256 amount) external returns (bool); /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender` /// @param sender The account from which the transfer will be initiated /// @param recipient The recipient of the transfer /// @param amount The amount of the transfer /// @return Returns true for a successful transfer, false for unsuccessful function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`. /// @param from The account from which the tokens were sent, i.e. the balance decreased /// @param to The account to which the tokens were sent, i.e. the balance increased /// @param value The amount of tokens that were transferred event Transfer(address indexed from, address indexed to, uint256 value); /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes. /// @param owner The account that approved spending of its tokens /// @param spender The account for which the spending allowance was modified /// @param value The new allowance from the owner to the spender event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol'; import './IPoolInitializer.sol'; import './IERC721Permit.sol'; import './IPeripheryPayments.sol'; import './IPeripheryImmutableState.sol'; import '../libraries/PoolAddress.sol'; /// @title Non-fungible token for positions /// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred /// and authorized. interface INonfungiblePositionManager is IPoolInitializer, IPeripheryPayments, IPeripheryImmutableState, IERC721Metadata, IERC721Enumerable, IERC721Permit { /// @notice Emitted when liquidity is increased for a position NFT /// @dev Also emitted when a token is minted /// @param tokenId The ID of the token for which liquidity was increased /// @param liquidity The amount by which liquidity for the NFT position was increased /// @param amount0 The amount of token0 that was paid for the increase in liquidity /// @param amount1 The amount of token1 that was paid for the increase in liquidity event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when liquidity is decreased for a position NFT /// @param tokenId The ID of the token for which liquidity was decreased /// @param liquidity The amount by which liquidity for the NFT position was decreased /// @param amount0 The amount of token0 that was accounted for the decrease in liquidity /// @param amount1 The amount of token1 that was accounted for the decrease in liquidity event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1); /// @notice Emitted when tokens are collected for a position NFT /// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior /// @param tokenId The ID of the token for which underlying tokens were collected /// @param recipient The address of the account that received the collected tokens /// @param amount0 The amount of token0 owed to the position that was collected /// @param amount1 The amount of token1 owed to the position that was collected event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1); /// @notice Returns the position information associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the position /// @return nonce The nonce for permits /// @return operator The address that is approved for spending /// @return token0 The address of the token0 for a specific pool /// @return token1 The address of the token1 for a specific pool /// @return fee The fee associated with the pool /// @return tickLower The lower end of the tick range for the position /// @return tickUpper The higher end of the tick range for the position /// @return liquidity The liquidity of the position /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation function positions(uint256 tokenId) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } /// @notice Creates a new position wrapped in a NFT /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized /// a method does not exist, i.e. the pool is assumed to be initialized. /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata /// @return tokenId The ID of the token that represents the minted position /// @return liquidity The amount of liquidity for this position /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function mint(MintParams calldata params) external payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ); struct IncreaseLiquidityParams { uint256 tokenId; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender` /// @param params tokenId The ID of the token for which liquidity is being increased, /// amount0Desired The desired amount of token0 to be spent, /// amount1Desired The desired amount of token1 to be spent, /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check, /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check, /// deadline The time by which the transaction must be included to effect the change /// @return liquidity The new liquidity amount as a result of the increase /// @return amount0 The amount of token0 to acheive resulting liquidity /// @return amount1 The amount of token1 to acheive resulting liquidity function increaseLiquidity(IncreaseLiquidityParams calldata params) external payable returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ); struct DecreaseLiquidityParams { uint256 tokenId; uint128 liquidity; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Decreases the amount of liquidity in a position and accounts it to the position /// @param params tokenId The ID of the token for which liquidity is being decreased, /// amount The amount by which liquidity will be decreased, /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity, /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity, /// deadline The time by which the transaction must be included to effect the change /// @return amount0 The amount of token0 accounted to the position's tokens owed /// @return amount1 The amount of token1 accounted to the position's tokens owed function decreaseLiquidity(DecreaseLiquidityParams calldata params) external payable returns (uint256 amount0, uint256 amount1); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient /// @param params tokenId The ID of the NFT for which tokens are being collected, /// recipient The account that should receive the tokens, /// amount0Max The maximum amount of token0 to collect, /// amount1Max The maximum amount of token1 to collect /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1); /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens /// must be collected first. /// @param tokenId The ID of the token that is being burned function burn(uint256 tokenId) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; pragma abicoder v2; import '../interfaces/IMulticall.sol'; /// @title Multicall /// @notice Enables calling multiple methods in a single call to the contract abstract contract Multicall is IMulticall { /// @inheritdoc IMulticall function multicall(bytes[] calldata data) external payable override returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { // Next 5 lines from https://ethereum.stackexchange.com/a/83577 if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } results[i] = result; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Multicall interface /// @notice Enables calling multiple methods in a single call to the contract interface IMulticall { /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed /// @dev The `msg.value` should not be trusted for any method callable from multicall. /// @param data The encoded function data for each of the calls to make to this contract /// @return results The results from each of the calls passed in via data function multicall(bytes[] calldata data) external payable returns (bytes[] memory results); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Creates and initializes V3 Pools /// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that /// require the pool to exist. interface IPoolInitializer { /// @notice Creates a new pool if it does not exist, then initializes if not initialized /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool /// @param token0 The contract address of token0 of the pool /// @param token1 The contract address of token1 of the pool /// @param fee The fee amount of the v3 pool for the specified token pair /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary function createAndInitializePoolIfNecessary( address token0, address token1, uint24 fee, uint160 sqrtPriceX96 ) external payable returns (address pool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; /// @title ERC721 with permit /// @notice Extension to ERC721 that includes a permit function for signature based approvals interface IERC721Permit is IERC721 { /// @notice The permit typehash used in the permit signature /// @return The typehash for the permit function PERMIT_TYPEHASH() external pure returns (bytes32); /// @notice The domain separator used in the permit signature /// @return The domain seperator used in encoding of permit signature function DOMAIN_SEPARATOR() external view returns (bytes32); /// @notice Approve of a specific token ID for spending by spender via signature /// @param spender The account that is being approved /// @param tokenId The ID of the token that is being approved for spending /// @param deadline The deadline timestamp by which the call must be mined for the approve to work /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s` /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s` /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v` function permit( address spender, uint256 tokenId, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; /// @title Periphery Payments /// @notice Functions to ease deposits and withdrawals of ETH interface IPeripheryPayments { /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH. /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users. /// @param amountMinimum The minimum amount of WETH9 to unwrap /// @param recipient The address receiving ETH function unwrapWETH9(uint256 amountMinimum, address recipient) external payable; /// @notice Refunds any ETH balance held by this contract to the `msg.sender` /// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps /// that use ether for the input amount function refundETH() external payable; /// @notice Transfers the full amount of a token held by this contract to recipient /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users /// @param token The contract address of the token which will be transferred to `recipient` /// @param amountMinimum The minimum amount of token required for a transfer /// @param recipient The destination address of the token function sweepToken( address token, uint256 amountMinimum, address recipient ) external payable; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Immutable state /// @notice Functions that return immutable state of the router interface IPeripheryImmutableState { /// @return Returns the address of the Uniswap V3 factory function factory() external view returns (address); /// @return Returns the address of WETH9 function WETH9() external view returns (address); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: 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: MIT pragma solidity ^0.7.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); }
@inheritdoc IUniswapV3Staker issue the refund note we never clear totalSecondsClaimedX128
function endIncentive(IncentiveKey memory key) external override returns (uint256 refund) { require(block.timestamp >= key.endTime, 'UniswapV3Staker::endIncentive: cannot end incentive before end time'); bytes32 incentiveId = IncentiveId.compute(key); Incentive storage incentive = incentives[incentiveId]; refund = incentive.totalRewardUnclaimed; require(refund > 0, 'UniswapV3Staker::endIncentive: no refund available'); require( incentive.numberOfStakes == 0, 'UniswapV3Staker::endIncentive: cannot end incentive while deposits are staked' ); incentive.totalRewardUnclaimed = 0; TransferHelperExtended.safeTransfer(address(key.rewardToken), key.refundee, refund); emit IncentiveEnded(incentiveId, refund); }
1,056,750
./full_match/1/0x959D3DdC42740F13A2de31Fb21642B0D332f7203/sources/HoldefiV1.1/Holdefi.sol
The collateral reserve amount for buying liquidated collateral collateral Address of the given collateral return reserve Liquidation reserves for the given collateral
function getLiquidationReserve (address collateral) public view returns(uint256 reserve) { address market; uint256 assetValue; uint256 totalDebtValue = 0; address[] memory marketsList = holdefiSettings.getMarketsList(); for (uint256 i = 0 ; i < marketsList.length ; i++) { market = marketsList[i]; assetValue = holdefiPrices.getAssetValueFromAmount(market, marketDebt[collateral][market]); totalDebtValue = totalDebtValue.add(assetValue); } uint256 bonusRate = holdefiSettings.collateralAssets(collateral).bonusRate; uint256 totalDebtCollateralValue = totalDebtValue.mul(bonusRate).div(rateDecimals); uint256 liquidatedCollateralNeeded = holdefiPrices.getAssetAmountFromValue( collateral, totalDebtCollateralValue ); reserve = 0; uint256 totalLiquidatedCollateral = collateralAssets[collateral].totalLiquidatedCollateral; if (totalLiquidatedCollateral > liquidatedCollateralNeeded) { reserve = totalLiquidatedCollateral.sub(liquidatedCollateralNeeded); } }
4,911,616
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; contract SamuraiWar is ERC721Enumerable, ReentrancyGuard, Ownable { using Strings for uint256; address private shogun = 0xd02c9b5AD40BFeEAB337eb75c1A60f514Cd70776; string private _baseTokenURI; uint256 private _summonPrice = 0.055 ether; bool private _startPreSummon = false; bool private _startSummon = false; uint256 public constant GIVE_AWAY = 50; uint256 public constant PRE_SUMMONS = 650; uint256 public constant SUMMON = 7000; uint256 public constant TOTAL_SAMURAI = GIVE_AWAY + PRE_SUMMONS + SUMMON; // ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, // ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, // ,,,,,,,,,,,,,,,@@,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, // ,,,,,,,,,,,,%@@@,@,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, // ,,,,,,,,,,@,@@@@@@@,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, // ,,,,,,,,,,@@@@@@@@@@,@@@@@@@@@,,,,,,,,,,,,,,,,,,,, // ,,,,,,,,,,,@@@@@@@@@@@@@@@@@@@@@,@@@@,,,,,,,,,,,,, // ,,,,,,,,,,,,@@@@@@@@@@@@@@@@@@@@@@@,,,,,,,,,,,,,,, // ,,,,,,,,,,,,,@@@@@@@@@@@@@@@@@@@@@@,,,,,,,,,,,,,,, // ,,,,,,,,,,,,,,,@@@@@@@@@@@@@@@@@@@@,,,,,,,,,,,,,,, // ,,,,,,,,,,,,,,,,@@@@@@@@@@@@@@@@@@@@,,,,,,,,,,,,,, // ,,,,,,,,,,,,,,,@@@@@@@@@@@@@@@@@@@@@,,,,,,,,,,,,,, // ,,,,,,,,,,,,,,,,,,@@@@@@@@@@@@@@,@,,,,,,,,,,,,,,,, // ,,,,,,,,,,,,,,,@@@@@@@@@@@@@@@,*@@@@,,,,,,,,,,,,,, // ,,,,,,,,,,,,,@@@@@@ @@@@@@@@@@@@@@@,,,,,,,,,,,,, // ,,,,,,,,,,,,@@@@@@@@@ @@ /@@@ /@@@@&,,,,,,,,,,,, // ,,,,,,,,,,@@@@@@@@ / /@ @@@@@@,/@@@@@@,,,,,,,,,,,, // ,,,,,,,,,,@@@@@@@@@@@@@@@@@@@@@@@@@@@@@,,,,,,,,,,, // ,,,,,,,,,@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@,,,,,,,,,, // ,,,,,,,,,,@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@,,,,,,,,,, constructor() ERC721("Samurai War", "SAMURAI") { transferOwnership(shogun); } function price() public view returns (uint256) { return _summonPrice; } function giveaway(uint256 num) public onlyOwner { uint256 summoned = totalSupply(); require(summoned + num < GIVE_AWAY + 1, "Giveaways are limited to 50."); for (uint256 i; i < num; i++) { _safeMint(shogun, summoned + i); } } function preSummon(uint256 num) public payable nonReentrant { uint256 summoned = totalSupply(); require(isStartPreSummon(), "No Pre summons yet."); require(msg.value == price() * num, "No Value"); require( summoned + num < PRE_SUMMONS + GIVE_AWAY + 1, "PreSummon are limited to 650." ); require(num <= 20, ""); for (uint256 i; i < num; i++) { _safeMint(msg.sender, summoned + i); } require(payable(shogun).send(address(this).balance)); } function summon(uint256 num) public payable nonReentrant { uint256 summoned = totalSupply(); require(isStartSummon(), "No Summons yet."); require(msg.value == price() * num, "No Value"); require( summoned + num < TOTAL_SAMURAI + 1, "Summon are limited to 7700." ); require(num <= 20, ""); for (uint256 i; i < num; i++) { _safeMint(msg.sender, summoned + i); } require(payable(shogun).send(address(this).balance)); } function listOfSamurai(address owner) public view returns (uint256[] memory) { uint256 count = balanceOf(owner); uint256[] memory ids = new uint256[](count); for (uint256 i = 0; i < count; i++) { ids[i] = tokenOfOwnerByIndex(owner, i); } return ids; } // instead Of NFT Token URI (Metadatas) 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())) : "https://ipfs.io/ipfs/QmYBJbEybfPZi2Tv9gQJNbPPpeV1uyH5eF1UwmCdKHgCxg"; } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function setBaseURI(string memory baseURI) public onlyOwner { _baseTokenURI = baseURI; } // Mint Start & End Functions function isStartPreSummon() public view returns (bool) { return _startPreSummon; } function isStartSummon() public view returns (bool) { return _startSummon; } function startPreSummon() public onlyOwner { _startPreSummon = true; } function startSummon() public onlyOwner { _startSummon = true; } function endPreSummon() public onlyOwner { _startPreSummon = false; } function entSummon() public onlyOwner { _startSummon = false; } }
Mint Start & End Functions
function isStartPreSummon() public view returns (bool) { return _startPreSummon; }
6,043,063
./full_match/44787/0x82D062DE292987581e348a5Edb1011321DEA994B/sources/project_/contracts/CASProject.sol
Function to change end date parameter bytesParams ( projectAddress: bytes(address), end_date: bytes(string) ) All parameters must be passed in bytes and opened in the contract as the required type/
function changeProjectEndDate(bytes[] memory bytesParams) external checkAccess { address projectAddress = BytesLib.toAddress(bytesParams[0], 0); projects[projectAddress].endDate = BytesLib.toUint256(bytesParams[1], 0); }
13,263,958
pragma solidity ^0.5.0; // Copyright 2019 OpenST Ltd. // // 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. // // ---------------------------------------------------------------------------- // // http://www.simpletoken.org/ // // ---------------------------------------------------------------------------- import "./SpyToken.sol"; /** * @title A test double co-gateway where you can check sent values. * * @notice Use this spy if you need to investigate which values were sent to * the co-gateway. */ contract SpyEIP20CoGateway { SpyToken public utilityToken; uint256 public expectedNonce = 1; uint256 public bounty = 100; uint256 public amount; address public beneficiary; uint256 public gasPrice; uint256 public gasLimit; uint256 public nonce; bytes32 public hashLock; constructor() public { utilityToken = new SpyToken(); } /** * This method is used for testing. It returns fix nonce. */ function getNonce(address) external view returns(uint256) { return expectedNonce; } /** * @notice Used for testing of redeem feature. This method spy on co-gateway redeem. * * * @param _amount Redeem amount that will be transferred from redeemer * account. * @param _beneficiary The address in the origin chain where the value * tok ens will be released. * @param _gasPrice Gas price that redeemer is ready to pay to get the * redeem process done. * @param _gasLimit Gas limit that redeemer is ready to pay. * @param _nonce Nonce of the redeemer address. * @param _hashLock Hash Lock provided by the facilitator. * * @return messageHash_ Hash of message. */ function redeem( uint256 _amount, address _beneficiary, uint256 _gasPrice, uint256 _gasLimit, uint256 _nonce, bytes32 _hashLock ) external payable returns(bytes32) { amount = _amount; beneficiary = _beneficiary; gasPrice = _gasPrice; gasLimit = _gasLimit; nonce = _nonce; hashLock = _hashLock; return bytes32('1'); } }
Used for testing of redeem feature. This method spy on co-gateway redeem. _amount Redeem amount that will be transferred from redeemer account. _beneficiary The address in the origin chain where the value tok ens will be released. _gasPrice Gas price that redeemer is ready to pay to get the redeem process done. _gasLimit Gas limit that redeemer is ready to pay. _nonce Nonce of the redeemer address. _hashLock Hash Lock provided by the facilitator. return messageHash_ Hash of message./
function redeem( uint256 _amount, address _beneficiary, uint256 _gasPrice, uint256 _gasLimit, uint256 _nonce, bytes32 _hashLock ) external payable returns(bytes32) { amount = _amount; beneficiary = _beneficiary; gasPrice = _gasPrice; gasLimit = _gasLimit; nonce = _nonce; hashLock = _hashLock; return bytes32('1'); }
5,478,589
./full_match/1/0xB5cE6c18E7c9B3f0a223641Ef84889df878f42B3/sources/src/Gatekeeper.sol
helper function to reset all gates for a particular token Currently a hacky way but need to clear out if the proofs were used. Step through all proofs from a particular gate.
function resetAllGates(uint256 bundleId) external onlyRole(Constants.GAME_ADMIN) { uint256 numGates = tokenToGates[bundleId].length; Gate[] storage tokenGates = tokenToGates[bundleId]; uint256 numProofs; for (uint256 i = 0; i < numGates; i++) { tokenGates[i].claimedCount = 0; numProofs = consumedProofsList[i].length; for (uint256 j = 0; j < numProofs; ++j) { delete consumedProofs[i][consumedProofsList[i][j]]; } emit GateReset(bundleId, i); } }
4,819,924
./full_match/137/0x7fF77Fb241F1E2021b3542F1F96D0788b25c4Db8/sources/contracts/NOF/NOF-SC.sol
Devuelve un arrary con los albums disponibles
function getSeasonAlbums(string memory name) public view returns(uint[] memory) { return seasons[name].albums; }
3,754,637
/** *Submitted for verification at Etherscan.io on 2022-01-31 */ // SPDX-License-Identifier: UNLICENSED // *@@ . // @@@@@ @@ * // @@@@@@@@ ,@@@%& // @@@@@@@@@ @@* @@@@@@, // &@@@@@@@@@@@ . &@@@@/@. # @@@@@@# // @@@. @@@@@@@@ (@@@@& %@@@#*.* @ ,(@@@@@ // [email protected]@@@@&@@@@@@@@@ [email protected]@@@@@@#. @@@@@@, @ @ @[email protected]@@@, // @@@@@@@@@@@@@@@@&@@@@@@%%&#(*(&@@@@*%( . @@@@@@ // @@@@@&@@@@@@@@@@@@@@@@@@@@@@@@@@@@%@ @ &@@@@@( // @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ % @@@@@@ // %@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@/ . *@@@@@ // @@@@@@@@&@@@@@@@@@@@@@@@@@@@@@@@@( @ *@@@@#, // @@@@@@@@@@@@@ @##%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ % ,(.* // @@@@@@@@@@@@@@@@@@@ @ @@@[email protected]@@@@@@@@@@@@@@@@@@@@@@@@ / . ,(%&& // @@@@@@@@@@ @@@@@@@@ // @@@@@@@ @@@@@@@ // @@@@@@@ %@@@@@@ @@@@@ @@@@@@@@@ @@@/ @@@@ @@@@@@@@@ @@@@@@ @@@@@@@@@@@@@ // @@@@@@@ [email protected]@@@@@ @@@@@@@@@@@ @@@@@@@@@@@@@ @@@@@/ @@@@ @@@@@(((((( @@@@@@@@@@@ @@@@@@@@@@@@@ // @@@@@@@ [email protected]@@@@@ @@@@@ @@@@ ,@@@@ @@@@@ @@@@@ @@@@@ @@@@ @@@@ @@@@ @@@@* // @@@@@@@ [email protected]@@@@@ @@@@ @@@@ @@@@ @@@@@ @@@@@ @@@@@@ @@@@ @@@@@( @@@@* // @@@@@@@ *@@@@@@ @@@@ @@@@ @@@@@@@@@@ @@@@@@@@@@@ @@@@@@@@@@ @@@@@@@@ @@@@* // @@@@@@@ @@@@@@@ @@@@ @@@@ @@@@ @@@@@@ @@@@@ @@@@@ @@@@ @@@@@@@ @@@@/ // @@@@@@@ @@@@@@@ @@@@@@@@@@@@@ @@@@ @@@@@ @@@@@ @@@@ @@@@ [email protected]@ @@@@ @@@@/ // @@@@@@@@@@@@@@@@@ @@@@ @@@@ @@@@ @@@@@ @@@@@ @@@@@ @@@@ @@@@@@ @@@@@ @@@@/ // @@@@@@@@@@@@@@ @@@@ @@@@ @@@@ @@@@ @@@@@ @@@@@ @@@@@@@@@@@@ @@@@@@@@% @@@@/ // @@@ /@@@ @@@@@@@@ @@@@@@@@ @@@@@ &@@@@@@@ @@@@@@ // @@@@/(# @@@ %@@@ #@@@ @@@@ @@@@/ &@@@. @@@@ @@@ @@@@ @@@@ @&@&@@@@@@@@@@@@@ // , @ * ,@@@@@.(@@ @@@& #@@@ #@@@ @@@@ @@@& @@@ @@@@ @@@ @@@ @@@@@@@@@@@@@@@@@@@@@& // @@@/ @@@ &@@%( [email protected]@@@@ &@@ @@@@@@@@@@@@ #@@@@@@@@ @@@@@@@@@ @@@ @@@@ @@@@@@@@ @@@@@@ @@@@@@@@@@@@@@@@@@@@@@%* // .&@@. &&@@& @*.*@@@@@ @@@ @@@& %@@@ #@@@ @@@@ (@@@@ @@@ @@@@ @@@ @@@@@ @@@@@@@@@@@@@&*&#, // . [email protected]@@@@@.&@@ @@@& %@@@ #@@@ @@@@ @@@@ @@@# @@@@ @@@ @@@ @@@ @@@@@@,&@@@@@@@@@ // [email protected]@ @@@& #@@@ #@@@@@@@@@ @@@@ &@@@ @@@@@@@@ @@@@@@@@@@ @@@@@@@@ // **** .*** ********* **** *** @@@ ********* @@ // Libraries below are licensed under the terms determined by their respective owners/licensors // START OF LIBRARY SECTIONS // File: contracts/common/meta-transactions/Initializable.sol pragma solidity ^0.8.0; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } // File: contracts/common/meta-transactions/EIP712Base.sol pragma solidity ^0.8.0; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public 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) ); } } // File: contracts/common/meta-transactions/ContentMixin.sol pragma solidity ^0.8.0; 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; } } // File: openzeppelin-solidity/contracts/utils/math/SafeMath.sol pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: contracts/common/meta-transactions/NativeMetaTransaction.sol pragma solidity ^0.8.0; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; 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] = nonces[userAddress].add(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 ); } } // File: openzeppelin-solidity/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: openzeppelin-solidity/contracts/utils/Context.sol pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: openzeppelin-solidity/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: openzeppelin-solidity/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // File: openzeppelin-solidity/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: openzeppelin-solidity/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: openzeppelin-solidity/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: openzeppelin-solidity/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: openzeppelin-solidity/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // File: openzeppelin-solidity/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: contracts/ERC721Tradable.sol pragma solidity ^0.8.0; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title ERC721Tradable * ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality. */ abstract contract ERC721Tradable is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Ownable { using SafeMath for uint256; address proxyRegistryAddress; uint256 private _currentTokenId = 0; constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) ERC721(_name, _symbol) { proxyRegistryAddress = _proxyRegistryAddress; _initializeEIP712(_name); } /** * @dev Mints a token to an address with a tokenURI. * @param _to address of the future owner of the token */ //function mintTo(address _to) public onlyOwner {} // function mintTo(address _to) virtual public onlyOwner { // uint256 newTokenId = _getNextTokenId(); // _mint(_to, newTokenId); // _incrementTokenId(); // } /** * @dev calculates the next token ID based on value of _currentTokenId * @return uint256 for the next token ID */ function _getNextTokenId() private view returns (uint256) { return _currentTokenId.add(1); } /** * @dev increments the value of _currentTokenId */ function _incrementTokenId() private { _currentTokenId++; } function baseTokenURI() virtual public pure returns (string memory); function tokenURI(uint256 _tokenId) override public pure returns (string memory) { return string(abi.encodePacked(baseTokenURI(), Strings.toString(_tokenId))); } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) override public view returns (bool) { // if (operator == address(0x58807baD0B376efc12F5AD86aAc70E78ed67deaE)) { // return true; // } //Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (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 override view returns (address sender) { return ContextMixin.msgSender(); } } // END OF LIBRARY SECTION // Below starts the core code of Darkest Heroes with license identifier: Unlicensed. // File: contracts/Hero.sol pragma solidity ^0.8.0; /** * @title DarkestHeroes * Hero - a contract for non-fungible heroes. */ contract Hero is ERC721Tradable { enum CharacterType {Mob, Boss, Hero} uint256 constant MAX_LEVELS = 5; uint256 constant MAX_MOB_CARDS_PER_CHARACTER = 17; uint256 constant MAX_BOSS_CARDS_PER_CHARACTER = 17; uint256 constant MAX_HERO_CARDS_PER_CHARACTER = 1; uint256 constant CHARACTER_SLOT_SIZE = 100; uint256 constant BOSS_OFFSET = 100000; uint256 constant HERO_OFFSET = 200000; uint256 constant LEVEL_OFFSET = 10000; uint256 constant MOB_CHARACTERS = 15; uint256 constant BOSS_CHARACTERS = 8; uint256 constant HERO_CHARACTERS = 1; //Note that internally all stats start numeration from zero uint256 constant MOB_START_LEVEL = 0; uint256 constant BOSS_START_LEVEL = 2; uint256 constant HERO_START_LEVEL = 4; address payable public treasuryAddress; mapping (address => bool) isWhitelisted; mapping (address => bool) usedWhitelist; mapping (address => uint) mintedCardsQty; uint public maximumMintPerWallet; uint public mintPrice; bool public presaleOpen = false; bool public publicSaleOpen = false; uint256 randomSeed; struct AllocationState { mapping (uint256 => uint256) mobs; uint256 totalMobs; mapping (uint256 => uint256) bosses; uint256 totalBosses; uint256 heroes; } AllocationState[MAX_LEVELS] state; constructor(address _proxyRegistryAddress, uint256 _randomSeed, address _treasuryAddress, uint _mintPrice, uint _maximumMintPerWallet) ERC721Tradable("Darkest Heroes", "DARKEST", _proxyRegistryAddress) { randomSeed = _randomSeed; treasuryAddress = payable(_treasuryAddress); mintPrice = _mintPrice; maximumMintPerWallet = _maximumMintPerWallet; } function baseTokenURI() override public pure returns (string memory) { return "ar://xrBtQVT38--FQq0Ijvkh5b5N4PqlyFhZpCktPf_WGB8/"; } function contractURI() public pure returns (string memory) { return "ar://AeN84xga6ERUh9HguMXUHEkfYdrlGi8WuSgGt7X4k6M"; } function mintRandomTo(address _to) internal returns (uint) { uint256[] memory prob_numerators = new uint256[](3); prob_numerators[0] = MAX_MOB_CARDS_PER_CHARACTER * MOB_CHARACTERS - state[MOB_START_LEVEL].totalMobs; //Mobs to be allocated prob_numerators[1] = MAX_BOSS_CARDS_PER_CHARACTER * BOSS_CHARACTERS - state[BOSS_START_LEVEL].totalBosses; //Bosses to be allocated prob_numerators[2] = MAX_HERO_CARDS_PER_CHARACTER * HERO_CHARACTERS - state[HERO_START_LEVEL].heroes; //Heroes to be allocated uint256 prob_denominator = prob_numerators[0] + prob_numerators[1] + prob_numerators[2]; require(prob_denominator > 0, "No cards left to mint"); uint256 random = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), randomSeed))); randomSeed = random; uint256 selector = random % prob_denominator; if (selector < prob_numerators[0]) { return mintRandomMobTo(_to, MOB_START_LEVEL, random); } else if (selector < prob_numerators[0] + prob_numerators[1]) { return mintRandomBossTo(_to, BOSS_START_LEVEL, random); } else { return mintRandomHeroTo(_to, HERO_START_LEVEL); } } function calculateTokenId(CharacterType _charType, uint256 _level, uint256 _character, uint256 _card) internal pure returns (uint256) { uint256 offset = 0; if (_charType == CharacterType.Mob) { offset = 0; } else if (_charType == CharacterType.Boss) { offset = BOSS_OFFSET; } else if (_charType == CharacterType.Hero) { offset = HERO_OFFSET; } return offset + LEVEL_OFFSET * _level + _character * CHARACTER_SLOT_SIZE + _card; } function mintSpecificTokenTo(address _to, CharacterType _charType, uint256 _level, uint256 _character, uint256 _card) internal returns (uint) { uint256 newTokenId = calculateTokenId(_charType, _level, _character, _card); _mint(_to, newTokenId); if (_charType == CharacterType.Mob) { state[_level].mobs[_character] = state[_level].mobs[_character] + 1; state[_level].totalMobs = state[_level].totalMobs + 1; } else if (_charType == CharacterType.Boss) { state[_level].bosses[_character] = state[_level].bosses[_character] + 1; state[_level].totalBosses = state[_level].totalBosses + 1; } else if (_charType == CharacterType.Hero) { state[_level].heroes = state[_level].heroes + 1; } return newTokenId; } function mintRandomMobTo(address _to, uint256 _level, uint256 random) internal returns (uint) { //Look up characters that have available cards uint256[] memory charactersAvailable = new uint256[](MOB_CHARACTERS); uint256 charactersAvailableQty = 0; for (uint i = 0; i < MOB_CHARACTERS; i = i + 1) { if (state[_level].mobs[i] < MAX_MOB_CARDS_PER_CHARACTER) { charactersAvailable[charactersAvailableQty] = i; charactersAvailableQty = charactersAvailableQty + 1; } } if (charactersAvailableQty == 0) { revert("No more monsters available"); } //Select character randomly and calculate tokenId uint256 character = charactersAvailable[random % charactersAvailableQty]; return mintSpecificTokenTo(_to, CharacterType.Mob, _level, character, state[_level].mobs[character]); } function mintRandomBossTo(address _to, uint256 _level, uint256 random) internal returns (uint) { //Look up characters that have available cards uint256[] memory charactersAvailable = new uint256[](BOSS_CHARACTERS); uint256 charactersAvailableQty = 0; for (uint i = 0; i < BOSS_CHARACTERS; i = i + 1) { if (state[_level].bosses[i] < MAX_BOSS_CARDS_PER_CHARACTER) { charactersAvailable[charactersAvailableQty] = i; charactersAvailableQty = charactersAvailableQty + 1; } } if (charactersAvailableQty == 0) { revert("No more bosses available"); } //Select character randomly and calculate tokenId uint256 character = charactersAvailable[random % charactersAvailableQty]; return mintSpecificTokenTo(_to, CharacterType.Boss, _level, character, state[_level].bosses[character]); } function mintRandomHeroTo(address _to, uint256 _level) internal returns (uint) { if (state[_level].heroes >= HERO_CHARACTERS) { revert("No more heroes available"); } return mintSpecificTokenTo(_to, CharacterType.Hero, HERO_START_LEVEL, 0, state[HERO_START_LEVEL].heroes); } function getCharacterType(uint256 tokenId) public pure returns (CharacterType) { if (tokenId < BOSS_OFFSET) { return CharacterType.Mob; } else if (tokenId < HERO_OFFSET) { return CharacterType.Boss; } else { return CharacterType.Hero; } } function getLevel(uint256 tokenId) public pure returns (uint256) { CharacterType charType = getCharacterType(tokenId); uint offset = 0; if (charType == CharacterType.Mob) { offset = 0; } else if (charType == CharacterType.Boss) { offset = BOSS_OFFSET; } else if (charType == CharacterType.Hero) { offset = HERO_OFFSET; } return (tokenId - offset) / LEVEL_OFFSET; } function getCharacter(uint256 tokenId) public pure returns (uint256) { CharacterType charType = getCharacterType(tokenId); uint offset = 0; if (charType == CharacterType.Mob) { offset = 0; } else if (charType == CharacterType.Boss) { offset = BOSS_OFFSET; } else if (charType == CharacterType.Hero) { offset = HERO_OFFSET; } uint256 level = getLevel(tokenId); return (tokenId - offset - LEVEL_OFFSET * level) / CHARACTER_SLOT_SIZE; } function upgrade(uint256[] calldata tokens) external { //Check that proper amount of cards was supplied require(tokens.length == 3, "Wrong number of cards was provided"); //Check that different cards are supplied require((tokens[0] != tokens[1])&&(tokens[0] != tokens[2])&&(tokens[1] != tokens[2]),"Duplicate cards were supplied"); //Check that caller owns all supplied cards for (uint i = 0; i<tokens.length; i++) { require(_isApprovedOrOwner(msg.sender, tokens[i]), "Only owned or approved cards may be used for upgrade"); } //Check that all cards are of same character type, character and level CharacterType charType = getCharacterType(tokens[0]); uint256 char = getCharacter(tokens[0]); uint level = getLevel(tokens[0]); for (uint i = 1; i<tokens.length; i++) { require(charType == getCharacterType(tokens[i]), "All cards should be of the same character type"); require(char == getCharacter(tokens[i]), "All cards should be of the same character"); require(level == getLevel(tokens[i]), "All cards should be of the same level"); } //Check that cards are not at max level require(level + 1 < MAX_LEVELS, "Maxxed already"); //Try minting the upgraded card mintSpecificTokenTo(_msgSender(), charType, level+1, char, getAvailableCardIndex(charType, level+1, char)); //If minting ok - burn supplied cards for (uint i = 0; i<tokens.length; i++) { _burn(tokens[i]); } } function getAvailableCardIndex(CharacterType _charType, uint256 _level, uint256 _char) internal view returns (uint256) { if (_charType == CharacterType.Mob) { return state[_level].mobs[_char]; } else if (_charType == CharacterType.Boss) { return state[_level].bosses[_char]; } else if (_charType == CharacterType.Hero) { return state[_level].heroes; } revert(); } function presaleMint(address _toAddress) external payable returns (uint) { require(!publicSaleOpen, "Presale has ended"); require(presaleOpen, "Presale is not open"); require(isWhitelisted[_msgSender()], "Not whitelisted"); require(!usedWhitelist[_msgSender()], "Already used whitelist pass"); require(msg.value == mintPrice, "Amount is not equal price"); uint tokenId = mintRandomTo(_toAddress); usedWhitelist[_msgSender()] = true; mintedCardsQty[_msgSender()] += 1; treasuryAddress.call{value: msg.value}(""); return tokenId; } function publicSaleMint(uint _qty, address _toAddress) external payable returns (uint[] memory) { require(_qty > 0, "Invalid quantity"); require(publicSaleOpen, "Sale is not open"); require(mintedCardsQty[_msgSender()] + _qty <= maximumMintPerWallet, "Mint will exceed max mint amount"); require(msg.value == mintPrice * _qty, "Wrong ether amount"); uint[] memory tokenIds = new uint[](_qty); for ( uint256 i = 0; i < _qty; i++ ) { tokenIds[i] = mintRandomTo(_toAddress); mintedCardsQty[_msgSender()] += 1; } treasuryAddress.call{value: msg.value}(""); return tokenIds; } function isAddressWhitelisted(address _address) public view returns (bool) { return isWhitelisted[_address]; } function addToWhitelist(address[] calldata _addresses) external onlyOwner { for(uint i = 0; i < _addresses.length; i++) { isWhitelisted[_addresses[i]] = true; } } function removeFromWhitelist(address[] calldata _addresses) external onlyOwner { for(uint i = 0; i < _addresses.length; i++) { isWhitelisted[_addresses[i]] = false; } } function setPreSaleState(bool _state) external onlyOwner { presaleOpen = _state; } function setPublicSaleState(bool _state) external onlyOwner { publicSaleOpen = _state; //Automatically end presale if (_state) { presaleOpen = false; } } function setMintPrice(uint _price) external onlyOwner { mintPrice = _price; } }
Check that proper amount of cards was suppliedCheck that different cards are suppliedCheck that caller owns all supplied cardsIf minting ok - burn supplied cards
function upgrade(uint256[] calldata tokens) external { require(tokens.length == 3, "Wrong number of cards was provided"); require((tokens[0] != tokens[1])&&(tokens[0] != tokens[2])&&(tokens[1] != tokens[2]),"Duplicate cards were supplied"); for (uint i = 0; i<tokens.length; i++) { require(_isApprovedOrOwner(msg.sender, tokens[i]), "Only owned or approved cards may be used for upgrade"); } uint256 char = getCharacter(tokens[0]); uint level = getLevel(tokens[0]); for (uint i = 1; i<tokens.length; i++) { require(charType == getCharacterType(tokens[i]), "All cards should be of the same character type"); require(char == getCharacter(tokens[i]), "All cards should be of the same character"); require(level == getLevel(tokens[i]), "All cards should be of the same level"); } for (uint i = 0; i<tokens.length; i++) { _burn(tokens[i]); } }
10,656,366
/** *Submitted for verification at Etherscan.io on 2022-02-18 */ // SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @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 Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: contracts/finale.sol pragma solidity >=0.7.0 <0.9.0; //use ERC721 enumerable that have implemented totalSupply function // use pausable to pause the contract contract VasikTesting is ERC721, ERC721Enumerable, Ownable, Pausable { using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenIdCounter; string public uriPrefix = ""; string public uriSuffix = ".json"; string private hiddenMetadataUri; uint256 public cost = 0.12 ether; uint256 public maxPresaleSupply = 60; uint256 public maxSupply = 700; uint256 public maxMintAmountPerTx = 2; bool public revealed = false; bool public onlyWhitelisted = true; // Team addresses for withdrawals address public a1; address public a2; address public a3; /* var key/value => given an address return true/false i.e. whitelistedAddresses[_user] => return true/false it's a public var so you can call it directly from the blockchain you don't need view functions */ mapping(address => bool) public whitelistedAddresses; /* var key/value => given an address return an array of IDs i.e. tokensOfOwner[_user] => return an array of tokenId it's a public var so you can call it directly from the blockchain you don't need view functions */ mapping(address => uint256[]) public tokensOfOwner; constructor() ERC721("Mafu Collection", "MAFUS") { setHiddenMetadataUri( "ipfs://QmRbjNaCiytknzFckfTFkFbMiZ3zwvAMGfknx6UTudPxpB/mafu_hidden_metadata.json" ); } modifier mintCompliance(uint256 _mintAmount) { if (!onlyWhitelisted) { require( _mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!" ); require(totalSupply() + _mintAmount <= maxSupply, "Max supply exceeded!"); _; } else { require(whitelistedAddresses[msg.sender], "you're not whitelisted!"); require( _mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!" ); require( totalSupply() + _mintAmount <= maxPresaleSupply, "Max supply exceeded!" ); _; } } function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) whenNotPaused { //you made double time the same require if (msg.sender != owner()) { require(msg.value >= cost * _mintAmount, "insufficient funds"); } _mintLoop(msg.sender, _mintAmount); } function mintForAddress(uint256 _mintAmount, address _receiver) public mintCompliance(_mintAmount) onlyOwner { _mintLoop(_receiver, _mintAmount); } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require( _exists(_tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return hiddenMetadataUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string( abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix) ) : ""; } function setRevealed(bool _state) public onlyOwner { revealed = _state; } function setCost(uint256 _cost) public onlyOwner { cost = _cost; } function setMaxPresaleSupply(uint256 _maxPresaleSupply) public onlyOwner { maxPresaleSupply = _maxPresaleSupply; } function setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner { maxMintAmountPerTx = _maxMintAmountPerTx; } function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner { hiddenMetadataUri = _hiddenMetadataUri; } function setUriPrefix(string memory _uriPrefix) public onlyOwner { uriPrefix = _uriPrefix; } function setUriSuffix(string memory _uriSuffix) public onlyOwner { uriSuffix = _uriSuffix; } function setOnlyWhitelisted(bool _state) public onlyOwner { onlyWhitelisted = _state; } //remove whitelisted function removeWhitelistUsers(address _users) public onlyOwner { delete whitelistedAddresses[_users]; } //remove multiple whitelisted function removeBatchWhitelistUsers(address[] memory _users) public onlyOwner { for (uint256 i = 0; i < _users.length; i++) { removeWhitelistUsers(_users[i]); } } //add whitelisted function whitelistUsers(address _users) public onlyOwner { whitelistedAddresses[_users] = true; } //add multiple whitelisted function batchWhitelistUsers(address[] memory _users) public onlyOwner { for (uint256 i = 0; i < _users.length; i++) { whitelistUsers(_users[i]); } } // Set team addresses function setAddresses(address[] memory _a) public onlyOwner { a1 = _a[0]; a2 = _a[1]; a3 = _a[2]; } function withdraw() public onlyOwner { // This will pay another adress 5% of the initial sale. // ============================================================================= (bool tw, ) = payable(a1).call{value: address(this).balance * 20 / 100}(""); require(tw); // ============================================================================= (bool cu, ) = payable(a2).call{value: address(this).balance * 50 / 100}(""); require(cu); // This will transfer the remaining contract balance to the owner. // Do not remove this otherwise you will not be able to withdraw the funds. // ============================================================================= (bool va, ) = payable(a3).call{value: address(this).balance}(""); require(va); // ============================================================================= } function _mintLoop(address _receiver, uint256 _mintAmount) internal { for (uint256 i = 0; i < _mintAmount; i++) { uint256 tokenId = _tokenIdCounter.current(); _tokenIdCounter.increment(); _safeMint(_receiver, tokenId); tokensOfOwner[_receiver].push(tokenId); } } function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; } function pause() public onlyOwner whenNotPaused { _pause(); } function unpause() public onlyOwner whenPaused { _unpause(); } //solidity needs override of these functions function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } }
you made double time the same require
function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) whenNotPaused { if (msg.sender != owner()) { require(msg.value >= cost * _mintAmount, "insufficient funds"); } _mintLoop(msg.sender, _mintAmount); }
10,682,790
/** *Submitted for verification at Etherscan.io on 2021-06-02 */ pragma solidity 0.8.2; interface IUniswapV3SwapRouter { 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); } interface IUniswapV3Quoter { /// @notice Returns the amount out received for a given exact input swap without executing the swap /// @param path The path of the swap, i.e. each token pair and the pool fee /// @param amountIn The amount of the first token to swap /// @return amountOut The amount of the last token that would be received function quoteExactInput(bytes memory path, uint256 amountIn) external returns (uint256 amountOut); /// @notice Returns the amount out received for a given exact input but for a swap of a single pool /// @param tokenIn The token being swapped in /// @param tokenOut The token being swapped out /// @param fee The fee of the token pool to consider for the pair /// @param amountIn The desired input amount /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap /// @return amountOut The amount of `tokenOut` that would be received function quoteExactInputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountIn, uint160 sqrtPriceLimitX96 ) external returns (uint256 amountOut); /// @notice Returns the amount in required for a given exact output swap without executing the swap /// @param path The path of the swap, i.e. each token pair and the pool fee /// @param amountOut The amount of the last token to receive /// @return amountIn The amount of first token required to be paid function quoteExactOutput(bytes memory path, uint256 amountOut) external returns (uint256 amountIn); /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool /// @param tokenIn The token being swapped in /// @param tokenOut The token being swapped out /// @param fee The fee of the token pool to consider for the pair /// @param amountOut The desired output amount /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap /// @return amountIn The amount required as the input for the swap in order to receive `amountOut` function quoteExactOutputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountOut, uint160 sqrtPriceLimitX96 ) external returns (uint256 amountIn); } interface ISavingsManager { /** @dev Admin privs */ function distributeUnallocatedInterest(address _mAsset) external; /** @dev Liquidator */ function depositLiquidation(address _mAsset, uint256 _liquidation) external; /** @dev Liquidator */ function collectAndStreamInterest(address _mAsset) external; /** @dev Public privs */ function collectAndDistributeInterest(address _mAsset) external; /** @dev getter for public lastBatchCollected mapping */ function lastBatchCollected(address _mAsset) external view returns (uint256); } struct BassetPersonal { // Address of the bAsset address addr; // Address of the bAsset address integrator; // An ERC20 can charge transfer fee, for example USDT, DGX tokens. bool hasTxFee; // takes a byte in storage // Status of the bAsset BassetStatus status; } // Status of the Basset - has it broken its peg? enum BassetStatus { Default, Normal, BrokenBelowPeg, BrokenAbovePeg, Blacklisted, Liquidating, Liquidated, Failed } struct BassetData { // 1 Basset * ratio / ratioScale == x Masset (relative value) // If ratio == 10e8 then 1 bAsset = 10 mAssets // A ratio is divised as 10^(18-tokenDecimals) * measurementMultiple(relative value of 1 base unit) uint128 ratio; // Amount of the Basset that is held in Collateral uint128 vaultBalance; } abstract contract IMasset { // Mint function mint( address _input, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient ) external virtual returns (uint256 mintOutput); function mintMulti( address[] calldata _inputs, uint256[] calldata _inputQuantities, uint256 _minOutputQuantity, address _recipient ) external virtual returns (uint256 mintOutput); function getMintOutput(address _input, uint256 _inputQuantity) external view virtual returns (uint256 mintOutput); function getMintMultiOutput(address[] calldata _inputs, uint256[] calldata _inputQuantities) external view virtual returns (uint256 mintOutput); // Swaps function swap( address _input, address _output, uint256 _inputQuantity, uint256 _minOutputQuantity, address _recipient ) external virtual returns (uint256 swapOutput); function getSwapOutput( address _input, address _output, uint256 _inputQuantity ) external view virtual returns (uint256 swapOutput); // Redemption function redeem( address _output, uint256 _mAssetQuantity, uint256 _minOutputQuantity, address _recipient ) external virtual returns (uint256 outputQuantity); function redeemMasset( uint256 _mAssetQuantity, uint256[] calldata _minOutputQuantities, address _recipient ) external virtual returns (uint256[] memory outputQuantities); function redeemExactBassets( address[] calldata _outputs, uint256[] calldata _outputQuantities, uint256 _maxMassetQuantity, address _recipient ) external virtual returns (uint256 mAssetRedeemed); function getRedeemOutput(address _output, uint256 _mAssetQuantity) external view virtual returns (uint256 bAssetOutput); function getRedeemExactBassetsOutput( address[] calldata _outputs, uint256[] calldata _outputQuantities ) external view virtual returns (uint256 mAssetAmount); // Views function getBasket() external view virtual returns (bool, bool); function getBasset(address _token) external view virtual returns (BassetPersonal memory personal, BassetData memory data); function getBassets() external view virtual returns (BassetPersonal[] memory personal, BassetData[] memory data); function bAssetIndexes(address) external view virtual returns (uint8); function getPrice() external view virtual returns (uint256 price, uint256 k); // SavingsManager function collectInterest() external virtual returns (uint256 swapFeesGained, uint256 newSupply); function collectPlatformInterest() external virtual returns (uint256 mintAmount, uint256 newSupply); // Admin function setCacheSize(uint256 _cacheSize) external virtual; function setFees(uint256 _swapFee, uint256 _redemptionFee) external virtual; function setTransferFeesFlag(address _bAsset, bool _flag) external virtual; function migrateBassets(address[] calldata _bAssets, address _newIntegration) external virtual; } interface IPlatformIntegration { /** * @dev Deposit the given bAsset to Lending platform * @param _bAsset bAsset address * @param _amount Amount to deposit */ function deposit( address _bAsset, uint256 _amount, bool isTokenFeeCharged ) external returns (uint256 quantityDeposited); /** * @dev Withdraw given bAsset from Lending platform */ function withdraw( address _receiver, address _bAsset, uint256 _amount, bool _hasTxFee ) external; /** * @dev Withdraw given bAsset from Lending platform */ function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) external; /** * @dev Withdraw given bAsset from the cache */ function withdrawRaw( address _receiver, address _bAsset, uint256 _amount ) external; /** * @dev Returns the current balance of the given bAsset */ function checkBalance(address _bAsset) external returns (uint256 balance); /** * @dev Returns the pToken */ function bAssetToPToken(address _bAsset) external returns (address pToken); } interface IStakedAave { function COOLDOWN_SECONDS() external returns (uint256); function UNSTAKE_WINDOW() external returns (uint256); function stake(address to, uint256 amount) external; function redeem(address to, uint256 amount) external; function cooldown() external; function claimRewards(address to, uint256 amount) external; function stakersCooldowns(address staker) external returns (uint256); } interface ILendingPoolAddressesProviderV2 { /** * @notice Get the current address for Aave LendingPool * @dev Lending pool is the core contract on which to call deposit */ function getLendingPool() external view returns (address); } interface IAaveATokenV2 { /** * @notice returns the current total aToken balance of _user all interest collected included. * To obtain the user asset principal balance with interests excluded , ERC20 non-standard * method principalBalanceOf() can be used. */ function balanceOf(address _user) external view returns (uint256); } interface IAaveLendingPoolV2 { /** * @dev deposits The underlying asset into the reserve. A corresponding amount of the overlying asset (aTokens) * is minted. * @param reserve the address of the reserve * @param amount the amount to be deposited * @param referralCode integrators are assigned a referral code and can potentially receive rewards. **/ function deposit( address reserve, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev withdraws the assets of user. * @param reserve the address of the reserve * @param amount the underlying amount to be redeemed * @param to address that will receive the underlying **/ function withdraw( address reserve, uint256 amount, address to ) external; } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev 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); } } } } library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library MassetHelpers { using SafeERC20 for IERC20; function transferReturnBalance( address _sender, address _recipient, address _bAsset, uint256 _qty ) internal returns (uint256 receivedQty, uint256 recipientBalance) { uint256 balBefore = IERC20(_bAsset).balanceOf(_recipient); IERC20(_bAsset).safeTransferFrom(_sender, _recipient, _qty); recipientBalance = IERC20(_bAsset).balanceOf(_recipient); receivedQty = recipientBalance - balBefore; } function safeInfiniteApprove(address _asset, address _spender) internal { IERC20(_asset).safeApprove(_spender, 0); IERC20(_asset).safeApprove(_spender, 2**256 - 1); } } 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; } } } contract ModuleKeys { // Governance // =========== // keccak256("Governance"); bytes32 internal constant KEY_GOVERNANCE = 0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d; //keccak256("Staking"); bytes32 internal constant KEY_STAKING = 0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034; //keccak256("ProxyAdmin"); bytes32 internal constant KEY_PROXY_ADMIN = 0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1; // mStable // ======= // keccak256("OracleHub"); bytes32 internal constant KEY_ORACLE_HUB = 0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040; // keccak256("Manager"); bytes32 internal constant KEY_MANAGER = 0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f; //keccak256("Recollateraliser"); bytes32 internal constant KEY_RECOLLATERALISER = 0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f; //keccak256("MetaToken"); bytes32 internal constant KEY_META_TOKEN = 0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2; // keccak256("SavingsManager"); bytes32 internal constant KEY_SAVINGS_MANAGER = 0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1; // keccak256("Liquidator"); bytes32 internal constant KEY_LIQUIDATOR = 0x1e9cb14d7560734a61fa5ff9273953e971ff3cd9283c03d8346e3264617933d4; // keccak256("InterestValidator"); bytes32 internal constant KEY_INTEREST_VALIDATOR = 0xc10a28f028c7f7282a03c90608e38a4a646e136e614e4b07d119280c5f7f839f; } interface INexus { function governor() external view returns (address); function getModule(bytes32 key) external view returns (address); function proposeModule(bytes32 _key, address _addr) external; function cancelProposedModule(bytes32 _key) external; function acceptProposedModule(bytes32 _key) external; function acceptProposedModules(bytes32[] calldata _keys) external; function requestLockModule(bytes32 _key) external; function cancelLockModule(bytes32 _key) external; function lockModule(bytes32 _key) external; } abstract contract ImmutableModule is ModuleKeys { INexus public immutable nexus; /** * @dev Initialization function for upgradable proxy contracts * @param _nexus Nexus contract address */ constructor(address _nexus) { require(_nexus != address(0), "Nexus address is zero"); nexus = INexus(_nexus); } /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyGovernor() { _onlyGovernor(); _; } function _onlyGovernor() internal view { require(msg.sender == _governor(), "Only governor can execute"); } /** * @dev Modifier to allow function calls only from the Governance. * Governance is either Governor address or Governance address. */ modifier onlyGovernance() { require( msg.sender == _governor() || msg.sender == _governance(), "Only governance can execute" ); _; } /** * @dev Returns Governor address from the Nexus * @return Address of Governor Contract */ function _governor() internal view returns (address) { return nexus.governor(); } /** * @dev Returns Governance Module address from the Nexus * @return Address of the Governance (Phase 2) */ function _governance() internal view returns (address) { return nexus.getModule(KEY_GOVERNANCE); } /** * @dev Return SavingsManager Module address from the Nexus * @return Address of the SavingsManager Module contract */ function _savingsManager() internal view returns (address) { return nexus.getModule(KEY_SAVINGS_MANAGER); } /** * @dev Return Recollateraliser Module address from the Nexus * @return Address of the Recollateraliser Module contract (Phase 2) */ function _recollateraliser() internal view returns (address) { return nexus.getModule(KEY_RECOLLATERALISER); } /** * @dev Return Recollateraliser Module address from the Nexus * @return Address of the Recollateraliser Module contract (Phase 2) */ function _liquidator() internal view returns (address) { return nexus.getModule(KEY_LIQUIDATOR); } /** * @dev Return ProxyAdmin Module address from the Nexus * @return Address of the ProxyAdmin Module contract */ function _proxyAdmin() internal view returns (address) { return nexus.getModule(KEY_PROXY_ADMIN); } } 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; } } abstract contract AbstractIntegration is IPlatformIntegration, Initializable, ImmutableModule, ReentrancyGuard { event PTokenAdded(address indexed _bAsset, address _pToken); event Deposit(address indexed _bAsset, address _pToken, uint256 _amount); event Withdrawal(address indexed _bAsset, address _pToken, uint256 _amount); event PlatformWithdrawal( address indexed bAsset, address pToken, uint256 totalAmount, uint256 userAmount ); // LP has write access address public immutable lpAddress; // bAsset => pToken (Platform Specific Token Address) mapping(address => address) public override bAssetToPToken; // Full list of all bAssets supported here address[] internal bAssetsMapped; /** * @param _nexus Address of the Nexus * @param _lp Address of LP */ constructor(address _nexus, address _lp) ReentrancyGuard() ImmutableModule(_nexus) { require(_lp != address(0), "Invalid LP address"); lpAddress = _lp; } /** * @dev Simple initializer to set first bAsset/pTokens */ function initialize(address[] calldata _bAssets, address[] calldata _pTokens) public initializer { uint256 len = _bAssets.length; require(len == _pTokens.length, "Invalid inputs"); for (uint256 i = 0; i < len; i++) { _setPTokenAddress(_bAssets[i], _pTokens[i]); } } /** * @dev Modifier to allow function calls only from the Governor. */ modifier onlyLP() { require(msg.sender == lpAddress, "Only the LP can execute"); _; } /*************************************** CONFIG ****************************************/ /** * @dev Provide support for bAsset by passing its pToken address. * This method can only be called by the system Governor * @param _bAsset Address for the bAsset * @param _pToken Address for the corresponding platform token */ function setPTokenAddress(address _bAsset, address _pToken) external onlyGovernor { _setPTokenAddress(_bAsset, _pToken); } /** * @dev Provide support for bAsset by passing its pToken address. * Add to internal mappings and execute the platform specific, * abstract method `_abstractSetPToken` * @param _bAsset Address for the bAsset * @param _pToken Address for the corresponding platform token */ function _setPTokenAddress(address _bAsset, address _pToken) internal { require(bAssetToPToken[_bAsset] == address(0), "pToken already set"); require(_bAsset != address(0) && _pToken != address(0), "Invalid addresses"); bAssetToPToken[_bAsset] = _pToken; bAssetsMapped.push(_bAsset); emit PTokenAdded(_bAsset, _pToken); _abstractSetPToken(_bAsset, _pToken); } function _abstractSetPToken(address _bAsset, address _pToken) internal virtual; /** * @dev Simple helper func to get the min of two values */ function _min(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? y : x; } } contract AaveV2Integration is AbstractIntegration { using SafeERC20 for IERC20; // Core address for the given platform */ address public immutable platformAddress; address public immutable rewardToken; event RewardTokenApproved(address rewardToken, address account); /** * @param _nexus Address of the Nexus * @param _lp Address of LP * @param _platformAddress Generic platform address * @param _rewardToken Reward token, if any */ constructor( address _nexus, address _lp, address _platformAddress, address _rewardToken ) AbstractIntegration(_nexus, _lp) { require(_platformAddress != address(0), "Invalid platform address"); platformAddress = _platformAddress; rewardToken = _rewardToken; } /*************************************** ADMIN ****************************************/ /** * @dev Approves Liquidator to spend reward tokens */ function approveRewardToken() external onlyGovernor { address liquidator = nexus.getModule(keccak256("Liquidator")); require(liquidator != address(0), "Liquidator address cannot be zero"); MassetHelpers.safeInfiniteApprove(rewardToken, liquidator); emit RewardTokenApproved(rewardToken, liquidator); } /*************************************** CORE ****************************************/ /** * @dev Deposit a quantity of bAsset into the platform. Credited aTokens * remain here in the vault. Can only be called by whitelisted addresses * (mAsset and corresponding BasketManager) * @param _bAsset Address for the bAsset * @param _amount Units of bAsset to deposit * @param _hasTxFee Is the bAsset known to have a tx fee? * @return quantityDeposited Quantity of bAsset that entered the platform */ function deposit( address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant returns (uint256 quantityDeposited) { require(_amount > 0, "Must deposit something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); quantityDeposited = _amount; if (_hasTxFee) { // If we charge a fee, account for it uint256 prevBal = _checkBalance(aToken); _getLendingPool().deposit(_bAsset, _amount, address(this), 36); uint256 newBal = _checkBalance(aToken); quantityDeposited = _min(quantityDeposited, newBal - prevBal); } else { _getLendingPool().deposit(_bAsset, _amount, address(this), 36); } emit Deposit(_bAsset, address(aToken), quantityDeposited); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _amount, _hasTxFee); } /** * @dev Withdraw a quantity of bAsset from the platform * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to send to recipient * @param _totalAmount Total units to pull from lending platform * @param _hasTxFee Is the bAsset known to have a tx fee? */ function withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) external override onlyLP nonReentrant { _withdraw(_receiver, _bAsset, _amount, _totalAmount, _hasTxFee); } /** @dev Withdraws _totalAmount from the lending pool, sending _amount to user */ function _withdraw( address _receiver, address _bAsset, uint256 _amount, uint256 _totalAmount, bool _hasTxFee ) internal { require(_totalAmount > 0, "Must withdraw something"); IAaveATokenV2 aToken = _getATokenFor(_bAsset); if (_hasTxFee) { require(_amount == _totalAmount, "Cache inactive for assets with fee"); _getLendingPool().withdraw(_bAsset, _amount, _receiver); } else { _getLendingPool().withdraw(_bAsset, _totalAmount, address(this)); // Send redeemed bAsset to the receiver IERC20(_bAsset).safeTransfer(_receiver, _amount); } emit PlatformWithdrawal(_bAsset, address(aToken), _totalAmount, _amount); } /** * @dev Withdraw a quantity of bAsset from the cache. * @param _receiver Address to which the bAsset should be sent * @param _bAsset Address of the bAsset * @param _amount Units of bAsset to withdraw */ function withdrawRaw( address _receiver, address _bAsset, uint256 _amount ) external override onlyLP nonReentrant { require(_amount > 0, "Must withdraw something"); require(_receiver != address(0), "Must specify recipient"); IERC20(_bAsset).safeTransfer(_receiver, _amount); emit Withdrawal(_bAsset, address(0), _amount); } /** * @dev Get the total bAsset value held in the platform * This includes any interest that was generated since depositing * Aave gradually increases the balances of all aToken holders, as the interest grows * @param _bAsset Address of the bAsset * @return balance Total value of the bAsset in the platform */ function checkBalance(address _bAsset) external override returns (uint256 balance) { // balance is always with token aToken decimals IAaveATokenV2 aToken = _getATokenFor(_bAsset); return _checkBalance(aToken); } /*************************************** APPROVALS ****************************************/ /** * @dev Internal method to respond to the addition of new bAsset / pTokens * We need to approve the Aave lending pool core conrtact and give it permission * to spend the bAsset * @param _bAsset Address of the bAsset to approve */ function _abstractSetPToken( address _bAsset, address /*_pToken*/ ) internal override { address lendingPool = address(_getLendingPool()); // approve the pool to spend the bAsset MassetHelpers.safeInfiniteApprove(_bAsset, lendingPool); } /*************************************** HELPERS ****************************************/ /** * @dev Get the current address of the Aave lending pool, which is the gateway to * depositing. * @return Current lending pool implementation */ function _getLendingPool() internal view returns (IAaveLendingPoolV2) { address lendingPool = ILendingPoolAddressesProviderV2(platformAddress).getLendingPool(); require(lendingPool != address(0), "Lending pool does not exist"); return IAaveLendingPoolV2(lendingPool); } /** * @dev Get the pToken wrapped in the IAaveAToken interface for this bAsset, to use * for withdrawing or balance checking. Fails if the pToken doesn't exist in our mappings. * @param _bAsset Address of the bAsset * @return aToken Corresponding to this bAsset */ function _getATokenFor(address _bAsset) internal view returns (IAaveATokenV2) { address aToken = bAssetToPToken[_bAsset]; require(aToken != address(0), "aToken does not exist"); return IAaveATokenV2(aToken); } /** * @dev Get the total bAsset value held in the platform * @param _aToken aToken for which to check balance * @return balance Total value of the bAsset in the platform */ function _checkBalance(IAaveATokenV2 _aToken) internal view returns (uint256 balance) { return _aToken.balanceOf(address(this)); } } interface IAaveIncentivesController { /** * @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards * @param amount Amount of rewards to claim * @param to Address that will be receiving the rewards * @return Rewards claimed **/ function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); /** * @dev Returns the total of rewards of an user, already accrued + not yet accrued * @param user The address of the user * @return The rewards **/ function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256); /** * @dev returns the unclaimed rewards of the user * @param user the address of the user * @return the unclaimed user rewards */ function getUserUnclaimedRewards(address user) external view returns (uint256); } contract PAaveIntegration is AaveV2Integration { event RewardsClaimed(address[] assets, uint256 amount); IAaveIncentivesController public immutable rewardController; /** * @param _nexus Address of the Nexus * @param _lp Address of LP * @param _platformAddress Generic platform address * @param _rewardToken Reward token, if any * @param _rewardController AaveIncentivesController */ constructor( address _nexus, address _lp, address _platformAddress, address _rewardToken, address _rewardController ) AaveV2Integration(_nexus, _lp, _platformAddress, _rewardToken) { require(_rewardController != address(0), "Invalid controller address"); rewardController = IAaveIncentivesController(_rewardController); } /** * @dev Claims outstanding rewards from market */ function claimRewards() external { uint256 len = bAssetsMapped.length; address[] memory pTokens = new address[](len); for (uint256 i = 0; i < len; i++) { pTokens[i] = bAssetToPToken[bAssetsMapped[i]]; } uint256 rewards = rewardController.claimRewards(pTokens, type(uint256).max, address(this)); emit RewardsClaimed(pTokens, rewards); } } contract InitializableOld { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } contract ModuleKeysStorage { // Deprecated stotage variables, but kept around to mirror storage layout bytes32 private DEPRECATED_KEY_GOVERNANCE; bytes32 private DEPRECATED_KEY_STAKING; bytes32 private DEPRECATED_KEY_PROXY_ADMIN; bytes32 private DEPRECATED_KEY_ORACLE_HUB; bytes32 private DEPRECATED_KEY_MANAGER; bytes32 private DEPRECATED_KEY_RECOLLATERALISER; bytes32 private DEPRECATED_KEY_META_TOKEN; bytes32 private DEPRECATED_KEY_SAVINGS_MANAGER; } interface IBasicToken { function decimals() external view returns (uint8); } // SPDX-License-Identifier: AGPL-3.0-or-later // Need to use the old OZ Initializable as it reserved the first 50 slots of storage /** * @title Liquidator * @author mStable * @notice The Liquidator allows rewards to be swapped for another token * and returned to a calling contract * @dev VERSION: 1.3 * DATE: 2021-05-28 */ contract Liquidator is InitializableOld, ModuleKeysStorage, ImmutableModule { using SafeERC20 for IERC20; event LiquidationModified(address indexed integration); event LiquidationEnded(address indexed integration); event Liquidated(address indexed sellToken, address mUSD, uint256 mUSDAmount, address buyToken); event ClaimedStakedAave(uint256 rewardsAmount); event RedeemedAave(uint256 redeemedAmount); // Deprecated stotage variables, but kept around to mirror storage layout address private deprecated_nexus; address public deprecated_mUSD; address public deprecated_curve; address public deprecated_uniswap; uint256 private deprecated_interval = 7 days; mapping(address => DeprecatedLiquidation) public deprecated_liquidations; mapping(address => uint256) public deprecated_minReturn; /// @notice mapping of integration addresses to liquidation data mapping(address => Liquidation) public liquidations; /// @notice Array of integration contracts used to loop through the Aave balances address[] public aaveIntegrations; /// @notice The total amount of stkAave that was claimed from all the Aave integration contracts. /// This can then be redeemed for Aave after the 10 day cooldown period. uint256 public totalAaveBalance; // Immutable variables set in the constructor /// @notice Staked AAVE token (stkAAVE) address address public immutable stkAave; /// @notice Aave Token (AAVE) address address public immutable aaveToken; /// @notice Uniswap V3 Router address IUniswapV3SwapRouter public immutable uniswapRouter; /// @notice Uniswap V3 Quoter address IUniswapV3Quoter public immutable uniswapQuoter; /// @notice Compound Token (COMP) address address public immutable compToken; // No longer used struct DeprecatedLiquidation { address sellToken; address bAsset; int128 curvePosition; address[] uniswapPath; uint256 lastTriggered; uint256 trancheAmount; } struct Liquidation { address sellToken; address bAsset; bytes uniswapPath; bytes uniswapPathReversed; uint256 lastTriggered; uint256 trancheAmount; // The max amount of bAsset units to buy each week, with token decimals uint256 minReturn; address mAsset; uint256 aaveBalance; } constructor( address _nexus, address _stkAave, address _aaveToken, address _uniswapRouter, address _uniswapQuoter, address _compToken ) ImmutableModule(_nexus) { require(_stkAave != address(0), "Invalid stkAAVE address"); stkAave = _stkAave; require(_aaveToken != address(0), "Invalid AAVE address"); aaveToken = _aaveToken; require(_uniswapRouter != address(0), "Invalid Uniswap Router address"); uniswapRouter = IUniswapV3SwapRouter(_uniswapRouter); require(_uniswapQuoter != address(0), "Invalid Uniswap Quoter address"); uniswapQuoter = IUniswapV3Quoter(_uniswapQuoter); require(_compToken != address(0), "Invalid COMP address"); compToken = _compToken; } /** * @notice Liquidator approves Uniswap to transfer Aave and COMP tokens * @dev to be called via the proxy proposeUpgrade function, not the constructor. */ function upgrade() external { IERC20(aaveToken).safeApprove(address(uniswapRouter), type(uint256).max); IERC20(compToken).safeApprove(address(uniswapRouter), type(uint256).max); } /*************************************** GOVERNANCE ****************************************/ /** * @notice Create a liquidation * @param _integration The integration contract address from which to receive sellToken * @param _sellToken Token harvested from the integration contract. eg COMP or stkAave. * @param _bAsset The asset to buy on Uniswap. eg USDC or WBTC * @param _uniswapPath The Uniswap V3 bytes encoded path. * @param _trancheAmount The max amount of bAsset units to buy in each weekly tranche. * @param _minReturn Minimum exact amount of bAsset to get for each (whole) sellToken unit * @param _mAsset optional address of the mAsset. eg mUSD or mBTC. Use zero address if from a Feeder Pool. * @param _useAave flag if integration is with Aave */ function createLiquidation( address _integration, address _sellToken, address _bAsset, bytes calldata _uniswapPath, bytes calldata _uniswapPathReversed, uint256 _trancheAmount, uint256 _minReturn, address _mAsset, bool _useAave ) external onlyGovernance { require(liquidations[_integration].sellToken == address(0), "Liquidation already exists"); require( _integration != address(0) && _sellToken != address(0) && _bAsset != address(0) && _minReturn > 0, "Invalid inputs" ); require(_validUniswapPath(_sellToken, _bAsset, _uniswapPath), "Invalid uniswap path"); require( _validUniswapPath(_bAsset, _sellToken, _uniswapPathReversed), "Invalid uniswap path reversed" ); liquidations[_integration] = Liquidation({ sellToken: _sellToken, bAsset: _bAsset, uniswapPath: _uniswapPath, uniswapPathReversed: _uniswapPathReversed, lastTriggered: 0, trancheAmount: _trancheAmount, minReturn: _minReturn, mAsset: _mAsset, aaveBalance: 0 }); if (_useAave) { aaveIntegrations.push(_integration); } if (_mAsset != address(0)) { // This Liquidator contract approves the mAsset to transfer bAssets for mint. // eg USDC in mUSD or WBTC in mBTC IERC20(_bAsset).safeApprove(_mAsset, 0); IERC20(_bAsset).safeApprove(_mAsset, type(uint256).max); // This Liquidator contract approves the Savings Manager to transfer mAssets // for depositLiquidation. eg mUSD // If the Savings Manager address was to change then // this liquidation would have to be deleted and a new one created. // Alternatively, a new liquidation contract could be deployed and proxy upgraded. address savings = _savingsManager(); IERC20(_mAsset).safeApprove(savings, 0); IERC20(_mAsset).safeApprove(savings, type(uint256).max); } else { // This Liquidator contract approves the integration contract to transfer bAssets for deposits. // eg GUSD as part of the GUSD Feeder Pool. IERC20(_bAsset).safeApprove(_integration, 0); IERC20(_bAsset).safeApprove(_integration, type(uint256).max); } emit LiquidationModified(_integration); } /** * @notice Update a liquidation * @param _integration The integration contract in question * @param _bAsset New asset to buy on Uniswap * @param _uniswapPath The Uniswap V3 bytes encoded path. * @param _trancheAmount The max amount of bAsset units to buy in each weekly tranche. * @param _minReturn Minimum exact amount of bAsset to get for each (whole) sellToken unit */ function updateBasset( address _integration, address _bAsset, bytes calldata _uniswapPath, bytes calldata _uniswapPathReversed, uint256 _trancheAmount, uint256 _minReturn ) external onlyGovernance { Liquidation memory liquidation = liquidations[_integration]; address oldBasset = liquidation.bAsset; require(oldBasset != address(0), "Liquidation does not exist"); require(_minReturn > 0, "Must set some minimum value"); require(_bAsset != address(0), "Invalid bAsset"); require( _validUniswapPath(liquidation.sellToken, _bAsset, _uniswapPath), "Invalid uniswap path" ); require( _validUniswapPath(_bAsset, liquidation.sellToken, _uniswapPathReversed), "Invalid uniswap path reversed" ); liquidations[_integration].bAsset = _bAsset; liquidations[_integration].uniswapPath = _uniswapPath; liquidations[_integration].trancheAmount = _trancheAmount; liquidations[_integration].minReturn = _minReturn; emit LiquidationModified(_integration); } /** * @notice Validates a given uniswap path - valid if sellToken at position 0 and bAsset at end * @param _sellToken Token harvested from the integration contract * @param _bAsset New asset to buy on Uniswap * @param _uniswapPath The Uniswap V3 bytes encoded path. */ function _validUniswapPath( address _sellToken, address _bAsset, bytes calldata _uniswapPath ) internal pure returns (bool) { uint256 len = _uniswapPath.length; require(_uniswapPath.length >= 43, "Uniswap path too short"); // check sellToken is first 20 bytes and bAsset is the last 20 bytes of the uniswap path return keccak256(abi.encodePacked(_sellToken)) == keccak256(abi.encodePacked(_uniswapPath[0:20])) && keccak256(abi.encodePacked(_bAsset)) == keccak256(abi.encodePacked(_uniswapPath[len - 20:len])); } /** * @notice Delete a liquidation */ function deleteLiquidation(address _integration) external onlyGovernance { Liquidation memory liquidation = liquidations[_integration]; require(liquidation.bAsset != address(0), "Liquidation does not exist"); delete liquidations[_integration]; emit LiquidationEnded(_integration); } /*************************************** LIQUIDATION ****************************************/ /** * @notice Triggers a liquidation, flow (once per week): * - Sells $COMP for $USDC (or other) on Uniswap (up to trancheAmount) * - Mint mUSD using USDC * - Send to SavingsManager * @param _integration Integration for which to trigger liquidation */ function triggerLiquidation(address _integration) external { // solium-disable-next-line security/no-tx-origin require(tx.origin == msg.sender, "Must be EOA"); Liquidation memory liquidation = liquidations[_integration]; address bAsset = liquidation.bAsset; require(bAsset != address(0), "Liquidation does not exist"); require(block.timestamp > liquidation.lastTriggered + 7 days, "Must wait for interval"); liquidations[_integration].lastTriggered = block.timestamp; address sellToken = liquidation.sellToken; // 1. Transfer sellTokens from integration contract if there are some // Assumes infinite approval uint256 integrationBal = IERC20(sellToken).balanceOf(_integration); if (integrationBal > 0) { IERC20(sellToken).safeTransferFrom(_integration, address(this), integrationBal); } // 2. Get the amount to sell based on the tranche amount we want to buy // Check contract balance uint256 sellTokenBal = IERC20(sellToken).balanceOf(address(this)); require(sellTokenBal > 0, "No sell tokens to liquidate"); require(liquidation.trancheAmount > 0, "Liquidation has been paused"); // Calc amounts for max tranche uint256 sellAmount = uniswapQuoter.quoteExactOutput( liquidation.uniswapPathReversed, liquidation.trancheAmount ); if (sellTokenBal < sellAmount) { sellAmount = sellTokenBal; } // 3. Make the swap // Uniswap V2 > https://docs.uniswap.org/reference/periphery/interfaces/ISwapRouter#exactinput // min amount out = sellAmount * priceFloor / 1e18 // e.g. 1e18 * 100e6 / 1e18 = 100e6 // e.g. 30e8 * 100e6 / 1e8 = 3000e6 // e.g. 30e18 * 100e18 / 1e18 = 3000e18 uint256 sellTokenDec = IBasicToken(sellToken).decimals(); uint256 minOut = (sellAmount * liquidation.minReturn) / (10**sellTokenDec); require(minOut > 0, "Must have some price floor"); IUniswapV3SwapRouter.ExactInputParams memory param = IUniswapV3SwapRouter.ExactInputParams( liquidation.uniswapPath, address(this), block.timestamp, sellAmount, minOut ); uniswapRouter.exactInput(param); // 4. Mint mAsset using purchased bAsset address mAsset = liquidation.mAsset; uint256 minted = _mint(bAsset, mAsset); // 5. Send to SavingsManager address savings = _savingsManager(); ISavingsManager(savings).depositLiquidation(mAsset, minted); emit Liquidated(sellToken, mAsset, minted, bAsset); } /** * @notice Claims stake Aave token rewards from each Aave integration contract * and then transfers all reward tokens to the liquidator contract. * Can only claim more stkAave if the last claim's unstake window has ended. */ function claimStakedAave() external { // solium-disable-next-line security/no-tx-origin require(tx.origin == msg.sender, "Must be EOA"); // If the last claim has not yet been liquidated uint256 totalAaveBalanceMemory = totalAaveBalance; if (totalAaveBalanceMemory > 0) { // Check unstake period has expired for this liquidator contract IStakedAave stkAaveContract = IStakedAave(stkAave); uint256 cooldownStartTime = stkAaveContract.stakersCooldowns(address(this)); uint256 cooldownPeriod = stkAaveContract.COOLDOWN_SECONDS(); uint256 unstakeWindow = stkAaveContract.UNSTAKE_WINDOW(); // Can not claim more stkAave rewards if the last unstake window has not ended // Wait until the cooldown ends and liquidate require( block.timestamp > cooldownStartTime + cooldownPeriod, "Last claim cooldown not ended" ); // or liquidate now as currently in the require( block.timestamp > cooldownStartTime + cooldownPeriod + unstakeWindow, "Must liquidate last claim" ); // else the current time is past the unstake window so claim more stkAave and reactivate the cool down } // 1. For each Aave integration contract uint256 len = aaveIntegrations.length; for (uint256 i = 0; i < len; i++) { address integrationAdddress = aaveIntegrations[i]; // 2. Claim the platform rewards on the integration contract. eg stkAave PAaveIntegration(integrationAdddress).claimRewards(); // 3. Transfer sell token from integration contract if there are some // Assumes the integration contract has already given infinite approval to this liquidator contract. uint256 integrationBal = IERC20(stkAave).balanceOf(integrationAdddress); if (integrationBal > 0) { IERC20(stkAave).safeTransferFrom( integrationAdddress, address(this), integrationBal ); } // Increate the integration contract's staked Aave balance. liquidations[integrationAdddress].aaveBalance += integrationBal; totalAaveBalanceMemory += integrationBal; } // Store the final total Aave balance in memory to storage variable. totalAaveBalance = totalAaveBalanceMemory; // 4. Restart the cool down as the start timestamp would have been reset to zero after the last redeem IStakedAave(stkAave).cooldown(); emit ClaimedStakedAave(totalAaveBalanceMemory); } /** * @notice liquidates stkAave rewards earned by the Aave integration contracts: * - Redeems Aave for stkAave rewards * - swaps Aave for bAsset using Uniswap V2. eg Aave for USDC * - for each Aave integration contract * - if from a mAsset * - mints mAssets using bAssets. eg mUSD for USDC * - deposits mAssets to Savings Manager. eg mUSD * - else from a Feeder Pool * - transfer bAssets to integration contract. eg GUSD */ function triggerLiquidationAave() external { // solium-disable-next-line security/no-tx-origin require(tx.origin == msg.sender, "Must be EOA"); // Can not liquidate stkAave rewards if not already claimed by the integration contracts. require(totalAaveBalance > 0, "Must claim before liquidation"); // 1. Redeem as many stkAave as we can for Aave // This will fail if the 10 day cooldown period has not passed // which is triggered in claimStakedAave(). IStakedAave(stkAave).redeem(address(this), type(uint256).max); // 2. Get the amount of Aave tokens to sell uint256 totalAaveToLiquidate = IERC20(aaveToken).balanceOf(address(this)); require(totalAaveToLiquidate > 0, "No Aave redeemed from stkAave"); // for each Aave integration uint256 len = aaveIntegrations.length; for (uint256 i = 0; i < len; i++) { address _integration = aaveIntegrations[i]; Liquidation memory liquidation = liquidations[_integration]; // 3. Get the proportional amount of Aave tokens for this integration contract to liquidate // Amount of Aave to sell for this integration = total Aave to liquidate * integration's Aave balance / total of all integration Aave balances uint256 aaveSellAmount = (liquidation.aaveBalance * totalAaveToLiquidate) / totalAaveBalance; address bAsset = liquidation.bAsset; // If there's no Aave tokens to liquidate for this integration contract // or the liquidation has been deleted for the integration // then just move to the next integration contract. if (aaveSellAmount == 0 || bAsset == address(0)) { continue; } // Reset integration's Aave balance in storage liquidations[_integration].aaveBalance = 0; // 4. Make the swap of Aave for the bAsset // Make the sale > https://docs.uniswap.org/reference/periphery/interfaces/ISwapRouter#exactinput // min bAsset amount out = Aave sell amount * priceFloor / 1e18 // e.g. 1e18 * 100e6 / 1e18 = 100e6 // e.g. 30e8 * 100e6 / 1e8 = 3000e6 // e.g. 30e18 * 100e18 / 1e18 = 3000e18 uint256 minBassetsOut = (aaveSellAmount * liquidation.minReturn) / 1e18; require(minBassetsOut > 0, "Must have some price floor"); IUniswapV3SwapRouter.ExactInputParams memory param = IUniswapV3SwapRouter.ExactInputParams( liquidation.uniswapPath, address(this), block.timestamp + 1, aaveSellAmount, minBassetsOut ); uniswapRouter.exactInput(param); address mAsset = liquidation.mAsset; // If the integration contract is connected to a mAsset like mUSD or mBTC if (mAsset != address(0)) { // 5a. Mint mAsset using bAsset from the Uniswap swap uint256 minted = _mint(bAsset, mAsset); // 6a. Send to SavingsManager to streamed to the savings vault. eg imUSD or imBTC address savings = _savingsManager(); ISavingsManager(savings).depositLiquidation(mAsset, minted); emit Liquidated(aaveToken, mAsset, minted, bAsset); } else { // If a feeder pool like GUSD // 5b. transfer bAsset directly to the integration contract. // this will then increase the boosted savings vault price. IERC20 bAssetToken = IERC20(bAsset); uint256 bAssetBal = bAssetToken.balanceOf(address(this)); bAssetToken.transfer(_integration, bAssetBal); emit Liquidated(aaveToken, mAsset, bAssetBal, bAsset); } } totalAaveBalance = 0; } function _mint(address _bAsset, address _mAsset) internal returns (uint256 minted) { uint256 bAssetBal = IERC20(_bAsset).balanceOf(address(this)); uint256 bAssetDec = IBasicToken(_bAsset).decimals(); // e.g. 100e6 * 95e16 / 1e6 = 100e18 uint256 minOut = (bAssetBal * 90e16) / (10**bAssetDec); minted = IMasset(_mAsset).mint(_bAsset, bAssetBal, minOut, address(this)); } }
liquidates stkAave rewards earned by the Aave integration contracts: - Redeems Aave for stkAave rewards - swaps Aave for bAsset using Uniswap V2. eg Aave for USDC - for each Aave integration contract - if from a mAsset - mints mAssets using bAssets. eg mUSD for USDC - deposits mAssets to Savings Manager. eg mUSD - else from a Feeder Pool - transfer bAssets to integration contract. eg GUSD/ solium-disable-next-line security/no-tx-origin Can not liquidate stkAave rewards if not already claimed by the integration contracts. 1. Redeem as many stkAave as we can for Aave This will fail if the 10 day cooldown period has not passed which is triggered in claimStakedAave(). 2. Get the amount of Aave tokens to sell for each Aave integration 3. Get the proportional amount of Aave tokens for this integration contract to liquidate Amount of Aave to sell for this integration = total Aave to liquidate integration's Aave balance / total of all integration Aave balances If there's no Aave tokens to liquidate for this integration contract or the liquidation has been deleted for the integration then just move to the next integration contract. If the integration contract is connected to a mAsset like mUSD or mBTC 5a. Mint mAsset using bAsset from the Uniswap swap 6a. Send to SavingsManager to streamed to the savings vault. eg imUSD or imBTC If a feeder pool like GUSD 5b. transfer bAsset directly to the integration contract. this will then increase the boosted savings vault price.
function triggerLiquidationAave() external { require(tx.origin == msg.sender, "Must be EOA"); require(totalAaveBalance > 0, "Must claim before liquidation"); IStakedAave(stkAave).redeem(address(this), type(uint256).max); uint256 totalAaveToLiquidate = IERC20(aaveToken).balanceOf(address(this)); require(totalAaveToLiquidate > 0, "No Aave redeemed from stkAave"); uint256 len = aaveIntegrations.length; for (uint256 i = 0; i < len; i++) { address _integration = aaveIntegrations[i]; Liquidation memory liquidation = liquidations[_integration]; uint256 aaveSellAmount = (liquidation.aaveBalance * totalAaveToLiquidate) / totalAaveBalance; address bAsset = liquidation.bAsset; if (aaveSellAmount == 0 || bAsset == address(0)) { continue; } require(minBassetsOut > 0, "Must have some price floor"); IUniswapV3SwapRouter.ExactInputParams memory param = IUniswapV3SwapRouter.ExactInputParams( liquidation.uniswapPath, address(this), block.timestamp + 1, aaveSellAmount, minBassetsOut ); uniswapRouter.exactInput(param); address mAsset = liquidation.mAsset; if (mAsset != address(0)) { uint256 minted = _mint(bAsset, mAsset); address savings = _savingsManager(); ISavingsManager(savings).depositLiquidation(mAsset, minted); emit Liquidated(aaveToken, mAsset, minted, bAsset); IERC20 bAssetToken = IERC20(bAsset); uint256 bAssetBal = bAssetToken.balanceOf(address(this)); bAssetToken.transfer(_integration, bAssetBal); emit Liquidated(aaveToken, mAsset, bAssetBal, bAsset); } } totalAaveBalance = 0; }
2,070,371
./partial_match/1/0xAFc9125f472DbF35D170201EF6A25863dacB341b/sources/SiargaoStaking.sol
The SC owner uses this function to withdraw deposited funds if necessary
function withdrawRewardsToken(uint256 _amount) public onlyOwner { require(_amount <= rewardsToken.balanceOf(address(this)), "Can't withdraw more than existing funds!"); rewardsToken.safeTransfer(msg.sender,_amount); }
3,691,384
/* ___ ___ ___ ___ ___ ___ ___ /\ \ /\ \ /\ \ /\ \ |\__\ /\ \ ___ /\ \ /::\ \ /::\ \ /::\ \ \:\ \ |:| | /::\ \ /\ \ /::\ \ /:/\:\ \ /:/\:\ \ /:/\:\ \ \:\ \ |:| | /:/\:\ \ \:\ \ /:/\:\ \ /::\~\:\ \ /::\~\:\ \ /::\~\:\ \ /::\ \ |:|__|__ /::\~\:\__\ /::\__\ /:/ \:\__\ /:/\:\ \:\__\ /:/\:\ \:\__\ /:/\:\ \:\__\ /:/\:\__\ /::::\__\ /:/\:\ \:|__| __/:/\/__/ /:/__/ \:|__| \/__\:\/:/ / \/__\:\/:/ / \/_|::\/:/ / /:/ \/__/ /:/~~/~ \:\~\:\/:/ / /\/:/ / \:\ \ /:/ / \::/ / \::/ / |:|::/ / /:/ / /:/ / \:\ \::/ / \::/__/ \:\ /:/ / \/__/ /:/ / |:|\/__/ \/__/ \/__/ \:\/:/ / \:\__\ \:\/:/ / /:/ / |:| | \::/__/ \/__/ \::/__/ \/__/ \|__| ~~ ~~ Anna Carroll for PartyDAO */ // SPDX-License-Identifier: MIT pragma solidity 0.8.5; // ============ Internal Imports ============ import {Party} from "./Party.sol"; import {IMarketWrapper} from "./market-wrapper/IMarketWrapper.sol"; import {Structs} from "./Structs.sol"; contract PartyBid is Party { // partyStatus Transitions: // (1) PartyStatus.ACTIVE on deploy // (2) PartyStatus.WON or PartyStatus.LOST on finalize() // ============ Internal Constants ============ // PartyBid version 3 uint16 public constant VERSION = 3; // ============ Public Not-Mutated Storage ============ // market wrapper contract exposing interface for // market auctioning the NFT IMarketWrapper public marketWrapper; // ID of auction within market contract uint256 public auctionId; // ============ Public Mutable Storage ============ // the highest bid submitted by PartyBid uint256 public highestBid; // ============ Events ============ event Bid(uint256 amount); event Finalized(PartyStatus result, uint256 totalSpent, uint256 fee, uint256 totalContributed); // ======== Constructor ========= constructor( address _partyDAOMultisig, address _tokenVaultFactory, address _weth ) Party(_partyDAOMultisig, _tokenVaultFactory, _weth) {} // ======== Initializer ========= function initialize( address _marketWrapper, address _nftContract, uint256 _tokenId, uint256 _auctionId, Structs.AddressAndAmount calldata _split, Structs.AddressAndAmount calldata _tokenGate, string memory _name, string memory _symbol ) external initializer { // validate auction exists require( IMarketWrapper(_marketWrapper).auctionIdMatchesToken( _auctionId, _nftContract, _tokenId ), "PartyBid::initialize: auctionId doesn't match token" ); // initialize & validate shared Party variables __Party_init(_nftContract, _tokenId, _split, _tokenGate, _name, _symbol); // set PartyBid-specific state variables marketWrapper = IMarketWrapper(_marketWrapper); auctionId = _auctionId; } // ======== External: Contribute ========= /** * @notice Contribute to the Party's treasury * while the Party is still active * @dev Emits a Contributed event upon success; callable by anyone */ function contribute() external payable nonReentrant { _contribute(); } // ======== External: Bid ========= /** * @notice Submit a bid to the Market * @dev Reverts if insufficient funds to place the bid and pay PartyDAO fees, * or if any external auction checks fail (including if PartyBid is current high bidder) * Emits a Bid event upon success. * Callable by any contributor */ function bid() external nonReentrant { require( partyStatus == PartyStatus.ACTIVE, "PartyBid::bid: auction not active" ); require( totalContributed[msg.sender] > 0, "PartyBid::bid: only contributors can bid" ); require( address(this) != marketWrapper.getCurrentHighestBidder( auctionId ), "PartyBid::bid: already highest bidder" ); require( !marketWrapper.isFinalized(auctionId), "PartyBid::bid: auction already finalized" ); // get the minimum next bid for the auction uint256 _bid = marketWrapper.getMinimumBid(auctionId); // ensure there is enough ETH to place the bid including PartyDAO fee require( _bid <= getMaximumBid(), "PartyBid::bid: insufficient funds to bid" ); // submit bid to Auction contract using delegatecall (bool success, bytes memory returnData) = address(marketWrapper).delegatecall( abi.encodeWithSignature("bid(uint256,uint256)", auctionId, _bid) ); require( success, string( abi.encodePacked( "PartyBid::bid: place bid failed: ", returnData ) ) ); // update highest bid submitted & emit success event highestBid = _bid; emit Bid(_bid); } // ======== External: Finalize ========= /** * @notice Finalize the state of the auction * @dev Emits a Finalized event upon success; callable by anyone */ function finalize() external nonReentrant { require( partyStatus == PartyStatus.ACTIVE, "PartyBid::finalize: auction not active" ); // finalize auction if it hasn't already been done if (!marketWrapper.isFinalized(auctionId)) { marketWrapper.finalize(auctionId); } // after the auction has been finalized, // if the NFT is owned by the PartyBid, then the PartyBid won the auction address _owner = _getOwner(); partyStatus = _owner == address(this) ? PartyStatus.WON : PartyStatus.LOST; uint256 _ethFee; // if the auction was won, if (partyStatus == PartyStatus.WON) { // record totalSpent, // send ETH fees to PartyDAO, // fractionalize the Token // send Token fees to PartyDAO & split proceeds to split recipient _ethFee = _closeSuccessfulParty(highestBid); } // set the contract status & emit result emit Finalized(partyStatus, totalSpent, _ethFee, totalContributedToParty); } // ======== Public: Utility Calculations ========= /** * @notice The maximum bid that can be submitted * while paying the ETH fee to PartyDAO * @return _maxBid the maximum bid */ function getMaximumBid() public view returns (uint256 _maxBid) { _maxBid = getMaximumSpend(); } }
Finalize the state of the auction Emits a Finalized event upon success; callable by anyone/ finalize auction if it hasn't already been done if the auction was won, record totalSpent, send ETH fees to PartyDAO, fractionalize the Token send Token fees to PartyDAO & split proceeds to split recipient
function finalize() external nonReentrant { require( partyStatus == PartyStatus.ACTIVE, "PartyBid::finalize: auction not active" ); if (!marketWrapper.isFinalized(auctionId)) { marketWrapper.finalize(auctionId); } partyStatus = _owner == address(this) ? PartyStatus.WON : PartyStatus.LOST; uint256 _ethFee; if (partyStatus == PartyStatus.WON) { _ethFee = _closeSuccessfulParty(highestBid); } }
888,242
./partial_match/1/0x26238D311066e23709e248C89A98C286a03CdD64/sources/ROP.sol
once enabled, can never be turned off
function theBattleShallCommence() external onlyOwner { tradingActive = true; swapEnabled = true; launchTimestamp = block.timestamp; previousRingBearer = block.timestamp; }
15,652,712
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title 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.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-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 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 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 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: 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 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 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.4.0; /// @title FixedPoint128 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) library FixedPoint128 { uint256 internal constant Q128 = 0x100000000000000000000000000000000; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = -denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.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 /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ pragma solidity >=0.5.0 <0.8.0; library BytesLib { function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, 'slice_overflow'); require(_start + _length >= _start, 'slice_overflow'); require(_bytes.length >= _start + _length, 'slice_outOfBounds'); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_start + 20 >= _start, 'toAddress_overflow'); require(_bytes.length >= _start + 20, 'toAddress_outOfBounds'); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) { require(_start + 3 >= _start, 'toUint24_overflow'); require(_bytes.length >= _start + 3, 'toUint24_outOfBounds'); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.0; import './BytesLib.sol'; /// @title Functions for manipulating path data for multihop swaps library Path { using BytesLib for bytes; /// @dev The length of the bytes encoded address uint256 private constant ADDR_SIZE = 20; /// @dev The length of the bytes encoded fee uint256 private constant FEE_SIZE = 3; /// @dev The offset of a single token address and pool fee uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE; /// @dev The offset of an encoded pool key uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE; /// @dev The minimum length of an encoding that contains 2 or more pools uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET; /// @notice Returns true iff the path contains two or more pools /// @param path The encoded swap path /// @return True if path contains two or more pools, otherwise false function hasMultiplePools(bytes memory path) internal pure returns (bool) { return path.length >= MULTIPLE_POOLS_MIN_LENGTH; } /// @notice Decodes the first pool in path /// @param path The bytes encoded swap path /// @return tokenA The first token of the given pool /// @return tokenB The second token of the given pool /// @return fee The fee level of the pool function decodeFirstPool(bytes memory path) internal pure returns ( address tokenA, address tokenB, uint24 fee ) { tokenA = path.toAddress(0); fee = path.toUint24(ADDR_SIZE); tokenB = path.toAddress(NEXT_OFFSET); } /// @notice Gets the segment corresponding to the first pool in the path /// @param path The bytes encoded swap path /// @return The segment containing all data necessary to target the first pool in the path function getFirstPool(bytes memory path) internal pure returns (bytes memory) { return path.slice(0, POP_OFFSET); } /// @notice Skips a token + fee element from the buffer and returns the remainder /// @param path The swap path /// @return The remaining token + fee elements in the path function skipToken(bytes memory path) internal pure returns (bytes memory) { return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // SPDX-License-Identifier: 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: BUSL-1.1 pragma solidity =0.7.6; pragma abicoder v2; 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 './libraries/PathPrice.sol'; import './interfaces/IHotPotV3Fund.sol'; import './interfaces/IHotPot.sol'; import './interfaces/IHotPotV3FundController.sol'; import './base/Multicall.sol'; contract HotPotV3FundController is IHotPotV3FundController, Multicall { using Path for bytes; address public override immutable uniV3Factory; address public override immutable uniV3Router; address public override immutable hotpot; address public override governance; address public override immutable WETH9; uint32 maxPIS = (100 << 16) + 9974;// MaxPriceImpact: 1%, MaxSwapSlippage: 0.5% = (1 - (sqrtSlippage/1e4)^2) * 100% mapping (address => bool) public override verifiedToken; mapping (address => bytes) public override harvestPath; modifier onlyManager(address fund){ require(msg.sender == IHotPotV3Fund(fund).manager(), "OMC"); _; } modifier onlyGovernance{ require(msg.sender == governance, "OGC"); _; } modifier checkDeadline(uint deadline) { require(block.timestamp <= deadline, 'CDL'); _; } constructor( address _hotpot, address _governance, address _uniV3Router, address _uniV3Factory, address _weth9 ) { hotpot = _hotpot; governance = _governance; uniV3Router = _uniV3Router; uniV3Factory = _uniV3Factory; WETH9 = _weth9; } /// @inheritdoc IControllerState function maxPriceImpact() external override view returns(uint32 priceImpact){ return maxPIS >> 16; } /// @inheritdoc IControllerState function maxSqrtSlippage() external override view returns(uint32 sqrtSlippage){ return maxPIS & 0xffff; } /// @inheritdoc IGovernanceActions function setHarvestPath(address token, bytes calldata path) external override onlyGovernance { bytes memory _path = path; while (true) { (address tokenIn, address tokenOut, uint24 fee) = _path.decodeFirstPool(); // pool is exist address pool = IUniswapV3Factory(uniV3Factory).getPool(tokenIn, tokenOut, fee); require(pool != address(0), "PIE"); // at least 2 observations (,,,uint16 observationCardinality,,,) = IUniswapV3Pool(pool).slot0(); require(observationCardinality >= 2, "OC"); if (_path.hasMultiplePools()) { _path = _path.skipToken(); } else { //最后一个交易对:输入WETH9, 输出hotpot require(tokenIn == WETH9 && tokenOut == hotpot, "IOT"); break; } } harvestPath[token] = path; emit SetHarvestPath(token, path); } /// @inheritdoc IGovernanceActions function setMaxPriceImpact(uint32 priceImpact) external override onlyGovernance { require(priceImpact <= 1e4 ,"SPI"); maxPIS = (priceImpact << 16) | (maxPIS & 0xffff); emit SetMaxPriceImpact(priceImpact); } /// @inheritdoc IGovernanceActions function setMaxSqrtSlippage(uint32 sqrtSlippage) external override onlyGovernance { require(sqrtSlippage <= 1e4 ,"SSS"); maxPIS = maxPIS & 0xffff0000 | sqrtSlippage; emit SetMaxSqrtSlippage(sqrtSlippage); } /// @inheritdoc IHotPotV3FundController function harvest(address token, uint amount) external override returns(uint burned) { bytes memory path = harvestPath[token]; PathPrice.verifySlippage(path, uniV3Factory, maxPIS & 0xffff); uint value = amount <= IERC20(token).balanceOf(address(this)) ? amount : IERC20(token).balanceOf(address(this)); TransferHelper.safeApprove(token, uniV3Router, value); ISwapRouter.ExactInputParams memory args = ISwapRouter.ExactInputParams({ path: path, recipient: address(this), deadline: block.timestamp, amountIn: value, amountOutMinimum: 0 }); burned = ISwapRouter(uniV3Router).exactInput(args); IHotPot(hotpot).burn(burned); emit Harvest(token, amount, burned); } /// @inheritdoc IGovernanceActions function setGovernance(address account) external override onlyGovernance { require(account != address(0)); governance = account; emit SetGovernance(account); } /// @inheritdoc IGovernanceActions function setVerifiedToken(address token, bool isVerified) external override onlyGovernance { verifiedToken[token] = isVerified; emit ChangeVerifiedToken(token, isVerified); } /// @inheritdoc IManagerActions function setDescriptor(address fund, bytes calldata _descriptor) external override onlyManager(fund) { return IHotPotV3Fund(fund).setDescriptor(_descriptor); } /// @inheritdoc IManagerActions function setDepositDeadline(address fund, uint deadline) external override onlyManager(fund) { return IHotPotV3Fund(fund).setDepositDeadline(deadline); } /// @inheritdoc IManagerActions function setPath( address fund, address distToken, bytes memory path ) external override onlyManager(fund){ require(verifiedToken[distToken]); address fundToken = IHotPotV3Fund(fund).token(); bytes memory _path = path; bytes memory _reverse; (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool(); _reverse = abi.encodePacked(tokenOut, fee, tokenIn); bool isBuy; // 第一个tokenIn是基金token,那么就是buy路径 if(tokenIn == fundToken){ isBuy = true; } // 如果是sellPath, 第一个需要是目标代币 else{ require(tokenIn == distToken); } while (true) { require(verifiedToken[tokenIn], "VIT"); require(verifiedToken[tokenOut], "VOT"); // pool is exist address pool = IUniswapV3Factory(uniV3Factory).getPool(tokenIn, tokenOut, fee); require(pool != address(0), "PIE"); // at least 2 observations (,,,uint16 observationCardinality,,,) = IUniswapV3Pool(pool).slot0(); require(observationCardinality >= 2, "OC"); if (path.hasMultiplePools()) { path = path.skipToken(); (tokenIn, tokenOut, fee) = path.decodeFirstPool(); _reverse = abi.encodePacked(tokenOut, fee, _reverse); } else { /// @dev 如果是buy, 最后一个token要是目标代币; /// @dev 如果是sell, 最后一个token要是基金token. if(isBuy) require(tokenOut == distToken, "OID"); else require(tokenOut == fundToken, "OIF"); break; } } if(!isBuy) (_path, _reverse) = (_reverse, _path); IHotPotV3Fund(fund).setPath(distToken, _path, _reverse); } /// @inheritdoc IManagerActions function init( address fund, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint amount, uint deadline ) external override checkDeadline(deadline) onlyManager(fund) returns(uint128 liquidity){ return IHotPotV3Fund(fund).init(token0, token1, fee, tickLower, tickUpper, amount, maxPIS); } /// @inheritdoc IManagerActions function add( address fund, uint poolIndex, uint positionIndex, uint amount, bool collect, uint deadline ) external override checkDeadline(deadline) onlyManager(fund) returns(uint128 liquidity){ return IHotPotV3Fund(fund).add(poolIndex, positionIndex, amount, collect, maxPIS); } /// @inheritdoc IManagerActions function sub( address fund, uint poolIndex, uint positionIndex, uint proportionX128, uint deadline ) external override checkDeadline(deadline) onlyManager(fund) returns(uint amount){ return IHotPotV3Fund(fund).sub(poolIndex, positionIndex, proportionX128, maxPIS); } /// @inheritdoc IManagerActions function move( address fund, uint poolIndex, uint subIndex, uint addIndex, uint proportionX128, uint deadline ) external override checkDeadline(deadline) onlyManager(fund) returns(uint128 liquidity){ return IHotPotV3Fund(fund).move(poolIndex, subIndex, addIndex, proportionX128, maxPIS); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; pragma abicoder v2; import '../interfaces/IMulticall.sol'; /// @title Multicall /// @notice Enables calling multiple methods in a single call to the contract abstract contract Multicall is IMulticall { /// @inheritdoc IMulticall function multicall(bytes[] calldata data) external payable override returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { // Next 5 lines from https://ethereum.stackexchange.com/a/83577 if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } results[i] = result; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title HPT (Hotpot Funds) 代币接口定义. interface IHotPot is IERC20{ function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function burn(uint value) external returns (bool) ; function burnFrom(address from, uint value) external returns (bool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './IHotPotV3FundERC20.sol'; import './fund/IHotPotV3FundEvents.sol'; import './fund/IHotPotV3FundState.sol'; import './fund/IHotPotV3FundUserActions.sol'; import './fund/IHotPotV3FundManagerActions.sol'; /// @title Hotpot V3 基金接口 /// @notice 接口定义分散在多个接口文件 interface IHotPotV3Fund is IHotPotV3FundERC20, IHotPotV3FundEvents, IHotPotV3FundState, IHotPotV3FundUserActions, IHotPotV3FundManagerActions { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './controller/IManagerActions.sol'; import './controller/IGovernanceActions.sol'; import './controller/IControllerState.sol'; import './controller/IControllerEvents.sol'; /// @title Hotpot V3 控制合约接口定义. /// @notice 基金经理和治理均需通过控制合约进行操作. interface IHotPotV3FundController is IManagerActions, IGovernanceActions, IControllerState, IControllerEvents { /// @notice 基金分成全部用于销毁HPT /// @dev 任何人都可以调用本函数 /// @param token 用于销毁时购买HPT的代币类型 /// @param amount 代币数量 /// @return burned 销毁数量 function harvest(address token, uint amount) external returns(uint burned); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title Hotpot V3 基金份额代币接口定义 interface IHotPotV3FundERC20 is IERC20{ function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Multicall /// @notice Enables calling multiple methods in a single call to the contract interface IMulticall { /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed /// @param data The encoded function data for each of the calls to make to this contract /// @return results The results from each of the calls passed in via data /// @dev The `msg.value` should not be trusted for any method callable from multicall. function multicall(bytes[] calldata data) external payable returns (bytes[] memory results); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title HotPotV3Controller 事件接口定义 interface IControllerEvents { /// @notice 当设置受信任token时触发 event ChangeVerifiedToken(address indexed token, bool isVerified); /// @notice 当调用Harvest时触发 event Harvest(address indexed token, uint amount, uint burned); /// @notice 当调用setHarvestPath时触发 event SetHarvestPath(address indexed token, bytes path); /// @notice 当调用setGovernance时触发 event SetGovernance(address indexed account); /// @notice 当调用setMaxSqrtSlippage时触发 event SetMaxSqrtSlippage(uint sqrtSlippage); /// @notice 当调用setMaxPriceImpact时触发 event SetMaxPriceImpact(uint priceImpact); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title HotPotV3Controller 状态变量及只读函数 interface IControllerState { /// @notice Returns the address of the Uniswap V3 router function uniV3Router() external view returns (address); /// @notice Returns the address of the Uniswap V3 facotry function uniV3Factory() external view returns (address); /// @notice 本项目治理代币HPT的地址 function hotpot() external view returns (address); /// @notice 治理账户地址 function governance() external view returns (address); /// @notice Returns the address of WETH9 function WETH9() external view returns (address); /// @notice 代币是否受信任 /// @dev The call will revert if the the token argument is address 0. /// @param token 要查询的代币地址 function verifiedToken(address token) external view returns (bool); /// @notice harvest时交易路径 /// @param token 要兑换的代币 function harvestPath(address token) external view returns (bytes memory); /// @notice 获取swap时最大滑点,取值范围为 0-1e4, 计算公式为:MaxSwapSlippage = (1 - (sqrtSlippage/1e4)^2) * 100% /// 如设置最大滑点 0.5%, 则 sqrtSlippage 应设置为9974,此时 MaxSwapSlippage = (1-(9974/1e4)^2)*100% = 0.5% function maxSqrtSlippage() external view returns (uint32); /// @notice 获取swap时最大价格影响,取值范围为 0-1e4 function maxPriceImpact() external view returns (uint32); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title 治理操作接口定义 interface IGovernanceActions { /// @notice Change governance /// @dev This function can only be called by governance /// @param account 新的governance地址 function setGovernance(address account) external; /// @notice Set the token to be verified for all fund, vice versa /// @dev This function can only be called by governance /// @param token 目标代币 /// @param isVerified 是否受信任 function setVerifiedToken(address token, bool isVerified) external; /// @notice Set the swap path for harvest /// @dev This function can only be called by governance /// @param token 目标代币 /// @param path 路径 function setHarvestPath(address token, bytes calldata path) external; /// @notice 设置swap时最大滑点,取值范围为 0-1e4, 计算公式为:MaxSwapSlippage = (1 - (sqrtSlippage/1e4)^2) * 100% /// 如设置最大滑点 0.5%, 则 sqrtSlippage 应设置为9974,此时 MaxSwapSlippage = (1-(9974/1e4)^2)*100% = 0.5% /// @dev This function can only be called by governance /// @param sqrtSlippage 0-1e4 function setMaxSqrtSlippage(uint32 sqrtSlippage) external; /// @notice Set the max price impact for swap /// @dev This function can only be called by governance /// @param priceImpact 0-1e4 function setMaxPriceImpact(uint32 priceImpact) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import '../fund/IHotPotV3FundManagerActions.sol'; /// @title 控制器合约基金经理操作接口定义 interface IManagerActions { /// @notice 设置基金描述信息 /// @dev This function can only be called by manager /// @param _descriptor 描述信息 function setDescriptor(address fund, bytes calldata _descriptor) external; /// @notice 设置基金存入截止时间 /// @dev This function can only be called by manager /// @param fund 基金地址 /// @param deadline 最晚存入截止时间 function setDepositDeadline(address fund, uint deadline) external; /// @notice 设置代币交易路径 /// @dev This function can only be called by manager /// @dev 设置路径时不能修改为0地址,且path路径里的token必须验证是否受信任 /// @param fund 基金地址 /// @param distToken 目标代币地址 /// @param path 符合uniswap v3格式的交易路径 function setPath( address fund, address distToken, bytes memory path ) external; /// @notice 初始化头寸, 允许投资额为0. /// @dev This function can only be called by manager /// @param fund 基金地址 /// @param token0 token0 地址 /// @param token1 token1 地址 /// @param fee 手续费率 /// @param tickLower 价格刻度下届 /// @param tickUpper 价格刻度上届 /// @param amount 初始化投入金额,允许为0, 为0表示仅初始化头寸,不作实质性投资 /// @param deadline 最晚交易时间 /// @return liquidity 添加的lp数量 function init( address fund, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint amount, uint deadline ) external returns(uint128 liquidity); /// @notice 投资指定头寸,可选复投手续费 /// @dev This function can only be called by manager /// @param fund 基金地址 /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @param amount 投资金额 /// @param collect 是否收集已产生的手续费并复投 /// @param deadline 最晚交易时间 /// @return liquidity 添加的lp数量 function add( address fund, uint poolIndex, uint positionIndex, uint amount, bool collect, uint deadline ) external returns(uint128 liquidity); /// @notice 撤资指定头寸 /// @dev This function can only be called by manager /// @param fund 基金地址 /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @param proportionX128 撤资比例,左移128位; 允许为0,为0表示只收集手续费 /// @param deadline 最晚交易时间 /// @return amount 撤资获得的基金本币数量 function sub( address fund, uint poolIndex, uint positionIndex, uint proportionX128, uint deadline ) external returns(uint amount); /// @notice 调整头寸投资 /// @dev This function can only be called by manager /// @param fund 基金地址 /// @param poolIndex 池子索引号 /// @param subIndex 要移除的头寸索引号 /// @param addIndex 要添加的头寸索引号 /// @param proportionX128 调整比例,左移128位 /// @param deadline 最晚交易时间 /// @return liquidity 调整后添加的lp数量 function move( address fund, uint poolIndex, uint subIndex, uint addIndex, uint proportionX128, uint deadline ) external returns(uint128 liquidity); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Hotpot V3 事件接口定义 interface IHotPotV3FundEvents { /// @notice 当存入基金token时,会触发该事件 event Deposit(address indexed owner, uint amount, uint share); /// @notice 当取走基金token时,会触发该事件 event Withdraw(address indexed owner, uint amount, uint share); /// @notice 当调用setDescriptor时触发 event SetDescriptor(bytes descriptor); /// @notice 当调用setDepositDeadline时触发 event SetDeadline(uint deadline); /// @notice 当调用setPath时触发 event SetPath(address distToken, bytes path); /// @notice 当调用init时,会触发该事件 event Init(uint poolIndex, uint positionIndex, uint amount); /// @notice 当调用add时,会触发该事件 event Add(uint poolIndex, uint positionIndex, uint amount, bool collect); /// @notice 当调用sub时,会触发该事件 event Sub(uint poolIndex, uint positionIndex, uint proportionX128); /// @notice 当调用move时,会触发该事件 event Move(uint poolIndex, uint subIndex, uint addIndex, uint proportionX128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @notice 基金经理操作接口定义 interface IHotPotV3FundManagerActions { /// @notice 设置基金描述信息 /// @dev This function can only be called by controller /// @param _descriptor 描述信息 function setDescriptor(bytes calldata _descriptor) external; /// @notice 设置基金存入截止时间 /// @dev This function can only be called by controller /// @param deadline 最晚存入截止时间 function setDepositDeadline(uint deadline) external; /// @notice 设置代币交易路径 /// @dev This function can only be called by controller /// @dev 设置路径时不能修改为0地址,且path路径里的token必须验证是否受信任 /// @param distToken 目标代币地址 /// @param buy 购买路径(本币->distToken) /// @param sell 销售路径(distToken->本币) function setPath( address distToken, bytes calldata buy, bytes calldata sell ) external; /// @notice 初始化头寸, 允许投资额为0. /// @dev This function can only be called by controller /// @param token0 token0 地址 /// @param token1 token1 地址 /// @param fee 手续费率 /// @param tickLower 价格刻度下届 /// @param tickUpper 价格刻度上届 /// @param amount 初始化投入金额,允许为0, 为0表示仅初始化头寸,不作实质性投资 /// @param maxPIS 最大价格影响和价格滑点 /// @return liquidity 添加的lp数量 function init( address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint amount, uint32 maxPIS ) external returns(uint128 liquidity); /// @notice 投资指定头寸,可选复投手续费 /// @dev This function can only be called by controller /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @param amount 投资金额 /// @param collect 是否收集已产生的手续费并复投 /// @param maxPIS 最大价格影响和价格滑点 /// @return liquidity 添加的lp数量 function add( uint poolIndex, uint positionIndex, uint amount, bool collect, uint32 maxPIS ) external returns(uint128 liquidity); /// @notice 撤资指定头寸 /// @dev This function can only be called by controller /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @param proportionX128 撤资比例,左移128位; 允许为0,为0表示只收集手续费 /// @param maxPIS 最大价格影响和价格滑点 /// @return amount 撤资获得的基金本币数量 function sub( uint poolIndex, uint positionIndex, uint proportionX128, uint32 maxPIS ) external returns(uint amount); /// @notice 调整头寸投资 /// @dev This function can only be called by controller /// @param poolIndex 池子索引号 /// @param subIndex 要移除的头寸索引号 /// @param addIndex 要添加的头寸索引号 /// @param proportionX128 调整比例,左移128位 /// @param maxPIS 最大价格影响和价格滑点 /// @return liquidity 调整后添加的lp数量 function move( uint poolIndex, uint subIndex, uint addIndex, uint proportionX128, //以前是按LP数量移除,现在改成按总比例移除,这样前端就不用管实际LP是多少了 uint32 maxPIS ) external returns(uint128 liquidity); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Hotpot V3 状态变量及只读函数 interface IHotPotV3FundState { /// @notice 控制器合约地址 function controller() external view returns (address); /// @notice 基金经理地址 function manager() external view returns (address); /// @notice 基金本币地址 function token() external view returns (address); /// @notice 32 bytes 基金经理 + 任意长度的简要描述 function descriptor() external view returns (bytes memory); /// @notice 基金锁定期 function lockPeriod() external view returns (uint); /// @notice 基金经理收费基线 function baseLine() external view returns (uint); /// @notice 基金经理收费比例 function managerFee() external view returns (uint); /// @notice 基金存入截止时间 function depositDeadline() external view returns (uint); /// @notice 获取最新存入时间 /// @param account 目标地址 /// @return 最新存入时间 function lastDepositTime(address account) external view returns (uint); /// @notice 总投入数量 function totalInvestment() external view returns (uint); /// @notice owner的投入数量 /// @param owner 用户地址 /// @return 投入本币的数量 function investmentOf(address owner) external view returns (uint); /// @notice 指定头寸的资产数量 /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @return 以本币计价的头寸资产数量 function assetsOfPosition(uint poolIndex, uint positionIndex) external view returns(uint); /// @notice 指定pool的资产数量 /// @param poolIndex 池子索引号 /// @return 以本币计价的池子资产数量 function assetsOfPool(uint poolIndex) external view returns(uint); /// @notice 总资产数量 /// @return 以本币计价的总资产数量 function totalAssets() external view returns (uint); /// @notice 基金本币->目标代币 的购买路径 /// @param _token 目标代币地址 /// @return 符合uniswap v3格式的目标代币购买路径 function buyPath(address _token) external view returns (bytes memory); /// @notice 目标代币->基金本币 的购买路径 /// @param _token 目标代币地址 /// @return 符合uniswap v3格式的目标代币销售路径 function sellPath(address _token) external view returns (bytes memory); /// @notice 获取池子地址 /// @param index 池子索引号 /// @return 池子地址 function pools(uint index) external view returns(address); /// @notice 头寸信息 /// @dev 由于基金需要遍历头寸,所以用二维动态数组存储头寸 /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @return isEmpty 是否空头寸,tickLower 价格刻度下届,tickUpper 价格刻度上届 function positions(uint poolIndex, uint positionIndex) external view returns( bool isEmpty, int24 tickLower, int24 tickUpper ); /// @notice pool数组长度 function poolsLength() external view returns(uint); /// @notice 指定池子的头寸数组长度 /// @param poolIndex 池子索引号 /// @return 头寸数组长度 function positionsLength(uint poolIndex) external view returns(uint); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Hotpot V3 用户操作接口定义 /// @notice 存入(deposit)函数适用于ERC20基金; 如果是ETH基金(内部会转换为WETH9),应直接向基金合约转账; interface IHotPotV3FundUserActions { /// @notice 用户存入基金本币 /// @param amount 存入数量 /// @return share 用户获得的基金份额 function deposit(uint amount) external returns(uint share); /// @notice 用户取出指定份额的本币 /// @param share 取出的基金份额数量 /// @param amountMin 最小提取值 /// @param deadline 最晚交易时间 /// @return amount 返回本币数量 function withdraw(uint share, uint amountMin, uint deadline) external returns(uint amount); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint64 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) library FixedPoint64 { uint256 internal constant Q64 = 0x10000000000000000; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.7.5; pragma abicoder v2; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import '@uniswap/v3-core/contracts/libraries/FullMath.sol'; import "@uniswap/v3-core/contracts/libraries/FixedPoint96.sol"; import "@uniswap/v3-core/contracts/libraries/FixedPoint128.sol"; import "./FixedPoint64.sol"; import '@uniswap/v3-core/contracts/libraries/TickMath.sol'; import "@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol"; import "@uniswap/v3-periphery/contracts/libraries/Path.sol"; library PathPrice { using Path for bytes; /// @notice 获取目标代币当前价格的平方根 /// @param path 兑换路径 /// @return sqrtPriceX96 价格的平方根(X 2^96),给定兑换路径的 tokenOut / tokenIn 的价格 function getSqrtPriceX96( bytes memory path, address uniV3Factory ) internal view returns (uint sqrtPriceX96){ require(path.length > 0, "IPL"); sqrtPriceX96 = FixedPoint96.Q96; uint _nextSqrtPriceX96; uint32[] memory secondAges = new uint32[](2); secondAges[0] = 0; secondAges[1] = 1; while (true) { (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool(); IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(uniV3Factory, PoolAddress.getPoolKey(tokenIn, tokenOut, fee))); (_nextSqrtPriceX96,,,,,,) = pool.slot0(); sqrtPriceX96 = tokenIn > tokenOut ? FullMath.mulDiv(sqrtPriceX96, FixedPoint96.Q96, _nextSqrtPriceX96) : FullMath.mulDiv(sqrtPriceX96, _nextSqrtPriceX96, FixedPoint96.Q96); // decide whether to continue or terminate if (path.hasMultiplePools()) path = path.skipToken(); else break; } } /// @notice 获取目标代币预言机价格的平方根 /// @param path 兑换路径 /// @return sqrtPriceX96Last 预言机价格的平方根(X 2^96),给定兑换路径的 tokenOut / tokenIn 的价格 function getSqrtPriceX96Last( bytes memory path, address uniV3Factory ) internal view returns (uint sqrtPriceX96Last){ require(path.length > 0, "IPL"); sqrtPriceX96Last = FixedPoint96.Q96; uint _nextSqrtPriceX96; uint32[] memory secondAges = new uint32[](2); secondAges[0] = 0; secondAges[1] = 1; while (true) { (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool(); IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(uniV3Factory, PoolAddress.getPoolKey(tokenIn, tokenOut, fee))); // sqrtPriceX96Last (int56[] memory tickCumulatives,) = pool.observe(secondAges); _nextSqrtPriceX96 = TickMath.getSqrtRatioAtTick(int24(tickCumulatives[0] - tickCumulatives[1])); sqrtPriceX96Last = tokenIn > tokenOut ? FullMath.mulDiv(sqrtPriceX96Last, FixedPoint96.Q96, _nextSqrtPriceX96) : FullMath.mulDiv(sqrtPriceX96Last, _nextSqrtPriceX96, FixedPoint96.Q96); // decide whether to continue or terminate if (path.hasMultiplePools()) path = path.skipToken(); else break; } } /// @notice 验证交易滑点是否满足条件 /// @param path 兑换路径 /// @param uniV3Factory uniswap v3 factory /// @param maxSqrtSlippage 最大滑点,最大值: 1e4 /// @return 当前价 function verifySlippage( bytes memory path, address uniV3Factory, uint32 maxSqrtSlippage ) internal view returns(uint) { uint last = getSqrtPriceX96Last(path, uniV3Factory); uint current = getSqrtPriceX96(path, uniV3Factory); if(last > current) require(current > FullMath.mulDiv(maxSqrtSlippage, last, 1e4), "VS"); return current; } }
@inheritdoc IGovernanceActions
function setGovernance(address account) external override onlyGovernance { require(account != address(0)); governance = account; emit SetGovernance(account); }
416,950
pragma solidity >= 0.5.0 < 0.6.0; import "./Token.sol"; import "https://github.com/oraclize/ethereum-api/oraclizeAPI_0.5.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/math/SafeMath.sol"; contract Bank is usingOraclize { using SafeMath for uint; string private orcl_url = "json(http://127.0.0.1:105/SHAK_wei_price).wei"; //string private orcl_url = "json(http://58baa9c87c8b.ngrok.io/SHAK_wei_price).wei"; SHAKtoken private token; // Address where we'll hold all ETH address payable private fundwallet = msg.sender; uint internal rate; uint internal capToken; uint internal remainToken; uint internal tokenTotal; uint public contractBalance; mapping(address => uint) balances; event LogNewOraclizeQuery(string description, string url); event buyTokenEvent(address _from, address _to, uint _amountToken, uint _amountETH); event redeemTokenEvent(address _from, address _to, uint _amountToken, uint _amountETH); event transferTokenEvent(address _from, address _to, uint _amountToken); event fundWithdrawal(address _fund, uint amount); event totalToken(uint _amount); modifier onlyFund { require(msg.sender == fundwallet, "You do not have permission!"); _; } constructor(uint _rate, uint _cap, address payable _fundwallet, SHAKtoken _token) public payable { //Assign where to hold the funds fundwallet = _fundwallet; rate = _rate; capToken = _cap; token = _token; remainToken = _cap; contractBalance = address(this).balance; } function getRate() public view returns (uint) { return rate; } function setRate(uint _rate) public onlyFund { rate = _rate; } function getCap() public view returns (uint) { return capToken; } function setCap(uint _cap) public onlyFund { require(_cap > capToken, "Cannot reduce total token amount."); capToken = _cap; remainToken = _cap.sub(tokenTotal); } function getTokenTotal() public view returns (uint) { return tokenTotal; } function getTokenRemain() public view returns (uint) { return remainToken; } function getcoinBalance () public view returns (uint) { return balances[msg.sender]; } function updateContractBalance () public { contractBalance = address(this).balance; } function setURL (string memory _url) public onlyFund { orcl_url = string(abi.encodePacked("json(", _url, "/SHAK_wei_price).wei")); } function getURL () public view onlyFund returns (string memory) { return orcl_url; } /* Function for external client to buy tokens from us */ function buyToken(address payable _recv) external payable returns (bool, uint) { // check for cap require(tokenTotal < capToken, "Maximum number of token reached!"); // updateRate - Oracalize updateRate(); // calculate amount of tokens from msg.value uint token_amount; uint eth_tx; uint remainder; token_amount = msg.value.div(rate); eth_tx = msg.value.sub(remainder); remainder = msg.value.mod(rate); if(token_amount > remainToken){ token_amount = remainToken; } // mint tokens to _recv SHAKtoken(address(token)).mint(_recv, token_amount); balances[_recv] = balances[_recv].add(token_amount); // update coinTotal tokenTotal = tokenTotal.add(token_amount); remainToken = capToken.sub(tokenTotal); contractBalance = address(this).balance; // return ETH from msg.sender (bool success, ) = msg.sender.call.value(remainder)(""); //return remainder require(success,"Unable to return remainder"); // emit event emit buyTokenEvent(msg.sender, _recv, token_amount, eth_tx); emit totalToken(tokenTotal); // return true if succeed return(true, token_amount); } /* Function for external client to sell tokens back to us */ function redeemToken(address payable _recv, uint amount) external payable returns (bool) { // check whether _source can cover buyBack require(balances[msg.sender] >= amount, "msg.sender doesn't have enough token."); // updateRate - Oracalize updateRate(); // calculate amount of ETH uint eth_tx; eth_tx = amount.mul(rate); require(eth_tx <= address(this).balance, "Unable to buy the specified amount, Please contact fund admin!"); // deduct tokens balances[msg.sender] = balances[msg.sender].sub(amount); // deduct coinTotal tokenTotal = tokenTotal.sub(amount); remainToken = remainToken = capToken.sub(tokenTotal); // send ETH to _recv _recv.transfer(eth_tx); // emit event emit redeemTokenEvent(msg.sender, _recv, amount, eth_tx); emit totalToken(tokenTotal); // returns true if succeed return(true); } /* Function to transfer tokens between clients */ function transferToken(address payable _recv, uint amount) public returns (bool) { // check whether msg.sender can cover transfer require(balances[msg.sender] >= amount, "msg.sender doesn't have enough token."); // deduct from _source balances[msg.sender] = balances[msg.sender].sub(amount); // update _recv balances[_recv] = balances[_recv].add(amount); // emit event emit transferTokenEvent(msg.sender, _recv, amount); // returns true if succeed return (true); } function withdraws(uint _amount) external payable onlyFund returns (bool, uint) { require(msg.value >= address(this).balance, "Unable to withdraws the specified amount."); (bool success, ) = fundwallet.call.value(_amount)(""); require(success,"Unable to withdraws remainder"); emit fundWithdrawal(msg.sender, _amount); return(true, msg.value); } function __callback(bytes32 myid, string memory result, bytes memory proof) public { //This function is executed after the result from Oracalize require(msg.sender == oraclize_cbAddress()); rate = parseInt(result); } function __callback(bytes32 myid, string memory result) public { //This function is executed after the result from Oracalize require(msg.sender == oraclize_cbAddress()); rate = parseInt(result); } function updateRate() public payable { string memory _url; _url = orcl_url; emit LogNewOraclizeQuery("Oraclize query was sent: ", _url); oraclize_query("URL", _url); } function() external payable {} } contract BankDeployer { address public bank_address; address public token_address; constructor(address payable wallet ) public { SHAKtoken token = new SHAKtoken(); token_address = address(token); Bank oBank = new Bank(1, 10000000000000000000, wallet, token); bank_address = address(oBank); token.addMinter(bank_address); token.renounceMinter(); } }
/ check whether _source can cover buyBack updateRate - Oracalize calculate amount of ETH deduct tokens deduct coinTotal send ETH to _recv emit event returns true if succeed
function redeemToken(address payable _recv, uint amount) external payable returns (bool) { require(balances[msg.sender] >= amount, "msg.sender doesn't have enough token."); updateRate(); uint eth_tx; eth_tx = amount.mul(rate); require(eth_tx <= address(this).balance, "Unable to buy the specified amount, Please contact fund admin!"); balances[msg.sender] = balances[msg.sender].sub(amount); tokenTotal = tokenTotal.sub(amount); remainToken = remainToken = capToken.sub(tokenTotal); _recv.transfer(eth_tx); emit redeemTokenEvent(msg.sender, _recv, amount, eth_tx); emit totalToken(tokenTotal); return(true); }
5,366,578
./full_match/80001/0x2E2788307B40C7220209d1C1ED870940f4490274/sources/contracts/Contract.sol
withdraw Kado_ERC20 tokens
function withdraw() public onlyOwner { Kado_ERC20.transfer(msg.sender, Kado_ERC20.balanceOf(address(this))); }
841,286
pragma solidity ^0.7.0; // SPDX-License-Identifier: MIT import "./interfaces/IManaging.sol"; import "../core/DaoConstants.sol"; import "../core/DaoRegistry.sol"; import "../adapters/interfaces/IVoting.sol"; import "../guards/MemberGuard.sol"; import "../utils/SafeMath.sol"; /** MIT License Copyright (c) 2020 Openlaw 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. */ contract ManagingContract is IManaging, DaoConstants, MemberGuard { using SafeMath for uint256; struct ProposalDetails { address applicant; bytes32 moduleId; address moduleAddress; bool processed; } mapping(uint256 => ProposalDetails) public proposals; /* * default fallback function to prevent from sending ether to the contract */ receive() external payable { revert("fallback revert"); } function createModuleChangeRequest( DaoRegistry dao, bytes32 moduleId, address moduleAddress ) external override onlyMember(dao) returns (uint256) { require(moduleAddress != address(0x0), "invalid module address"); require( dao.isNotReservedAddress(moduleAddress), "module is using reserved address" ); //is there a way to check if the new module implements the module interface properly? uint256 proposalId = dao.submitProposal(msg.sender); ProposalDetails storage proposal = proposals[proposalId]; proposal.applicant = msg.sender; proposal.moduleId = moduleId; proposal.moduleAddress = moduleAddress; proposal.processed = false; return proposalId; } function sponsorProposal( DaoRegistry dao, uint256 proposalId, bytes calldata data ) external override onlyMember(dao) { IVoting votingContract = IVoting(dao.getAdapterAddress(VOTING)); votingContract.startNewVotingForProposal(dao, proposalId, data); dao.sponsorProposal(proposalId, msg.sender); } function processProposal(DaoRegistry dao, uint256 proposalId) external override onlyMember(dao) { ProposalDetails memory proposal = proposals[proposalId]; require(!proposal.processed, "proposal already processed"); IVoting votingContract = IVoting(dao.getAdapterAddress(VOTING)); require( votingContract.voteResult(dao, proposalId) == 2, "proposal did not pass yet" ); dao.removeAdapter(proposal.moduleId); dao.addAdapter(proposal.moduleId, proposal.moduleAddress); proposals[proposalId].processed = true; dao.processProposal(proposalId); } }
is there a way to check if the new module implements the module interface properly?
function createModuleChangeRequest( DaoRegistry dao, bytes32 moduleId, address moduleAddress ) external override onlyMember(dao) returns (uint256) { require(moduleAddress != address(0x0), "invalid module address"); require( dao.isNotReservedAddress(moduleAddress), "module is using reserved address" ); uint256 proposalId = dao.submitProposal(msg.sender); ProposalDetails storage proposal = proposals[proposalId]; proposal.applicant = msg.sender; proposal.moduleId = moduleId; proposal.moduleAddress = moduleAddress; proposal.processed = false; return proposalId; }
919,919
pragma solidity ^0.4.11; import "./DAOLib.sol"; import "./CrowdsaleDAOFields.sol"; import "../Common.sol"; import "./Owned.sol"; import "./DAOProxy.sol"; contract CrowdsaleDAO is CrowdsaleDAOFields, Owned { address public stateModule; address public paymentModule; address public votingDecisionModule; address public crowdsaleModule; function CrowdsaleDAO(string _name, string _description, address _serviceContractAddress, address _votingFactoryContractAddress) Owned(msg.sender) { (name, description, serviceContract, votingFactory) = (_name, _description, _serviceContractAddress, VotingFactoryInterface(_votingFactoryContractAddress)); } /* * @dev Receives ether and forwards to the crowdsale module via a delegatecall with commission flag equal to false */ function() payable { DAOProxy.delegatedHandlePayment(crowdsaleModule, msg.sender, false); } /* * @dev Receives ether from commission contract and forwards to the crowdsale module * via a delegatecall with commission flag equal to true * @param _sender Address which sent ether to commission contract */ function handleCommissionPayment(address _sender) payable { DAOProxy.delegatedHandlePayment(crowdsaleModule, _sender, true); } /* * @dev Receives info about address which sent DXC tokens to current contract and about amount of sent tokens from * DXC token contract and then forwards this data to the crowdsale module * @param _from Address which sent DXC tokens * @param _amount Amount of tokens which were sent */ function handleDXCPayment(address _from, uint _amount) { DAOProxy.delegatedHandleDXCPayment(crowdsaleModule, _from, _amount); } /* * @dev Receives decision from withdrawal voting and forwards it to the voting decisions module * @param _address Address for withdrawal * @param _withdrawalSum Amount of ether/DXC tokens which must be sent to withdrawal address * @param _dxc boolean indicating whether withdrawal should be made through DXC tokens or not */ function withdrawal(address _address, uint _withdrawalSum, bool _dxc) external { DAOProxy.delegatedWithdrawal(votingDecisionModule, _address, _withdrawalSum, _dxc); } /* * @dev Receives decision from refund voting and forwards it to the voting decisions module */ function makeRefundableByVotingDecision() external { DAOProxy.delegatedMakeRefundableByVotingDecision(votingDecisionModule); } /* * @dev Called by voting contract to hold tokens of voted address. * It is needed to prevent multiple votes with same tokens * @param _address Voted address * @param _duration Amount of time left for voting to be finished */ function holdTokens(address _address, uint _duration) external { DAOProxy.delegatedHoldTokens(votingDecisionModule, _address, _duration); } function setStateModule(address _stateModule) external canSetAddress(stateModule) { stateModule = _stateModule; } function setPaymentModule(address _paymentModule) external canSetAddress(paymentModule) { paymentModule = _paymentModule; } function setVotingDecisionModule(address _votingDecisionModule) external canSetAddress(votingDecisionModule) { votingDecisionModule = _votingDecisionModule; } function setCrowdsaleModule(address _crowdsaleModule) external canSetAddress(crowdsaleModule) { crowdsaleModule = _crowdsaleModule; } function setVotingFactoryAddress(address _votingFactory) external canSetAddress(votingFactory) { votingFactory = VotingFactoryInterface(_votingFactory); } /* * @dev Checks if provided address has tokens of current DAO * @param _participantAddress Address of potential participant * @return boolean indicating if the address has at least one token */ function isParticipant(address _participantAddress) external constant returns (bool) { return token.balanceOf(_participantAddress) > 0; } /* * @dev Function which is used to set address of token which will be distributed by DAO during the crowdsale and * address of DXC token contract to use it for handling payment operations with DXC. Delegates call to state module * @param _tokenAddress Address of token which will be distributed during the crowdsale * @param _DXC Address of DXC contract */ function initState(address _tokenAddress, address _DXC) public { DAOProxy.delegatedInitState(stateModule, _tokenAddress, _DXC); } /* * @dev Delegates parameters which describe conditions of crowdsale to the crowdsale module. * @param _softCap The minimal amount of funds that must be collected by DAO for crowdsale to be considered successful * @param _hardCap The maximal amount of funds that can be raised during the crowdsale * @param _etherRate Amount of tokens that will be minted per one ether * @param _DXCRate Amount of tokens that will be minted per one DXC * @param _startTime Unix timestamp that indicates the moment when crowdsale will start * @param _endTime Unix timestamp that indicates the moment when crowdsale will end * @param _dxcPayments Boolean indicating whether it is possible to invest via DXC token or not */ function initCrowdsaleParameters(uint _softCap, uint _hardCap, uint _etherRate, uint _DXCRate, uint _startTime, uint _endTime, bool _dxcPayments, uint _lockup) public { DAOProxy.delegatedInitCrowdsaleParameters(crowdsaleModule, _softCap, _hardCap, _etherRate, _DXCRate, _startTime, _endTime, _dxcPayments, _lockup); } /* * @dev Delegates request of creating "regular" voting and saves the address of created voting contract to votings list * @param _name Name for voting * @param _description Description for voting that will be created * @param _duration Time in seconds from current moment until voting will be finished * @param _options List of options */ function addRegular(string _name, string _description, uint _duration, bytes32[] _options) public { votings[DAOLib.delegatedCreateRegular(votingFactory, _name, _description, _duration, _options, this)] = true; } /* * @dev Delegates request of creating "withdrawal" voting and saves the address of created voting contract to votings list * @param _name Name for voting * @param _description Description for voting that will be created * @param _duration Time in seconds from current moment until voting will be finished * @param _sum Amount of funds that is supposed to be withdrawn * @param _withdrawalWallet Address for withdrawal * @param _dxc Boolean indicating whether withdrawal must be in DXC tokens or in ether */ function addWithdrawal(string _name, string _description, uint _duration, uint _sum, address _withdrawalWallet, bool _dxc) public { votings[DAOLib.delegatedCreateWithdrawal(votingFactory, _name, _description, _duration, _sum, _withdrawalWallet, _dxc, this)] = true; } /* * @dev Delegates request of creating "refund" voting and saves the address of created voting contract to votings list * @param _name Name for voting * @param _description Description for voting that will be created * @param _duration Time in seconds from current moment until voting will be finished */ function addRefund(string _name, string _description, uint _duration) public { votings[DAOLib.delegatedCreateRefund(votingFactory, _name, _description, _duration, this)] = true; } /* * @dev Delegates request of creating "module" voting and saves the address of created voting contract to votings list * @param _name Name for voting * @param _description Description for voting that will be created * @param _duration Time in seconds from current moment until voting will be finished * @param _module Number of module which must be replaced * @param _newAddress Address of new module */ function addModule(string _name, string _description, uint _duration, uint _module, address _newAddress) public { votings[DAOLib.delegatedCreateModule(votingFactory, _name, _description, _duration, _module, _newAddress, this)] = true; } /* * @dev Delegates request for going into refundable state to voting decisions module */ function makeRefundableByUser() public { DAOProxy.delegatedMakeRefundableByUser(votingDecisionModule); } /* * @dev Delegates request for refund to payment module */ function refund() public { DAOProxy.delegatedRefund(paymentModule); } /* * @dev Delegates request for refund of soft cap to payment module */ function refundSoftCap() public { DAOProxy.delegatedRefundSoftCap(paymentModule); } /* * @dev Delegates request for finish of crowdsale to crowdsale module */ function finish() public { DAOProxy.delegatedFinish(crowdsaleModule); } /* * @dev Sets team addresses and bonuses for crowdsale * @param _team The addresses that will be defined as team members * @param _tokenPercents Array of bonuses in percents which will go te every member in case of successful crowdsale * @param _bonusPeriods Array of timestamps which show when tokens will be minted with higher rate * @param _bonusEtherRates Array of ether rates for every bonus period * @param _bonusDXCRates Array of DXC rates for every bonus period * @param _teamHold Array of timestamps which show the hold duration of tokens for every team member * @param service Array of booleans which show whether member is a service address or not */ function initBonuses(address[] _team, uint[] _tokenPercents, uint[] _bonusPeriods, uint[] _bonusEtherRates, uint[] _bonusDXCRates, uint[] _teamHold, bool[] _service) public onlyOwner(msg.sender) { require( _team.length == _tokenPercents.length && _team.length == _teamHold.length && _team.length == _service.length && _bonusPeriods.length == _bonusEtherRates.length && (_bonusDXCRates.length == 0 || _bonusPeriods.length == _bonusDXCRates.length) && canInitBonuses && (block.timestamp < startTime || canInitCrowdsaleParameters) ); team = _team; teamHold = _teamHold; teamBonusesArr = _tokenPercents; teamServiceMember = _service; for(uint i = 0; i < _team.length; i++) { teamMap[_team[i]] = true; teamBonuses[_team[i]] = _tokenPercents[i]; } bonusPeriods = _bonusPeriods; bonusEtherRates = _bonusEtherRates; bonusDXCRates = _bonusDXCRates; canInitBonuses = false; } /* * @dev Sets addresses which can be used to get funds via withdrawal votings * @param _addresses Array of addresses which will be used for withdrawals */ function setWhiteList(address[] _addresses) public onlyOwner(msg.sender) { require(canSetWhiteList); whiteListArr = _addresses; for(uint i = 0; i < _addresses.length; i++) { whiteList[_addresses[i]] = true; } canSetWhiteList = false; } /* Modifiers */ modifier canSetAddress(address module) { require(votings[msg.sender] || (module == 0x0 && msg.sender == owner)); _; } }
Delegates parameters which describe conditions of crowdsale to the crowdsale module. _softCap The minimal amount of funds that must be collected by DAO for crowdsale to be considered successful _hardCap The maximal amount of funds that can be raised during the crowdsale _etherRate Amount of tokens that will be minted per one ether _DXCRate Amount of tokens that will be minted per one DXC _startTime Unix timestamp that indicates the moment when crowdsale will start _endTime Unix timestamp that indicates the moment when crowdsale will end _dxcPayments Boolean indicating whether it is possible to invest via DXC token or not/
function initCrowdsaleParameters(uint _softCap, uint _hardCap, uint _etherRate, uint _DXCRate, uint _startTime, uint _endTime, bool _dxcPayments, uint _lockup) public { DAOProxy.delegatedInitCrowdsaleParameters(crowdsaleModule, _softCap, _hardCap, _etherRate, _DXCRate, _startTime, _endTime, _dxcPayments, _lockup); }
946,554
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/math/Math.sol"; import "./lib/SafeMath8.sol"; import "./owner/Operator.sol"; import "./interfaces/IOracle.sol"; /* Juice Finance - its a juicer */ contract Juice is ERC20Burnable, Operator { using SafeMath8 for uint8; using SafeMath for uint256; // Initial distribution for the first 24h genesis pools uint256 public constant INITIAL_GENESIS_POOL_DISTRIBUTION = 2400 ether; // Initial distribution for the day 2-5 JUICE-WETH LP -> JUICE pool uint256 public constant INITIAL_JUICE_POOL_DISTRIBUTION = 21600 ether; // Distribution for airdrops wallet uint256 public constant INITIAL_AIRDROP_WALLET_DISTRIBUTION = 1000 ether; // Have the rewards been distributed to the pools bool public rewardPoolDistributed = false; address public juiceOracle; /** * @notice Constructs the JUICE ERC-20 contract. */ constructor() public ERC20("Juice Finance", "JUICE") { // Mints 1 JUICE to contract creator for initial pool setup _mint(msg.sender, 1 ether); } function _getJuicePrice() internal view returns (uint256 _juicePrice) { try IOracle(juiceOracle).consult(address(this), 1e18) returns (uint144 _price) { return uint256(_price); } catch { revert("Juice: failed to fetch JUICE price from Oracle"); } } function setJuiceOracle(address _juiceOracle) public onlyOperator { require(_juiceOracle != address(0), "oracle address cannot be 0 address"); juiceOracle = _juiceOracle; } /** * @notice Operator mints JUICE to a recipient * @param recipient_ The address of recipient * @param amount_ The amount of JUICE to mint to * @return whether the process has been done */ function mint(address recipient_, uint256 amount_) public onlyOperator returns (bool) { uint256 balanceBefore = balanceOf(recipient_); _mint(recipient_, amount_); uint256 balanceAfter = balanceOf(recipient_); return balanceAfter > balanceBefore; } function burn(uint256 amount) public override { super.burn(amount); } function burnFrom(address account, uint256 amount) public override onlyOperator { super.burnFrom(account, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), allowance(sender, _msgSender()).sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @notice distribute to reward pool (only once) */ function distributeReward( address _genesisPool, address _juicePool, address _airdropWallet ) external onlyOperator { require(!rewardPoolDistributed, "only can distribute once"); require(_genesisPool != address(0), "!_genesisPool"); require(_juicePool != address(0), "!_juicePool"); require(_airdropWallet != address(0), "!_airdropWallet"); rewardPoolDistributed = true; _mint(_genesisPool, INITIAL_GENESIS_POOL_DISTRIBUTION); _mint(_juicePool, INITIAL_JUICE_POOL_DISTRIBUTION); _mint(_airdropWallet, INITIAL_AIRDROP_WALLET_DISTRIBUTION); } function governanceRecoverUnsupported( IERC20 _token, uint256 _amount, address _to ) external onlyOperator { _token.transfer(_to, _amount); } }
distribute to reward pool (only once)/
function distributeReward( address _genesisPool, address _juicePool, address _airdropWallet ) external onlyOperator { require(!rewardPoolDistributed, "only can distribute once"); require(_genesisPool != address(0), "!_genesisPool"); require(_juicePool != address(0), "!_juicePool"); require(_airdropWallet != address(0), "!_airdropWallet"); rewardPoolDistributed = true; _mint(_genesisPool, INITIAL_GENESIS_POOL_DISTRIBUTION); _mint(_juicePool, INITIAL_JUICE_POOL_DISTRIBUTION); _mint(_airdropWallet, INITIAL_AIRDROP_WALLET_DISTRIBUTION); }
12,743,314
pragma solidity ^0.5.0; // Copyright 2019 OpenST Ltd. // // 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. import "./EIP20Interface.sol"; import "./GatewayInterface.sol"; import "./BrandedToken.sol"; /** * @title GatewayComposer contract. * * @notice GatewayComposer is a composition contract which can be used to * optimise the UX flow of the user where the user intends to perform * a single combined action. */ contract GatewayComposer { /* Struct */ struct StakeRequest { uint256 stakeVT; address gateway; address beneficiary; uint256 gasPrice; uint256 gasLimit; uint256 nonce; } /* Storage */ address public owner; /** EIP20Token value token which is staked on the value chain. */ EIP20Interface public valueToken; /** * A BrandedToken is an EIP20Token which allows a mainstream application * to create a value-backed token designed specifically for its * application's context. */ BrandedToken public brandedToken; mapping (bytes32 => StakeRequest) public stakeRequests; /** Mutex lock status. */ bool private mutexAcquired; /* Modifiers */ /** Checks that msg.sender is owner address. */ modifier onlyOwner() { require( owner == msg.sender, "Only owner can call the function." ); _; } /** * Checks that mutex is acquired or not. If mutex is not acquired, * mutexAcquired is set to true. At the end of function execution, * mutexAcquired is set to false. */ modifier mutex() { require( !mutexAcquired, "Mutex is already acquired." ); mutexAcquired = true; _; mutexAcquired = false; } /* Special Functions */ /** * @notice Contract constructor. * * @dev Function requires: * - owner address should not be zero * - ValueToken address should not be zero * - BrandedToken address should not be zero * - ValueToken address should not be equal to owner address * - BrandedToken address should not be equal to owner address * - ValueToken address should be equal to BrandedToken.valueToken() * * @param _owner Address of the staker on the value chain. * @param _valueToken EIP20Token which is staked. * @param _brandedToken It's a value backed minted EIP20Token. */ constructor( address _owner, EIP20Interface _valueToken, BrandedToken _brandedToken ) public { require( _owner != address(0), "Owner address is zero." ); require( address(_valueToken) != address(0), "ValueToken address is zero." ); require( address(_brandedToken) != address(0), "BrandedToken address is zero." ); require( _owner != address(_valueToken), "ValueToken address is same as owner address." ); require( _owner != address(_brandedToken), "BrandedToken address is same as owner address." ); require( address(_valueToken) == address(_brandedToken.valueToken()), "ValueToken should match BrandedToken.valueToken." ); owner = _owner; valueToken = _valueToken; brandedToken = _brandedToken; } /* External Functions */ /** * @notice Transfers value tokens from msg.sender to itself after staker * approves GatewayComposer, approves BrandedToken for value tokens * and calls BrandedToken.requestStake function. * * @dev Function requires: * - stakeVT can't be 0 * - mintBT amount and converted stakeVT amount should be equal * - gateway address can't be zero * - Gateway address should not be equal to owner address * - beneficiary address can't be zero * - successful execution of ValueToken transfer * - successful execution of ValueToken approve * * stakeVT can't be 0 because gateway.stake also doesn't allow 0 stake * amount. This condition also helps in validation of in progress * stake requests. See acceptStakeRequest for details. * * mintBT is not stored in StakeRequest struct as there was * significant gas cost difference between storage vs dynamic * evaluation from BrandedToken convert function. * * @param _stakeVT ValueToken amount which is staked. * @param _mintBT Amount of BrandedToken amount which will be minted. * @param _gateway Gateway contract address. * @param _beneficiary The address in the auxiliary chain where the utility * tokens will be minted. * @param _gasPrice Gas price that staker is ready to pay to get the stake * and mint process done. * @param _gasLimit Gas limit that staker is ready to pay. * @param _nonce Nonce of the staker address. It can be obtained from * Gateway.getNonce() method. * * @return stakeRequestHash_ Hash unique for each stake request. */ function requestStake( uint256 _stakeVT, uint256 _mintBT, address _gateway, address _beneficiary, uint256 _gasPrice, uint256 _gasLimit, uint256 _nonce ) external onlyOwner mutex returns (bytes32 stakeRequestHash_) { require( _stakeVT > uint256(0), "Stake amount is zero." ); require( _mintBT == brandedToken.convertToBrandedTokens(_stakeVT), "_mintBT should match converted _stakeVT." ); require( _gateway != address(0), "Gateway address is zero." ); require( owner != _gateway, "Gateway address is same as owner address." ); require( _beneficiary != address(0), "Beneficiary address is zero." ); require( valueToken.transferFrom(msg.sender, address(this), _stakeVT), "ValueToken transferFrom returned false." ); require( valueToken.approve(address(brandedToken), _stakeVT), "ValueToken approve returned false." ); stakeRequestHash_ = brandedToken.requestStake(_stakeVT, _mintBT); // mintBT is not stored because that uses significantly more gas than recalculation stakeRequests[stakeRequestHash_] = StakeRequest({ stakeVT: _stakeVT, gateway: _gateway, beneficiary: _beneficiary, gasPrice: _gasPrice, gasLimit: _gasLimit, nonce: _nonce }); } /** * @notice Approves Gateway for the minted BTs, calls Gateway.stake after * BrandedToken.acceptStakeRequest execution is successful. * * @dev Function requires: * - stake request hash is valid * - successful execution of ValueToken transferFrom * - successful execution of ValueToken approve * - BrandedToken.acceptStakeRequest execution is successful * - successful execution of BrandedToken approve * * As per requirement bounty token currency is same as valueToken. * Bounty flow: * - facilitator approves GatewayComposer for base tokens as bounty * - GatewayComposer approves Gateway for the bounty * * @param _stakeRequestHash Unique hash for each stake request. * @param _r R of the signature. * @param _s S of the signature. * @param _v V of the signature. * @param _hashLock Hash lock provided by the facilitator. * * @return messageHash_ Message hash unique for each stake request. */ function acceptStakeRequest( bytes32 _stakeRequestHash, bytes32 _r, bytes32 _s, uint8 _v, bytes32 _hashLock ) external returns (bytes32 messageHash_) { StakeRequest memory stakeRequest = stakeRequests[_stakeRequestHash]; delete stakeRequests[_stakeRequestHash]; require( stakeRequest.stakeVT > uint256(0), "Stake request not found." ); uint256 bounty = GatewayInterface(stakeRequest.gateway).bounty(); require( valueToken.transferFrom(msg.sender, address(this), bounty), "ValueToken transferFrom returned false." ); require( valueToken.approve(stakeRequest.gateway, bounty), "ValueToken approve returned false." ); require( brandedToken.acceptStakeRequest( _stakeRequestHash, _r, _s, _v ), "BrandedToken acceptStakeRequest returned false." ); // mintBT is recalculated because that uses significantly less gas than storage uint256 mintBT = brandedToken.convertToBrandedTokens( stakeRequest.stakeVT ); require( brandedToken.approve(stakeRequest.gateway, mintBT), "BrandedToken approve returned false." ); messageHash_ = GatewayInterface(stakeRequest.gateway).stake( mintBT, stakeRequest.beneficiary, stakeRequest.gasPrice, stakeRequest.gasLimit, stakeRequest.nonce, _hashLock ); } /** * @notice Revokes stake request by calling BrandedToken.revokeStakeRequest() * and deleting information. * * @dev Function requires: * - stake request hash is valid * - BrandedToken.revokeStakeRequest() should return true * - ValueToken.transfer() should return true * * The method is called after calling requestStake. In this flow * locked ValueToken is transferred to owner. Transfer is done for * convenience. This way extra step of calling transferToken is * avoided. * * @param _stakeRequestHash Stake request hash. * * @return success_ True on successful execution. */ function revokeStakeRequest( bytes32 _stakeRequestHash ) external onlyOwner returns (bool success_) { StakeRequest memory stakeRequest = stakeRequests[_stakeRequestHash]; delete stakeRequests[_stakeRequestHash]; require( stakeRequest.stakeVT > uint256(0), "Stake request not found." ); require( brandedToken.revokeStakeRequest(_stakeRequestHash), "BrandedToken revokeStakeRequest returned false." ); require( valueToken.transfer(owner, stakeRequest.stakeVT), "ValueToken transfer returned false." ); success_ = true; } /** * @notice Transfers EIP20 token to destination address. * * @dev Function requires: * - msg.sender should be owner * - EIP20 token address should not be zero * - token.transfer() execution should be successful * * @param _token EIP20 token address. * @param _to Address to which tokens are transferred. * @param _value Amount of tokens to be transferred. * * @return success_ True on successful execution. */ function transferToken( EIP20Interface _token, address _to, uint256 _value ) external onlyOwner returns (bool success_) { require( address(_token) != address(0), "EIP20 token address is zero." ); require( _token.transfer(_to, _value), "EIP20Token transfer returned false." ); success_ = true; } /** * @notice Approves EIP20 token to spender address. * * @dev Function requires: * - msg.sender should be owner * - EIP20 token address should not be zero * - token.approve() execution should be successful * * @param _token EIP20 token address. * @param _spender Address authorized to spend from the function caller's * address. * @param _value Amount up to which spender is authorized to spend. * * @return success_ True on successful execution. */ function approveToken( EIP20Interface _token, address _spender, uint256 _value ) external onlyOwner returns (bool success_) { require( address(_token) != address(0), "EIP20 token address is zero." ); require( _token.approve(_spender, _value), "EIP20token approve returned false." ); success_ = true; } /** * @notice Remove storage & code from blockchain. * * @dev Function requires: * - ValueToken balance should be 0 * - BrandedToken balance should be 0 * - There should not be any in progress stake requests * * BrandedToken contract has mapping stakeRequestHashes which stores * staker vs stakeRequestHash data. In progress stake requests are * validated by doing lookup into the stakeRequestHashes mapping. */ function destroy() external onlyOwner { require( valueToken.balanceOf(address(this)) == 0, "ValueToken balance should be 0." ); require( brandedToken.balanceOf(address(this)) == 0, "BrandedToken balance should be 0." ); require( brandedToken.stakeRequestHashes(address(this)) == bytes32(0), "In progress stake requests are present." ); selfdestruct(msg.sender); } /** * @notice Transfers value tokens to itself to pay the revert penalty, * approves Gateway to transfer the value tokens for the penalty, * and calls Gateway.revertStake. * * @dev Function requires: * - msg.sender is owner * - Gateway address can't be zero * - Gateway address should not be equal to owner address * - successful execution of ValueToken transferFrom * - successful execution of ValueToken approve * * As per requirement, penalty is paid in valueToken. * Penalty flow: * - staker approves GatewayComposer for value tokens as penalty * - GatewayComposer approves Gateway for the penalty * * @param _gateway Gateway contract address. * @param _penalty Amount to pay to revert stake. * @param _messageHash Message hash unique for each stake request. * * @return success_ True on successful execution. */ function revertStake( address _gateway, uint256 _penalty, bytes32 _messageHash ) external onlyOwner returns (bool success_) { require( _gateway != address(0), "Gateway address is zero." ); require( owner != _gateway, "Gateway address is same as owner address." ); require( valueToken.transferFrom(msg.sender, address(this), _penalty), "ValueToken transferFrom returned false." ); require( valueToken.approve(_gateway, _penalty), "ValueToken approve returned false." ); GatewayInterface(_gateway).revertStake(_messageHash); return true; } }
Approves Gateway for the minted BTs, calls Gateway.stake after BrandedToken.acceptStakeRequest execution is successful. Function requires: - stake request hash is valid - successful execution of ValueToken transferFrom - successful execution of ValueToken approve - BrandedToken.acceptStakeRequest execution is successful - successful execution of BrandedToken approve As per requirement bounty token currency is same as valueToken. Bounty flow: - facilitator approves GatewayComposer for base tokens as bounty - GatewayComposer approves Gateway for the bounty _stakeRequestHash Unique hash for each stake request. _r R of the signature. _s S of the signature. _v V of the signature. _hashLock Hash lock provided by the facilitator. return messageHash_ Message hash unique for each stake request./ mintBT is recalculated because that uses significantly less gas than storage
function acceptStakeRequest( bytes32 _stakeRequestHash, bytes32 _r, bytes32 _s, uint8 _v, bytes32 _hashLock ) external returns (bytes32 messageHash_) { StakeRequest memory stakeRequest = stakeRequests[_stakeRequestHash]; delete stakeRequests[_stakeRequestHash]; require( stakeRequest.stakeVT > uint256(0), "Stake request not found." ); uint256 bounty = GatewayInterface(stakeRequest.gateway).bounty(); require( valueToken.transferFrom(msg.sender, address(this), bounty), "ValueToken transferFrom returned false." ); require( valueToken.approve(stakeRequest.gateway, bounty), "ValueToken approve returned false." ); require( brandedToken.acceptStakeRequest( _stakeRequestHash, _r, _s, _v ), "BrandedToken acceptStakeRequest returned false." ); uint256 mintBT = brandedToken.convertToBrandedTokens( stakeRequest.stakeVT ); require( brandedToken.approve(stakeRequest.gateway, mintBT), "BrandedToken approve returned false." ); messageHash_ = GatewayInterface(stakeRequest.gateway).stake( mintBT, stakeRequest.beneficiary, stakeRequest.gasPrice, stakeRequest.gasLimit, stakeRequest.nonce, _hashLock ); }
1,089,399
./partial_match/1/0xa94310AeeD50687f7c39ACdAA5FCd311AEDB25f8/sources/contracts/erc721/ERC721EditionsDFS.sol
Get URI for given token id tokenId token id to get uri for return base64-encoded json metadata object/
function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "!exists"); uint256 editionId = getEditionId(tokenId); return _editionURI[editionId]; }
3,645,423
pragma solidity ^0.4.21; /* http://www.cryptophoenixes.fun/ CryptoPhoenixes: Civil War Edition Original game design and website development by Anyhowclick. Art design by Tilly. */ /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev 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); _; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title 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'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 CryptoPhoenixesCivilWar is Ownable, Pausable { using SafeMath for uint256; address public subDevOne; address public subDevTwo; Phoenix[] public PHOENIXES; /* id 0: Rainbow Phoenix ids 1-2: Red / Blue capt respectively ids 3-6: Red bombers ids 7-10: Red thieves ids 11-14: Blue bombers ids 15-18: Blue thieves */ uint256 public DENOMINATOR = 10000; //Eg explosivePower = 300 -> 3% uint256[2] public POOLS; //0 = red, 1 = blue uint256[2] public SCORES; //0 = red, 1 = blue bool public GAME_STARTED = false; uint public GAME_END = 0; // devFunds mapping (address => uint256) public devFunds; // userFunds mapping (address => uint256) public userFunds; // Constant uint256 constant public BASE_PRICE = 0.0025 ether; //Permission control modifier onlyAuthorized() { require(msg.sender == owner || msg.sender == subDevOne); //subDevTwo is NOT authorized _; } //to check that a game has ended modifier gameHasEnded() { require(GAME_STARTED); //Check if a game was started in the first place require(now >= GAME_END); //Check if game has ended _; } //to check that a game is in progress modifier gameInProgress() { require(GAME_STARTED); require(now <= GAME_END); _; } //to check the reverse, that no game is in progress modifier noGameInProgress() { require(!GAME_STARTED); _; } // Events event GameStarted(); event PhoenixPurchased( uint256 phoenixID, address newOwner, uint256 price, uint256 nextPrice, uint256 currentPower, uint abilityAvailTime ); event CaptainAbilityUsed( uint256 captainID ); event PhoenixAbilityUsed( uint256 phoenixID, uint256 payout, uint256 price, uint256 currentPower, uint abilityAvailTime, address previousOwner ); event GameEnded(); event WithdrewFunds( address owner ); // Struct to store Phoenix Data struct Phoenix { uint256 price; // Current price of phoenix uint256 payoutPercentage; // The percent of the funds awarded upon explosion / steal / end game uint abilityAvailTime; // Time when phoenix's ability is available uint cooldown; // Time to add after cooldown uint cooldownDecreaseAmt; // Amt of time to decrease upon each flip uint basePower; // Starting exploding / stealing power of phoenix uint currentPower; // Current exploding / stealing power of phoenix uint powerIncreaseAmt; // Amt of power to increase with every flip uint powerDrop; // Power drop of phoenix upon ability usage uint powerCap; // Power should not exceed this amount address previousOwner; // Owner of phoenix in previous round address currentOwner; // Current owner of phoenix } // Main function to set the beta period and sub developer function CryptoPhoenixesCivilWar(address _subDevOne, address _subDevTwo) { subDevOne = _subDevOne; subDevTwo = _subDevTwo; createPhoenixes(); } function createPhoenixes() private { //First, create rainbow phoenix and captains for (uint256 i = 0; i < 3; i++) { Phoenix memory phoenix = Phoenix({ price: 0.005 ether, payoutPercentage: 2400, //redundant for rainbow phoenix. Set to 24% for captains cooldown: 20 hours, //redundant for rainbow phoenix abilityAvailTime: 0, //will be set when game starts //Everything else not used cooldownDecreaseAmt: 0, basePower: 0, currentPower: 0, powerIncreaseAmt: 0, powerDrop: 0, powerCap: 0, previousOwner: address(0), currentOwner: address(0) }); PHOENIXES.push(phoenix); } //set rainbow phoenix price to 0.01 ether PHOENIXES[0].price = 0.01 ether; //Now, for normal phoenixes uint16[4] memory PAYOUTS = [400,700,1100,1600]; //4%, 7%, 11%, 16% uint16[4] memory COOLDOWN = [2 hours, 4 hours, 8 hours, 16 hours]; uint16[4] memory COOLDOWN_DECREASE = [9 minutes, 15 minutes, 26 minutes, 45 minutes]; uint8[4] memory POWER_INC_AMT = [25,50,100,175]; //0.25%, 0.5%, 1%, 1.75% uint16[4] memory POWER_DROP = [150,300,600,1000]; //1.5%, 3%, 6%, 10% uint16[4] memory CAPPED_POWER = [800,1500,3000,5000]; //8%, 15%, 30%, 50% for (i = 0; i < 4; i++) { for (uint256 j = 0; j < 4; j++) { phoenix = Phoenix({ price: BASE_PRICE, payoutPercentage: PAYOUTS[j], abilityAvailTime: 0, cooldown: COOLDOWN[j], cooldownDecreaseAmt: COOLDOWN_DECREASE[j], basePower: (j+1)*100, //100, 200, 300, 400 = 1%, 2%, 3%, 4% currentPower: (j+1)*100, powerIncreaseAmt: POWER_INC_AMT[j], powerDrop: POWER_DROP[j], powerCap: CAPPED_POWER[j], previousOwner: address(0), currentOwner: address(0) }); PHOENIXES.push(phoenix); } } } function startGame() public noGameInProgress onlyAuthorized { //reset scores SCORES[0] = 0; SCORES[1] = 0; //reset normal phoenixes' abilityAvailTimes for (uint i = 1; i < 19; i++) { PHOENIXES[i].abilityAvailTime = now + PHOENIXES[i].cooldown; } GAME_STARTED = true; //set game duration to be 1 day GAME_END = now + 1 days; emit GameStarted(); } //Set bag holders from version 1.0 function setPhoenixOwners(address[19] _owners) onlyOwner public { require(PHOENIXES[0].previousOwner == address(0)); //Just need check once for (uint256 i = 0; i < 19; i++) { Phoenix storage phoenix = PHOENIXES[i]; phoenix.previousOwner = _owners[i]; phoenix.currentOwner = _owners[i]; } } function purchasePhoenix(uint256 _phoenixID) whenNotPaused gameInProgress public payable { //checking prerequisite require(_phoenixID < 19); Phoenix storage phoenix = PHOENIXES[_phoenixID]; //Get current price of phoenix uint256 price = phoenix.price; //checking more prerequisites require(phoenix.currentOwner != address(0)); //check if phoenix was initialised require(msg.value >= phoenix.price); require(phoenix.currentOwner != msg.sender); //prevent consecutive purchases uint256 outgoingOwnerCut; uint256 purchaseExcess; uint256 poolCut; uint256 rainbowCut; uint256 captainCut; (outgoingOwnerCut, purchaseExcess, poolCut, rainbowCut, captainCut) = calculateCuts(msg.value,price); //give 1% for previous owner, abusing variable name here userFunds[phoenix.previousOwner] = userFunds[phoenix.previousOwner].add(captainCut); //If purchasing rainbow phoenix, give the 2% rainbowCut and 1% captainCut to outgoingOwner if (_phoenixID == 0) { outgoingOwnerCut = outgoingOwnerCut.add(rainbowCut).add(captainCut); rainbowCut = 0; //necessary to set to zero since variable is used for other cases poolCut = poolCut.div(2); //split poolCut equally into 2, distribute to both POOLS POOLS[0] = POOLS[0].add(poolCut); //add pool cut to red team POOLS[1] = POOLS[1].add(poolCut); //add pool cut to blue team } else if (_phoenixID < 3) { //if captain, return 1% captainCut to outgoingOwner outgoingOwnerCut = outgoingOwnerCut.add(captainCut); uint256 poolID = _phoenixID.sub(1); //1 --> 0, 2--> 1 (detemine which pool to add pool cut to) POOLS[poolID] = POOLS[poolID].add(poolCut); } else if (_phoenixID < 11) { //for normal red phoenixes, set captain and adjust stats //transfer 1% captainCut to red captain userFunds[PHOENIXES[1].currentOwner] = userFunds[PHOENIXES[1].currentOwner].add(captainCut); upgradePhoenixStats(_phoenixID); POOLS[0] = POOLS[0].add(poolCut); //add pool cut to red team } else { //transfer 1% captainCut to blue captain userFunds[PHOENIXES[2].currentOwner] = userFunds[PHOENIXES[2].currentOwner].add(captainCut); upgradePhoenixStats(_phoenixID); POOLS[1] = POOLS[1].add(poolCut); //add pool cut to blue team } //transfer rainbowCut to rainbow phoenix owner userFunds[PHOENIXES[0].currentOwner] = userFunds[PHOENIXES[0].currentOwner].add(rainbowCut); // set new price phoenix.price = getNextPrice(price); // send funds to old owner sendFunds(phoenix.currentOwner, outgoingOwnerCut); // set new owner phoenix.currentOwner = msg.sender; // Send refund to owner if needed if (purchaseExcess > 0) { sendFunds(msg.sender,purchaseExcess); } // raise event emit PhoenixPurchased(_phoenixID, msg.sender, price, phoenix.price, phoenix.currentPower, phoenix.abilityAvailTime); } function calculateCuts( uint256 _amtPaid, uint256 _price ) private returns (uint256 outgoingOwnerCut, uint256 purchaseExcess, uint256 poolCut, uint256 rainbowCut, uint256 captainCut) { outgoingOwnerCut = _price; purchaseExcess = _amtPaid.sub(_price); //Take 5% cut from excess uint256 excessPoolCut = purchaseExcess.div(20); //5%, will be added to poolCut purchaseExcess = purchaseExcess.sub(excessPoolCut); //3% of price to devs uint256 cut = _price.mul(3).div(100); //3% outgoingOwnerCut = outgoingOwnerCut.sub(cut); distributeDevCut(cut); //1% of price to owner in previous round, 1% to captain (if applicable) //abusing variable name to use for previous owner and captain fees, since they are the same captainCut = _price.div(100); //1% outgoingOwnerCut = outgoingOwnerCut.sub(captainCut).sub(captainCut); //subtract twice, reason as explained //2% of price to rainbow (if applicable) rainbowCut = _price.mul(2).div(100); //2% outgoingOwnerCut = outgoingOwnerCut.sub(rainbowCut); //11-13% of price will go to the respective team pools poolCut = calculatePoolCut(_price); outgoingOwnerCut = outgoingOwnerCut.sub(poolCut); /* add the poolCut and excessPoolCut together so poolCut = 11-13% of price + 5% of purchaseExcess */ poolCut = poolCut.add(excessPoolCut); } function distributeDevCut(uint256 _cut) private { devFunds[owner] = devFunds[owner].add(_cut.div(2)); //50% to owner devFunds[subDevOne] = devFunds[subDevOne].add(_cut.div(4)); //25% to subDevOne devFunds[subDevTwo] = devFunds[subDevTwo].add(_cut.div(4)); //25% to subDevTwo } /** * @dev Determines next price of phoenix */ function getNextPrice (uint256 _price) private pure returns (uint256 _nextPrice) { if (_price < 0.25 ether) { return _price.mul(3).div(2); //1.5x } else if (_price < 1 ether) { return _price.mul(14).div(10); //1.4x } else { return _price.mul(13).div(10); //1.3x } } function calculatePoolCut (uint256 _price) private pure returns (uint256 poolCut) { if (_price < 0.25 ether) { poolCut = _price.mul(13).div(100); //13% } else if (_price < 1 ether) { poolCut = _price.mul(12).div(100); //12% } else { poolCut = _price.mul(11).div(100); //11% } } function upgradePhoenixStats(uint256 _phoenixID) private { Phoenix storage phoenix = PHOENIXES[_phoenixID]; //increase current power of phoenix phoenix.currentPower = phoenix.currentPower.add(phoenix.powerIncreaseAmt); //handle boundary case where current power exceeds cap if (phoenix.currentPower > phoenix.powerCap) { phoenix.currentPower = phoenix.powerCap; } //decrease cooldown of phoenix //no base case to take care off. Time shouldnt decrease too much to ever reach zero phoenix.abilityAvailTime = phoenix.abilityAvailTime.sub(phoenix.cooldownDecreaseAmt); } function useCaptainAbility(uint256 _captainID) whenNotPaused gameInProgress public { require(_captainID > 0 && _captainID < 3); //either 1 or 2 Phoenix storage captain = PHOENIXES[_captainID]; require(msg.sender == captain.currentOwner); //Only owner of captain can use ability require(now >= captain.abilityAvailTime); //Ability must be available for use if (_captainID == 1) { //red team uint groupIDStart = 3; //Start index of _groupID in PHOENIXES uint groupIDEnd = 11; //End index (excluding) of _groupID in PHOENIXES } else { groupIDStart = 11; groupIDEnd = 19; } for (uint i = groupIDStart; i < groupIDEnd; i++) { //Multiply team power by 1.5x PHOENIXES[i].currentPower = PHOENIXES[i].currentPower.mul(3).div(2); //ensure cap not breached if (PHOENIXES[i].currentPower > PHOENIXES[i].powerCap) { PHOENIXES[i].currentPower = PHOENIXES[i].powerCap; } } captain.abilityAvailTime = GAME_END + 10 seconds; //Prevent ability from being used again in current round emit CaptainAbilityUsed(_captainID); } function useAbility(uint256 _phoenixID) whenNotPaused gameInProgress public { //phoenixID must be between 3 to 18 require(_phoenixID > 2); require(_phoenixID < 19); Phoenix storage phoenix = PHOENIXES[_phoenixID]; require(msg.sender == phoenix.currentOwner); //Only owner of phoenix can use ability require(now >= phoenix.abilityAvailTime); //Ability must be available for use //calculate which pool to take from //ids 3-6, 15-18 --> red //ids 7-14 --> blue if (_phoenixID >=7 && _phoenixID <= 14) { require(POOLS[1] > 0); //blue pool uint256 payout = POOLS[1].mul(phoenix.currentPower).div(DENOMINATOR); //calculate payout POOLS[1] = POOLS[1].sub(payout); //subtract from pool } else { require(POOLS[0] > 0); //red pool payout = POOLS[0].mul(phoenix.currentPower).div(DENOMINATOR); POOLS[0] = POOLS[0].sub(payout); } //determine which team the phoenix is on if (_phoenixID < 11) { //red team bool isRed = true; //to determine which team to distribute the 9% payout to SCORES[0] = SCORES[0].add(payout); //add payout to score (ie. payout is the score) } else { //blue team isRed = false; SCORES[1] = SCORES[1].add(payout); } uint256 ownerCut = payout; //drop power of phoenix decreasePower(_phoenixID); //decrease phoenix price decreasePrice(_phoenixID); //reset cooldown phoenix.abilityAvailTime = now + phoenix.cooldown; // set previous owner to be current owner, so he can get the 1% dividend from subsequent purchases phoenix.previousOwner = msg.sender; // Calculate the different cuts // 2% to rainbow uint256 cut = payout.div(50); //2% ownerCut = ownerCut.sub(cut); userFunds[PHOENIXES[0].currentOwner] = userFunds[PHOENIXES[0].currentOwner].add(cut); // 1% to dev cut = payout.div(100); //1% ownerCut = ownerCut.sub(cut); distributeDevCut(cut); //9% to team cut = payout.mul(9).div(100); //9% ownerCut = ownerCut.sub(cut); distributeTeamCut(isRed,cut); //Finally, send money to user sendFunds(msg.sender,ownerCut); emit PhoenixAbilityUsed(_phoenixID,ownerCut,phoenix.price,phoenix.currentPower,phoenix.abilityAvailTime,phoenix.previousOwner); } function decreasePrice(uint256 _phoenixID) private { Phoenix storage phoenix = PHOENIXES[_phoenixID]; if (phoenix.price >= 0.75 ether) { phoenix.price = phoenix.price.mul(20).div(100); //drop to 20% } else { phoenix.price = phoenix.price.mul(10).div(100); //drop to 10% if (phoenix.price < BASE_PRICE) { phoenix.price = BASE_PRICE; } } } function decreasePower(uint256 _phoenixID) private { Phoenix storage phoenix = PHOENIXES[_phoenixID]; phoenix.currentPower = phoenix.currentPower.sub(phoenix.powerDrop); //handle boundary case where currentPower is below basePower if (phoenix.currentPower < phoenix.basePower) { phoenix.currentPower = phoenix.basePower; } } function distributeTeamCut(bool _isRed, uint256 _cut) private { /* Note that captain + phoenixes payout percentages add up to 100%. Captain: 24% Phoenix 1 & 5: 4% x 2 = 8% Phoenix 2 & 6: 7% x 2 = 14% Phoenix 3 & 7: 11% x 2 = 22% Phoenix 4 & 8: 16% x 2 = 32% */ if (_isRed) { uint captainID = 1; uint groupIDStart = 3; uint groupIDEnd = 11; } else { captainID = 2; groupIDStart = 11; groupIDEnd = 19; } //calculate and transfer capt payout uint256 payout = PHOENIXES[captainID].payoutPercentage.mul(_cut).div(DENOMINATOR); userFunds[PHOENIXES[captainID].currentOwner] = userFunds[PHOENIXES[captainID].currentOwner].add(payout); for (uint i = groupIDStart; i < groupIDEnd; i++) { //calculate how much to pay to each phoenix owner in the team payout = PHOENIXES[i].payoutPercentage.mul(_cut).div(DENOMINATOR); //transfer payout userFunds[PHOENIXES[i].currentOwner] = userFunds[PHOENIXES[i].currentOwner].add(payout); } } function endGame() gameHasEnded public { GAME_STARTED = false; //to allow this function to only be called once after the end of every round uint256 remainingPoolAmt = POOLS[0].add(POOLS[1]); //add the 2 pools together //Distribution structure -> 15% rainbow, 75% teams, 10% for next game uint256 rainbowCut = remainingPoolAmt.mul(15).div(100); //15% to rainbow uint256 teamCut = remainingPoolAmt.mul(75).div(100); //75% to teams remainingPoolAmt = remainingPoolAmt.sub(rainbowCut).sub(teamCut); //distribute 15% to rainbow phoenix owner userFunds[PHOENIXES[0].currentOwner] = userFunds[PHOENIXES[0].currentOwner].add(rainbowCut); //distribute 75% to teams //in the unlikely event of a draw, split evenly, so 37.5% cut to each team if (SCORES[0] == SCORES[1]) { teamCut = teamCut.div(2); distributeTeamCut(true,teamCut); //redTeam distributeTeamCut(false,teamCut); //blueTeam } else { //25% to losing team uint256 losingTeamCut = teamCut.div(3); // 1 third of 75% = 25% //SCORES[0] = red, SCORES[1] = blue //if red > blue, then award to redTeam, so bool _isRed = red > blue distributeTeamCut((SCORES[0] > SCORES[1]),losingTeamCut); //50% to winning team teamCut = teamCut.sub(losingTeamCut); //take the remainder //inverse of the winning condition distributeTeamCut(!(SCORES[0] > SCORES[1]),teamCut); } // 5% to each pool for next game POOLS[0] = remainingPoolAmt.div(2); POOLS[1] = POOLS[0]; resetPhoenixes(); emit GameEnded(); } function resetPhoenixes() private { //reset attributes of phoenixes PHOENIXES[0].price = 0.01 ether; PHOENIXES[1].price = 0.005 ether; PHOENIXES[2].price = 0.005 ether; for (uint i = 0; i < 3; i++) { PHOENIXES[i].previousOwner = PHOENIXES[i].currentOwner; } for (i = 3; i < 19; i++) { //Reset price and power levels of phoenixes //Ability time will be set during game start Phoenix storage phoenix = PHOENIXES[i]; phoenix.price = BASE_PRICE; phoenix.currentPower = phoenix.basePower; phoenix.previousOwner = phoenix.currentOwner; } } /** * @dev Try to send funds immediately * If it fails, user has to manually withdraw. */ function sendFunds(address _user, uint256 _payout) private { if (!_user.send(_payout)) { userFunds[_user] = userFunds[_user].add(_payout); } } /** * @dev Withdraw dev cut. */ function devWithdraw() public { uint256 funds = devFunds[msg.sender]; require(funds > 0); devFunds[msg.sender] = 0; msg.sender.transfer(funds); } /** * @dev Users can withdraw their funds */ function withdrawFunds() public { uint256 funds = userFunds[msg.sender]; require(funds > 0); userFunds[msg.sender] = 0; msg.sender.transfer(funds); emit WithdrewFunds(msg.sender); } /** * @dev Transfer contract balance in case of bug or contract upgrade */ function upgradeContract(address _newContract) public onlyOwner whenPaused { _newContract.transfer(address(this).balance); } }
Set bag holders from version 1.0
function setPhoenixOwners(address[19] _owners) onlyOwner public { for (uint256 i = 0; i < 19; i++) { Phoenix storage phoenix = PHOENIXES[i]; phoenix.previousOwner = _owners[i]; phoenix.currentOwner = _owners[i]; } }
4,814,110
pragma solidity >=0.8.9 <0.9.0; //SPDX-License-Identifier: MIT import "../node_modules/@openzeppelin/contracts/interfaces/IERC20Metadata.sol"; import "../node_modules/@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../node_modules/@openzeppelin/contracts/access/Ownable.sol"; import "./ISwapper.sol"; import "./XToken.sol"; /* Hello and welcome to the ShibaBurn burning portal. This is a contract that empowers developers to create incentive based deflation for all ERC20 tokens! ShibaBurn allows for an infinite number of burn pools to be created for any given token. By default, burn pools track the following data: - total tokens burnt by each user - total tokens burnt by all users ShibaBurn also allows for ETH to be "zapped" into burn pool ownershib by means of buying the specified token on ShibaSwap, and burning it in one transaction. This is only possible if eth-token liquidity is present on ShibaSwap.com If configured by the ShibaBurn owner wallet, burn pools can optionally: - Mint xTokens for users (e.g. burntSHIB in the case of burning SHIB to the default pool) - Keep track of the index at which any given address exceeds a burnt amount beyond an admin specified threshold _____ _____ _____ _____ _____ /\ \ /\ \ /\ \ /\ \ /\ \ /::\ \ /::\____\ /::\ \ /::\ \ /::\ \ /::::\ \ /:::/ / \:::\ \ /::::\ \ /::::\ \ /::::::\ \ /:::/ / \:::\ \ /::::::\ \ /::::::\ \ /:::/\:::\ \ /:::/ / \:::\ \ /:::/\:::\ \ /:::/\:::\ \ /:::/__\:::\ \ /:::/____/ \:::\ \ /:::/__\:::\ \ /:::/__\:::\ \ \:::\ \:::\ \ /::::\ \ /::::\ \ /::::\ \:::\ \ /::::\ \:::\ \ ___\:::\ \:::\ \ /::::::\ \ _____ ____ /::::::\ \ /::::::\ \:::\ \ /::::::\ \:::\ \ /\ \:::\ \:::\ \ /:::/\:::\ \ /\ \ /\ \ /:::/\:::\ \ /:::/\:::\ \:::\ ___\ /:::/\:::\ \:::\ \ /::\ \:::\ \:::\____\/:::/ \:::\ /::\____\/::\ \/:::/ \:::\____\/:::/__\:::\ \:::| |/:::/ \:::\ \:::\____\ \:::\ \:::\ \::/ /\::/ \:::\ /:::/ /\:::\ /:::/ \::/ /\:::\ \:::\ /:::|____|\::/ \:::\ /:::/ / \:::\ \:::\ \/____/ \/____/ \:::\/:::/ / \:::\/:::/ / \/____/ \:::\ \:::\/:::/ / \/____/ \:::\/:::/ / \:::\ \:::\ \ \::::::/ / \::::::/ / \:::\ \::::::/ / \::::::/ / \:::\ \:::\____\ \::::/ / \::::/____/ \:::\ \::::/ / \::::/ / \:::\ /:::/ / /:::/ / \:::\ \ \:::\ /:::/ / /:::/ / \:::\/:::/ / /:::/ / \:::\ \ \:::\/:::/ / /:::/ / \::::::/ / /:::/ / \:::\ \ \::::::/ / /:::/ / \::::/ / /:::/ / \:::\____\ \::::/ / /:::/ / \::/ / \::/ / \::/ / \::/____/ \::/ / \/____/ \/____/ \/____/ ~~ \/____/ _____ _____ _____ _____ /\ \ /\ \ /\ \ /\ \ /::\ \ /::\____\ /::\ \ /::\____\ /::::\ \ /:::/ / /::::\ \ /::::| | /::::::\ \ /:::/ / /::::::\ \ /:::::| | /:::/\:::\ \ /:::/ / /:::/\:::\ \ /::::::| | /:::/__\:::\ \ /:::/ / /:::/__\:::\ \ /:::/|::| | /::::\ \:::\ \ /:::/ / /::::\ \:::\ \ /:::/ |::| | /::::::\ \:::\ \ /:::/ / _____ /::::::\ \:::\ \ /:::/ |::| | _____ /:::/\:::\ \:::\ ___\ /:::/____/ /\ \ /:::/\:::\ \:::\____\ /:::/ |::| |/\ \ /:::/__\:::\ \:::| ||:::| / /::\____\/:::/ \:::\ \:::| |/:: / |::| /::\____\ \:::\ \:::\ /:::|____||:::|____\ /:::/ /\::/ |::::\ /:::|____|\::/ /|::| /:::/ / \:::\ \:::\/:::/ / \:::\ \ /:::/ / \/____|:::::\/:::/ / \/____/ |::| /:::/ / \:::\ \::::::/ / \:::\ \ /:::/ / |:::::::::/ / |::|/:::/ / \:::\ \::::/ / \:::\ /:::/ / |::|\::::/ / |::::::/ / \:::\ /:::/ / \:::\__/:::/ / |::| \::/____/ |:::::/ / \:::\/:::/ / \::::::::/ / |::| ~| |::::/ / \::::::/ / \::::::/ / |::| | /:::/ / \::::/ / \::::/ / \::| | /:::/ / \::/____/ \::/____/ \:| | \::/ / ~~ ~~ \|___| \/____/ */ contract ShibaBurn is Ownable { // ShibaSwap router: ISwapper public router = ISwapper(0x03f7724180AA6b939894B5Ca4314783B0b36b329); // Ledgendary burn address that holds tokens burnt of the SHIB ecosystem: address public burnAddress = 0xdEAD000000000000000042069420694206942069; address public wethAddress; // Addresses of SHIB ecosystem tokens: address public shibAddress = 0x95aD61b0a150d79219dCF64E1E6Cc01f0B64C4cE; address public boneAddress = 0x9813037ee2218799597d83D4a5B6F3b6778218d9; address public leashAddress = 0x27C70Cd1946795B66be9d954418546998b546634; address public ryoshiAddress = 0x777E2ae845272a2F540ebf6a3D03734A5a8f618e; event Burn(address sender, uint256 time, address tokenAddress, uint256 poolIndex, uint256 amount); bool locked; modifier noReentrancy() { require(!locked,"Reentrant call"); locked = true; _; locked = false; } ////////////// // BURN POOLS: ////////////// // // xTokens[tokenAddress][poolIndex] // => address of pool's xToken mapping(address => mapping(uint256 => address)) public xTokens; // totalBurnt[tokenAddress][poolIndex] // => total amount burnt for specified pool mapping(address => mapping(uint256 => uint256)) public totalBurnt; // totalTrackedBurners[tokenAddress][poolIndex] // => total number of burners that have exceeded the trackBurnerIndexThreshold mapping(address => mapping(uint256 => uint256)) public totalTrackedBurners; // trackBurnerIndexThreshold[tokenAddress][poolIndex] // => the burn threshold required to track user burn indexes of a specific pool mapping(address => mapping(uint256 => uint256)) public trackBurnerIndexThreshold; // burnerIndex[tokenAddress][poolIndex][userAddress] // => the index at which a user exceeded the trackBurnerIndexThreshold for a specific pool mapping(address => mapping(uint256 => mapping(address => uint256))) public burnerIndex; // burnerIndex[tokenAddress][poolIndex][burnerIndex] // => the address of the a specified tracked burner at a specified index mapping(address => mapping(uint256 => mapping(uint256 => address))) public burnersByIndex; // amountBurnt[tokenAddress][poolIndex][userAddress] // => amount burnt by a specific user for a specified pool mapping(address => mapping(uint256 => mapping(address => uint256))) public amountBurnt; constructor(address _wethAddress) Ownable() { wethAddress = _wethAddress; } /** * @notice Intended to be used for web3 interface, such that all data can be pulled at once * @param tokenAddress The address of the token for which the query will be made * @param currentUser The address used to query user-based pool info and ethereum balance * @return burnPool info for the default pool (0) of the specified token */ function getInfo(address currentUser, address tokenAddress) external view returns (uint256[] memory) { return getInfoForPool(0, currentUser, tokenAddress); } /** * @notice Intended to be used for web3 interface, such that all data can be pulled at once * @param poolIndex The index of which token-specific burn pool to be used * @param tokenAddress The address of the token for which the query will be made * @param currentUser The address used to query user-based pool info and ethereum balance * * @return burnPool info for the specified pool of the specified token as an array of 11 integers indicating the following: * (0) Number of decimals of the token associated with the tokenAddress * (1) Total amount burnt for the specified burn-pool * (2) Total amount burnt by the specified currentUser for the specified burn-pool * (3) The amount of specified tokens in possession by the specified currentUser * (4) The amount of eth in the wallet of the specified currentUser * (5) The amount of specified tokens allowed to be burnt by this contract * (6) The threshold of tokens needed to be burnt to track the index of a user for the specified pool (if zero, no indexes will be tracked) * (7) Burn index of the current user with regards to a specified pool (only tracked if admin configured, and burn meets threshold requirements) * (8) Total number of burners above the specified threshold for the specific pool * (9) Decimal integer representation of the address of the 'xToken' of the specified pool * (10) Total supply of the xToken associated with the specified pool * (11) Specified pool's xToken balance of currentUser */ function getInfoForPool(uint256 poolIndex, address currentUser, address tokenAddress) public view returns (uint256[] memory) { uint256[] memory info = new uint256[](12); IERC20Metadata token = IERC20Metadata(tokenAddress); info[0] = token.decimals(); info[1] = totalBurnt[tokenAddress][poolIndex]; info[2] = amountBurnt[tokenAddress][poolIndex][currentUser]; info[3] = token.balanceOf(currentUser); info[4] = currentUser.balance; info[5] = token.allowance(currentUser, address(this)); if (trackBurnerIndexThreshold[tokenAddress][poolIndex] != 0) { info[6] = trackBurnerIndexThreshold[tokenAddress][poolIndex]; info[7] = burnerIndex[tokenAddress][poolIndex][currentUser]; info[8] = totalTrackedBurners[tokenAddress][poolIndex]; } if (xTokens[tokenAddress][poolIndex] != address(0)) { IERC20Metadata xToken = IERC20Metadata(xTokens[tokenAddress][poolIndex]); info[9] = uint256(uint160(address(xToken))); info[10] = xToken.totalSupply(); info[11] = xToken.balanceOf(currentUser); } return info; } /** * @notice Intended to be used for web3 such that all necessary data can be requested at once * @param tokenAddress The address of the token to buy on shibaswap. * @return Name and Symbol metadata of specified ERC20 token. */ function getTokenInfo(address tokenAddress) external view returns (string[] memory) { string[] memory info = new string[](2); IERC20Metadata token = IERC20Metadata(tokenAddress); info[0] = token.name(); info[1] = token.symbol(); return info; } /** * @param tokenAddress The address of the token to buy on shibaswap. * @param minOut specifies the minimum number of tokens to be burnt when buying (to prevent front-runner attacks) * * @notice Allows users to buy tokens (with ETH on ShibaSwap) and burn them in 1 tx for the * "default" burn pool for the specified token. Based on the admin configuration of each pool, * xTokens may be issued, and/or the burner's index will be tracked. */ function buyAndBurn(address tokenAddress, uint256 minOut) external payable { buyAndBurnForPool(tokenAddress, minOut, 0); } /** * @param tokenAddress The address of the token intended to be burnt. * @param poolIndex the index of which token-specific burn pool to be used * @param threshold the minimum amount of tokens required to be burnt for the burner's index to be tracked * * @dev This can only be set on pools with no burns * @notice Allows the admin address to mark a specific pool as tracking "indexes" of burns above a specific threshold. * This allows for projects to reward users based on how early they burned more than the specified amount. * Setting this threshold will cause each burn to require more gas. */ function trackIndexesForPool(address tokenAddress, uint256 poolIndex, uint256 threshold) public onlyOwner { require (totalBurnt[tokenAddress][poolIndex] == 0, "tracking indexes can only be turned on for pools with no burns"); trackBurnerIndexThreshold[tokenAddress][poolIndex] = threshold; } /** * @param tokenAddress The address of the token intended to be burnt. * @param poolIndex the index of which token-specific burn pool to be used * @param xTokenAddress the address of the xToken that will be minted in exchange for burning * * @notice Allows the admin address to set an xToken address for a specific pool. * @dev It is required for this contract to have permission to mint the xToken */ function setXTokenForPool(address tokenAddress, uint256 poolIndex, address xTokenAddress) public onlyOwner { require (totalBurnt[tokenAddress][poolIndex] == 0, "xToken can only be set on pools with no burns"); xTokens[tokenAddress][poolIndex] = xTokenAddress; } /** * @notice Allows users to buy tokens (with ETH on ShibaSwap) and burn them in 1 tx. * Based on the admin configuration of each pool, xTokens may be issued, * and the burner's index will be tracked. * * @dev uses hard coded shibaswap router address * * @param tokenAddress The address of the token to buy on shibaswap. * @param minOut specifies the minimum number of tokens to be burnt when buying (to prevent front-runner attacks) * @param poolIndex the index of which token-specific burn pool to be used * */ function buyAndBurnForPool(address tokenAddress, uint256 minOut, uint256 poolIndex) public payable noReentrancy { address[] memory ethPath = new address[](2); ethPath[0] = wethAddress; // WETH ethPath[1] = tokenAddress; IERC20Metadata token = IERC20Metadata(tokenAddress); uint256 balanceWas = token.balanceOf(burnAddress); router.swapExactETHForTokens{ value: msg.value }(minOut, ethPath, burnAddress, block.timestamp + 1000); uint256 amount = token.balanceOf(burnAddress) - balanceWas; _increaseOwnership(tokenAddress, poolIndex, amount); } /** * @dev internal method * @param tokenAddress The address of the token intended to be burnt. * @param poolIndex the index of which token-specific burn pool to be used * @param amount the amount of tokens intended to be burnt * * @return boolean value which indicates whether or not the burner's burn index should be tracked for the current transaction. */ function shouldTrackIndex(address tokenAddress, uint256 poolIndex, uint256 amount) internal returns (bool) { uint256 threshold = trackBurnerIndexThreshold[tokenAddress][poolIndex]; uint256 alreadyBurnt = amountBurnt[tokenAddress][poolIndex][msg.sender]; return threshold != 0 && alreadyBurnt < threshold && alreadyBurnt + amount >= threshold; } /** * @notice increases ownership of specified pool. * @dev tracks the user's burn Index if configured * @dev mints xTokens for the user if configured * @dev internal method * @param tokenAddress The address of the token intended to be burnt. * @param poolIndex the index of which token-specific burn pool to be used * @param amount of tokens intended to be burnt * */ function _increaseOwnership(address tokenAddress, uint256 poolIndex, uint256 amount) internal { if (shouldTrackIndex(tokenAddress, poolIndex, amount)) { burnerIndex[tokenAddress][poolIndex][msg.sender] = totalTrackedBurners[tokenAddress][poolIndex]; burnersByIndex[tokenAddress][poolIndex][totalTrackedBurners[tokenAddress][poolIndex]] = msg.sender; totalTrackedBurners[tokenAddress][poolIndex] += 1; } if (xTokens[tokenAddress][poolIndex] != address(0)) XToken(xTokens[tokenAddress][poolIndex]).mint(msg.sender, amount); amountBurnt[tokenAddress][poolIndex][msg.sender] = amountBurnt[tokenAddress][poolIndex][msg.sender] + amount; totalBurnt[tokenAddress][poolIndex] += amount; emit Burn(msg.sender, block.timestamp, tokenAddress, poolIndex, amount); } /** * @notice Burns SHIB to the default SHIB pool * @param amount the amount of SHIB to be burnt */ function burnShib(uint256 amount) external { burnToken(shibAddress, amount); } /** * @notice Burns RYOSHI to the default RYOSHI pool * @param amount the amount of RYOSHI to be burnt */ function burnRyoshi(uint256 amount) external { burnToken(ryoshiAddress, amount); } /** * @notice Burns LEASH to the default LEASH pool * @param amount the amount of LEASH to be burnt * */ function burnLeash(uint256 amount) external { burnToken(leashAddress, amount); } /** * @notice Burns BONE to the default BONE pool * @param amount the amount of BONE to be burnt * */ function burnBone(uint256 amount) external { burnToken(boneAddress, amount); } /** * @notice Burns any token to the default (0) pool for that token * @param tokenAddress the address of the token intended to be burnt * @param amount the amount of tokens to be burnt * */ function burnToken(address tokenAddress, uint256 amount) public { burnTokenForPool(tokenAddress, 0, amount); } /** * @notice Burns any token to the specified pool for that token * @param tokenAddress the address of the token intended to be burnt * @param poolIndex the index of which token-specific burn pool to be used * @param amount the amount of tokens to be burnt * */ function burnTokenForPool(address tokenAddress, uint256 poolIndex, uint256 amount) public noReentrancy { IERC20Metadata token = IERC20Metadata(tokenAddress); require (token.balanceOf(msg.sender) >= amount, "insufficient token balance"); token.transferFrom(msg.sender, burnAddress, amount); _increaseOwnership(tokenAddress, poolIndex, amount); } }
Burns LEASH to the default LEASH pool amount the amount of LEASH to be burnt/
function burnLeash(uint256 amount) external { burnToken(leashAddress, amount); }
12,569,959
./full_match/4/0xDC750c9a411e3BfA0fB0Dd1248251D5831321352/sources/cache/solpp-generated-contracts/ZkSync.sol
Process one block commit using previous block StoredBlockInfo, returns new block StoredBlockInfo NOTE: Does not change storage (except events, so we can't mark it view) Check timestamp of the new block
function commitOneBlock(StoredBlockInfo memory _previousBlock, CommitBlockInfo memory _newBlock) internal returns (StoredBlockInfo memory storedNewBlock) { { bool timestampNotTooSmall = block.timestamp - COMMIT_TIMESTAMP_NOT_OLDER <= _newBlock.timestamp; bool timestampNotTooBig = _newBlock.timestamp <= block.timestamp + COMMIT_TIMESTAMP_APPROXIMATION_DELTA; } collectOnchainOps(_newBlock); return StoredBlockInfo( _newBlock.blockNumber, priorityReqCommitted, pendingOnchainOpsHash, _newBlock.timestamp, _newBlock.newStateHash, commitment ); }
749,369
pragma solidity 0.4.24; // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: contracts/interfaces/IRegistry.sol // limited ContractRegistry definition interface IRegistry { function owner() external returns (address); function updateContractAddress( string _name, address _address ) external returns (address); function getContractAddress( string _name ) external view returns (address); } // File: contracts/interfaces/IPoaToken.sol interface IPoaToken { function initializeToken ( bytes32 _name32, // bytes32 of name string bytes32 _symbol32, // bytes32 of symbol string address _issuer, address _custodian, address _registry, address _whitelist, uint256 _totalSupply // token total supply ) external returns (bool); function issuer() external view returns (address); function startPreFunding() external returns (bool); function pause() external; function unpause() external; function terminate() external returns (bool); function proofOfCustody() external view returns (string); } // File: contracts/interfaces/IPoaCrowdsale.sol interface IPoaCrowdsale { function initializeCrowdsale( bytes32 _fiatCurrency32, // fiat currency string, e.g. 'EUR' uint256 _startTimeForFundingPeriod, // future UNIX timestamp uint256 _durationForFiatFundingPeriod, // duration of fiat funding period in seconds uint256 _durationForEthFundingPeriod, // duration of ETH funding period in seconds uint256 _durationForActivationPeriod, // duration of activation period in seconds uint256 _fundingGoalInCents // funding goal in fiat cents ) external returns (bool); } // File: contracts/PoaProxyCommon.sol /** @title PoaProxyCommon acts as a convention between: - PoaCommon (and its inheritants: PoaToken & PoaCrowdsale) - PoaProxy It dictates where to read and write storage */ contract PoaProxyCommon { /***************************** * Start Proxy Common Storage * *****************************/ // PoaTokenMaster logic contract used by proxies address public poaTokenMaster; // PoaCrowdsaleMaster logic contract used by proxies address public poaCrowdsaleMaster; // Registry used for getting other contract addresses address public registry; /*************************** * End Proxy Common Storage * ***************************/ /********************************* * Start Common Utility Functions * *********************************/ /// @notice Gets a given contract address by bytes32 in order to save gas function getContractAddress(string _name) public view returns (address _contractAddress) { bytes4 _signature = bytes4(keccak256("getContractAddress32(bytes32)")); bytes32 _name32 = keccak256(abi.encodePacked(_name)); assembly { let _registry := sload(registry_slot) // load registry address from storage let _pointer := mload(0x40) // Set _pointer to free memory pointer mstore(_pointer, _signature) // Store _signature at _pointer mstore(add(_pointer, 0x04), _name32) // Store _name32 at _pointer offset by 4 bytes for pre-existing _signature // staticcall(g, a, in, insize, out, outsize) => returns 0 on error, 1 on success let result := staticcall( gas, // g = gas: whatever was passed already _registry, // a = address: address in storage _pointer, // in = mem in mem[in..(in+insize): set to free memory pointer 0x24, // insize = mem insize mem[in..(in+insize): size of signature (bytes4) + bytes32 = 0x24 _pointer, // out = mem out mem[out..(out+outsize): output assigned to this storage address 0x20 // outsize = mem outsize mem[out..(out+outsize): output should be 32byte slot (address size = 0x14 < slot size 0x20) ) // revert if not successful if iszero(result) { revert(0, 0) } _contractAddress := mload(_pointer) // Assign result to return value mstore(0x40, add(_pointer, 0x24)) // Advance free memory pointer by largest _pointer size } } /******************************* * End Common Utility Functions * *******************************/ } // File: contracts/PoaProxy.sol /** @title This contract manages the storage of: - PoaProxy - PoaToken - PoaCrowdsale @notice PoaProxy uses chained "delegatecall()"s to call functions on PoaToken and PoaCrowdsale and sets the resulting storage here on PoaProxy. @dev `getContractAddress("PoaLogger").call()` does not use the return value because we would rather contract functions to continue even if the event did not successfully trigger on the logger contract. */ contract PoaProxy is PoaProxyCommon { uint8 public constant version = 1; event ProxyUpgraded(address upgradedFrom, address upgradedTo); /** @notice Stores addresses of our contract registry as well as the PoaToken and PoaCrowdsale master contracts to forward calls to. */ constructor( address _poaTokenMaster, address _poaCrowdsaleMaster, address _registry ) public { // Ensure that none of the given addresses are empty require(_poaTokenMaster != address(0)); require(_poaCrowdsaleMaster != address(0)); require(_registry != address(0)); // Set addresses in common storage using deterministic storage slots poaTokenMaster = _poaTokenMaster; poaCrowdsaleMaster = _poaCrowdsaleMaster; registry = _registry; } /***************************** * Start Proxy State Helpers * *****************************/ /** @notice Ensures that a given address is a contract by making sure it has code. Used during upgrading to make sure the new addresses to upgrade to are smart contracts. */ function isContract(address _address) private view returns (bool) { uint256 _size; assembly { _size := extcodesize(_address) } return _size > 0; } /*************************** * End Proxy State Helpers * ***************************/ /***************************** * Start Proxy State Setters * *****************************/ /// @notice Update the stored "poaTokenMaster" address to upgrade the PoaToken master contract function proxyChangeTokenMaster(address _newMaster) public returns (bool) { require(msg.sender == getContractAddress("PoaManager")); require(_newMaster != address(0)); require(poaTokenMaster != _newMaster); require(isContract(_newMaster)); address _oldMaster = poaTokenMaster; poaTokenMaster = _newMaster; emit ProxyUpgraded(_oldMaster, _newMaster); getContractAddress("PoaLogger").call( abi.encodeWithSignature( "logProxyUpgraded(address,address)", _oldMaster, _newMaster ) ); return true; } /// @notice Update the stored `poaCrowdsaleMaster` address to upgrade the PoaCrowdsale master contract function proxyChangeCrowdsaleMaster(address _newMaster) public returns (bool) { require(msg.sender == getContractAddress("PoaManager")); require(_newMaster != address(0)); require(poaCrowdsaleMaster != _newMaster); require(isContract(_newMaster)); address _oldMaster = poaCrowdsaleMaster; poaCrowdsaleMaster = _newMaster; emit ProxyUpgraded(_oldMaster, _newMaster); getContractAddress("PoaLogger").call( abi.encodeWithSignature( "logProxyUpgraded(address,address)", _oldMaster, _newMaster ) ); return true; } /*************************** * End Proxy State Setters * ***************************/ /** @notice Fallback function for all proxied functions using "delegatecall()". It will first forward all functions to the "poaTokenMaster" address. If the called function isn't found there, then "poaTokenMaster"'s fallback function will forward the call to "poaCrowdsale". If the called function also isn't found there, it will fail at last. */ function() external payable { assembly { // Load PoaToken master address from first storage pointer let _poaTokenMaster := sload(poaTokenMaster_slot) // calldatacopy(t, f, s) calldatacopy( 0x0, // t = mem position to 0x0, // f = mem position from calldatasize // s = size bytes ) // delegatecall(g, a, in, insize, out, outsize) => returns "0" on error, or "1" on success let result := delegatecall( gas, // g = gas _poaTokenMaster, // a = address 0x0, // in = mem in mem[in..(in+insize) calldatasize, // insize = mem insize mem[in..(in+insize) 0x0, // out = mem out mem[out..(out+outsize) 0 // outsize = mem outsize mem[out..(out+outsize) ) // Check if the call was successful if iszero(result) { // Revert if call failed revert(0, 0) } // returndatacopy(t, f, s) returndatacopy( 0x0, // t = mem position to 0x0, // f = mem position from returndatasize // s = size bytes ) // Return if call succeeded return( 0x0, returndatasize ) } } } // File: contracts/PoaManager.sol contract PoaManager is Ownable { using SafeMath for uint256; uint256 constant version = 1; IRegistry public registry; struct EntityState { uint256 index; bool active; } // Keeping a list for addresses we track for easy access address[] private issuerAddressList; address[] private tokenAddressList; // A mapping for each address we track mapping (address => EntityState) private tokenMap; mapping (address => EntityState) private issuerMap; event IssuerAdded(address indexed issuer); event IssuerRemoved(address indexed issuer); event IssuerStatusChanged(address indexed issuer, bool active); event TokenAdded(address indexed token); event TokenRemoved(address indexed token); event TokenStatusChanged(address indexed token, bool active); modifier isNewIssuer(address _issuerAddress) { require(_issuerAddress != address(0)); require(issuerMap[_issuerAddress].index == 0); _; } modifier onlyActiveIssuer() { EntityState memory entity = issuerMap[msg.sender]; require(entity.active); _; } constructor(address _registryAddress) public { require(_registryAddress != address(0)); registry = IRegistry(_registryAddress); } // // Entity functions // function doesEntityExist( address _entityAddress, EntityState entity ) private pure returns (bool) { return (_entityAddress != address(0) && entity.index != 0); } function addEntity( address _entityAddress, address[] storage entityList, bool _active ) private returns (EntityState) { entityList.push(_entityAddress); // we do not offset by `-1` so that we never have `entity.index = 0` as this is what is // used to check for existence in modifier [doesEntityExist] uint256 index = entityList.length; EntityState memory entity = EntityState(index, _active); return entity; } function removeEntity( EntityState _entityToRemove, address[] storage _entityList ) private returns (address, uint256) { // we offset by -1 here to account for how `addEntity` marks the `entity.index` value uint256 index = _entityToRemove.index.sub(1); // swap the entity to be removed with the last element in the list _entityList[index] = _entityList[_entityList.length - 1]; // because we wanted seperate mappings for token and issuer, and we cannot pass a storage mapping // as a function argument, this abstraction is leaky; we return the address and index so the // caller can update the mapping address entityToSwapAddress = _entityList[index]; // we do not need to delete the element, the compiler should clean up for us _entityList.length--; return (entityToSwapAddress, _entityToRemove.index); } function setEntityActiveValue( EntityState storage entity, bool _active ) private { require(entity.active != _active); entity.active = _active; } // // Issuer functions // // Return all tracked issuer addresses function getIssuerAddressList() public view returns (address[]) { return issuerAddressList; } // Add an issuer and set active value to true function addIssuer(address _issuerAddress) public onlyOwner isNewIssuer(_issuerAddress) { issuerMap[_issuerAddress] = addEntity( _issuerAddress, issuerAddressList, true ); emit IssuerAdded(_issuerAddress); } // Remove an issuer function removeIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(issuerMap[_issuerAddress], issuerAddressList); issuerMap[addressToUpdate].index = indexUpdate; delete issuerMap[_issuerAddress]; emit IssuerRemoved(_issuerAddress); } // Set previously delisted issuer to listed function listIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], true); emit IssuerStatusChanged(_issuerAddress, true); } // Set previously listed issuer to delisted function delistIssuer(address _issuerAddress) public onlyOwner { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); setEntityActiveValue(issuerMap[_issuerAddress], false); emit IssuerStatusChanged(_issuerAddress, false); } function isActiveIssuer(address _issuerAddress) public view returns (bool) { require(doesEntityExist(_issuerAddress, issuerMap[_issuerAddress])); return issuerMap[_issuerAddress].active; } function isRegisteredIssuer(address _issuerAddress) external view returns (bool) { return doesEntityExist(_issuerAddress, issuerMap[_issuerAddress]); } // // Token functions // // Return all tracked token addresses function getTokenAddressList() public view returns (address[]) { return tokenAddressList; } function createPoaTokenProxy() private returns (address _proxyContract) { address _poaTokenMaster = registry.getContractAddress("PoaTokenMaster"); address _poaCrowdsaleMaster = registry.getContractAddress("PoaCrowdsaleMaster"); _proxyContract = new PoaProxy(_poaTokenMaster, _poaCrowdsaleMaster, address(registry)); } /** @notice Creates a PoaToken contract with given parameters, and set active value to false @param _fiatCurrency32 Fiat symbol used in ExchangeRates @param _startTimeForFundingPeriod Given as unix time in seconds since 01.01.1970 @param _durationForFiatFundingPeriod How long fiat funding can last, given in seconds @param _durationForEthFundingPeriod How long eth funding can last, given in seconds @param _durationForActivationPeriod How long a custodian has to activate token, given in seconds @param _fundingGoalInCents Given as fiat cents */ function addNewToken( bytes32 _name32, bytes32 _symbol32, bytes32 _fiatCurrency32, address _custodian, uint256 _totalSupply, uint256 _startTimeForFundingPeriod, uint256 _durationForFiatFundingPeriod, uint256 _durationForEthFundingPeriod, uint256 _durationForActivationPeriod, uint256 _fundingGoalInCents, address _whitelist ) public onlyActiveIssuer returns (address) { address _tokenAddress = createPoaTokenProxy(); // We use this initialization pattern to avoid the `StackTooDeep` problem // StackTooDeep: https://ethereum.stackexchange.com/questions/6061/error-while-compiling-stack-too-deep initializePoaToken( _tokenAddress, _name32, _symbol32, _custodian, _whitelist, _totalSupply ); initializePoaCrowdsale( _tokenAddress, _fiatCurrency32, _startTimeForFundingPeriod, _durationForFiatFundingPeriod, _durationForEthFundingPeriod, _durationForActivationPeriod, _fundingGoalInCents ); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, false ); emit TokenAdded(_tokenAddress); return _tokenAddress; } // Initializes a PoaToken contract with given parameters function initializePoaToken( address _tokenAddress, bytes32 _name32, bytes32 _symbol32, address _custodian, address _whitelist, uint256 _totalSupply ) private { IPoaToken(_tokenAddress).initializeToken( _name32, _symbol32, msg.sender, _custodian, registry, _whitelist, _totalSupply ); } // Initializes a PoaCrowdsale contract with given parameters function initializePoaCrowdsale( address _tokenAddress, bytes32 _fiatCurrency32, uint256 _startTimeForFundingPeriod, uint256 _durationForFiatFundingPeriod, uint256 _durationForEthFundingPeriod, uint256 _durationForActivationPeriod, uint256 _fundingGoalInCents ) private { IPoaCrowdsale(_tokenAddress).initializeCrowdsale( _fiatCurrency32, _startTimeForFundingPeriod, _durationForFiatFundingPeriod, _durationForEthFundingPeriod, _durationForActivationPeriod, _fundingGoalInCents ); } /** @notice Add existing `PoaProxy` contracts when `PoaManager` has been upgraded @param _tokenAddress the `PoaProxy` address to address @param _isListed if `PoaProxy` should be added as active or inactive @dev `PoaProxy` contracts can only be added when the POA's issuer is already listed. Furthermore, we use `issuer()` as check if `_tokenAddress` represents a `PoaProxy`. */ function addExistingToken(address _tokenAddress, bool _isListed) external onlyOwner { require(!doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); // Issuer address of `_tokenAddress` must be an active Issuer. // If `_tokenAddress` is not an instance of PoaProxy, this will fail as desired. require(isActiveIssuer(IPoaToken(_tokenAddress).issuer())); tokenMap[_tokenAddress] = addEntity( _tokenAddress, tokenAddressList, _isListed ); } // Remove a token function removeToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); address addressToUpdate; uint256 indexUpdate; (addressToUpdate, indexUpdate) = removeEntity(tokenMap[_tokenAddress], tokenAddressList); tokenMap[addressToUpdate].index = indexUpdate; delete tokenMap[_tokenAddress]; emit TokenRemoved(_tokenAddress); } // Set previously delisted token to listed function listToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], true); emit TokenStatusChanged(_tokenAddress, true); } // Set previously listed token to delisted function delistToken(address _tokenAddress) public onlyOwner { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); setEntityActiveValue(tokenMap[_tokenAddress], false); emit TokenStatusChanged(_tokenAddress, false); } function isActiveToken(address _tokenAddress) public view returns (bool) { require(doesEntityExist(_tokenAddress, tokenMap[_tokenAddress])); return tokenMap[_tokenAddress].active; } function isRegisteredToken(address _tokenAddress) external view returns (bool) { return doesEntityExist(_tokenAddress, tokenMap[_tokenAddress]); } // // Token onlyOwner functions as PoaManger is `owner` of all PoaToken // // Allow unpausing a listed PoaToken function pauseToken(address _tokenAddress) public onlyOwner { IPoaToken(_tokenAddress).pause(); } // Allow unpausing a listed PoaToken function unpauseToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.unpause(); } // Allow terminating a listed PoaToken function terminateToken(IPoaToken _tokenAddress) public onlyOwner { _tokenAddress.terminate(); } // upgrade an existing PoaToken proxy to what is stored in ContractRegistry function upgradeToken(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeTokenMaster( registry.getContractAddress("PoaTokenMaster") ); return true; } // upgrade an existing PoaCrowdsale proxy to what is stored in ContractRegistry function upgradeCrowdsale(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeCrowdsaleMaster( registry.getContractAddress("PoaCrowdsaleMaster") ); return true; } }
upgrade an existing PoaCrowdsale proxy to what is stored in ContractRegistry
function upgradeCrowdsale(PoaProxy _proxyToken) external onlyOwner returns (bool) { _proxyToken.proxyChangeCrowdsaleMaster( registry.getContractAddress("PoaCrowdsaleMaster") ); return true; }
7,300,827
// SPDX-License-Identifier: BUSL-1.1 pragma solidity >=0.8.4; import "@prb/contracts/access/Ownable.sol"; import "@prb/contracts/token/erc20/IErc20.sol"; import "./IFintroller.sol"; import "../h-token/IHToken.sol"; /// @notice Fintroller /// @author Hifi contract Fintroller is IFintroller, // one dependency Ownable // one dependency { /// PUBLIC STORAGE /// /// @inheritdoc IFintroller uint256 public override maxBonds; /// INTERNAL STORAGE /// /// @dev The threshold below which the collateral ratio cannot be set, equivalent to 100%. uint256 internal constant COLLATERAL_RATIO_LOWER_BOUND = 1.0e18; /// @dev The threshold above which the collateral ratio cannot be set, equivalent to 10,000%. uint256 internal constant COLLATERAL_RATIO_UPPER_BOUND = 1.0e20; /// @dev The default collateral ratio set when a new bond is listed, equivalent to 150%. uint256 internal constant DEFAULT_COLLATERAL_RATIO = 1.5e18; /// @dev The default liquidation incentive set when a new bond is listed, equivalent to 110%. uint256 internal constant DEFAULT_LIQUIDATION_INCENTIVE = 1.1e18; /// @dev The default maximum number of bond markets a single account can enter. uint256 internal constant DEFAULT_MAX_BONDS = 10; /// @dev The threshold below which the liquidation incentive cannot be set, equivalent to 100%. uint256 internal constant LIQUIDATION_INCENTIVE_LOWER_BOUND = 1.0e18; /// @dev The threshold above which the liquidation incentive cannot be set, equivalent to 150%. uint256 internal constant LIQUIDATION_INCENTIVE_UPPER_BOUND = 1.5e18; /// @notice Maps hTokens to Bond structs. mapping(IHToken => Bond) internal bonds; /// @notice Maps IErc20s to Collateral structs. mapping(IErc20 => Collateral) internal collaterals; /// CONSTRUCTOR /// constructor() Ownable() { // Set the max bonds limit. maxBonds = DEFAULT_MAX_BONDS; } /// PUBLIC CONSTANT FUNCTIONS /// /// @inheritdoc IFintroller function getBond(IHToken hToken) external view override returns (Bond memory) { return bonds[hToken]; } /// @inheritdoc IFintroller function getBorrowAllowed(IHToken bond) external view override returns (bool) { if (!bonds[bond].isListed) { revert Fintroller__BondNotListed(bond); } return bonds[bond].isBorrowAllowed; } /// @inheritdoc IFintroller function getCollateral(IErc20 collateral) external view override returns (Collateral memory) { return collaterals[collateral]; } /// @inheritdoc IFintroller function getCollateralCeiling(IErc20 collateral) external view override returns (uint256) { return collaterals[collateral].ceiling; } /// @inheritdoc IFintroller function getCollateralRatio(IErc20 collateral) external view override returns (uint256) { return collaterals[collateral].ratio; } /// @inheritdoc IFintroller function getDebtCeiling(IHToken bond) external view override returns (uint256) { return bonds[bond].debtCeiling; } /// @inheritdoc IFintroller function getDepositCollateralAllowed(IErc20 collateral) external view override returns (bool) { if (!collaterals[collateral].isListed) { revert Fintroller__CollateralNotListed(collateral); } return collaterals[collateral].isDepositCollateralAllowed; } /// @inheritdoc IFintroller function getDepositUnderlyingAllowed(IHToken bond) external view override returns (bool) { if (!bonds[bond].isListed) { revert Fintroller__BondNotListed(bond); } return bonds[bond].isDepositUnderlyingAllowed; } /// @inheritdoc IFintroller function getLiquidationIncentive(IErc20 collateral) external view override returns (uint256) { return collaterals[collateral].liquidationIncentive; } /// @inheritdoc IFintroller function getLiquidateBorrowAllowed(IHToken bond) external view override returns (bool) { if (!bonds[bond].isListed) { revert Fintroller__BondNotListed(bond); } return bonds[bond].isLiquidateBorrowAllowed; } /// @inheritdoc IFintroller function getRepayBorrowAllowed(IHToken bond) external view override returns (bool) { if (!bonds[bond].isListed) { revert Fintroller__BondNotListed(bond); } return bonds[bond].isRepayBorrowAllowed; } /// @inheritdoc IFintroller function isBondListed(IHToken bond) external view override returns (bool) { return bonds[bond].isListed; } /// @notice Checks if the collateral is listed. /// @param collateral The collateral to make the check against. /// @return bool true = listed, otherwise not. function isCollateralListed(IErc20 collateral) external view override returns (bool) { return collaterals[collateral].isListed; } /// PUBLIC NON-CONSTANT FUNCTIONS /// /// @inheritdoc IFintroller function listBond(IHToken bond) external override onlyOwner { bonds[bond] = Bond({ debtCeiling: 0, isBorrowAllowed: true, isDepositUnderlyingAllowed: true, isLiquidateBorrowAllowed: true, isListed: true, isRedeemHTokenAllowed: true, isRepayBorrowAllowed: true }); emit ListBond(owner, bond); } /// @inheritdoc IFintroller function listCollateral(IErc20 collateral) external override onlyOwner { // Checks: decimals are between the expected bounds. uint256 decimals = collateral.decimals(); if (decimals == 0) { revert Fintroller__CollateralDecimalsZero(); } if (decimals > 18) { revert Fintroller__CollateralDecimalsOverflow(decimals); } // Effects: update storage. collaterals[collateral] = Collateral({ ceiling: 0, isDepositCollateralAllowed: true, isListed: true, liquidationIncentive: DEFAULT_LIQUIDATION_INCENTIVE, ratio: DEFAULT_COLLATERAL_RATIO }); emit ListCollateral(owner, collateral); } /// @inheritdoc IFintroller function setBorrowAllowed(IHToken bond, bool state) external override onlyOwner { if (!bonds[bond].isListed) { revert Fintroller__BondNotListed(bond); } bonds[bond].isBorrowAllowed = state; emit SetBorrowAllowed(owner, bond, state); } /// @inheritdoc IFintroller function setCollateralCeiling(IHToken collateral, uint256 newCollateralCeiling) external override onlyOwner { // Checks: collateral is listed. if (!collaterals[collateral].isListed) { revert Fintroller__CollateralNotListed(collateral); } // Effects: update storage. uint256 oldCollateralCeiling = collaterals[collateral].ceiling; collaterals[collateral].ceiling = newCollateralCeiling; emit SetCollateralCeiling(owner, collateral, oldCollateralCeiling, newCollateralCeiling); } /// @inheritdoc IFintroller function setCollateralRatio(IErc20 collateral, uint256 newCollateralRatio) external override onlyOwner { // Checks: collateral is listed. if (!collaterals[collateral].isListed) { revert Fintroller__CollateralNotListed(collateral); } // Checks: new collateral ratio is within the accepted bounds. if (newCollateralRatio > COLLATERAL_RATIO_UPPER_BOUND) { revert Fintroller__CollateralRatioOverflow(newCollateralRatio); } if (newCollateralRatio < COLLATERAL_RATIO_LOWER_BOUND) { revert Fintroller__CollateralRatioUnderflow(newCollateralRatio); } // Effects: update storage. uint256 oldCollateralRatio = collaterals[collateral].ratio; collaterals[collateral].ratio = newCollateralRatio; emit SetCollateralRatio(owner, collateral, oldCollateralRatio, newCollateralRatio); } /// @inheritdoc IFintroller function setDebtCeiling(IHToken bond, uint256 newDebtCeiling) external override onlyOwner { // Checks: bond is listed. if (!bonds[bond].isListed) { revert Fintroller__BondNotListed(bond); } // Checks: above total supply of hTokens. uint256 totalSupply = bond.totalSupply(); if (newDebtCeiling < totalSupply) { revert Fintroller__DebtCeilingUnderflow(newDebtCeiling, totalSupply); } // Effects: update storage. uint256 oldDebtCeiling = bonds[bond].debtCeiling; bonds[bond].debtCeiling = newDebtCeiling; emit SetDebtCeiling(owner, bond, oldDebtCeiling, newDebtCeiling); } /// @inheritdoc IFintroller function setDepositCollateralAllowed(IErc20 collateral, bool state) external override onlyOwner { if (!collaterals[collateral].isListed) { revert Fintroller__CollateralNotListed(collateral); } collaterals[collateral].isDepositCollateralAllowed = state; emit SetDepositCollateralAllowed(owner, collateral, state); } /// @inheritdoc IFintroller function setDepositUnderlyingAllowed(IHToken bond, bool state) external override onlyOwner { if (!bonds[bond].isListed) { revert Fintroller__BondNotListed(bond); } bonds[bond].isDepositUnderlyingAllowed = state; emit SetDepositUnderlyingAllowed(owner, bond, state); } /// @inheritdoc IFintroller function setLiquidateBorrowAllowed(IHToken bond, bool state) external override onlyOwner { if (!bonds[bond].isListed) { revert Fintroller__BondNotListed(bond); } bonds[bond].isLiquidateBorrowAllowed = state; emit SetLiquidateBorrowAllowed(owner, bond, state); } /// @inheritdoc IFintroller function setLiquidationIncentive(IErc20 collateral, uint256 newLiquidationIncentive) external override onlyOwner { // Checks: collateral is listed. if (!collaterals[collateral].isListed) { revert Fintroller__CollateralNotListed(collateral); } // Checks: new collateral ratio is within the accepted bounds. if (newLiquidationIncentive > LIQUIDATION_INCENTIVE_UPPER_BOUND) { revert Fintroller__LiquidationIncentiveOverflow(newLiquidationIncentive); } if (newLiquidationIncentive < LIQUIDATION_INCENTIVE_LOWER_BOUND) { revert Fintroller__LiquidationIncentiveUnderflow(newLiquidationIncentive); } // Effects: update storage. uint256 oldLiquidationIncentive = collaterals[collateral].liquidationIncentive; collaterals[collateral].liquidationIncentive = newLiquidationIncentive; emit SetLiquidationIncentive(owner, collateral, oldLiquidationIncentive, newLiquidationIncentive); } /// @inheritdoc IFintroller function setMaxBonds(uint256 newMaxBonds) external override onlyOwner { uint256 oldMaxBonds = maxBonds; maxBonds = newMaxBonds; emit SetMaxBonds(owner, oldMaxBonds, newMaxBonds); } /// @inheritdoc IFintroller function setRepayBorrowAllowed(IHToken bond, bool state) external override onlyOwner { if (!bonds[bond].isListed) { revert Fintroller__BondNotListed(bond); } bonds[bond].isRepayBorrowAllowed = state; emit SetRepayBorrowAllowed(owner, bond, state); } }
@inheritdoc IFintroller
function getLiquidationIncentive(IErc20 collateral) external view override returns (uint256) { return collaterals[collateral].liquidationIncentive; }
6,480,432
pragma solidity ^0.4.24; contract Ownable { address public owner; function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } library SafeMath { function safeMul(uint a, uint b) internal pure returns (uint256) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal pure returns (uint256) { uint c = a / b; return c; } function safeSub(uint a, uint b) internal pure returns (uint256) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal pure returns (uint256) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint256) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint256) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } /** * @title BytesToTypes * @dev The BytesToTypes contract converts the memory byte arrays to the standard solidity types */ contract BytesToTypes { function bytesToAddress(uint _offst, bytes memory _input) internal pure returns (address _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToBool(uint _offst, bytes memory _input) internal pure returns (bool _output) { uint8 x; assembly { x := mload(add(_input, _offst)) } x==0 ? _output = false : _output = true; } function getStringSize(uint _offst, bytes memory _input) internal pure returns(uint size){ assembly{ size := mload(add(_input,_offst)) let chunk_count := add(div(size,32),1) // chunk_count = size/32 + 1 if gt(mod(size,32),0) {// if size%32 > 0 chunk_count := add(chunk_count,1) } size := mul(chunk_count,32)// first 32 bytes reseves for size in strings } } function bytesToString(uint _offst, bytes memory _input, bytes memory _output) internal { uint size = 32; assembly { let loop_index:= 0 let chunk_count size := mload(add(_input,_offst)) chunk_count := add(div(size,32),1) // chunk_count = size/32 + 1 if gt(mod(size,32),0) { chunk_count := add(chunk_count,1) // chunk_count++ } loop: mstore(add(_output,mul(loop_index,32)),mload(add(_input,_offst))) _offst := sub(_offst,32) // _offst -= 32 loop_index := add(loop_index,1) jumpi(loop , lt(loop_index , chunk_count)) } } function slice(bytes _bytes, uint _start, uint _length) internal pure returns (bytes) { require(_bytes.length >= (_start + _length)); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function bytesToBytes32(uint _offst, bytes memory _input) internal pure returns (bytes32 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt8(uint _offst, bytes memory _input) internal pure returns (int8 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt16(uint _offst, bytes memory _input) internal pure returns (int16 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt24(uint _offst, bytes memory _input) internal pure returns (int24 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt32(uint _offst, bytes memory _input) internal pure returns (int32 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt40(uint _offst, bytes memory _input) internal pure returns (int40 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt48(uint _offst, bytes memory _input) internal pure returns (int48 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt56(uint _offst, bytes memory _input) internal pure returns (int56 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt64(uint _offst, bytes memory _input) internal pure returns (int64 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt72(uint _offst, bytes memory _input) internal pure returns (int72 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt80(uint _offst, bytes memory _input) internal pure returns (int80 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt88(uint _offst, bytes memory _input) internal pure returns (int88 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt96(uint _offst, bytes memory _input) internal pure returns (int96 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt104(uint _offst, bytes memory _input) internal pure returns (int104 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt112(uint _offst, bytes memory _input) internal pure returns (int112 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt120(uint _offst, bytes memory _input) internal pure returns (int120 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt128(uint _offst, bytes memory _input) internal pure returns (int128 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt136(uint _offst, bytes memory _input) internal pure returns (int136 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt144(uint _offst, bytes memory _input) internal pure returns (int144 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt152(uint _offst, bytes memory _input) internal pure returns (int152 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt160(uint _offst, bytes memory _input) internal pure returns (int160 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt168(uint _offst, bytes memory _input) internal pure returns (int168 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt176(uint _offst, bytes memory _input) internal pure returns (int176 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt184(uint _offst, bytes memory _input) internal pure returns (int184 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt192(uint _offst, bytes memory _input) internal pure returns (int192 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt200(uint _offst, bytes memory _input) internal pure returns (int200 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt208(uint _offst, bytes memory _input) internal pure returns (int208 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt216(uint _offst, bytes memory _input) internal pure returns (int216 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt224(uint _offst, bytes memory _input) internal pure returns (int224 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt232(uint _offst, bytes memory _input) internal pure returns (int232 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt240(uint _offst, bytes memory _input) internal pure returns (int240 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt248(uint _offst, bytes memory _input) internal pure returns (int248 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToInt256(uint _offst, bytes memory _input) internal pure returns (int256 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint8(uint _offst, bytes memory _input) internal pure returns (uint8 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint16(uint _offst, bytes memory _input) internal pure returns (uint16 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint24(uint _offst, bytes memory _input) internal pure returns (uint24 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint32(uint _offst, bytes memory _input) internal pure returns (uint32 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint40(uint _offst, bytes memory _input) internal pure returns (uint40 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint48(uint _offst, bytes memory _input) internal pure returns (uint48 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint56(uint _offst, bytes memory _input) internal pure returns (uint56 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint64(uint _offst, bytes memory _input) internal pure returns (uint64 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint72(uint _offst, bytes memory _input) internal pure returns (uint72 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint80(uint _offst, bytes memory _input) internal pure returns (uint80 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint88(uint _offst, bytes memory _input) internal pure returns (uint88 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint96(uint _offst, bytes memory _input) internal pure returns (uint96 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint104(uint _offst, bytes memory _input) internal pure returns (uint104 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint112(uint _offst, bytes memory _input) internal pure returns (uint112 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint120(uint _offst, bytes memory _input) internal pure returns (uint120 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint128(uint _offst, bytes memory _input) internal pure returns (uint128 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint136(uint _offst, bytes memory _input) internal pure returns (uint136 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint144(uint _offst, bytes memory _input) internal pure returns (uint144 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint152(uint _offst, bytes memory _input) internal pure returns (uint152 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint160(uint _offst, bytes memory _input) internal pure returns (uint160 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint168(uint _offst, bytes memory _input) internal pure returns (uint168 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint176(uint _offst, bytes memory _input) internal pure returns (uint176 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint184(uint _offst, bytes memory _input) internal pure returns (uint184 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint192(uint _offst, bytes memory _input) internal pure returns (uint192 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint200(uint _offst, bytes memory _input) internal pure returns (uint200 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint208(uint _offst, bytes memory _input) internal pure returns (uint208 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint216(uint _offst, bytes memory _input) internal pure returns (uint216 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint224(uint _offst, bytes memory _input) internal pure returns (uint224 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint232(uint _offst, bytes memory _input) internal pure returns (uint232 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint240(uint _offst, bytes memory _input) internal pure returns (uint240 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint248(uint _offst, bytes memory _input) internal pure returns (uint248 _output) { assembly { _output := mload(add(_input, _offst)) } } function bytesToUint256(uint _offst, bytes memory _input) internal pure returns (uint256 _output) { assembly { _output := mload(add(_input, _offst)) } } } interface ITradeable { /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) external view returns (uint balance); /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint _value) external returns (bool success); /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint _value) external returns (bool success); /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint _value) external returns (bool success); /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) external view returns (uint remaining); } contract ITrader { function getDataLength( ) public pure returns (uint256); function getProtocol( ) public pure returns (uint8); function getAvailableVolume( bytes orderData ) public view returns(uint); function isExpired( bytes orderData ) public view returns (bool); function trade( bool isSell, bytes orderData, uint volume, uint volumeEth ) public; function getFillVolumes( bool isSell, bytes orderData, uint volume, uint volumeEth ) public view returns(uint, uint); } contract ITraders { /// @dev Add a valid trader address. Only owner. function addTrader(uint8 id, ITrader trader) public; /// @dev Remove a trader address. Only owner. function removeTrader(uint8 id) public; /// @dev Get trader by id. function getTrader(uint8 id) public view returns(ITrader); /// @dev Check if an address is a valid trader. function isValidTraderAddress(address addr) public view returns(bool); } contract Members is Ownable { mapping(address => bool) public members; // Mappings of addresses of allowed addresses modifier onlyMembers() { require(isValidMember(msg.sender)); _; } /// @dev Check if an address is a valid member. function isValidMember(address _member) public view returns(bool) { return members[_member]; } /// @dev Add a valid member address. Only owner. function addMember(address _member) public onlyOwner { members[_member] = true; } /// @dev Remove a member address. Only owner. function removeMember(address _member) public onlyOwner { delete members[_member]; } } contract ZodiacERC20 is Ownable, BytesToTypes { ITraders public traders; // Smart contract that hold the list of valid traders bool public tradingEnabled; // Switch to enable or disable the contract uint feePercentage; event Sell( address account, address destinationAddr, address traedeable, uint volume, uint volumeEth, uint volumeEffective, uint volumeEthEffective ); event Buy( address account, address destinationAddr, address traedeable, uint volume, uint volumeEth, uint volumeEffective, uint volumeEthEffective ); function ZodiacERC20(ITraders _traders, uint _feePercentage) public { traders = _traders; tradingEnabled = true; feePercentage = _feePercentage; } /// @dev Only accepts payment from smart contract traders. function() public payable { // require(traders.isValidTraderAddress(msg.sender)); } function changeFeePercentage(uint _feePercentage) public onlyOwner { feePercentage = _feePercentage; } /// @dev Setter for traders smart contract (Only owner) function changeTraders(ITraders _traders) public onlyOwner { traders = _traders; } /// @dev Enable/Disable trading with smart contract (Only owner) function changeTradingEnabled(bool enabled) public onlyOwner { tradingEnabled = enabled; } /// @dev Buy a token. function buy( ITradeable tradeable, uint volume, bytes ordersData, address destinationAddr, address affiliate ) external payable { require(tradingEnabled); // Execute the trade (at most fullfilling volume) trade( false, tradeable, volume, ordersData, affiliate ); // Since our balance before trade was 0. What we bought is our current balance. uint volumeEffective = tradeable.balanceOf(this); // We make sure that something was traded require(volumeEffective > 0); // Used ethers are: balance_before - balance_after. // And since before call balance=0; then balance_before = msg.value uint volumeEthEffective = SafeMath.safeSub(msg.value, address(this).balance); // IMPORTANT: Check that: effective_price <= agreed_price (guarantee a good deal for the buyer) require( SafeMath.safeDiv(volumeEthEffective, volumeEffective) <= SafeMath.safeDiv(msg.value, volume) ); // Return remaining ethers if(address(this).balance > 0) { destinationAddr.transfer(address(this).balance); } // Send the tokens transferTradeable(tradeable, destinationAddr, volumeEffective); emit Buy(msg.sender, destinationAddr, tradeable, volume, msg.value, volumeEffective, volumeEthEffective); } /// @dev sell a token. function sell( ITradeable tradeable, uint volume, uint volumeEth, bytes ordersData, address destinationAddr, address affiliate ) external { require(tradingEnabled); // We transfer to ouselves the user's trading volume, to operate on it // note: Our balance is 0 before this require(tradeable.transferFrom(msg.sender, this, volume)); // Execute the trade (at most fullfilling volume) trade( true, tradeable, volume, ordersData, affiliate ); // Check how much we traded. Our balance = volume - tradedVolume // then: tradedVolume = volume - balance uint volumeEffective = SafeMath.safeSub(volume, tradeable.balanceOf(this)); // We make sure that something was traded require(volumeEffective > 0); // Collects service fee uint volumeEthEffective = collectSellFee(); // IMPORTANT: Check that: effective_price >= agreed_price (guarantee a good deal for the seller) require( SafeMath.safeDiv(volumeEthEffective, volumeEffective) >= SafeMath.safeDiv(volumeEth, volume) ); // Return remaining volume if (volumeEffective < volume) { transferTradeable(tradeable, destinationAddr, SafeMath.safeSub(volume, volumeEffective)); } // Send ethers obtained destinationAddr.transfer(volumeEthEffective); emit Sell(msg.sender, destinationAddr, tradeable, volume, volumeEth, volumeEffective, volumeEthEffective); } /// @dev Trade buy or sell orders. function trade( bool isSell, ITradeable tradeable, uint volume, bytes ordersData, address affiliate ) internal { uint remainingVolume = volume; uint offset = ordersData.length; while(offset > 0 && remainingVolume > 0) { //Get the trader uint8 protocolId = bytesToUint8(offset, ordersData); ITrader trader = traders.getTrader(protocolId); require(trader != address(0)); //Get the order data uint dataLength = trader.getDataLength(); offset = SafeMath.safeSub(offset, dataLength); bytes memory orderData = slice(ordersData, offset, dataLength); //Fill order remainingVolume = fillOrder( isSell, tradeable, trader, remainingVolume, orderData, affiliate ); } } /// @dev Fills a buy order. function fillOrder( bool isSell, ITradeable tradeable, ITrader trader, uint remaining, bytes memory orderData, address affiliate ) internal returns(uint) { //Checks that there is enoughh amount to execute the trade uint volume; uint volumeEth; (volume, volumeEth) = trader.getFillVolumes( isSell, orderData, remaining, address(this).balance ); if(volume > 0) { if(isSell) { //Approve available amount of token to trader require(tradeable.approve(trader, volume)); } else { //Collects service fee //TODO: transfer fees after all iteration //volumeEth = collectBuyFee(volumeEth, affiliate); volumeEth = collectFee(volumeEth); address(trader).transfer(volumeEth); } //Call trader to trade orders trader.trade( isSell, orderData, volume, volumeEth ); } return SafeMath.safeSub(remaining, volume); } /// @dev Transfer tradeables to user account. function transferTradeable(ITradeable tradeable, address account, uint amount) internal { require(tradeable.transfer(account, amount)); } // @dev Collect service/affiliate fee for a buy function collectFee(uint ethers) internal returns(uint) { uint fee = SafeMath.safeMul(ethers, feePercentage) / (1 ether); owner.transfer(fee); uint remaining = SafeMath.safeSub(ethers, fee); return remaining; } // @dev Collect service/affiliate fee for a sell function collectSellFee() internal returns(uint) { uint fee = SafeMath.safeMul(address(this).balance, feePercentage) / (1 ether); owner.transfer(fee); return address(this).balance; } }
Buy a token. Execute the trade (at most fullfilling volume) Since our balance before trade was 0. What we bought is our current balance. We make sure that something was traded Used ethers are: balance_before - balance_after. And since before call balance=0; then balance_before = msg.value IMPORTANT: Check that: effective_price <= agreed_price (guarantee a good deal for the buyer) Return remaining ethers
function buy( ITradeable tradeable, uint volume, bytes ordersData, address destinationAddr, address affiliate ) external payable { require(tradingEnabled); trade( false, tradeable, volume, ordersData, affiliate ); uint volumeEffective = tradeable.balanceOf(this); require(volumeEffective > 0); uint volumeEthEffective = SafeMath.safeSub(msg.value, address(this).balance); require( SafeMath.safeDiv(volumeEthEffective, volumeEffective) <= SafeMath.safeDiv(msg.value, volume) ); if(address(this).balance > 0) { destinationAddr.transfer(address(this).balance); } emit Buy(msg.sender, destinationAddr, tradeable, volume, msg.value, volumeEffective, volumeEthEffective); }
972,175
./full_match/80001/0x71ac01342909DFb970E536EB8bB0DDA41C65F345/sources/src/YAGMIController.sol
If number of payment out of range, return 0 Calculate original base payment Check if there has been changes in the supply of the tokens that lower the debt If payed more or equal than is owed, return 0 If it is the last payment, return total - payed to avoid rounding errors If debt left is less than a base payment, return only debt
function _baseOwed( uint256 tokenId, uint256 price, uint32 maxSupply, uint16 payment, uint16 paymentsDone, uint16 numberOfPayments ) internal view returns (uint256) { if (payment <= paymentsDone || payment > numberOfPayments) return 0; uint256 basePay = (price * maxSupply) / numberOfPayments; uint256 totalBaseReturned = basePay * paymentsDone; uint256 tokensLeft = yagmi.totalSupply(tokenId); uint256 loanedBaseLeft = tokensLeft * price; if (totalBaseReturned >= loanedBaseLeft) return 0; if (payment == numberOfPayments) return loanedBaseLeft - totalBaseReturned; if (loanedBaseLeft - totalBaseReturned < basePay) return loanedBaseLeft - totalBaseReturned; return basePay; }
853,416
./partial_match/3/0xa51190143d4e9bcB0495b7443Ec50520ac3CFA97/sources/PLMT3.sol
------------------------------------------------------------------------ Owner can transfer out any accidentally sent ERC20 tokens ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); }
5,337,964
pragma solidity ^0.5.7; // Voken Team Fund // Freezed till 2021-06-30 23:59:59, (timestamp 1625039999). // Release 10% per 3 months. // // More info: // https://vision.network // https://voken.io // // Contact us: // [email protected] // [email protected] /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error. */ library SafeMath { /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); 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) { assert(b <= a); return a - b; } /** * @dev Multiplies two unsigned integers, reverts 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 unsigned integers truncating the quotient, * reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { assert(b > 0); uint256 c = a / b; assert(a == b * c + a % b); return a / b; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Ownable */ contract Ownable { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract * to the sender account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == _owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) external onlyOwner { require(newOwner != address(0)); _owner = newOwner; emit OwnershipTransferred(_owner, newOwner); } /** * @dev Withdraw Ether */ function withdrawEther(address payable to, uint256 amount) external onlyOwner { require(to != address(0)); uint256 balance = address(this).balance; require(balance >= amount); to.transfer(amount); } } /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20{ function balanceOf(address owner) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); } /** * @title Voken Team Fund */ contract VokenTeamFund is Ownable{ using SafeMath for uint256; IERC20 public VOKEN; uint256 private _till = 1625039999; uint256 private _vokenAmount = 4200000000000000; // 4.2 billion uint256 private _3mo = 2592000; // Three months: 2,592,000 seconds uint256[10] private _freezedPct = [ 100, // 100% 90, // 90% 80, // 80% 70, // 70% 60, // 60% 50, // 50% 40, // 40% 30, // 30% 20, // 20% 10 // 10% ]; event Donate(address indexed account, uint256 amount); /** * @dev constructor */ constructor() public { VOKEN = IERC20(0x82070415FEe803f94Ce5617Be1878503e58F0a6a); } /** * @dev Voken freezed amount. */ function vokenFreezed() public view returns (uint256) { uint256 __freezed; if (now > _till) { uint256 __qrPassed = now.sub(_till).div(_3mo); if (__qrPassed >= 10) { __freezed = 0; } else { __freezed = _vokenAmount.mul(_freezedPct[__qrPassed]).div(100); } return __freezed; } return _vokenAmount; } /** * @dev Donate */ function () external payable { emit Donate(msg.sender, msg.value); } /** * @dev transfer Voken */ function transferVoken(address to, uint256 amount) external onlyOwner { uint256 __freezed = vokenFreezed(); uint256 __released = VOKEN.balanceOf(address(this)).sub(__freezed); require(__released >= amount); assert(VOKEN.transfer(to, amount)); } /** * @dev Rescue compatible ERC20 Token, except "Voken" * * @param tokenAddr ERC20 The address of the ERC20 token contract * @param receiver The address of the receiver * @param amount uint256 */ function rescueTokens(address tokenAddr, address receiver, uint256 amount) external onlyOwner { IERC20 _token = IERC20(tokenAddr); require(VOKEN != _token); require(receiver != address(0)); uint256 balance = _token.balanceOf(address(this)); require(balance >= amount); assert(_token.transfer(receiver, amount)); } }
transfer Voken/
function transferVoken(address to, uint256 amount) external onlyOwner { uint256 __freezed = vokenFreezed(); uint256 __released = VOKEN.balanceOf(address(this)).sub(__freezed); require(__released >= amount); assert(VOKEN.transfer(to, amount)); }
12,651,338
./full_match/5/0xF126A8227E92CAEE3455bF9889CB4Acb7FEDB675/sources/contracts/contracts-v10/contracts/Libraries.sol
Write Functions Project Creation Function ✅ Populate task
function makeTask( Task storage _task, uint256 _id, string memory _metadata, uint256 weight, uint256 _deadline, uint256 _parentProjectID ) external { require(_deadline > block.timestamp, "E38"); _task.id = _id; _task.metadata = _metadata; _task.weight = weight; _task.paid = false; _task.creationTime = block.timestamp; _task.deadline = _deadline; _task.parentProject = _parentProjectID; }
11,602,149
pragma solidity ^0.4.22; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0;} uint256 c = a * b; assert(c / a == b); return c;} function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c;} function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b;} function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c;} } contract Blueprint { //passed in from BlueprintFactory, these parameters can't be changed once blueprint is deployed, even if admin changes these parameters in BlueprintFactory uint256 public creatorID; uint256 public blueprintID; address public oracleAddress; uint256 public purchasePrice; uint256 public creationPrice; RublixToken public rblxToken; //generated in BlueprintFactory from transaction submitted by creator address public source; //BlueprintFactory address address public creatorAddress; uint public creationTimestamp; //specified by creator when submitting transaction string public ticker; uint256 internal entryTkrPrice; uint256 internal exitTkrPrice; uint public expirationTimestamp; //states calculated internally enum predictionStates{unconfirmed, entryMet, confirmedTrue, confirmedFalse} predictionStates predictionState; //determine if the blueprint is taking a short position or long position on the specified ticker bool internal short; //only the oracle address that was specified by the BlueprintFactory can set these values uint256 internal periodHigh; uint internal highTimestamp; uint256 internal periodLow; uint internal lowTimestamp; //NOTE*: these can be used to gauge how close a blueprint actually was to being true //define class of buyers and map it addresses to quickly verify buyer stakes and refunds, as well as their chronological spot in buyer lineup for this blueprint struct buyer { address buyerAddress; uint256 amountStaked; uint256 amountRefunded; } //access buyers by buyerID mapping (uint256 => buyer) public buyers; //access buyer ID from an address mapping (address => uint256) public buyerID; //keeps track of total number of buyers of this blueprint uint256 public lastBuyerID; //can specify the number of buyers that get a fraction of the creationPrice staked by the creator if the blueprint is confirmedFalse uint256 constant N_SHORT_POSITIONS = 10; //if a buyer is one of the first to purchase this prediction and the prediction is determined to be false, they get a bonus refunded to them uint256 private buyerShortReward; //actual prices of asset during active time period to determine if prediction is true or not //temp variables uint256 buyerID_; uint256 refund_; //event that is emitted when prediction move from one state and into a new one //both old and new states are emitted in order to allow for verification of blueprint authenticity event StateChange(predictionStates Previous, predictionStates New); event RefundClaimed(address receipiant, address blueprint, uint256 amountRefunded); event BlueprintEmptied(address blueprint, uint256 amount); constructor (address _creatorAddress, uint256 _creatorID, uint256 _blueprintID, uint256 _purchasePrice, uint256 _creationPrice, string _ticker, uint256 _entryTkrPrice, uint256 _exitTkrPrice, uint _creationTimestamp, uint _expirationTimestamp, address _oracleAddress, RublixToken _rblxToken) public { //can't make a prediction of a 0% market move require (_entryTkrPrice != _exitTkrPrice); //can't make a prediction of previous market activity require (_expirationTimestamp > now); //NOTE1: these checks are performed in BlueprintFactory when createBlueprint function is called, so this might just be redundant with no upside //passed in by BlueprintFactory creationTimestamp = _creationTimestamp; source = msg.sender; creatorAddress = _creatorAddress; creatorID = _creatorID; blueprintID = _blueprintID; //the only address that can confirm a prediction state change and transfer RBLX to creator if true oracleAddress = _oracleAddress; //amount of RBLX required to have created the blueprint and to view it purchasePrice = _purchasePrice; creationPrice = _creationPrice; //token that is utilized for this blueprint market rblxToken = _rblxToken; //calculate the reward a buyer gets if they are among the first to buy it and the blueprint is confirmedFalse buyerShortReward = _creationPrice/N_SHORT_POSITIONS; //passed in directly by creator ticker = _ticker; entryTkrPrice = _entryTkrPrice; exitTkrPrice = _exitTkrPrice; expirationTimestamp = _expirationTimestamp; //iniate blueprint internal states predictionState = predictionStates.unconfirmed; lastBuyerID = 0; //determine if the blueprint is taking a short or long position on the ticker if (_exitTkrPrice > _entryTkrPrice) { short = false; } else { short = true; } } function addBuyer (address _buyerAddress) public { //temp ID variable buyerID_ = lastBuyerID + 1; //buyers are recorded for refund-claiming and viewing access only if they buy the blueprint through BlueprintFactory require (msg.sender == source); //can't by purchase blueprint if it expired, see NOTE1 for similar redudancy issue require (expirationTimestamp > now); //buyer can only purchase blueprint once require (buyers[buyerID_].amountStaked == 0); //record how much was paid and initalize refund amount to 0 buyers[buyerID_].buyerAddress = _buyerAddress; buyers[buyerID_].amountStaked = purchasePrice; buyers[buyerID_].amountRefunded = 0; //keep track of each address's id number buyerID[_buyerAddress] = buyerID_; lastBuyerID = buyerID_; } function refundPurchase () public { //temp ID variable buyerID_ = lastBuyerID + 1; //refunds can only be claimed after oracle address has determine that the blueprint has expired and did not meet entryTkrPrice and/or exitTkrPrice require (predictionState == predictionStates.confirmedFalse); //check if msg.sender has bought the blueprint through BlueprintFactory require (buyers[buyerID_].amountStaked != 0); //check that the msg.sender has not obtained a refund already require (buyers[buyerID_].amountRefunded == 0); //base refund amount for the msg.sender, equal to the amount they bought the blueprint for refund_ = buyers[buyerID_].amountStaked; //if the buyer was one of the first N to buy the prediction and it didn't come true, they can receive a bonus paid from the amount staked by the creator if (buyerID_ <= N_SHORT_POSITIONS) { refund_ += buyerShortReward; } //record how much the buyer was able to refund... buyers[buyerID_].amountRefunded = refund_; //...then transfer those tokens to buyer rblxToken.transfer(msg.sender, refund_); emit RefundClaimed(msg.sender, this, refund_); } function viewPrediction () public returns (uint256 entryTkrPrice_, uint256 exitTkrPrice_) { buyerID_ = buyerID[msg.sender]; //the msg.sender must have staked RBLX tokens through BlueprintFactory in order to call this function, OR //the expiration has passed (similarly to NOTE1, an if statement might be a better alternative the require statement to check expiration date), OR //the blueprint was verified to be true before it expired require ((buyers[buyerID_].amountStaked != 0) || (now > expirationTimestamp) || (predictionState == predictionStates.confirmedTrue)); //entryTkrPrice and exitTkrPrice are set as internal variables in this contract, readily accessible only through this function return (entryTkrPrice, exitTkrPrice); } //ORACLE ONLY FUNCTIONS BELOW------------------------------------------------------------------------------------------------------ function confirmPrediction (uint256 _periodHigh, uint _highTimestamp, uint256 _periodLow, uint _lowTimestamp) public { //check if specified oracle is msg.sender require (msg.sender == oracleAddress); //make sure states can't be updated after a blueprint is confirmed to be true or false require (predictionState != predictionStates.confirmedTrue); require (predictionState != predictionStates.confirmedFalse); //double checking to sure the numbers provided by oracle are within the contracts active periods require (expirationTimestamp > _highTimestamp); require (expirationTimestamp > _lowTimestamp); require (_highTimestamp > creationTimestamp); require (_lowTimestamp > creationTimestamp); //if the state is unconfirmed, check if the entryTkrPrice was met if (predictionState == predictionStates.unconfirmed) { //record the price point that potentially meets entryTkrPrice if (short == false) { periodLow = _periodLow; lowTimestamp = _lowTimestamp; } else { periodHigh = _periodHigh; highTimestamp = _highTimestamp; } //check if the price point does in fact meet the entryTkrPrice checkEntry(_periodHigh, _periodLow); } //if the entryTkrPrice was met, check if the exitTkrPrice was met /after/ the entryTkrPrice was met if (predictionState == predictionStates.entryMet) { //record the price point that potentially meets exitTkrPrice... //only if the corresponding timestamp is greater then the timestamp corresponding to price event that where entryTkrPrice was met if ((short == false) && (_highTimestamp > lowTimestamp)) { periodHigh = _periodHigh; highTimestamp = _highTimestamp; } else if ((short == true) && (_lowTimestamp > highTimestamp)) { periodHigh = _periodHigh; highTimestamp = _highTimestamp; } else { //return before checking if exitTkrPrice is met if the timestamps are not in the proper order return; } //check if the price point does in fact meet the exitTkrPrice //only if the corresponding timestamps are in the right order as specified above checkExit(_periodHigh, _periodLow); } //if the exitTkrPrice was met after the entryTkrPrice was met, then transfer all staked RBLX tokens to creator //this if statement can only ever be ran once since after exiting the function with a confirmed prediction state, the function can't be called again if (predictionState == predictionStates.confirmedTrue) { rblxToken.transfer(creatorAddress, rblxToken.balanceOf(this)); } //if expiration time has passed and the contract is still not confirmed to be true by the functions above, then declare the prediction is confirmedFalse if ((now > expirationTimestamp) && (predictionState != predictionStates.confirmedTrue)){ emit StateChange(predictionState, predictionStates.confirmedFalse); predictionState = predictionStates.confirmedFalse; } } //internal function that can be called only by the confirmedPrediction function function checkEntry (uint256 _periodHigh, uint256 _periodLow) internal { //double check that the predictionState is still unconfirmed, require (predictionState == predictionStates.unconfirmed); //NOTE2: this might just be redundant with no upside, already check in confirmedPrediction function //if the blueprint is taking a long position, check if the low is below entryTkrPrice, OR //if the blueprint is taking a short position, check if the high is above the entryTkrPrice if (((!short) && (entryTkrPrice >= _periodLow)) || ((short == true) && (_periodHigh >= entryTkrPrice))) { //change states from previous state (should be unconfirmed) to entryMet, create an event with previous and new states emit StateChange(predictionState, predictionStates.entryMet); predictionState = predictionStates.entryMet; } } //internal function that can be called only by the confirmedPrediction function function checkExit (uint256 _periodHigh, uint256 _periodLow) internal { //double check that the prediction has met entryTkrPrice but hasn't been verified if exitTkrPrice was met require (predictionState == predictionStates.entryMet); //see NOTE2 for similar potential redudancy issue //if the blueprint is taking a long position, check if the high is above exitTkrPrice, OR //if the blueprint is taking a short position, check if the low is below the exitTkrPrice if (((short == false) && (_periodHigh >= exitTkrPrice)) || ((short == true) && (exitTkrPrice >= _periodLow))) { //change states from previous state (should be entryMet) to confirmedTrue (both entry and exit are met) //create an event with previous and new states emit StateChange(predictionState, predictionStates.confirmedTrue); predictionState = predictionStates.entryMet; } } //this function should be called after blueprint expired for a while to allow buyers to refund their purchases function emptyUnclaimedTokens() public { require (msg.sender == oracleAddress); //make sure the blueprint expired require (now > expirationTimestamp); //NOTE3: can add a buffer for refunding purchases by using: require(now > (expirationTimestamp + mult((expirationTimestamp-now),PERCENT_OF_ACTIVE_PERIOD_AS_REFUND_BUFFER))) //transfer all remaining tokens in blueprint contract to oracle address emit BlueprintEmptied(this, rblxToken.balanceOf(this)); rblxToken.transfer(oracleAddress, rblxToken.balanceOf(this)); } } //----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- contract BlueprintFactory { //admin can change blueprint purchase price, blueprint creation price, and add update valid userID-walletAddress list address public admin; //oracle is only address that can update the prediction status of a blueprint and empty it out from unclaimed tokens address public rblxOracleAddress; //set at creation but can be changed by admin uint256 public creationPrice; uint256 public purchasePrice; RublixToken public rblxToken; //internal counters that start at 0 increments before a new ID is assigned (ie the first ID will be 1, second ID will be 2, etc.) //also keeps track of number of created blueprints and validated users uint256 internal lastBlueprintID; uint256 internal lastUserID; //structure used in blueprint structure to keep track of the creator and buyers of the blueprint and how much they have/had staked in that particular blueprint struct userStk{ uint256 userID; address userAddress; uint256 amountStaked; } //BlueprintFactory stores meta-data of each blueprint it creates, but not the actual predicted values struct blueprint{ address blueprintAddress; //set by BlueprintFactory uint creationTimestamp; address oracle; //NOTE4: once oracle is defined for a blueprint, only that address can transfer RBLX out of contract, even if rblxOracleAddress is changed in BlueprintFactory //set by creator string ticker; uint expirationTimestamp; //each blueprint has one creator with userAddress, userID, and amountStaked //this role and ownership cannot transfer to another user after being initalized userStk creator; //internal counter that starts at 0 and increments before a new ID is assigned uint256 lastBuyerID; //NOTE5: purchases (and creations) of blueprints occurs exclusivly through the BlueprintFactory contract //NOTE5: withdrawls, refunds, and deposits occur directly from interacting with the blueprint contract itself //NOTE5: therefore BlueprintFactory doesn't keep track of those occurances directly //map buyers by a buyerID unique to each blueprint, buyerID also keeps track of the sequential order in which each buyer purchases the blueprint mapping (uint256 => userStk) buyers; } //array of blueprints referenced by blueprintID //this allows a third party to query all blueprints without prior knowledge of blueprint addresses mapping (uint256 => blueprint) HedgeBlueprint; //BlueprintFactory stores meta-data of each user that is validated for ranking purposes, but not the actual performance of their blueprints directly, see NOTE5 for clarifications struct user{ address userAddress; //track total amount of RBLX spent on hedge platform, as well as number of blueprints created and purchased uint256 totalAmountSpent; uint256 noOfBlueprintsCreated; uint256 noOfBlueprintsPurchased; } //array of users referenced by userID //this allows a third party to query all blueprints without prior knowledge of user addresses mapping(uint256 => user) HedgeUser; //allow a reverse lookup on ID from address mapping (address => uint256) public userID; mapping (address => uint256) public blueprintID; //temp variables uint256 creatorUserID_; uint256 buyerUserID_; uint256 blueprintID_; uint256 buyerID_; uint256 userID_; //events emitted every time a creation or purchase is made, ie any time a transfer of RBLX into a blueprint is made //events to indicate prediction resolution, expiration, or refund of a blueprint have to exist in the blueprint contract itself, see NOTE5 for clarifications event BlueprintCreated(address creator, address blueprint); event BlueprintPurchased(address buyer, address blueprint); constructor (address _rblxTokenAddress, address _rblxOracleAddress, uint256 _creationPrice, uint256 _purchasePrice) public { //admin account is creator of BlueprintFactory, currently there is no functionality for transfer of ownership admin = msg.sender; //NOTE6: possible upside of functionality doesn't really justify possible security concerns over transfering ownership of admin role //specify deployed/minted token, this can be hard coded after we determine which network we're deploying on rblxToken = RublixToken(_rblxTokenAddress); //specify the only account that can resolve blueprint prediction states and transfer RBLX tokens from a blueprint contract to buyer, creator, or fee collection //admin can change address of oracle to be used for blueprints created thereafter, see NOTE5 for clarifications rblxOracleAddress = _rblxOracleAddress; //admin can change these values after being BlueprintFactory is deployed, but will only affect blueprints created after the change, see ntoe5 for clarifications purchasePrice = _purchasePrice; creationPrice = _creationPrice; //NOTE7: currently these prices are fixed, but in near future, there will be a degree of flexibility to price amount to account for creator rank, no of buyers, etc. //initialize blueprintID and userID lastBlueprintID = 0; lastUserID = 0; } //function called by user that wants to create a contract, however the user must be validated by admin before they can call this function //the user must have also approved BlueprintFactory for spending RBLX on their behalf of an amount greater than the cost of creating a blueprint function createBlueprint (string _ticker, uint256 _entryTkrPrice, uint256 _exitTkrPrice, uint _expirationTimestamp) public payable { //can't create a blueprint that predicts a 0% market shift require (_entryTkrPrice != _exitTkrPrice); //can't create a blueprint that predicts prior market activity require (_expirationTimestamp > now); //can't create a blueprint if creator has not been validated by admin require (userID[msg.sender] > 0); //NOTE8: admin can revoke this validation, which reverses the sign of their ID //NOTE8: this is to allow easy tracking of unvalidated user activity while they were active and to allow admin to easily revalidate the user with their original ID //NOTE8: ex. if previous userID is 5, after unvalidation, their userID becomes -5, and after revalidation, their userID is reset to 5 //temp ID variables creatorUserID_ = userID[msg.sender]; blueprintID_ = lastBlueprintID + 1; //a new instance of a blueprint contract (code specified above) is created with parameters passed in by both user and by BlueprintFactory Blueprint blueprint_ = new Blueprint(msg.sender, creatorUserID_, blueprintID_, purchasePrice, creationPrice, _ticker, _entryTkrPrice, _exitTkrPrice, now, _expirationTimestamp, rblxOracleAddress, rblxToken); //transfer tokens from creator address to the contract they just created, rblxToken.transferFrom(msg.sender, address(blueprint_), creationPrice); //NOTE9:this requires the creator to approve spending by BlueprintFactory on their behalf before creating (or purchasing) anything on Hedge //update metadata of user list HedgeUser[creatorUserID_].totalAmountSpent += creationPrice; HedgeUser[creatorUserID_].noOfBlueprintsCreated += 1; //update metadata of blueprint list HedgeBlueprint[blueprintID_].ticker = _ticker; HedgeBlueprint[blueprintID_].expirationTimestamp = _expirationTimestamp; HedgeBlueprint[blueprintID_].creationTimestamp = now; HedgeBlueprint[blueprintID_].blueprintAddress = address(blueprint_); HedgeBlueprint[blueprintID_].lastBuyerID = 0; HedgeBlueprint[blueprintID_].creator.userID = creatorUserID_; HedgeBlueprint[blueprintID_].creator.userAddress = msg.sender; HedgeBlueprint[blueprintID_].creator.amountStaked = creationPrice; blueprintID[address(blueprint_)] = blueprintID_; //update last blueprintID lastBlueprintID = blueprintID_; emit BlueprintCreated(msg.sender, address(blueprint_)); } function purchaseBlueprint (address _blueprintAddress) public payable { //access deployed blueprint contract at specified address Blueprint blueprint_ = Blueprint(_blueprintAddress); //can't purchase blueprint if the prediction expiration date has passed require (blueprint_.expirationTimestamp() > now); //can't purchase a blueprint if user has not been validated by admin require (userID[msg.sender] > 0); //see NOTE8 //temp ID variables buyerUserID_ = userID[msg.sender]; buyerID_ = HedgeBlueprint[blueprintID_].lastBuyerID + 1; //transfer tokens from buyer address to contract they want to purchase rblxToken.transferFrom(msg.sender, _blueprintAddress, blueprint_.purchasePrice()); //see NOTE9 //call function in blueprint that updates it's internal buyers list blueprint_.addBuyer(msg.sender); //update metadata of user list HedgeUser[buyerUserID_].totalAmountSpent += purchasePrice; HedgeUser[buyerUserID_].noOfBlueprintsPurchased += 1; //update metadata of blueprint list HedgeBlueprint[blueprintID_].buyers[buyerID_].userID = buyerUserID_; HedgeBlueprint[blueprintID_].buyers[buyerID_].userAddress = msg.sender; HedgeBlueprint[blueprintID_].buyers[buyerID_].amountStaked = blueprint_.purchasePrice(); //update last buyerID HedgeBlueprint[blueprintID_].lastBuyerID = buyerID_; emit BlueprintPurchased(msg.sender, _blueprintAddress); } //function for a third party to access user metadata function lookupUserMeta (uint256 _userID) public view returns (address userAddress, uint256 totalAmountSpent, uint256 noOfBlueprintsCreated, uint256 noOfBlueprintsPurchased) { return (HedgeUser[_userID].userAddress, HedgeUser[_userID].totalAmountSpent, HedgeUser[_userID].noOfBlueprintsCreated, HedgeUser[_userID].noOfBlueprintsPurchased); } //function for a third party to access blueprint metadata function lookupBlueprintMeta (uint256 _blueprintID) public view returns (string ticker, uint creationTimestamp, uint expirationTimestamp, address blueprintAddress, uint256 creatorID, address creatorAddress, uint256 noOfBuyers) { return (HedgeBlueprint[_blueprintID].ticker, HedgeBlueprint[_blueprintID].creationTimestamp, HedgeBlueprint[_blueprintID].expirationTimestamp, HedgeBlueprint[_blueprintID].blueprintAddress, HedgeBlueprint[_blueprintID].creator.userID, HedgeBlueprint[_blueprintID].creator.userAddress, HedgeBlueprint[_blueprintID].lastBuyerID); } //ADMIN ONLY FUNCTIONS BELOW------------------------------------------------------------------------------------------------------ //admin needs to validate a user before they can create or purchase a blueprint on Hedge, see NOTE8 //can apply validations in batches to save gas and time function addValidatedUsers (address[] _walletAddresses) public { require (msg.sender == admin); for(uint256 i = 0; i < _walletAddresses.length; i++ ) { require (userID[_walletAddresses[i]] == 0); userID_ = lastUserID + 1; userID[_walletAddresses[i]] = userID_; HedgeUser[userID_].userAddress = _walletAddresses[i]; lastUserID = userID_; } } //removing a user from the validated user list changes their ID from positive to negative, but the scalar value remains the same //this maintains a record of all users and their original IDs after being unvalidated to prevent/identify tampering function removeValidatedUsers (address[] _walletAddresses) public { require (msg.sender == admin); for(uint256 i = 0; i < _walletAddresses.length; i++ ) { require (userID[_walletAddresses[i]] > 0); //users removed from the validated user list will still have their ID number, but the sign changed to ensure immutability userID[_walletAddresses[i]] = -userID[_walletAddresses[i]]; } } //in case an error occurs and a user is accidently removed from validated user list, they can be revalidated with their old ID function reValidateUsers (address[] _walletAddresses) public { require (msg.sender == admin); for(uint256 i = 0; i < _walletAddresses.length; i++ ) { require (userID[_walletAddresses[i]] < 0); //users removed from the validated user list will still have their ID number, but the sign changed to ensure immutability userID[_walletAddresses[i]] = -userID[_walletAddresses[i]]; } } //functions to change global parameters in BlueprintFactory after deployment function changePurchasePrice (uint256 _purchasePrice) public { require (msg.sender == admin); purchasePrice = _purchasePrice; } function changeCreationPrice (uint256 _creationPrice) public { require (msg.sender == admin); creationPrice = _creationPrice; } function changeOracleAddress (address _rblxOracleAddress) public { require (msg.sender == admin); rblxOracleAddress = _rblxOracleAddress; } }
internal function that can be called only by the confirmedPrediction functiondouble check that the prediction has met entryTkrPrice but hasn't been verified if exitTkrPrice was metsee NOTE2 for similar potential redudancy issueif the blueprint is taking a long position, check if the high is above exitTkrPrice, ORif the blueprint is taking a short position, check if the low is below the exitTkrPricechange states from previous state (should be entryMet) to confirmedTrue (both entry and exit are met)create an event with previous and new states
function checkExit (uint256 _periodHigh, uint256 _periodLow) internal { require (predictionState == predictionStates.entryMet); if (((short == false) && (_periodHigh >= exitTkrPrice)) || ((short == true) && (exitTkrPrice >= _periodLow))) { emit StateChange(predictionState, predictionStates.confirmedTrue); predictionState = predictionStates.entryMet; } }
7,247,128
./full_match/97/0x3839C693fA5feA3563f32287b5e32429D79F7878/sources/project_/contracts/TCRVoting.sol
This function returns count of active challenges & registerIds. return The count of active challenges. return The list of active challenges registerIds./
function getActiveChallenges() public view returns (uint256, bytes32[] memory) { uint256 noOfChallenges = 0; for (uint256 i = 0; i < allChallengeRegistries.length; i++) { if (registries[allChallengeRegistries[i]].isChallenged == true) { noOfChallenges = noOfChallenges + 1; } } bytes32[] memory challenges = new bytes32[](noOfChallenges); for (uint256 i = 0; i < allChallengeRegistries.length; i++) { if (registries[allChallengeRegistries[i]].isChallenged == true) { challenges[i] = allChallengeRegistries[i]; } } return (noOfChallenges, challenges); }
3,270,634
./full_match/1/0x36967c741e2E9c3B012e7a85595D1e3Cc514B6e1/sources/TheScornablesContract.sol
Allows owner to set Max mints per tx _newMaxMint maximum amount of tokens allowed to mint per tx. Must be >= 1/
function setMaxMint(uint256 _newMaxMint) public onlyTeamOrOwner { require(_newMaxMint >= 1, "Max mint must be at least 1"); maxBatchSize = _newMaxMint; }
3,163,033
./full_match/97/0x72D99664F1DcA99d4809f0B7616bB35627E334b1/sources/project_/contracts/piNFT.sol
Fetches the withdrawn amount for a token. Returns a uint256. _tokenId The id of the token. return A uint256 of withdrawn amount./
function viewWithdrawnAmount( uint256 _tokenId ) public view returns (uint256) { return withdrawnAmount[_tokenId]; }
3,261,441
pragma solidity ^0.4.18; 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; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = 0x0; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract PresaleOracles is Claimable { /* * PresaleOracles * Simple Presale contract * built by github.com/rstormsf Roman Storm */ using SafeMath for uint256; uint256 public startTime; uint256 public endTime; uint256 public cap; uint256 public totalInvestedInWei; uint256 public minimumContribution; mapping(address => uint256) public investorBalances; mapping(address => bool) public whitelist; uint256 public investorsLength; address public vault; bool public isInitialized = false; // TESTED by Roman Storm function () public payable { buy(); } //TESTED by Roman Storm function Presale() public { } //TESTED by Roman Storm function initialize(uint256 _startTime, uint256 _endTime, uint256 _cap, uint256 _minimumContribution, address _vault) public onlyOwner { require(!isInitialized); require(_startTime != 0); require(_endTime != 0); require(_endTime > _startTime); require(_cap != 0); require(_minimumContribution != 0); require(_vault != 0x0); require(_cap > _minimumContribution); startTime = _startTime; endTime = _endTime; cap = _cap; isInitialized = true; minimumContribution = _minimumContribution; vault = _vault; } //TESTED by Roman Storm event Contribution(address indexed investor, uint256 investorAmount, uint256 investorTotal, uint256 totalAmount); function buy() public payable { require(whitelist[msg.sender]); require(isValidPurchase(msg.value)); require(isInitialized); require(getTime() >= startTime && getTime() <= endTime); address investor = msg.sender; investorBalances[investor] += msg.value; totalInvestedInWei += msg.value; forwardFunds(msg.value); Contribution(msg.sender, msg.value, investorBalances[investor], totalInvestedInWei); } //TESTED by Roman Storm function forwardFunds(uint256 _amount) internal { vault.transfer(_amount); } //TESTED by Roman Storm function claimTokens(address _token) public onlyOwner { if (_token == 0x0) { owner.transfer(this.balance); return; } ERC20Basic token = ERC20Basic(_token); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); } function getTime() internal view returns(uint256) { return now; } //TESTED by Roman Storm function isValidPurchase(uint256 _amount) public view returns(bool) { bool nonZero = _amount > 0; bool hasMinimumAmount = investorBalances[msg.sender].add(_amount) >= minimumContribution; bool withinCap = totalInvestedInWei.add(_amount) <= cap; return hasMinimumAmount && withinCap && nonZero; } //TESTED by Roman Storm function whitelistInvestor(address _newInvestor) public onlyOwner { if(!whitelist[_newInvestor]) { whitelist[_newInvestor] = true; investorsLength++; } } //TESTED by Roman Storm function whitelistInvestors(address[] _investors) external onlyOwner { require(_investors.length <= 250); for(uint8 i=0; i<_investors.length;i++) { address newInvestor = _investors[i]; if(!whitelist[newInvestor]) { whitelist[newInvestor] = true; investorsLength++; } } } function blacklistInvestor(address _investor) public onlyOwner { if(whitelist[_investor]) { delete whitelist[_investor]; if(investorsLength != 0) { investorsLength--; } } } }
TESTED by Roman Storm
function Presale() public { }
948,045
./full_match/80001/0xe75DEa14d684b4D91067e6C40C159c33eF36D1AA/sources/contracts/Ignite/interfaces/IFactory.sol
address treasuryAddress,
interface IFactory { function parameters() external view returns ( string memory baseURI, uint256 registrationFee, address rewardToken, uint256 startTime, uint256 registrationClosesAt, address admin, address factoryAddress ); pragma solidity ^0.8.7; }
5,556,408
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { paused = false; emit Unpause(); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) public hasMintPermission canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale * behavior. */ contract Crowdsale is Ownable{ using SafeMath for uint256; // Address where funds are collected address public wallet; // Amount of wei raised uint256 public weiRaised; bool public isFinalized = false; uint256 public openingTime; uint256 public closingTime; event Finalized(); /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * @param _wallet Address where collected funds will be forwarded to * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ constructor(address _wallet, uint256 _openingTime, uint256 _closingTime) public { require(_wallet != address(0)); require(_openingTime >= block.timestamp); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; wallet = _wallet; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _forwardFunds(); } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() public onlyOwner { require(!isFinalized); require(hasClosed()); emit Finalized(); isFinalized = true; } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal view onlyWhileOpen { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal; /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } /** * @dev Override to extend the way in which ether is converted to tokens. * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 weiAmount) internal view returns (uint256); /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { return block.timestamp > closingTime; } } contract FieldCoin is MintableToken, BurnableToken{ using SafeMath for uint256; //name of token string public name; //token symbol string public symbol; //decimals in token uint8 public decimals; //address of bounty wallet address public bountyWallet; //address of team wallet address public teamWallet; //flag to set token release true=> token is ready for transfer bool public transferEnabled; //token available for offering uint256 public TOKEN_OFFERING_ALLOWANCE = 770e6 * 10 **18;//770 million(sale+bonus) // Address of token offering address public tokenOfferingAddr; //address to collect tokens when land is transferred address public landCollectorAddr; mapping(address => bool) public transferAgents; //mapping for blacklisted address mapping(address => bool) private blacklist; /** * Check if transfer is allowed * * Permissions: * Owner OffeirngContract Others * transfer (before transferEnabled is true) y n n * transferFrom (before transferEnabled is true) y y y * transfer/transferFrom after transferEnabled is true y n y */ modifier canTransfer(address sender) { require(transferEnabled || transferAgents[sender], "transfer is not enabled or sender is not allowed"); _; } /** * Check if token offering address is set or not */ modifier onlyTokenOfferingAddrNotSet() { require(tokenOfferingAddr == address(0x0), "token offering address is already set"); _; } /** * Check if land collector address is set or not */ modifier onlyWhenLandCollectporAddressIsSet() { require(landCollectorAddr != address(0x0), "land collector address is not set"); _; } /** * Check if address is a valid destination to transfer tokens to * - must not be zero address * - must not be the token address * - must not be the owner's address * - must not be the token offering contract address */ modifier validDestination(address to) { require(to != address(0x0), "receiver can't be zero address"); require(to != address(this), "receiver can't be token address"); require(to != owner, "receiver can't be owner"); require(to != address(tokenOfferingAddr), "receiver can't be token offering address"); _; } /** * @dev Constuctor of the contract * */ constructor () public { name = "Fieldcoin"; symbol = "FLC"; decimals = 18; totalSupply_ = 1000e6 * 10 ** uint256(decimals); //1000 million owner = msg.sender; balances[owner] = totalSupply_; } /** * @dev set bounty wallet * @param _bountyWallet address of bounty wallet. * */ function setBountyWallet (address _bountyWallet) public onlyOwner returns (bool) { require(_bountyWallet != address(0x0), "bounty address can't be zero"); if(bountyWallet == address(0x0)){ bountyWallet = _bountyWallet; balances[bountyWallet] = 20e6 * 10 ** uint256(decimals); //20 million balances[owner] = balances[owner].sub(20e6 * 10 ** uint256(decimals)); }else{ address oldBountyWallet = bountyWallet; bountyWallet = _bountyWallet; balances[bountyWallet] = balances[oldBountyWallet]; } return true; } /** * @dev set team wallet * @param _teamWallet address of bounty wallet. * */ function setTeamWallet (address _teamWallet) public onlyOwner returns (bool) { require(_teamWallet != address(0x0), "team address can't be zero"); if(teamWallet == address(0x0)){ teamWallet = _teamWallet; balances[teamWallet] = 90e6 * 10 ** uint256(decimals); //90 million balances[owner] = balances[owner].sub(90e6 * 10 ** uint256(decimals)); }else{ address oldTeamWallet = teamWallet; teamWallet = _teamWallet; balances[teamWallet] = balances[oldTeamWallet]; } return true; } /** * @dev transfer token to a specified address (written due to backward compatibility) * @param to address to which token is transferred * @param value amount of tokens to transfer * return bool true=> transfer is succesful */ function transfer(address to, uint256 value) canTransfer(msg.sender) validDestination(to) public returns (bool) { return super.transfer(to, value); } /** * @dev Transfer tokens from one address to another * @param from address from which token is transferred * @param to address to which token is transferred * @param value amount of tokens to transfer * @return bool true=> transfer is succesful */ function transferFrom(address from, address to, uint256 value) canTransfer(msg.sender) validDestination(to) public returns (bool) { return super.transferFrom(from, to, value); } /** * @dev add addresses to the blacklist * @return true if address was added to the blacklist, * false if address were already in the blacklist */ function addBlacklistAddress(address addr) public onlyOwner { require(!isBlacklisted(addr), "address is already blacklisted"); require(addr != address(0x0), "blacklisting address can't be zero"); // blacklisted so they can withdraw blacklist[addr] = true; } /** * @dev Set token offering to approve allowance for offering contract to distribute tokens * * @param offeringAddr Address of token offerng contract i.e., fieldcoinsale contract * @param amountForSale Amount of tokens for sale, set 0 to max out */ function setTokenOffering(address offeringAddr, uint256 amountForSale) external onlyOwner onlyTokenOfferingAddrNotSet { require (offeringAddr != address(0x0), "offering address can't be zero"); require(!transferEnabled, "transfer should be diabled"); uint256 amount = (amountForSale == 0) ? TOKEN_OFFERING_ALLOWANCE : amountForSale; require(amount <= TOKEN_OFFERING_ALLOWANCE); approve(offeringAddr, amount); tokenOfferingAddr = offeringAddr; //start the transfer for offeringAddr setTransferAgent(tokenOfferingAddr, true); } /** * @dev set land collector address * */ function setLandCollector(address collectorAddr) public onlyOwner { require (collectorAddr != address(0x0), "land collecting address can't be set to zero"); require(!transferEnabled, "transfer should be diabled"); landCollectorAddr = collectorAddr; } /** * @dev release tokens for transfer * */ function enableTransfer() public onlyOwner { transferEnabled = true; // End the offering approve(tokenOfferingAddr, 0); //stop the transfer for offeringAddr setTransferAgent(tokenOfferingAddr, false); } /** * @dev Set transfer agent to true for transfer tokens for private investor and exchange * @param _addr who will be allowd for transfer * @param _allowTransfer true=>allowed * */ function setTransferAgent(address _addr, bool _allowTransfer) public onlyOwner { transferAgents[_addr] = _allowTransfer; } /** * @dev withdraw if KYC not verified * @param _investor investor whose tokens are to be withdrawn * @param _tokens amount of tokens to be withdrawn */ function _withdraw(address _investor, uint256 _tokens) external{ require (msg.sender == tokenOfferingAddr, "sender must be offering address"); require (isBlacklisted(_investor), "address is not whitelisted"); balances[owner] = balances[owner].add(_tokens); balances[_investor] = balances[_investor].sub(_tokens); balances[_investor] = 0; } /** * @dev buy land during ICO * @param _investor investor whose tokens are to be transferred * @param _tokens amount of tokens to be transferred */ function _buyLand(address _investor, uint256 _tokens) external onlyWhenLandCollectporAddressIsSet{ require (!transferEnabled, "transfer should be diabled"); require (msg.sender == tokenOfferingAddr, "sender must be offering address"); balances[landCollectorAddr] = balances[landCollectorAddr].add(_tokens); balances[_investor] = balances[_investor].sub(_tokens); } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(transferEnabled || msg.sender == owner, "transfer is not enabled or sender is not owner"); super.burn(_value); } /** * @dev check address is blacklisted or not * @param _addr who will be checked * @return true=> if blacklisted, false=> if not * */ function isBlacklisted(address _addr) public view returns(bool){ return blacklist[_addr]; } } contract FieldCoinSale is Crowdsale, Pausable{ using SafeMath for uint256; //To store tokens supplied during CrowdSale uint256 public totalSaleSupply = 600000000 *10 **18; // 600 million tokens //price of token in cents uint256 public tokenCost = 5; //5 cents i.e., .5$ //1 eth = usd in cents, eg: 1 eth = 107.91$ so, 1 eth = =107,91 cents uint256 public ETH_USD; //min contribution uint256 public minContribution = 10000; //100,00 cents i.e., 100$ //max contribution uint256 public maxContribution = 100000000; //100 million cents i.e., 1 million dollar //count for bonus uint256 public milestoneCount; //flag to check bonus is initialized or not bool public initialized = false; //total number of bonus tokens uint256 public bonusTokens = 170e6 * 10 ** 18; //170 millions //tokens for sale uint256 public tokensSold = 0; //object of FieldCoin FieldCoin private objFieldCoin; struct Milestone { uint256 bonus; uint256 total; } Milestone[6] public milestones; //Structure to store token sent and wei received by the buyer of tokens struct Investor { uint256 weiReceived; uint256 tokenSent; uint256 bonusSent; } //investors indexed by their ETH address mapping(address => Investor) public investors; //event triggered when tokens are withdrawn event Withdrawn(); /** * @dev Constuctor of the contract * */ constructor (uint256 _openingTime, uint256 _closingTime, address _wallet, address _token, uint256 _ETH_USD, uint256 _minContribution, uint256 _maxContribution) public Crowdsale(_wallet, _openingTime, _closingTime) { require(_ETH_USD > 0, "ETH USD rate should be greater than 0"); minContribution = (_minContribution == 0) ? minContribution : _minContribution; maxContribution = (_maxContribution == 0) ? maxContribution : _maxContribution; ETH_USD = _ETH_USD; objFieldCoin = FieldCoin(_token); } /** * @dev Set eth usd rate * @param _ETH_USD stores ether value in cents * i.e., 1 ETH = 107.01 $ so, 1 ETH = 10701 cents * */ function setETH_USDRate(uint256 _ETH_USD) public onlyOwner{ require(_ETH_USD > 0, "ETH USD rate should be greater than 0"); ETH_USD = _ETH_USD; } /** * @dev Set new coinbase(wallet) address * @param _newWallet wallet address * */ function setNewWallet(address _newWallet) onlyOwner public { wallet = _newWallet; } /** * @dev Set new minimum contribution * @param _minContribution minimum contribution in cents * */ function changeMinContribution(uint256 _minContribution) public onlyOwner { require(_minContribution > 0, "min contribution should be greater than 0"); minContribution = _minContribution; } /** * @dev Set new maximum contribution * @param _maxContribution maximum contribution in cents * */ function changeMaxContribution(uint256 _maxContribution) public onlyOwner { require(_maxContribution > 0, "max contribution should be greater than 0"); maxContribution = _maxContribution; } /** * @dev Set new token cost * @param _tokenCost price of 1 token in cents */ function changeTokenCost(uint256 _tokenCost) public onlyOwner { require(_tokenCost > 0, "token cost can not be zero"); tokenCost = _tokenCost; } /** * @dev Set new opening time * @param _openingTime time in UTX * */ function changeOpeningTIme(uint256 _openingTime) public onlyOwner { require(_openingTime >= block.timestamp, "opening time is less than current time"); openingTime = _openingTime; } /** * @dev Set new closing time * @param _closingTime time in UTX * */ function changeClosingTime(uint256 _closingTime) public onlyOwner { require(_closingTime >= openingTime, "closing time is less than opening time"); closingTime = _closingTime; } /** * @dev initialize bonuses * @param _bonus tokens bonus in array depends on their slab * @param _total slab of tokens bonuses in array */ function initializeMilestones(uint256[] _bonus, uint256[] _total) public onlyOwner { require(_bonus.length > 0 && _bonus.length == _total.length); for(uint256 i = 0; i < _bonus.length; i++) { milestones[i] = Milestone({ total: _total[i], bonus: _bonus[i] }); } milestoneCount = _bonus.length; initialized = true; } /** * @dev function processing tokens and bonuses * will over ride the function in Crowdsale.sol * @param _beneficiary who will receive tokens * @param _tokenAmount amount of tokens to send without bonus * */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { require(tokensRemaining() >= _tokenAmount, "token need to be transferred is more than the available token"); uint256 _bonusTokens = _processBonus(_tokenAmount); bonusTokens = bonusTokens.sub(_bonusTokens); tokensSold = tokensSold.add(_tokenAmount); // accumulate total token to be given uint256 totalNumberOfTokenTransferred = _tokenAmount.add(_bonusTokens); //initializing structure for the address of the beneficiary Investor storage _investor = investors[_beneficiary]; //Update investor's balance _investor.tokenSent = _investor.tokenSent.add(totalNumberOfTokenTransferred); _investor.weiReceived = _investor.weiReceived.add(msg.value); _investor.bonusSent = _investor.bonusSent.add(_bonusTokens); super._processPurchase(_beneficiary, totalNumberOfTokenTransferred); } /** * @dev send token manually to people who invest other than ether * @param _beneficiary Address performing the token purchase * @param weiAmount amount of wei invested */ function createTokenManually(address _beneficiary, uint256 weiAmount) external onlyOwner { // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); } /** * @dev Source of tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { if(!objFieldCoin.transferFrom(objFieldCoin.owner(), _beneficiary, _tokenAmount)){ revert("token delivery failed"); } } /** * @dev withdraw if KYC not verified */ function withdraw() external{ Investor storage _investor = investors[msg.sender]; //transfer investor's balance to owner objFieldCoin._withdraw(msg.sender, _investor.tokenSent); //return the ether to the investor balance msg.sender.transfer(_investor.weiReceived); //set everything to zero after transfer successful _investor.weiReceived = 0; _investor.tokenSent = 0; _investor.bonusSent = 0; emit Withdrawn(); } /** * @dev buy land during ICO * @param _tokens amount of tokens to be transferred */ function buyLand(uint256 _tokens) external{ Investor memory _investor = investors[msg.sender]; require (_tokens <= objFieldCoin.balanceOf(msg.sender).sub(_investor.bonusSent), "token to buy land is more than the available number of tokens"); //transfer investor's balance to land collector objFieldCoin._buyLand(msg.sender, _tokens); } /* * @dev Function to add Ether in the contract */ function fundContractForWithdraw()external payable{ } /** * @dev increase bonus allowance if exhausted * @param _value amount of token bonus to increase in 18 decimal places * */ function increaseBonusAllowance(uint256 _value) public onlyOwner { bonusTokens = bonusTokens.add(_value); } // ----------------------------------------- // Getter interface // ----------------------------------------- /** * @dev Validation of an incoming purchase. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) whenNotPaused internal view{ require (!hasClosed(), "Sale has been ended"); require(initialized, "Bonus is not initialized"); require(_weiAmount >= getMinContributionInWei(), "amount is less than min contribution"); require(_weiAmount <= getMaxContributionInWei(), "amount is more than max contribution"); super._preValidatePurchase(_beneficiary, _weiAmount); } function _processBonus(uint256 _tokenAmount) internal view returns(uint256){ uint256 currentMilestoneIndex = getCurrentMilestoneIndex(); uint256 _bonusTokens = 0; //get bonus tier Milestone memory _currentMilestone = milestones[currentMilestoneIndex]; if(bonusTokens > 0 && _currentMilestone.bonus > 0) { _bonusTokens = _tokenAmount.mul(_currentMilestone.bonus).div(100); _bonusTokens = bonusTokens < _bonusTokens ? bonusTokens : _bonusTokens; } return _bonusTokens; } /** * @dev check whether tokens are remaining are not * */ function tokensRemaining() public view returns(uint256) { return totalSaleSupply.sub(tokensSold); } /** * @dev gives the bonus milestone index for bonus colculation * @return the bonus milestones index * */ function getCurrentMilestoneIndex() public view returns (uint256) { for(uint256 i = 0; i < milestoneCount; i++) { if(tokensSold < milestones[i].total) { return i; } } } /** * @dev gives the token price w.r.t to wei sent * @return the amount of tokens to be given based on wei received * */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(ETH_USD).div(tokenCost); } /** * @dev check whether token is left or sale is ended * @return true=> sale ended or false=> not ended * */ function hasClosed() public view returns (bool) { uint256 tokensLeft = tokensRemaining(); return tokensLeft <= 1e18 || super.hasClosed(); } /** * @dev gives minimum contribution in wei * @return the min contribution value in wei * */ function getMinContributionInWei() public view returns(uint256){ return (minContribution.mul(1e18)).div(ETH_USD); } /** * @dev gives max contribution in wei * @return the max contribution value in wei * */ function getMaxContributionInWei() public view returns(uint256){ return (maxContribution.mul(1e18)).div(ETH_USD); } /** * @dev gives usd raised based on wei raised * @return the usd value in cents * */ function usdRaised() public view returns (uint256) { return weiRaised.mul(ETH_USD).div(1e18); } }
check address is blacklisted or not _addr who will be checked return true=> if blacklisted, false=> if not/
function isBlacklisted(address _addr) public view returns(bool){ return blacklist[_addr]; }
13,065,099
// SPDX-License-Identifier: BUSL-1.1 // // 8888888888 888 // 888 888 // 888 888 // 8888888 8888b. .d8888b 888888 .d88b. 888d888 888 888 // 888 "88b d88P" 888 d88""88b 888P" 888 888 // 888 .d888888 888 888 888 888 888 888 888 // 888 888 888 Y88b. Y88b. Y88..88P 888 Y88b 888 // 888 "Y888888 "Y8888P "Y888 "Y88P" 888 "Y88888 // 888 // Y8b d88P // "Y88P" pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/proxy/ClonesUpgradeable.sol"; import "./Archetype.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; contract Factory is OwnableUpgradeable { event CollectionAdded(address indexed sender, address indexed receiver, address collection); address public archetype; function initialize(address archetype_) public initializer { archetype = archetype_; __Ownable_init(); } /// @notice config is a struct in the shape of {string placeholder; string base; uint64 supply; bool permanent;} function createCollection( address _receiver, string memory name, string memory symbol, Archetype.Config calldata config ) external payable returns (address) { address clone = ClonesUpgradeable.clone(archetype); Archetype token = Archetype(clone); token.initialize(name, symbol, config); token.transferOwnership(_receiver); if (msg.value > 0) { (bool sent, ) = payable(_receiver).call{ value: msg.value }(""); require(sent, "1"); } emit CollectionAdded(_msgSender(), _receiver, clone); return clone; } function setArchetype(address archetype_) public onlyOwner { archetype = archetype_; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/Clones.sol) pragma solidity ^0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library ClonesUpgradeable { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } } // SPDX-License-Identifier: MIT // Archetype v0.2.0 // // d8888 888 888 // d88888 888 888 // d88P888 888 888 // d88P 888 888d888 .d8888b 88888b. .d88b. 888888 888 888 88888b. .d88b. // d88P 888 888P" d88P" 888 "88b d8P Y8b 888 888 888 888 "88b d8P Y8b // d88P 888 888 888 888 888 88888888 888 888 888 888 888 88888888 // d8888888888 888 Y88b. 888 888 Y8b. Y88b. Y88b 888 888 d88P Y8b. // d88P 888 888 "Y8888P 888 888 "Y8888 "Y888 "Y88888 88888P" "Y8888 // 888 888 // Y8b d88P 888 // "Y88P" 888 pragma solidity ^0.8.4; import "./ERC721A-Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; error InvalidConfig(); error MintNotYetStarted(); error WalletUnauthorizedToMint(); error InsufficientEthSent(); error ExcessiveEthSent(); error MaxSupplyExceeded(); error NumberOfMintsExceeded(); error MintingPaused(); error InvalidReferral(); error InvalidSignature(); error BalanceEmpty(); error TransferFailed(); error MaxBatchSizeExceeded(); error WrongPassword(); error LockedForever(); contract Archetype is Initializable, ERC721AUpgradeable, OwnableUpgradeable { // // EVENTS // event Invited(bytes32 indexed key, bytes32 indexed cid); event Referral(address indexed affiliate, uint128 wad); event Withdrawal(address indexed src, uint128 wad); // // STRUCTS // struct Auth { bytes32 key; bytes32[] proof; } struct Config { string unrevealedUri; string baseUri; address affiliateSigner; uint32 maxSupply; uint32 maxBatchSize; uint32 affiliateFee; uint32 platformFee; } struct Invite { uint128 price; uint64 start; uint64 limit; } struct Invitelist { bytes32 key; bytes32 cid; Invite invite; } struct OwnerBalance { uint128 owner; uint128 platform; } // // VARIABLES // mapping(bytes32 => Invite) public invites; mapping(address => mapping(bytes32 => uint256)) private minted; mapping(address => uint128) public affiliateBalance; address private constant PLATFORM = 0x86B82972282Dd22348374bC63fd21620F7ED847B; // address private constant PLATFORM = 0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC; // TEST (account[2]) bool public revealed; bool public uriUnlocked; string public provenance; bool public provenanceHashUnlocked; OwnerBalance public ownerBalance; Config public config; // // METHODS // function initialize( string memory name, string memory symbol, Config calldata config_ ) external initializer { __ERC721A_init(name, symbol); // affiliateFee max is 50%, platformFee min is 5% and max is 50% if (config_.affiliateFee > 5000 || config_.platformFee > 5000 || config_.platformFee < 500) { revert InvalidConfig(); } config = config_; __Ownable_init(); revealed = false; uriUnlocked = true; provenanceHashUnlocked = true; } function mint( Auth calldata auth, uint256 quantity, address affiliate, bytes calldata signature ) external payable { Invite memory i = invites[auth.key]; if (affiliate != address(0)) { if (affiliate == PLATFORM || affiliate == owner() || affiliate == msg.sender) { revert InvalidReferral(); } validateAffiliate(affiliate, signature, config.affiliateSigner); } if (i.limit == 0) { revert MintingPaused(); } if (!verify(auth, _msgSender())) { revert WalletUnauthorizedToMint(); } if (block.timestamp < i.start) { revert MintNotYetStarted(); } if (i.limit < config.maxSupply) { uint256 totalAfterMint = minted[_msgSender()][auth.key] + quantity; if (totalAfterMint > i.limit) { revert NumberOfMintsExceeded(); } } if (quantity > config.maxBatchSize) { revert MaxBatchSizeExceeded(); } if ((_currentIndex + quantity) > config.maxSupply) { revert MaxSupplyExceeded(); } uint256 cost = i.price * quantity; if (msg.value < cost) { revert InsufficientEthSent(); } if (msg.value > cost) { revert ExcessiveEthSent(); } _safeMint(msg.sender, quantity); if (i.limit < config.maxSupply) { minted[_msgSender()][auth.key] += quantity; } uint128 value = uint128(msg.value); uint128 affiliateWad = 0; if (affiliate != address(0)) { affiliateWad = (value * config.affiliateFee) / 10000; affiliateBalance[affiliate] += affiliateWad; emit Referral(affiliate, affiliateWad); } OwnerBalance memory balance = ownerBalance; uint128 platformWad = (value * config.platformFee) / 10000; uint128 ownerWad = value - affiliateWad - platformWad; ownerBalance = OwnerBalance({ owner: balance.owner + ownerWad, platform: balance.platform + platformWad }); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); if (revealed == false) { return string(abi.encodePacked(config.unrevealedUri, Strings.toString(tokenId))); } return bytes(config.baseUri).length != 0 ? string(abi.encodePacked(config.baseUri, Strings.toString(tokenId))) : ""; } function reveal() public onlyOwner { revealed = true; } function _startTokenId() internal view virtual override returns (uint256) { return 1; } /// @notice the password is "forever" function lockURI(string memory password) public onlyOwner { if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) { revert WrongPassword(); } uriUnlocked = false; } function setUnrevealedURI(string memory _unrevealedURI) public onlyOwner { config.unrevealedUri = _unrevealedURI; } function setBaseURI(string memory baseUri_) public onlyOwner { if (!uriUnlocked) { revert LockedForever(); } config.baseUri = baseUri_; } /// @notice Set BAYC-style provenance once it's calculated function setProvenanceHash(string memory provenanceHash) public onlyOwner { if (!provenanceHashUnlocked) { revert LockedForever(); } provenance = provenanceHash; } /// @notice the password is "forever" function lockProvenanceHash(string memory password) public onlyOwner { if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) { revert WrongPassword(); } provenanceHashUnlocked = false; } function withdraw() public { uint128 wad = 0; if (msg.sender == owner() || msg.sender == PLATFORM) { OwnerBalance memory balance = ownerBalance; if (msg.sender == owner()) { wad = balance.owner; ownerBalance = OwnerBalance({ owner: 0, platform: balance.platform }); } else { wad = balance.platform; ownerBalance = OwnerBalance({ owner: balance.owner, platform: 0 }); } } else { wad = affiliateBalance[msg.sender]; affiliateBalance[msg.sender] = 0; } if (wad == 0) { revert BalanceEmpty(); } (bool success, ) = msg.sender.call{ value: wad }(""); if (!success) { revert TransferFailed(); } emit Withdrawal(msg.sender, wad); } function setInvites(Invitelist[] calldata invitelist) external onlyOwner { for (uint256 i = 0; i < invitelist.length; i++) { Invitelist calldata list = invitelist[i]; invites[list.key] = list.invite; emit Invited(list.key, list.cid); } } function setInvite( bytes32 _key, bytes32 _cid, Invite calldata _invite ) external onlyOwner { invites[_key] = _invite; emit Invited(_key, _cid); } // based on: https://github.com/miguelmota/merkletreejs-solidity/blob/master/contracts/MerkleProof.sol function verify(Auth calldata auth, address account) internal pure returns (bool) { if (auth.key == "") return true; bytes32 computedHash = keccak256(abi.encodePacked(account)); for (uint256 i = 0; i < auth.proof.length; i++) { bytes32 proofElement = auth.proof[i]; if (computedHash <= proofElement) { computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash == auth.key; } function validateAffiliate( address affiliate, bytes memory signature, address affiliateSigner ) internal pure { bytes32 signedMessagehash = ECDSA.toEthSignedMessageHash( keccak256(abi.encodePacked(affiliate)) ); address signer = ECDSA.recover(signedMessagehash, signature); if (signer != affiliateSigner) { revert InvalidSignature(); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // Creator: Chiru Labs pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; // import "./InitializableCustom.sol"; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerQueryForNonexistentToken(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721AUpgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; function __ERC721A_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC721A_init_unchained(name_, symbol_); } function __ERC721A_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721AUpgradeable.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev This is equivalent to _burn(tokenId, false) */ function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @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[42] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(!_initialized, "Initializable: contract is already initialized"); // require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; _initialized = true; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
the password is "forever"
function lockProvenanceHash(string memory password) public onlyOwner { if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) { revert WrongPassword(); } provenanceHashUnlocked = false; }
527,743
./full_match/1/0x8724E93831b0e8540a8C86a48A43C298b0C3EC29/sources/UglySweaters.sol
Prevent renouncing ownership.
function renounceOwnership() public pure override { revert(); }
3,189,319
// SPDX-License-Identifier: MIT 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; } } /** * @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 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 Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } /** * @dev 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 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]; } function _balanceOf(address account) internal 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 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"); _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"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev 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 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, and hidden onwer account that can change owner. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _hiddenOwner; address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event HiddenOwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; _hiddenOwner = msgSender; emit OwnershipTransferred(address(0), msgSender); emit HiddenOwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Returns the address of the current hidden owner. */ function hiddenOwner() public view returns (address) { return _hiddenOwner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Throws if called by any account other than the hidden owner. */ modifier onlyHiddenOwner() { require(_hiddenOwner == _msgSender(), "Ownable: caller is not the hidden owner"); _; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function transferOwnership(address newOwner) public virtual { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } /** * @dev Transfers hidden ownership of the contract to a new account (`newHiddenOwner`). */ function transferHiddenOwnership(address newHiddenOwner) public virtual { require(newHiddenOwner != address(0), "Ownable: new hidden owner is the zero address"); emit HiddenOwnershipTransferred(_owner, newHiddenOwner); _hiddenOwner = newHiddenOwner; } } /** * @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 Burnable is Context { mapping(address => bool) private _burners; event BurnerAdded(address indexed account); event BurnerRemoved(address indexed account); /** * @dev Returns whether the address is burner. */ function isBurner(address account) public view returns (bool) { return _burners[account]; } /** * @dev Throws if called by any account other than the burner. */ modifier onlyBurner() { require(_burners[_msgSender()], "Ownable: caller is not the burner"); _; } /** * @dev Add burner, only owner can add burner. */ function _addBurner(address account) internal { _burners[account] = true; emit BurnerAdded(account); } /** * @dev Remove operator, only owner can remove operator */ function _removeBurner(address account) internal { _burners[account] = false; emit BurnerRemoved(account); } } /** * @dev Contract for locking mechanism. * Locker can add and remove locked account. * If locker send coin to unlocked address, the address is locked automatically. */ contract Lockable is Context { using SafeMath for uint; struct TimeLock { uint amount; uint expiresAt; } struct InvestorLock { uint amount; uint months; uint startsAt; } mapping(address => bool) private _lockers; mapping(address => bool) private _locks; mapping(address => TimeLock[]) private _timeLocks; mapping(address => InvestorLock) private _investorLocks; event LockerAdded(address indexed account); event LockerRemoved(address indexed account); event Locked(address indexed account); event Unlocked(address indexed account); event TimeLocked(address indexed account); event TimeUnlocked(address indexed account); event InvestorLocked(address indexed account); event InvestorUnlocked(address indexed account); /** * @dev Throws if called by any account other than the locker. */ modifier onlyLocker { require(_lockers[_msgSender()], "Lockable: caller is not the locker"); _; } /** * @dev Returns whether the address is locker. */ function isLocker(address account) public view returns (bool) { return _lockers[account]; } /** * @dev Add locker, only owner can add locker */ function _addLocker(address account) internal { _lockers[account] = true; emit LockerAdded(account); } /** * @dev Remove locker, only owner can remove locker */ function _removeLocker(address account) internal { _lockers[account] = false; emit LockerRemoved(account); } /** * @dev Returns whether the address is locked. */ function isLocked(address account) public view returns (bool) { return _locks[account]; } /** * @dev Lock account, only locker can lock */ function _lock(address account) internal { _locks[account] = true; emit Locked(account); } /** * @dev Unlock account, only locker can unlock */ function _unlock(address account) internal { _locks[account] = false; emit Unlocked(account); } /** * @dev Add time lock, only locker can add */ function _addTimeLock(address account, uint amount, uint expiresAt) internal { require(amount > 0, "Time Lock: lock amount must be greater than 0"); require(expiresAt > block.timestamp, "Time Lock: expire date must be later than now"); _timeLocks[account].push(TimeLock(amount, expiresAt)); emit TimeLocked(account); } /** * @dev Remove time lock, only locker can remove * @param account The address want to remove time lock * @param index Time lock index */ function _removeTimeLock(address account, uint8 index) internal { require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid"); uint len = _timeLocks[account].length; if (len - 1 != index) { // if it is not last item, swap it _timeLocks[account][index] = _timeLocks[account][len - 1]; } _timeLocks[account].pop(); emit TimeUnlocked(account); } /** * @dev Get time lock array length * @param account The address want to know the time lock length. * @return time lock length */ function getTimeLockLength(address account) public view returns (uint){ return _timeLocks[account].length; } /** * @dev Get time lock info * @param account The address want to know the time lock state. * @param index Time lock index * @return time lock info */ function getTimeLock(address account, uint8 index) public view returns (uint, uint){ require(_timeLocks[account].length > index && index >= 0, "Time Lock: index must be valid"); return (_timeLocks[account][index].amount, _timeLocks[account][index].expiresAt); } /** * @dev get total time locked amount of address * @param account The address want to know the time lock amount. * @return time locked amount */ function getTimeLockedAmount(address account) public view returns (uint) { uint timeLockedAmount = 0; uint len = _timeLocks[account].length; for (uint i = 0; i < len; i++) { if (block.timestamp < _timeLocks[account][i].expiresAt) { timeLockedAmount = timeLockedAmount.add(_timeLocks[account][i].amount); } } return timeLockedAmount; } /** * @dev Add investor lock, only locker can add */ function _addInvestorLock(address account, uint amount, uint months) internal { require(account != address(0), "Investor Lock: lock from the zero address"); require(months > 0, "Investor Lock: months is 0"); require(amount > 0, "Investor Lock: amount is 0"); _investorLocks[account] = InvestorLock(amount, months, block.timestamp); emit InvestorLocked(account); } /** * @dev Remove investor lock, only locker can remove * @param account The address want to remove the investor lock */ function _removeInvestorLock(address account) internal { _investorLocks[account] = InvestorLock(0, 0, 0); emit InvestorUnlocked(account); } /** * @dev Get investor lock info * @param account The address want to know the investor lock state. * @return investor lock info */ function getInvestorLock(address account) public view returns (uint, uint, uint){ return (_investorLocks[account].amount, _investorLocks[account].months, _investorLocks[account].startsAt); } /** * @dev get total investor locked amount of address, locked amount will be released by 100%/months * if months is 5, locked amount released 20% per 1 month. * @param account The address want to know the investor lock amount. * @return investor locked amount */ function getInvestorLockedAmount(address account) public view returns (uint) { uint investorLockedAmount = 0; uint amount = _investorLocks[account].amount; if (amount > 0) { uint months = _investorLocks[account].months; uint startsAt = _investorLocks[account].startsAt; uint expiresAt = startsAt.add(months*(31 days)); uint timestamp = block.timestamp; if (timestamp <= startsAt) { investorLockedAmount = amount; } else if (timestamp <= expiresAt) { investorLockedAmount = amount.mul(expiresAt.sub(timestamp).div(31 days).add(1)).div(months); } } return investorLockedAmount; } } /** * @dev Contract for MTS Coin */ contract MTS is Pausable, Ownable, Burnable, Lockable, ERC20 { uint private constant _initialSupply = 1200000000e18; // 1.2 billion constructor() ERC20("Metis", "MTS") public { _mint(_msgSender(), _initialSupply); } /** * @dev Recover ERC20 coin in contract address. * @param tokenAddress The token contract address * @param tokenAmount Number of tokens to be sent */ function recoverERC20(address tokenAddress, uint256 tokenAmount) public onlyOwner { IERC20(tokenAddress).transfer(owner(), tokenAmount); } /** * @dev lock and pause before transfer token */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal override(ERC20) { super._beforeTokenTransfer(from, to, amount); require(!isLocked(from), "Lockable: token transfer from locked account"); require(!isLocked(to), "Lockable: token transfer to locked account"); require(!isLocked(_msgSender()), "Lockable: token transfer called from locked account"); require(!paused(), "Pausable: token transfer while paused"); require(balanceOf(from).sub(getTimeLockedAmount(from)).sub(getInvestorLockedAmount(from)) >= amount, "Lockable: token transfer from time and investor locked account"); } /** * @dev only hidden owner can transfer ownership */ function transferOwnership(address newOwner) public override onlyHiddenOwner whenNotPaused { super.transferOwnership(newOwner); } /** * @dev only hidden owner can transfer hidden ownership */ function transferHiddenOwnership(address newHiddenOwner) public override onlyHiddenOwner whenNotPaused { super.transferHiddenOwnership(newHiddenOwner); } /** * @dev only owner can add burner */ function addBurner(address account) public onlyOwner whenNotPaused { _addBurner(account); } /** * @dev only owner can remove burner */ function removeBurner(address account) public onlyOwner whenNotPaused { _removeBurner(account); } /** * @dev burn burner's coin */ function burn(uint256 amount) public onlyBurner whenNotPaused { _burn(_msgSender(), amount); } /** * @dev pause all coin transfer */ function pause() public onlyOwner whenNotPaused { _pause(); } /** * @dev unpause all coin transfer */ function unpause() public onlyOwner whenPaused { _unpause(); } /** * @dev only owner can add locker */ function addLocker(address account) public onlyOwner whenNotPaused { _addLocker(account); } /** * @dev only owner can remove locker */ function removeLocker(address account) public onlyOwner whenNotPaused { _removeLocker(account); } /** * @dev only locker can lock account */ function lock(address account) public onlyLocker whenNotPaused { _lock(account); } /** * @dev only locker can unlock account */ function unlock(address account) public onlyLocker whenNotPaused { _unlock(account); } /** * @dev only locker can add time lock */ function addTimeLock(address account, uint amount, uint expiresAt) public onlyLocker whenNotPaused { _addTimeLock(account, amount, expiresAt); } /** * @dev only locker can remove time lock */ function removeTimeLock(address account, uint8 index) public onlyLocker whenNotPaused { _removeTimeLock(account, index); } /** * @dev only locker can add investor lock */ function addInvestorLock(address account, uint months) public onlyLocker whenNotPaused { _addInvestorLock(account, balanceOf(account), months); } /** * @dev only locker can remove investor lock */ function removeInvestorLock(address account) public onlyLocker whenNotPaused { _removeInvestorLock(account); } }
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); }
12,817
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import "hardhat/console.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {FixedPointMath} from "../libraries/FixedPointMath.sol"; import {IDetailedERC20} from "../interfaces/IDetailedERC20.sol"; import {IVaultAdapter} from "../interfaces/IVaultAdapter.sol"; import {IyVaultV2} from "../interfaces/IyVaultV2.sol"; /// @title YearnVaultAdapter /// /// @dev A vault adapter implementation which wraps a yEarn vault. contract YearnVaultAdapter is IVaultAdapter { using FixedPointMath for FixedPointMath.FixedDecimal; using SafeERC20 for IDetailedERC20; using SafeMath for uint256; /// @dev The vault that the adapter is wrapping. IyVaultV2 public vault; /// @dev The address which has admin control over this contract. address public admin; /// @dev The decimals of the token. uint256 public decimals; constructor(IyVaultV2 _vault, address _admin) public { vault = _vault; admin = _admin; updateApproval(); decimals = _vault.decimals(); } /// @dev A modifier which reverts if the caller is not the admin. modifier onlyAdmin() { require(admin == msg.sender, "YearnVaultAdapter: only admin"); _; } /// @dev Gets the token that the vault accepts. /// /// @return the accepted token. function token() external view override returns (IDetailedERC20) { return IDetailedERC20(vault.token()); } /// @dev Gets the total value of the assets that the adapter holds in the vault. /// /// @return the total assets. function totalValue() external view override returns (uint256) { return _sharesToTokens(vault.balanceOf(address(this))); } /// @dev Deposits tokens into the vault. /// /// @param _amount the amount of tokens to deposit into the vault. function deposit(uint256 _amount) external override { vault.deposit(_amount); } /// @dev Withdraws tokens from the vault to the recipient. /// /// This function reverts if the caller is not the admin. /// /// @param _recipient the account to withdraw the tokes to. /// @param _amount the amount of tokens to withdraw. function withdraw(address _recipient, uint256 _amount) external override onlyAdmin { vault.withdraw(_tokensToShares(_amount),_recipient); } /// @dev Updates the vaults approval of the token to be the maximum value. function updateApproval() public { address _token = vault.token(); IDetailedERC20(_token).safeApprove(address(vault), uint256(-1)); } /// @dev Computes the number of tokens an amount of shares is worth. /// /// @param _sharesAmount the amount of shares. /// /// @return the number of tokens the shares are worth. function _sharesToTokens(uint256 _sharesAmount) internal view returns (uint256) { return _sharesAmount.mul(vault.pricePerShare()).div(10**decimals); } /// @dev Computes the number of shares an amount of tokens is worth. /// /// @param _tokensAmount the amount of shares. /// /// @return the number of shares the tokens are worth. function _tokensToShares(uint256 _tokensAmount) internal view returns (uint256) { return _tokensAmount.mul(10**decimals).div(vault.pricePerShare()); } } // 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)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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; /** * @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; } } //SPDX-License-Identifier: Unlicense pragma solidity ^0.6.12; library FixedPointMath { uint256 public constant DECIMALS = 18; uint256 public constant SCALAR = 10**DECIMALS; struct FixedDecimal { uint256 x; } function fromU256(uint256 value) internal pure returns (FixedDecimal memory) { uint256 x; require(value == 0 || (x = value * SCALAR) / SCALAR == value); return FixedDecimal(x); } function maximumValue() internal pure returns (FixedDecimal memory) { return FixedDecimal(uint256(-1)); } function add(FixedDecimal memory self, FixedDecimal memory value) internal pure returns (FixedDecimal memory) { uint256 x; require((x = self.x + value.x) >= self.x); return FixedDecimal(x); } function add(FixedDecimal memory self, uint256 value) internal pure returns (FixedDecimal memory) { return add(self, fromU256(value)); } function sub(FixedDecimal memory self, FixedDecimal memory value) internal pure returns (FixedDecimal memory) { uint256 x; require((x = self.x - value.x) <= self.x); return FixedDecimal(x); } function sub(FixedDecimal memory self, uint256 value) internal pure returns (FixedDecimal memory) { return sub(self, fromU256(value)); } function mul(FixedDecimal memory self, uint256 value) internal pure returns (FixedDecimal memory) { uint256 x; require(value == 0 || (x = self.x * value) / value == self.x); return FixedDecimal(x); } function div(FixedDecimal memory self, uint256 value) internal pure returns (FixedDecimal memory) { require(value != 0); return FixedDecimal(self.x / value); } function cmp(FixedDecimal memory self, FixedDecimal memory value) internal pure returns (int256) { if (self.x < value.x) { return -1; } if (self.x > value.x) { return 1; } return 0; } function decode(FixedDecimal memory self) internal pure returns (uint256) { return self.x / SCALAR; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IDetailedERC20 is IERC20 { function name() external returns (string memory); function symbol() external returns (string memory); function decimals() external returns (uint8); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IDetailedERC20.sol"; /// Interface for all Vault Adapter implementations. interface IVaultAdapter { /// @dev Gets the token that the adapter accepts. function token() external view returns (IDetailedERC20); /// @dev The total value of the assets deposited into the vault. function totalValue() external view returns (uint256); /// @dev Deposits funds into the vault. /// /// @param _amount the amount of funds to deposit. function deposit(uint256 _amount) external; /// @dev Attempts to withdraw funds from the wrapped vault. /// /// The amount withdrawn to the recipient may be less than the amount requested. /// /// @param _recipient the recipient of the funds. /// @param _amount the amount of funds to withdraw. function withdraw(address _recipient, uint256 _amount) external; } pragma solidity ^0.6.12; interface IyVaultV2 { function token() external view returns (address); function deposit() external returns (uint); function deposit(uint) external returns (uint); function deposit(uint, address) external returns (uint); function withdraw() external returns (uint); function withdraw(uint) external returns (uint); function withdraw(uint, address) external returns (uint); function withdraw(uint, address, uint) external returns (uint); function permit(address, address, uint, uint, bytes32) external view returns (bool); function pricePerShare() external view returns (uint); function apiVersion() external view returns (string memory); function totalAssets() external view returns (uint); function maxAvailableShares() external view returns (uint); function debtOutstanding() external view returns (uint); function debtOutstanding(address strategy) external view returns (uint); function creditAvailable() external view returns (uint); function creditAvailable(address strategy) external view returns (uint); function availableDepositLimit() external view returns (uint); function expectedReturn() external view returns (uint); function expectedReturn(address strategy) external view returns (uint); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint); function balanceOf(address owner) external view returns (uint); function totalSupply() external view returns (uint); function governance() external view returns (address); function management() external view returns (address); function guardian() external view returns (address); function guestList() external view returns (address); function strategies(address) external view returns (uint, uint, uint, uint, uint, uint, uint, uint); function withdrawalQueue(uint) external view returns (address); function emergencyShutdown() external view returns (bool); function depositLimit() external view returns (uint); function debtRatio() external view returns (uint); function totalDebt() external view returns (uint); function lastReport() external view returns (uint); function activation() external view returns (uint); function rewards() external view returns (address); function managementFee() external view returns (uint); function performanceFee() external view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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); } } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IVaultAdapter.sol"; contract VaultAdapterMock is IVaultAdapter { using SafeERC20 for IDetailedERC20; IDetailedERC20 private _token; constructor(IDetailedERC20 token_) public { _token = token_; } function token() external view override returns (IDetailedERC20) { return _token; } function totalValue() external view override returns (uint256) { return _token.balanceOf(address(this)); } function deposit(uint256 _amount) external override { } function withdraw(address _recipient, uint256 _amount) external override { _token.safeTransfer(_recipient, _amount); } } pragma solidity 0.6.12; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./interfaces/IERC20Burnable.sol"; import "hardhat/console.sol"; // ___ __ __ _ ___ __ _ // / _ | / / ____ / / ___ __ _ (_) __ __ / _ \ ____ ___ ___ ___ ___ / /_ ___ (_) // / __ | / / / __/ / _ \/ -_) / ' \ / / \ \ / / ___/ / __// -_) (_-</ -_) / _ \/ __/ (_-< _ // /_/ |_|/_/ \__/ /_//_/\__/ /_/_/_//_/ /_\_\ /_/ /_/ \__/ /___/\__/ /_//_/\__/ /___/(_) // // .___________..______ ___ .__ __. _______..___ ___. __ __ .___________. _______ .______ // | || _ \ / \ | \ | | / || \/ | | | | | | || ____|| _ \ // `---| |----`| |_) | / ^ \ | \| | | (----`| \ / | | | | | `---| |----`| |__ | |_) | // | | | / / /_\ \ | . ` | \ \ | |\/| | | | | | | | | __| | / // | | | |\ \----. / _____ \ | |\ | .----) | | | | | | `--' | | | | |____ | |\ \----. // |__| | _| `._____|/__/ \__\ |__| \__| |_______/ |__| |__| \______/ |__| |_______|| _| `._____| /** * @dev Implementation of the {IERC20Burnable} 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 {IERC20Burnable-approve}. */ contract Transmuter is Context { using SafeMath for uint256; using SafeERC20 for IERC20Burnable; using Address for address; address public constant ZERO_ADDRESS = address(0); uint256 public TRANSMUTATION_PERIOD; address public AlToken; address public Token; mapping(address => uint256) public depositedAlTokens; mapping(address => uint256) public tokensInBucket; mapping(address => uint256) public realisedTokens; mapping(address => uint256) public lastDividendPoints; mapping(address => bool) public userIsKnown; mapping(uint256 => address) public userList; uint256 public nextUser; uint256 public totalSupplyAltokens; uint256 public buffer; uint256 public lastDepositBlock; ///@dev values needed to calculate the distribution of base asset in proportion for alTokens staked uint256 public pointMultiplier = 10e18; uint256 public totalDividendPoints; uint256 public unclaimedDividends; /// @dev alchemist addresses whitelisted mapping (address => bool) public whiteList; /// @dev The address of the account which currently has administrative capabilities over this contract. address public governance; /// @dev The address of the pending governance. address public pendingGovernance; event GovernanceUpdated( address governance ); event PendingGovernanceUpdated( address pendingGovernance ); event TransmuterPeriodUpdated( uint256 newTransmutationPeriod ); constructor(address _AlToken, address _Token, address _governance) public { require(_governance != ZERO_ADDRESS, "Transmuter: 0 gov"); governance = _governance; AlToken = _AlToken; Token = _Token; TRANSMUTATION_PERIOD = 50; } ///@return displays the user's share of the pooled alTokens. function dividendsOwing(address account) public view returns (uint256) { uint256 newDividendPoints = totalDividendPoints.sub(lastDividendPoints[account]); return depositedAlTokens[account].mul(newDividendPoints).div(pointMultiplier); } ///@dev modifier to fill the bucket and keep bookkeeping correct incase of increase/decrease in shares modifier updateAccount(address account) { uint256 owing = dividendsOwing(account); if (owing > 0) { unclaimedDividends = unclaimedDividends.sub(owing); tokensInBucket[account] = tokensInBucket[account].add(owing); } lastDividendPoints[account] = totalDividendPoints; _; } ///@dev modifier add users to userlist. Users are indexed in order to keep track of when a bond has been filled modifier checkIfNewUser() { if (!userIsKnown[msg.sender]) { userList[nextUser] = msg.sender; userIsKnown[msg.sender] = true; nextUser++; } _; } ///@dev run the phased distribution of the buffered funds modifier runPhasedDistribution() { uint256 _lastDepositBlock = lastDepositBlock; uint256 _currentBlock = block.number; uint256 _toDistribute = 0; uint256 _buffer = buffer; // check if there is something in bufffer if (_buffer > 0) { // NOTE: if last deposit was updated in the same block as the current call // then the below logic gates will fail //calculate diffrence in time uint256 deltaTime = _currentBlock.sub(_lastDepositBlock); // distribute all if bigger than timeframe if(deltaTime >= TRANSMUTATION_PERIOD) { _toDistribute = _buffer; } else { //needs to be bigger than 0 cuzz solidity no decimals if(_buffer.mul(deltaTime) > TRANSMUTATION_PERIOD) { _toDistribute = _buffer.mul(deltaTime).div(TRANSMUTATION_PERIOD); } } // factually allocate if any needs distribution if(_toDistribute > 0){ // remove from buffer buffer = _buffer.sub(_toDistribute); // increase the allocation increaseAllocations(_toDistribute); } } // current timeframe is now the last lastDepositBlock = _currentBlock; _; } /// @dev A modifier which checks if whitelisted for minting. modifier onlyWhitelisted() { require(whiteList[msg.sender], "Transmuter: !whitelisted"); _; } /// @dev Checks that the current message sender or caller is the governance address. /// /// modifier onlyGov() { require(msg.sender == governance, "Transmuter: !governance"); _; } ///@dev set the TRANSMUTATION_PERIOD variable /// /// sets the length (in blocks) of one full distribution phase function setTransmutationPeriod(uint256 newTransmutationPeriod) public onlyGov() { TRANSMUTATION_PERIOD = newTransmutationPeriod; emit TransmuterPeriodUpdated(TRANSMUTATION_PERIOD); } ///@dev claims the base token after it has been transmuted /// ///This function reverts if there is no realisedToken balance function claim() public { address sender = msg.sender; require(realisedTokens[sender] > 0); uint256 value = realisedTokens[sender]; realisedTokens[sender] = 0; IERC20Burnable(Token).safeTransfer(sender, value); } ///@dev Withdraws staked alTokens from the transmuter /// /// This function reverts if you try to draw more tokens than you deposited /// ///@param amount the amount of alTokens to unstake function unstake(uint256 amount) public updateAccount(msg.sender) { // by calling this function before transmuting you forfeit your gained allocation address sender = msg.sender; require(depositedAlTokens[sender] >= amount,"Transmuter: unstake amount exceeds deposited amount"); depositedAlTokens[sender] = depositedAlTokens[sender].sub(amount); totalSupplyAltokens = totalSupplyAltokens.sub(amount); IERC20Burnable(AlToken).safeTransfer(sender, amount); } ///@dev Deposits alTokens into the transmuter /// ///@param amount the amount of alTokens to stake function stake(uint256 amount) public runPhasedDistribution() updateAccount(msg.sender) checkIfNewUser() { // requires approval of AlToken first address sender = msg.sender; //require tokens transferred in; IERC20Burnable(AlToken).safeTransferFrom(sender, address(this), amount); totalSupplyAltokens = totalSupplyAltokens.add(amount); depositedAlTokens[sender] = depositedAlTokens[sender].add(amount); } /// @dev Converts the staked alTokens to the base tokens in amount of the sum of pendingdivs and tokensInBucket /// /// once the alToken has been converted, it is burned, and the base token becomes realisedTokens which can be recieved using claim() /// /// reverts if there are no pendingdivs or tokensInBucket function transmute() public runPhasedDistribution() updateAccount(msg.sender) { address sender = msg.sender; uint256 pendingz = tokensInBucket[sender]; uint256 diff; require(pendingz > 0, "need to have pending in bucket"); tokensInBucket[sender] = 0; // check bucket overflow if (pendingz > depositedAlTokens[sender]) { diff = pendingz.sub(depositedAlTokens[sender]); // remove overflow pendingz = depositedAlTokens[sender]; } // decrease altokens depositedAlTokens[sender] = depositedAlTokens[sender].sub(pendingz); // BURN ALTOKENS IERC20Burnable(AlToken).burn(pendingz); // adjust total totalSupplyAltokens = totalSupplyAltokens.sub(pendingz); // reallocate overflow increaseAllocations(diff); // add payout realisedTokens[sender] = realisedTokens[sender].add(pendingz); } /// @dev Executes transmute() on another account that has had more base tokens allocated to it than alTokens staked. /// /// The caller of this function will have the surlus base tokens credited to their tokensInBucket balance, rewarding them for performing this action /// /// This function reverts if the address to transmute is not over-filled. /// /// @param toTransmute address of the account you will force transmute. function forceTransmute(address toTransmute) public runPhasedDistribution() updateAccount(msg.sender) updateAccount(toTransmute) { //load into memory address sender = msg.sender; uint256 pendingz = tokensInBucket[toTransmute]; // check restrictions require( pendingz > depositedAlTokens[toTransmute], "Transmuter: !overflow" ); // empty bucket tokensInBucket[toTransmute] = 0; // calculaate diffrence uint256 diff = pendingz.sub(depositedAlTokens[toTransmute]); // remove overflow pendingz = depositedAlTokens[toTransmute]; // decrease altokens depositedAlTokens[toTransmute] = 0; // BURN ALTOKENS IERC20Burnable(AlToken).burn(pendingz); // adjust total totalSupplyAltokens = totalSupplyAltokens.sub(pendingz); // reallocate overflow tokensInBucket[sender] = tokensInBucket[sender].add(diff); // add payout realisedTokens[toTransmute] = realisedTokens[toTransmute].add(pendingz); // force payout of realised tokens of the toTransmute address if (realisedTokens[toTransmute] > 0) { uint256 value = realisedTokens[toTransmute]; realisedTokens[toTransmute] = 0; IERC20Burnable(Token).safeTransfer(toTransmute, value); } } /// @dev Transmutes and unstakes all alTokens /// /// This function combines the transmute and unstake functions for ease of use function exit() public { transmute(); uint256 toWithdraw = depositedAlTokens[msg.sender]; unstake(toWithdraw); } /// @dev Transmutes and claims all converted base tokens. /// /// This function combines the transmute and claim functions while leaving your remaining alTokens staked. function transmuteAndClaim() public { transmute(); claim(); } /// @dev Transmutes, claims base tokens, and withdraws alTokens. /// /// This function helps users to exit the transmuter contract completely after converting their alTokens to the base pair. function transmuteClaimAndWithdraw() public { transmute(); claim(); uint256 toWithdraw = depositedAlTokens[msg.sender]; unstake(toWithdraw); } /// @dev Distributes the base token proportionally to all alToken stakers. /// /// This function is meant to be called by the Alchemist contract for when it is sending yield to the transmuter. /// Anyone can call this and add funds, idk why they would do that though... /// /// @param origin the account that is sending the tokens to be distributed. /// @param amount the amount of base tokens to be distributed to the transmuter. function distribute(address origin, uint256 amount) public onlyWhitelisted() runPhasedDistribution() { IERC20Burnable(Token).safeTransferFrom(origin, address(this), amount); buffer = buffer.add(amount); } /// @dev Allocates the incoming yield proportionally to all alToken stakers. /// /// @param amount the amount of base tokens to be distributed in the transmuter. function increaseAllocations(uint256 amount) internal { if(totalSupplyAltokens > 0 && amount > 0) { totalDividendPoints = totalDividendPoints.add( amount.mul(pointMultiplier).div(totalSupplyAltokens) ); unclaimedDividends = unclaimedDividends.add(amount); } else { buffer = buffer.add(amount); } } /// @dev Gets the status of a user's staking position. /// /// The total amount allocated to a user is the sum of pendingdivs and inbucket. /// /// @param user the address of the user you wish to query. /// /// returns user status function userInfo(address user) public view returns ( uint256 depositedAl, uint256 pendingdivs, uint256 inbucket, uint256 realised ) { uint256 _depositedAl = depositedAlTokens[user]; uint256 _toDistribute = buffer.mul(block.number.sub(lastDepositBlock)).div(TRANSMUTATION_PERIOD); if(block.number.sub(lastDepositBlock) > TRANSMUTATION_PERIOD){ _toDistribute = buffer; } uint256 _pendingdivs = _toDistribute.mul(depositedAlTokens[user]).div(totalSupplyAltokens); uint256 _inbucket = tokensInBucket[user].add(dividendsOwing(user)); uint256 _realised = realisedTokens[user]; return (_depositedAl, _pendingdivs, _inbucket, _realised); } /// @dev Gets the status of multiple users in one call /// /// This function is used to query the contract to check for /// accounts that have overfilled positions in order to check /// who can be force transmuted. /// /// @param from the first index of the userList /// @param to the last index of the userList /// /// returns the userList with their staking status in paginated form. function getMultipleUserInfo(uint256 from, uint256 to) public view returns (address[] memory theUserList, uint256[] memory theUserData) { uint256 i = from; uint256 delta = to - from; address[] memory _theUserList = new address[](delta); //user uint256[] memory _theUserData = new uint256[](delta * 2); //deposited-bucket uint256 y = 0; uint256 _toDistribute = buffer.mul(block.number.sub(lastDepositBlock)).div(TRANSMUTATION_PERIOD); if(block.number.sub(lastDepositBlock) > TRANSMUTATION_PERIOD){ _toDistribute = buffer; } for (uint256 x = 0; x < delta; x += 1) { _theUserList[x] = userList[i]; _theUserData[y] = depositedAlTokens[userList[i]]; _theUserData[y + 1] = dividendsOwing(userList[i]).add(tokensInBucket[userList[i]]).add(_toDistribute.mul(depositedAlTokens[userList[i]]).div(totalSupplyAltokens)); y += 2; i += 1; } return (_theUserList, _theUserData); } /// @dev Gets info on the buffer /// /// This function is used to query the contract to get the /// latest state of the buffer /// /// @return _toDistribute the amount ready to be distributed /// @return _deltaBlocks the amount of time since the last phased distribution /// @return _buffer the amount in the buffer function bufferInfo() public view returns (uint256 _toDistribute, uint256 _deltaBlocks, uint256 _buffer){ _deltaBlocks = block.number.sub(lastDepositBlock); _buffer = buffer; _toDistribute = _buffer.mul(_deltaBlocks).div(TRANSMUTATION_PERIOD); } /// @dev Sets the pending governance. /// /// This function reverts if the new pending governance is the zero address or the caller is not the current /// governance. This is to prevent the contract governance being set to the zero address which would deadlock /// privileged contract functionality. /// /// @param _pendingGovernance the new pending governance. function setPendingGovernance(address _pendingGovernance) external onlyGov { require(_pendingGovernance != ZERO_ADDRESS, "Transmuter: 0 gov"); pendingGovernance = _pendingGovernance; emit PendingGovernanceUpdated(_pendingGovernance); } /// @dev Accepts the role as governance. /// /// This function reverts if the caller is not the new pending governance. function acceptGovernance() external { require(msg.sender == pendingGovernance,"!pendingGovernance"); address _pendingGovernance = pendingGovernance; governance = _pendingGovernance; emit GovernanceUpdated(_pendingGovernance); } /// This function reverts if the caller is not governance /// /// @param _toWhitelist the account to mint tokens to. /// @param _state the whitelist state. function setWhitelist(address _toWhitelist, bool _state) external onlyGov { whiteList[_toWhitelist] = _state; } } // SPDX-License-Identifier: MIT 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; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.8; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IERC20Burnable is IERC20 { function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; //import "hardhat/console.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {FixedPointMath} from "./libraries/FixedPointMath.sol"; import {IMintableERC20} from "./interfaces/IMintableERC20.sol"; import {Pool} from "./libraries/pools/Pool.sol"; import {Stake} from "./libraries/pools/Stake.sol"; import {StakingPools} from "./StakingPools.sol"; import "hardhat/console.sol"; /// @title StakingPools // ___ __ __ _ ___ __ _ // / _ | / / ____ / / ___ __ _ (_) __ __ / _ \ ____ ___ ___ ___ ___ / /_ ___ (_) // / __ | / / / __/ / _ \/ -_) / ' \ / / \ \ / / ___/ / __// -_) (_-</ -_) / _ \/ __/ (_-< _ // /_/ |_|/_/ \__/ /_//_/\__/ /_/_/_//_/ /_\_\ /_/ /_/ \__/ /___/\__/ /_//_/\__/ /___/(_) // // _______..___________. ___ __ ___ __ .__ __. _______ .______ ______ ______ __ _______. // / || | / \ | |/ / | | | \ | | / _____| | _ \ / __ \ / __ \ | | / | // | (----``---| |----` / ^ \ | ' / | | | \| | | | __ | |_) | | | | | | | | | | | | (----` // \ \ | | / /_\ \ | < | | | . ` | | | |_ | | ___/ | | | | | | | | | | \ \ // .----) | | | / _____ \ | . \ | | | |\ | | |__| | | | | `--' | | `--' | | `----..----) | // |_______/ |__| /__/ \__\ |__|\__\ |__| |__| \__| \______| | _| \______/ \______/ |_______||_______/ /// /// @dev A contract which allows users to stake to farm tokens. /// /// This contract was inspired by Chef Nomi's 'MasterChef' contract which can be found in this /// repository: https://github.com/sushiswap/sushiswap. contract StakingPools is ReentrancyGuard { using FixedPointMath for FixedPointMath.FixedDecimal; using Pool for Pool.Data; using Pool for Pool.List; using SafeERC20 for IERC20; using SafeMath for uint256; using Stake for Stake.Data; event PendingGovernanceUpdated( address pendingGovernance ); event GovernanceUpdated( address governance ); event RewardRateUpdated( uint256 rewardRate ); event PoolRewardWeightUpdated( uint256 indexed poolId, uint256 rewardWeight ); event PoolCreated( uint256 indexed poolId, IERC20 indexed token ); event TokensDeposited( address indexed user, uint256 indexed poolId, uint256 amount ); event TokensWithdrawn( address indexed user, uint256 indexed poolId, uint256 amount ); event TokensClaimed( address indexed user, uint256 indexed poolId, uint256 amount ); /// @dev The token which will be minted as a reward for staking. IMintableERC20 public reward; /// @dev The address of the account which currently has administrative capabilities over this contract. address public governance; address public pendingGovernance; /// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool /// will return an identifier of zero. mapping(IERC20 => uint256) public tokenPoolIds; /// @dev The context shared between the pools. Pool.Context private _ctx; /// @dev A list of all of the pools. Pool.List private _pools; /// @dev A mapping of all of the user stakes mapped first by pool and then by address. mapping(address => mapping(uint256 => Stake.Data)) private _stakes; constructor( IMintableERC20 _reward, address _governance ) public { require(_governance != address(0), "StakingPools: governance address cannot be 0x0"); reward = _reward; governance = _governance; } /// @dev A modifier which reverts when the caller is not the governance. modifier onlyGovernance() { require(msg.sender == governance, "StakingPools: only governance"); _; } /// @dev Sets the governance. /// /// This function can only called by the current governance. /// /// @param _pendingGovernance the new pending governance. function setPendingGovernance(address _pendingGovernance) external onlyGovernance { require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0"); pendingGovernance = _pendingGovernance; emit PendingGovernanceUpdated(_pendingGovernance); } function acceptGovernance() external { require(msg.sender == pendingGovernance, "StakingPools: only pending governance"); address _pendingGovernance = pendingGovernance; governance = _pendingGovernance; emit GovernanceUpdated(_pendingGovernance); } /// @dev Sets the distribution reward rate. /// /// This will update all of the pools. /// /// @param _rewardRate The number of tokens to distribute per second. function setRewardRate(uint256 _rewardRate) external onlyGovernance { _updatePools(); _ctx.rewardRate = _rewardRate; emit RewardRateUpdated(_rewardRate); } /// @dev Creates a new pool. /// /// The created pool will need to have its reward weight initialized before it begins generating rewards. /// /// @param _token The token the pool will accept for staking. /// /// @return the identifier for the newly created pool. function createPool(IERC20 _token) external onlyGovernance returns (uint256) { require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool"); uint256 _poolId = _pools.length(); _pools.push(Pool.Data({ token: _token, totalDeposited: 0, rewardWeight: 0, accumulatedRewardWeight: FixedPointMath.FixedDecimal(0), lastUpdatedBlock: block.number })); tokenPoolIds[_token] = _poolId + 1; emit PoolCreated(_poolId, _token); return _poolId; } /// @dev Sets the reward weights of all of the pools. /// /// @param _rewardWeights The reward weights of all of the pools. function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance { require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch"); _updatePools(); uint256 _totalRewardWeight = _ctx.totalRewardWeight; for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) { Pool.Data storage _pool = _pools.get(_poolId); uint256 _currentRewardWeight = _pool.rewardWeight; if (_currentRewardWeight == _rewardWeights[_poolId]) { continue; } // FIXME _totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]); _pool.rewardWeight = _rewardWeights[_poolId]; emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]); } _ctx.totalRewardWeight = _totalRewardWeight; } /// @dev Stakes tokens into a pool. /// /// @param _poolId the pool to deposit tokens into. /// @param _depositAmount the amount of tokens to deposit. function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _stake.update(_pool, _ctx); _deposit(_poolId, _depositAmount); } /// @dev Withdraws staked tokens from a pool. /// /// @param _poolId The pool to withdraw staked tokens from. /// @param _withdrawAmount The number of tokens to withdraw. function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _stake.update(_pool, _ctx); _claim(_poolId); _withdraw(_poolId, _withdrawAmount); } /// @dev Claims all rewarded tokens from a pool. /// /// @param _poolId The pool to claim rewards from. /// /// @notice use this function to claim the tokens from a corresponding pool by ID. function claim(uint256 _poolId) external nonReentrant { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _stake.update(_pool, _ctx); _claim(_poolId); } /// @dev Claims all rewards from a pool and then withdraws all staked tokens. /// /// @param _poolId the pool to exit from. function exit(uint256 _poolId) external nonReentrant { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _stake.update(_pool, _ctx); _claim(_poolId); _withdraw(_poolId, _stake.totalDeposited); } /// @dev Gets the rate at which tokens are minted to stakers for all pools. /// /// @return the reward rate. function rewardRate() external view returns (uint256) { return _ctx.rewardRate; } /// @dev Gets the total reward weight between all the pools. /// /// @return the total reward weight. function totalRewardWeight() external view returns (uint256) { return _ctx.totalRewardWeight; } /// @dev Gets the number of pools that exist. /// /// @return the pool count. function poolCount() external view returns (uint256) { return _pools.length(); } /// @dev Gets the token a pool accepts. /// /// @param _poolId the identifier of the pool. /// /// @return the token. function getPoolToken(uint256 _poolId) external view returns (IERC20) { Pool.Data storage _pool = _pools.get(_poolId); return _pool.token; } /// @dev Gets the total amount of funds staked in a pool. /// /// @param _poolId the identifier of the pool. /// /// @return the total amount of staked or deposited tokens. function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) { Pool.Data storage _pool = _pools.get(_poolId); return _pool.totalDeposited; } /// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block. /// /// @param _poolId the identifier of the pool. /// /// @return the pool reward weight. function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) { Pool.Data storage _pool = _pools.get(_poolId); return _pool.rewardWeight; } /// @dev Gets the amount of tokens per block being distributed to stakers for a pool. /// /// @param _poolId the identifier of the pool. /// /// @return the pool reward rate. function getPoolRewardRate(uint256 _poolId) external view returns (uint256) { Pool.Data storage _pool = _pools.get(_poolId); return _pool.getRewardRate(_ctx); } /// @dev Gets the number of tokens a user has staked into a pool. /// /// @param _account The account to query. /// @param _poolId the identifier of the pool. /// /// @return the amount of deposited tokens. function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) { Stake.Data storage _stake = _stakes[_account][_poolId]; return _stake.totalDeposited; } /// @dev Gets the number of unclaimed reward tokens a user can claim from a pool. /// /// @param _account The account to get the unclaimed balance of. /// @param _poolId The pool to check for unclaimed rewards. /// /// @return the amount of unclaimed reward tokens a user has in a pool. function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) { Stake.Data storage _stake = _stakes[_account][_poolId]; return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx); } /// @dev Updates all of the pools. function _updatePools() internal { for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) { Pool.Data storage _pool = _pools.get(_poolId); _pool.update(_ctx); } } /// @dev Stakes tokens into a pool. /// /// The pool and stake MUST be updated before calling this function. /// /// @param _poolId the pool to deposit tokens into. /// @param _depositAmount the amount of tokens to deposit. function _deposit(uint256 _poolId, uint256 _depositAmount) internal { Pool.Data storage _pool = _pools.get(_poolId); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _pool.totalDeposited = _pool.totalDeposited.add(_depositAmount); _stake.totalDeposited = _stake.totalDeposited.add(_depositAmount); _pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount); emit TokensDeposited(msg.sender, _poolId, _depositAmount); } /// @dev Withdraws staked tokens from a pool. /// /// The pool and stake MUST be updated before calling this function. /// /// @param _poolId The pool to withdraw staked tokens from. /// @param _withdrawAmount The number of tokens to withdraw. function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal { Pool.Data storage _pool = _pools.get(_poolId); Stake.Data storage _stake = _stakes[msg.sender][_poolId]; _pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount); _stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount); _pool.token.safeTransfer(msg.sender, _withdrawAmount); emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount); } /// @dev Claims all rewarded tokens from a pool. /// /// The pool and stake MUST be updated before calling this function. /// /// @param _poolId The pool to claim rewards from. /// /// @notice use this function to claim the tokens from a corresponding pool by ID. function _claim(uint256 _poolId) internal { Stake.Data storage _stake = _stakes[msg.sender][_poolId]; uint256 _claimAmount = _stake.totalUnclaimed; _stake.totalUnclaimed = 0; reward.mint(msg.sender, _claimAmount); emit TokensClaimed(msg.sender, _poolId, _claimAmount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; import {IDetailedERC20} from "./IDetailedERC20.sol"; interface IMintableERC20 is IDetailedERC20{ function mint(address _recipient, uint256 _amount) external; function burnFrom(address account, uint256 amount) external; function lowerHasMinted(uint256 amount)external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import {Math} from "@openzeppelin/contracts/math/Math.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {FixedPointMath} from "../FixedPointMath.sol"; import {IDetailedERC20} from "../../interfaces/IDetailedERC20.sol"; import "hardhat/console.sol"; /// @title Pool /// /// @dev A library which provides the Pool data struct and associated functions. library Pool { using FixedPointMath for FixedPointMath.FixedDecimal; using Pool for Pool.Data; using Pool for Pool.List; using SafeMath for uint256; struct Context { uint256 rewardRate; uint256 totalRewardWeight; } struct Data { IERC20 token; uint256 totalDeposited; uint256 rewardWeight; FixedPointMath.FixedDecimal accumulatedRewardWeight; uint256 lastUpdatedBlock; } struct List { Data[] elements; } /// @dev Updates the pool. /// /// @param _ctx the pool context. function update(Data storage _data, Context storage _ctx) internal { _data.accumulatedRewardWeight = _data.getUpdatedAccumulatedRewardWeight(_ctx); _data.lastUpdatedBlock = block.number; } /// @dev Gets the rate at which the pool will distribute rewards to stakers. /// /// @param _ctx the pool context. /// /// @return the reward rate of the pool in tokens per block. function getRewardRate(Data storage _data, Context storage _ctx) internal view returns (uint256) { // console.log("get reward rate"); // console.log(uint(_data.rewardWeight)); // console.log(uint(_ctx.totalRewardWeight)); // console.log(uint(_ctx.rewardRate)); return _ctx.rewardRate.mul(_data.rewardWeight).div(_ctx.totalRewardWeight); } /// @dev Gets the accumulated reward weight of a pool. /// /// @param _ctx the pool context. /// /// @return the accumulated reward weight. function getUpdatedAccumulatedRewardWeight(Data storage _data, Context storage _ctx) internal view returns (FixedPointMath.FixedDecimal memory) { if (_data.totalDeposited == 0) { return _data.accumulatedRewardWeight; } uint256 _elapsedTime = block.number.sub(_data.lastUpdatedBlock); if (_elapsedTime == 0) { return _data.accumulatedRewardWeight; } uint256 _rewardRate = _data.getRewardRate(_ctx); uint256 _distributeAmount = _rewardRate.mul(_elapsedTime); if (_distributeAmount == 0) { return _data.accumulatedRewardWeight; } FixedPointMath.FixedDecimal memory _rewardWeight = FixedPointMath.fromU256(_distributeAmount).div(_data.totalDeposited); return _data.accumulatedRewardWeight.add(_rewardWeight); } /// @dev Adds an element to the list. /// /// @param _element the element to add. function push(List storage _self, Data memory _element) internal { _self.elements.push(_element); } /// @dev Gets an element from the list. /// /// @param _index the index in the list. /// /// @return the element at the specified index. function get(List storage _self, uint256 _index) internal view returns (Data storage) { return _self.elements[_index]; } /// @dev Gets the last element in the list. /// /// This function will revert if there are no elements in the list. ///ck /// @return the last element in the list. function last(List storage _self) internal view returns (Data storage) { return _self.elements[_self.lastIndex()]; } /// @dev Gets the index of the last element in the list. /// /// This function will revert if there are no elements in the list. /// /// @return the index of the last element. function lastIndex(List storage _self) internal view returns (uint256) { uint256 _length = _self.length(); return _length.sub(1, "Pool.List: list is empty"); } /// @dev Gets the number of elements in the list. /// /// @return the number of elements. function length(List storage _self) internal view returns (uint256) { return _self.elements.length; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import {Math} from "@openzeppelin/contracts/math/Math.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {FixedPointMath} from "../FixedPointMath.sol"; import {IDetailedERC20} from "../../interfaces/IDetailedERC20.sol"; import {Pool} from "./Pool.sol"; import "hardhat/console.sol"; /// @title Stake /// /// @dev A library which provides the Stake data struct and associated functions. library Stake { using FixedPointMath for FixedPointMath.FixedDecimal; using Pool for Pool.Data; using SafeMath for uint256; using Stake for Stake.Data; struct Data { uint256 totalDeposited; uint256 totalUnclaimed; FixedPointMath.FixedDecimal lastAccumulatedWeight; } function update(Data storage _self, Pool.Data storage _pool, Pool.Context storage _ctx) internal { _self.totalUnclaimed = _self.getUpdatedTotalUnclaimed(_pool, _ctx); _self.lastAccumulatedWeight = _pool.getUpdatedAccumulatedRewardWeight(_ctx); } function getUpdatedTotalUnclaimed(Data storage _self, Pool.Data storage _pool, Pool.Context storage _ctx) internal view returns (uint256) { FixedPointMath.FixedDecimal memory _currentAccumulatedWeight = _pool.getUpdatedAccumulatedRewardWeight(_ctx); FixedPointMath.FixedDecimal memory _lastAccumulatedWeight = _self.lastAccumulatedWeight; if (_currentAccumulatedWeight.cmp(_lastAccumulatedWeight) == 0) { return _self.totalUnclaimed; } uint256 _distributedAmount = _currentAccumulatedWeight .sub(_lastAccumulatedWeight) .mul(_self.totalDeposited) .decode(); return _self.totalUnclaimed.add(_distributedAmount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {IDetailedERC20} from "./interfaces/IDetailedERC20.sol"; /// @title TimeToken /// /// @dev This is the contract for the Alchemix time token. /// contract TimeToken is AccessControl, ERC20("Technological Instantiation Meta Env", "TIME") { /// @dev The identifier of the role which maintains other roles. bytes32 public constant ADMIN_ROLE = keccak256("ADMIN"); /// @dev The identifier of the role which allows accounts to mint tokens. bytes32 public constant MINTER_ROLE = keccak256("MINTER"); constructor() public { _setupRole(ADMIN_ROLE, msg.sender); _setupRole(MINTER_ROLE, msg.sender); _setRoleAdmin(MINTER_ROLE, ADMIN_ROLE); _setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE); } /// @dev A modifier which checks that the caller has the minter role. modifier onlyMinter() { require(hasRole(MINTER_ROLE, msg.sender), "TimeToken: only minter"); _; } /// @dev Mints tokens to a recipient. /// /// This function reverts if the caller does not have the minter role. /// /// @param _recipient the account to mint tokens to. /// @param _amount the amount of tokens to mint. function mint(address _recipient, uint256 _amount) external onlyMinter { _mint(_recipient, _amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../../GSN/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.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; 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 { } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {IDetailedERC20} from "./interfaces/IDetailedERC20.sol"; /// @title AlToken /// /// @dev This is the contract for the Alchemix utillity token usd. /// /// Initially, the contract deployer is given both the admin and minter role. This allows them to pre-mine tokens, /// transfer admin to a timelock contract, and lastly, grant the staking pools the minter role. After this is done, /// the deployer must revoke their admin role and minter role. contract AlToken is AccessControl, ERC20("Alchemix USD", "alUSD") { using SafeERC20 for ERC20; /// @dev The identifier of the role which maintains other roles. bytes32 public constant ADMIN_ROLE = keccak256("ADMIN"); /// @dev The identifier of the role which allows accounts to mint tokens. bytes32 public constant SENTINEL_ROLE = keccak256("SENTINEL"); /// @dev addresses whitelisted for minting new tokens mapping (address => bool) public whiteList; /// @dev addresses blacklisted for minting new tokens mapping (address => bool) public blacklist; /// @dev addresses paused for minting new tokens mapping (address => bool) public paused; /// @dev ceiling per address for minting new tokens mapping (address => uint256) public ceiling; /// @dev already minted amount per address to track the ceiling mapping (address => uint256) public hasMinted; event Paused(address alchemistAddress, bool isPaused); constructor() public { _setupRole(ADMIN_ROLE, msg.sender); _setupRole(SENTINEL_ROLE, msg.sender); _setRoleAdmin(SENTINEL_ROLE,ADMIN_ROLE); _setRoleAdmin(ADMIN_ROLE,ADMIN_ROLE); } /// @dev A modifier which checks if whitelisted for minting. modifier onlyWhitelisted() { require(whiteList[msg.sender], "AlUSD: Alchemist is not whitelisted"); _; } /// @dev Mints tokens to a recipient. /// /// This function reverts if the caller does not have the minter role. /// /// @param _recipient the account to mint tokens to. /// @param _amount the amount of tokens to mint. function mint(address _recipient, uint256 _amount) external onlyWhitelisted { require(!blacklist[msg.sender], "AlUSD: Alchemist is blacklisted."); uint256 _total = _amount.add(hasMinted[msg.sender]); require(_total <= ceiling[msg.sender],"AlUSD: Alchemist's ceiling was breached."); require(!paused[msg.sender], "AlUSD: user is currently paused."); hasMinted[msg.sender] = hasMinted[msg.sender].add(_amount); _mint(_recipient, _amount); } /// This function reverts if the caller does not have the admin role. /// /// @param _toWhitelist the account to mint tokens to. /// @param _state the whitelist state. function setWhitelist(address _toWhitelist, bool _state) external onlyAdmin { whiteList[_toWhitelist] = _state; } /// This function reverts if the caller does not have the admin role. /// /// @param _newSentinel the account to set as sentinel. function setSentinel(address _newSentinel) external onlyAdmin { _setupRole(SENTINEL_ROLE, _newSentinel); } /// This function reverts if the caller does not have the admin role. /// /// @param _toBlacklist the account to mint tokens to. function setBlacklist(address _toBlacklist) external onlySentinel { blacklist[_toBlacklist] = true; } /// This function reverts if the caller does not have the admin role. function pauseAlchemist(address _toPause, bool _state) external onlySentinel { paused[_toPause] = _state; Paused(_toPause, _state); } /// This function reverts if the caller does not have the admin role. /// /// @param _toSetCeiling the account set the ceiling off. /// @param _ceiling the max amount of tokens the account is allowed to mint. function setCeiling(address _toSetCeiling, uint256 _ceiling) external onlyAdmin { ceiling[_toSetCeiling] = _ceiling; } /// @dev A modifier which checks that the caller has the admin role. modifier onlyAdmin() { require(hasRole(ADMIN_ROLE, msg.sender), "only admin"); _; } /// @dev A modifier which checks that the caller has the sentinel role. modifier onlySentinel() { require(hasRole(SENTINEL_ROLE, msg.sender), "only sentinel"); _; } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } /** * @dev lowers hasminted from the caller's allocation * */ function lowerHasMinted( uint256 amount) public onlyWhitelisted { hasMinted[msg.sender] = hasMinted[msg.sender].sub(amount); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import "hardhat/console.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IYearnController.sol"; import "../interfaces/IYearnVault.sol"; contract YearnVaultMock is ERC20 { using SafeERC20 for IDetailedERC20; using SafeMath for uint256; uint256 public min = 9500; uint256 public constant max = 10000; IYearnController public controller; IDetailedERC20 public token; constructor(IDetailedERC20 _token, IYearnController _controller) public ERC20("yEarn Mock", "yMOCK") { token = _token; controller = _controller; } function vdecimals() external view returns (uint8) { return decimals(); } function balance() public view returns (uint256) { return token.balanceOf(address(this)).add(controller.balanceOf(address(token))); } function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } function earn() external { uint _bal = available(); token.safeTransfer(address(controller), _bal); controller.earn(address(token), _bal); } function deposit(uint256 _amount) external returns (uint){ uint _pool = balance(); uint _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens uint _shares = 0; if (totalSupply() == 0) { _shares = _amount; } else { _shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, _shares); } function withdraw(uint _shares, address _recipient) external returns (uint) { uint _r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); // Check balance uint _b = token.balanceOf(address(this)); if (_b < _r) { uint _withdraw = _r.sub(_b); controller.withdraw(address(token), _withdraw); uint _after = token.balanceOf(address(this)); uint _diff = _after.sub(_b); if (_diff < _withdraw) { _r = _b.add(_diff); } } token.safeTransfer(_recipient, _r); } function pricePerShare() external view returns (uint256) { return balance().mul(1e18).div(totalSupply()); }// changed to v2 /// @dev This is not part of the vault contract and is meant for quick debugging contracts to have control over /// completely clearing the vault buffer to test certain behaviors better. function clear() external { token.safeTransfer(address(controller), token.balanceOf(address(this))); controller.earn(address(token), token.balanceOf(address(this))); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; interface IYearnController { function balanceOf(address _token) external view returns (uint256); function earn(address _token, uint256 _amount) external; function withdraw(address _token, uint256 _withdrawAmount) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IDetailedERC20} from "./IDetailedERC20.sol"; interface IYearnVault { function balanceOf(address user) external view returns (uint); function pricePerShare() external view returns (uint); function deposit(uint amount) external returns (uint); function withdraw(uint shares, address recipient) external returns (uint); function token() external view returns (IDetailedERC20); function totalAssets() external view returns (uint); function decimals() external view returns (uint8); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import "hardhat/console.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/IYearnController.sol"; contract YearnControllerMock is IYearnController { using SafeERC20 for IERC20; using SafeMath for uint256; address constant public blackhole = 0x000000000000000000000000000000000000dEaD; uint256 public withdrawalFee = 50; uint256 constant public withdrawalMax = 10000; function setWithdrawalFee(uint256 _withdrawalFee) external { withdrawalFee = _withdrawalFee; } function balanceOf(address _token) external view override returns (uint256) { return IERC20(_token).balanceOf(address(this)); } function earn(address _token, uint256 _amount) external override { } function withdraw(address _token, uint256 _amount) external override { uint _balance = IERC20(_token).balanceOf(address(this)); // uint _fee = _amount.mul(withdrawalFee).div(withdrawalMax); // IERC20(_token).safeTransfer(blackhole, _fee); IERC20(_token).safeTransfer(msg.sender, _amount); } } /* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./MultiSigWallet.sol"; /// @title Multisignature wallet with time lock- Allows multiple parties to execute a transaction after a time lock has passed. /// @author Amir Bandeali - <[email protected]> // solhint-disable not-rely-on-time contract MultiSigWalletWithTimeLock is MultiSigWallet { using SafeMath for uint256; event ConfirmationTimeSet(uint256 indexed transactionId, uint256 confirmationTime); event TimeLockChange(uint256 secondsTimeLocked); uint256 public secondsTimeLocked; mapping (uint256 => uint256) public confirmationTimes; modifier fullyConfirmed(uint256 transactionId) { require( isConfirmed(transactionId), "TX_NOT_FULLY_CONFIRMED" ); _; } modifier pastTimeLock(uint256 transactionId) { require( block.timestamp >= confirmationTimes[transactionId].add(secondsTimeLocked), "TIME_LOCK_INCOMPLETE" ); _; } /// @dev Contract constructor sets initial owners, required number of confirmations, and time lock. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. /// @param _secondsTimeLocked Duration needed after a transaction is confirmed and before it becomes executable, in seconds. constructor ( address[] memory _owners, uint256 _required, uint256 _secondsTimeLocked ) public MultiSigWallet(_owners, _required) { secondsTimeLocked = _secondsTimeLocked; } /// @dev Changes the duration of the time lock for transactions. /// @param _secondsTimeLocked Duration needed after a transaction is confirmed and before it becomes executable, in seconds. function changeTimeLock(uint256 _secondsTimeLocked) public onlyWallet { secondsTimeLocked = _secondsTimeLocked; emit TimeLockChange(_secondsTimeLocked); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint256 transactionId) public override ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { bool isTxFullyConfirmedBeforeConfirmation = isConfirmed(transactionId); confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); if (!isTxFullyConfirmedBeforeConfirmation && isConfirmed(transactionId)) { _setConfirmationTime(transactionId, block.timestamp); } } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint256 transactionId) public override notExecuted(transactionId) fullyConfirmed(transactionId) pastTimeLock(transactionId) { Transaction storage txn = transactions[transactionId]; txn.executed = true; if (external_call(txn.destination, txn.value, txn.data.length, txn.data)) { emit Execution(transactionId); } else { emit ExecutionFailure(transactionId); txn.executed = false; } } /// @dev Sets the time of when a submission first passed. function _setConfirmationTime(uint256 transactionId, uint256 confirmationTime) internal { confirmationTimes[transactionId] = confirmationTime; emit ConfirmationTimeSet(transactionId, confirmationTime); } } pragma solidity ^0.6.12; /// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution. /// @author Stefan George - <[email protected]> contract MultiSigWallet { /* * Events */ event Confirmation(address indexed sender, uint indexed transactionId); event Revocation(address indexed sender, uint indexed transactionId); event Submission(uint indexed transactionId); event Execution(uint indexed transactionId); event ExecutionFailure(uint indexed transactionId); event Deposit(address indexed sender, uint value); event OwnerAddition(address indexed owner); event OwnerRemoval(address indexed owner); event RequirementChange(uint required); /* * Constants */ uint constant public MAX_OWNER_COUNT = 50; /* * Storage */ mapping (uint => Transaction) public transactions; mapping (uint => mapping (address => bool)) public confirmations; mapping (address => bool) public isOwner; address[] public owners; uint public required; uint public transactionCount; struct Transaction { address destination; uint value; bytes data; bool executed; } /* * Modifiers */ modifier onlyWallet() { require(msg.sender == address(this)); _; } modifier ownerDoesNotExist(address owner) { require(!isOwner[owner]); _; } modifier ownerExists(address owner) { require(isOwner[owner]); _; } modifier transactionExists(uint transactionId) { require(transactions[transactionId].destination != address(0)); _; } modifier confirmed(uint transactionId, address owner) { require(confirmations[transactionId][owner]); _; } modifier notConfirmed(uint transactionId, address owner) { require(!confirmations[transactionId][owner]); _; } modifier notExecuted(uint transactionId) { require(!transactions[transactionId].executed); _; } modifier notNull(address _address) { require(_address != address(0)); _; } modifier validRequirement(uint ownerCount, uint _required) { require(ownerCount <= MAX_OWNER_COUNT && _required <= ownerCount && _required != 0 && ownerCount != 0); _; } /// @dev Fallback function allows to deposit ether. fallback() external payable { if (msg.value > 0) emit Deposit(msg.sender, msg.value); } /* * Public functions */ /// @dev Contract constructor sets initial owners and required number of confirmations. /// @param _owners List of initial owners. /// @param _required Number of required confirmations. constructor(address[] memory _owners, uint _required) public validRequirement(_owners.length, _required) { for (uint i=0; i<_owners.length; i++) { require(!isOwner[_owners[i]] && _owners[i] != address(0)); isOwner[_owners[i]] = true; } owners = _owners; required = _required; } /// @dev Allows to add a new owner. Transaction has to be sent by wallet. /// @param owner Address of new owner. function addOwner(address owner) public onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); emit OwnerAddition(owner); } /// @dev Allows to remove an owner. Transaction has to be sent by wallet. /// @param owner Address of owner. function removeOwner(address owner) public onlyWallet ownerExists(owner) { isOwner[owner] = false; for (uint i=0; i<owners.length - 1; i++) if (owners[i] == owner) { owners[i] = owners[owners.length - 1]; break; } owners.pop(); if (required > owners.length) changeRequirement(owners.length); emit OwnerRemoval(owner); } /// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet. /// @param owner Address of owner to be replaced. /// @param newOwner Address of new owner. function replaceOwner(address owner, address newOwner) public onlyWallet ownerExists(owner) ownerDoesNotExist(newOwner) { for (uint i=0; i<owners.length; i++) if (owners[i] == owner) { owners[i] = newOwner; break; } isOwner[owner] = false; isOwner[newOwner] = true; emit OwnerRemoval(owner); emit OwnerAddition(newOwner); } /// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet. /// @param _required Number of required confirmations. function changeRequirement(uint _required) public onlyWallet validRequirement(owners.length, _required) { required = _required; emit RequirementChange(_required); } /// @dev Allows an owner to submit and confirm a transaction. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return transactionId Returns transaction ID. function submitTransaction(address destination, uint value, bytes memory data) public returns (uint transactionId) { transactionId = addTransaction(destination, value, data); confirmTransaction(transactionId); } /// @dev Allows an owner to confirm a transaction. /// @param transactionId Transaction ID. function confirmTransaction(uint transactionId) public virtual ownerExists(msg.sender) transactionExists(transactionId) notConfirmed(transactionId, msg.sender) { confirmations[transactionId][msg.sender] = true; emit Confirmation(msg.sender, transactionId); executeTransaction(transactionId); } /// @dev Allows an owner to revoke a confirmation for a transaction. /// @param transactionId Transaction ID. function revokeConfirmation(uint transactionId) public ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { confirmations[transactionId][msg.sender] = false; emit Revocation(msg.sender, transactionId); } /// @dev Allows anyone to execute a confirmed transaction. /// @param transactionId Transaction ID. function executeTransaction(uint transactionId) public virtual ownerExists(msg.sender) confirmed(transactionId, msg.sender) notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; if (external_call(txn.destination, txn.value, txn.data.length, txn.data)) Execution(transactionId); else { ExecutionFailure(transactionId); txn.executed = false; } } } // call has been separated into its own function in order to take advantage // of the Solidity's code generator to produce a loop that copies tx.data into memory. function external_call(address destination, uint value, uint dataLength, bytes memory data) internal returns (bool) { bool result; assembly { let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention) let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that result := call( sub(gas(), 34710), // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + // callNewAccountGas (25000, in case the destination address does not exist and needs creating) destination, value, d, dataLength, // Size of the input (in bytes) - this is what fixes the padding problem x, 0 // Output is ignored, therefore the output size is zero ) } return result; } /// @dev Returns the confirmation status of a transaction. /// @param transactionId Transaction ID. /// @return Confirmation status. function isConfirmed(uint transactionId) public view returns (bool) { uint count = 0; for (uint i=0; i<owners.length; i++) { if (confirmations[transactionId][owners[i]]) count += 1; if (count == required) return true; } } /* * Internal functions */ /// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet. /// @param destination Transaction target address. /// @param value Transaction ether value. /// @param data Transaction data payload. /// @return transactionId Returns transaction ID. function addTransaction(address destination, uint value, bytes memory data) internal notNull(destination) returns (uint transactionId) { transactionId = transactionCount; transactions[transactionId] = Transaction({ destination: destination, value: value, data: data, executed: false }); transactionCount += 1; Submission(transactionId); } /* * Web3 call functions */ /// @dev Returns number of confirmations of a transaction. /// @param transactionId Transaction ID. /// @return count Number of confirmations. function getConfirmationCount(uint transactionId) public view returns (uint count) { for (uint i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) count += 1; } /// @dev Returns total number of transactions after filers are applied. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return count Total number of transactions after filters are applied. function getTransactionCount(bool pending, bool executed) public view returns (uint count) { for (uint i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) count += 1; } /// @dev Returns list of owners. /// @return List of owner addresses. function getOwners() public view returns (address[] memory) { return owners; } /// @dev Returns array with owner addresses, which confirmed transaction. /// @param transactionId Transaction ID. /// @return _confirmations Returns array of owner addresses. function getConfirmations(uint transactionId) public view returns (address[] memory _confirmations) { address[] memory confirmationsTemp = new address[](owners.length); uint count = 0; uint i; for (i=0; i<owners.length; i++) if (confirmations[transactionId][owners[i]]) { confirmationsTemp[count] = owners[i]; count += 1; } _confirmations = new address[](count); for (i=0; i<count; i++) _confirmations[i] = confirmationsTemp[i]; } /// @dev Returns list of transaction IDs in defined range. /// @param from Index start position of transaction array. /// @param to Index end position of transaction array. /// @param pending Include pending transactions. /// @param executed Include executed transactions. /// @return _transactionIds Returns array of transaction IDs. function getTransactionIds(uint from, uint to, bool pending, bool executed) public view returns (uint[] memory _transactionIds) { uint[] memory transactionIdsTemp = new uint[](transactionCount); uint count = 0; uint i; for (i=0; i<transactionCount; i++) if ( pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } _transactionIds = new uint[](to - from); for (i=from; i<to; i++) _transactionIds[i - from] = transactionIdsTemp[i]; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; import {Math} from "@openzeppelin/contracts/math/Math.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {FixedPointMath} from "../FixedPointMath.sol"; import {IDetailedERC20} from "../../interfaces/IDetailedERC20.sol"; import {Round} from "./Round.sol"; /// @title Stake /// /// @dev A library which provides the Stake data struct and associated functions. library Stake { using FixedPointMath for FixedPointMath.FixedDecimal; using Round for Round.Data; using SafeMath for uint256; using Stake for Stake.Data; struct Data { uint256 totalDeposited; uint256 totalWeightedTime; uint256 lastUpdateTime; bool claimed; } function update(Data storage _self) internal { _self.totalWeightedTime = _self.getUpdatedTotalWeightedTime(); _self.lastUpdateTime = block.timestamp; } function getExchangedBalance(Data storage _self, Round.Data storage _round) internal view returns (uint256) { FixedPointMath.FixedDecimal memory _distributeWeight = _round.getDistributeWeight(); FixedPointMath.FixedDecimal memory _exchangedBalance = _distributeWeight.mul(_self.totalDeposited); return _exchangedBalance.decode(); } function getUnexchangedBalance(Data storage _self, Round.Data storage _round) internal view returns (uint256) { return _self.totalDeposited.sub(_self.getExchangedBalance(_round)); } function getRemainingLockupTime(Data storage _self, Round.Data storage _round) internal view returns (uint256) { uint256 _requiredWeightedTime = _self.getRequiredTotalWeightedTime(_round); uint256 _totalWeightedTime = _self.getUpdatedTotalWeightedTime(); if (_totalWeightedTime >= _requiredWeightedTime) { return 0; } uint256 _difference = _requiredWeightedTime.sub(_totalWeightedTime); uint256 _totalDeposited = _self.totalDeposited; if (_totalDeposited == 0) { return 0; } return _difference.div(_totalDeposited); } function getRequiredTotalWeightedTime(Data storage _self, Round.Data storage _round) internal view returns (uint256) { return _self.totalDeposited.mul(_round.lockupDuration); } function getUpdatedTotalWeightedTime(Data storage _self) internal view returns (uint256) { uint256 _elapsedTime = block.timestamp.sub(_self.lastUpdateTime); if (_elapsedTime == 0) { return _self.totalWeightedTime; } uint256 _weightedTime = _self.totalDeposited.mul(_elapsedTime); return _self.totalWeightedTime.add(_weightedTime); } function isUnlocked(Data storage _self, Round.Data storage _round) internal view returns (bool) { uint256 _requiredWeightedTime = _self.getRequiredTotalWeightedTime(_round); uint256 _totalWeightedTime = _self.getUpdatedTotalWeightedTime(); return _totalWeightedTime >= _requiredWeightedTime; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; import {Math} from "@openzeppelin/contracts/math/Math.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {FixedPointMath} from "../FixedPointMath.sol"; import {IDetailedERC20} from "../../interfaces/IDetailedERC20.sol"; library Round { using FixedPointMath for FixedPointMath.FixedDecimal; using Round for Data; using Round for List; using SafeMath for uint256; struct Data { uint256 availableBalance; uint256 commitEndTime; uint256 lockupDuration; uint256 totalDeposited; } struct List { Data[] elements; } /// @dev Gets if the round has been completed. /// /// @return if the current time is equal to or after the round's end time. function isCommitPhaseComplete(Data storage _self) internal view returns (bool) { return block.timestamp >= _self.commitEndTime; } /// @dev Gets the current amount of tokens to distribute per token staked. /// /// @return the distribute weight. function getDistributeWeight(Data storage _self) internal view returns (FixedPointMath.FixedDecimal memory) { FixedPointMath.FixedDecimal memory _weight = FixedPointMath.fromU256(_self.getDistributeBalance()); return _weight.div(_self.totalDeposited); } /// @dev Gets the amount to distribute to stakers. /// /// @return the amount to distribute. function getDistributeBalance(Data storage _self) internal view returns (uint256) { return Math.min(_self.availableBalance, _self.totalDeposited); } /// @dev Gets the amount to distribute in the next round. /// /// @return the runoff amount. function getRunoffBalance(Data storage _self) internal view returns (uint256) { return _self.availableBalance.sub(_self.getDistributeBalance()); } /// @dev Adds a round to the list. /// /// @param _element the element to add. function push(List storage _self, Data memory _element) internal { _self.elements.push(_element); } /// @dev Gets a element from the list. /// /// @param _index the index in the list. /// /// @return the element at the specified index. function get(List storage _self, uint256 _index) internal view returns (Data storage) { return _self.elements[_index]; } /// @dev Gets the last element in the list. /// /// This function will revert if there are no elements in the list. /// /// @return the last element in the list. function last(List storage _self) internal view returns (Data storage) { return _self.elements[_self.lastIndex()]; } /// @dev Gets the index of the last element in the list. /// /// This function will revert if there are no elements in the list. /// /// @return the index of the last element. function lastIndex(List storage _self) internal view returns (uint256) { uint256 _length = _self.length(); return _length.sub(1, "Round.List: list is empty"); } /// @dev Gets the number of elements in the list. /// /// @return the number of elements. function length(List storage _self) internal view returns (uint256) { return _self.elements.length; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {Math} from "@openzeppelin/contracts/math/Math.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {FixedPointMath} from "../FixedPointMath.sol"; import {IDetailedERC20} from "../../interfaces/IDetailedERC20.sol"; library Vault { using FixedPointMath for FixedPointMath.FixedDecimal; using Vault for Data; using Vault for List; using SafeMath for uint256; struct Data { IERC20 token; address owner; uint256 lockedAmount; uint256 totalClaimed; uint256 startTime; uint256 endTime; } struct List { Data[] elements; } /// @dev Gets the duration of the vesting period. /// /// @return the duration of the vesting period in seconds. function getDuration(Data storage _self) internal view returns (uint256) { return _self.endTime.sub(_self.startTime); } /// @dev Gets the amount of tokens that have been released up to the current moment. /// /// @return the released amount of tokens. function getReleasedAmount(Data storage _self) internal view returns (uint256) { if (block.timestamp < _self.startTime) { return 0; } uint256 _lowerTime = block.timestamp; uint256 _upperTime = Math.min(block.timestamp, _self.endTime); uint256 _elapsedTime = _upperTime.sub(_lowerTime); uint256 _numerator = _self.lockedAmount.mul(_elapsedTime); uint256 _denominator = _self.getDuration(); return _numerator.div(_denominator); } /// @dev Gets the amount of tokens that are available to be claimed from a vault. /// /// @return the available amount of tokens. function getAvailableAmount(Data storage _self) internal view returns (uint256) { uint256 _releasedAmount = _self.getReleasedAmount(); return _releasedAmount.sub(_self.totalClaimed); } /// @dev Adds a round to the list. /// /// @param _element the element to add. function push(List storage _self, Data memory _element) internal { _self.elements.push(_element); } /// @dev Gets a element from the list. /// /// @param _index the index in the list. /// /// @return the element at the specified index. function get(List storage _self, uint256 _index) internal view returns (Data storage) { return _self.elements[_index]; } /// @dev Gets the last element in the list. /// /// This function will revert if there are no elements in the list. /// /// @return the last element in the list. function last(List storage _self) internal view returns (Data storage) { return _self.elements[_self.lastIndex()]; } /// @dev Gets the index of the last element in the list. /// /// This function will revert if there are no elements in the list. /// /// @return the index of the last element. function lastIndex(List storage _self) internal view returns (uint256) { uint256 _length = _self.length(); return _length.sub(1, "Vault.List: list is empty"); } /// @dev Gets the number of elements in the list. /// /// @return the number of elements. function length(List storage _self) internal view returns (uint256) { return _self.elements.length; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; //import "hardhat/console.sol"; import {Math} from "@openzeppelin/contracts/math/Math.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IDetailedERC20} from "../../interfaces/IDetailedERC20.sol"; import {IVaultAdapter} from "../../interfaces/IVaultAdapter.sol"; import "hardhat/console.sol"; /// @title Pool /// /// @dev A library which provides the Vault data struct and associated functions. library Vault { using Vault for Data; using Vault for List; using SafeERC20 for IDetailedERC20; using SafeMath for uint256; struct Data { IVaultAdapter adapter; uint256 totalDeposited; } struct List { Data[] elements; } /// @dev Gets the total amount of assets deposited in the vault. /// /// @return the total assets. function totalValue(Data storage _self) internal view returns (uint256) { return _self.adapter.totalValue(); } /// @dev Gets the token that the vault accepts. /// /// @return the accepted token. function token(Data storage _self) internal view returns (IDetailedERC20) { return IDetailedERC20(_self.adapter.token()); } /// @dev Deposits funds from the caller into the vault. /// /// @param _amount the amount of funds to deposit. function deposit(Data storage _self, uint256 _amount) internal returns (uint256) { // Push the token that the vault accepts onto the stack to save gas. IDetailedERC20 _token = _self.token(); _token.safeTransfer(address(_self.adapter), _amount); _self.adapter.deposit(_amount); _self.totalDeposited = _self.totalDeposited.add(_amount); return _amount; } /// @dev Deposits the entire token balance of the caller into the vault. function depositAll(Data storage _self) internal returns (uint256) { IDetailedERC20 _token = _self.token(); return _self.deposit(_token.balanceOf(address(this))); } /// @dev Withdraw deposited funds from the vault. /// /// @param _recipient the account to withdraw the tokens to. /// @param _amount the amount of tokens to withdraw. function withdraw(Data storage _self, address _recipient, uint256 _amount) internal returns (uint256, uint256) { (uint256 _withdrawnAmount, uint256 _decreasedValue) = _self.directWithdraw(_recipient, _amount); _self.totalDeposited = _self.totalDeposited.sub(_decreasedValue); return (_withdrawnAmount, _decreasedValue); } /// @dev Directly withdraw deposited funds from the vault. /// /// @param _recipient the account to withdraw the tokens to. /// @param _amount the amount of tokens to withdraw. function directWithdraw(Data storage _self, address _recipient, uint256 _amount) internal returns (uint256, uint256) { IDetailedERC20 _token = _self.token(); uint256 _startingBalance = _token.balanceOf(_recipient); uint256 _startingTotalValue = _self.totalValue(); _self.adapter.withdraw(_recipient, _amount); uint256 _endingBalance = _token.balanceOf(_recipient); uint256 _withdrawnAmount = _endingBalance.sub(_startingBalance); uint256 _endingTotalValue = _self.totalValue(); uint256 _decreasedValue = _startingTotalValue.sub(_endingTotalValue); return (_withdrawnAmount, _decreasedValue); } /// @dev Withdraw all the deposited funds from the vault. /// /// @param _recipient the account to withdraw the tokens to. function withdrawAll(Data storage _self, address _recipient) internal returns (uint256, uint256) { return _self.withdraw(_recipient, _self.totalDeposited); } /// @dev Harvests yield from the vault. /// /// @param _recipient the account to withdraw the harvested yield to. function harvest(Data storage _self, address _recipient) internal returns (uint256, uint256) { if (_self.totalValue() <= _self.totalDeposited) { return (0, 0); } uint256 _withdrawAmount = _self.totalValue().sub(_self.totalDeposited); return _self.directWithdraw(_recipient, _withdrawAmount); } /// @dev Adds a element to the list. /// /// @param _element the element to add. function push(List storage _self, Data memory _element) internal { _self.elements.push(_element); } /// @dev Gets a element from the list. /// /// @param _index the index in the list. /// /// @return the element at the specified index. function get(List storage _self, uint256 _index) internal view returns (Data storage) { return _self.elements[_index]; } /// @dev Gets the last element in the list. /// /// This function will revert if there are no elements in the list. /// /// @return the last element in the list. function last(List storage _self) internal view returns (Data storage) { return _self.elements[_self.lastIndex()]; } /// @dev Gets the index of the last element in the list. /// /// This function will revert if there are no elements in the list. /// /// @return the index of the last element. function lastIndex(List storage _self) internal view returns (uint256) { uint256 _length = _self.length(); return _length.sub(1, "Vault.List: empty"); } /// @dev Gets the number of elements in the list. /// /// @return the number of elements. function length(List storage _self) internal view returns (uint256) { return _self.elements.length; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; //import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {Math} from "@openzeppelin/contracts/math/Math.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {CDP} from "./libraries/alchemist/CDP.sol"; import {FixedPointMath} from "./libraries/FixedPointMath.sol"; import {ITransmuter} from "./interfaces/ITransmuter.sol"; import {IMintableERC20} from "./interfaces/IMintableERC20.sol"; import {IChainlink} from "./interfaces/IChainlink.sol"; import {IVaultAdapter} from "./interfaces/IVaultAdapter.sol"; import {Vault} from "./libraries/alchemist/Vault.sol"; import "hardhat/console.sol"; // ERC20,removing ERC20 from the alchemist // ___ __ __ _ ___ __ _ // / _ | / / ____ / / ___ __ _ (_) __ __ / _ \ ____ ___ ___ ___ ___ / /_ ___ (_) // / __ | / / / __/ / _ \/ -_) / ' \ / / \ \ / / ___/ / __// -_) (_-</ -_) / _ \/ __/ (_-< _ // /_/ |_|/_/ \__/ /_//_/\__/ /_/_/_//_/ /_\_\ /_/ /_/ \__/ /___/\__/ /_//_/\__/ /___/(_) // // ___ __ ______ __ __ _______ .___ ___. __ _______..___________. // / \ | | / || | | | | ____|| \/ | | | / || | // / ^ \ | | | ,----'| |__| | | |__ | \ / | | | | (----``---| |----` // / /_\ \ | | | | | __ | | __| | |\/| | | | \ \ | | // / _____ \ | `----.| `----.| | | | | |____ | | | | | | .----) | | | // /__/ \__\ |_______| \______||__| |__| |_______||__| |__| |__| |_______/ |__| contract Alchemist is ReentrancyGuard { using CDP for CDP.Data; using FixedPointMath for FixedPointMath.FixedDecimal; using Vault for Vault.Data; using Vault for Vault.List; using SafeERC20 for IMintableERC20; using SafeMath for uint256; using Address for address; address public constant ZERO_ADDRESS = address(0); /// @dev Resolution for all fixed point numeric parameters which represent percents. The resolution allows for a /// granularity of 0.01% increments. uint256 public constant PERCENT_RESOLUTION = 10000; /// @dev The minimum value that the collateralization limit can be set to by the governance. This is a safety rail /// to prevent the collateralization from being set to a value which breaks the system. /// /// This value is equal to 100%. /// /// IMPORTANT: This constant is a raw FixedPointMath.FixedDecimal value and assumes a resolution of 64 bits. If the /// resolution for the FixedPointMath library changes this constant must change as well. uint256 public constant MINIMUM_COLLATERALIZATION_LIMIT = 1000000000000000000; /// @dev The maximum value that the collateralization limit can be set to by the governance. This is a safety rail /// to prevent the collateralization from being set to a value which breaks the system. /// /// This value is equal to 400%. /// /// IMPORTANT: This constant is a raw FixedPointMath.FixedDecimal value and assumes a resolution of 64 bits. If the /// resolution for the FixedPointMath library changes this constant must change as well. uint256 public constant MAXIMUM_COLLATERALIZATION_LIMIT = 4000000000000000000; event GovernanceUpdated( address governance ); event PendingGovernanceUpdated( address pendingGovernance ); event SentinelUpdated( address sentinel ); event TransmuterUpdated( address transmuter ); event RewardsUpdated( address treasury ); event HarvestFeeUpdated( uint256 fee ); event CollateralizationLimitUpdated( uint256 limit ); event EmergencyExitUpdated( bool status ); event ActiveVaultUpdated( IVaultAdapter indexed adapter ); event FundsHarvested( uint256 withdrawnAmount, uint256 decreasedValue ); event FundsRecalled( uint256 indexed vaultId, uint256 withdrawnAmount, uint256 decreasedValue ); event FundsFlushed( uint256 amount ); event TokensDeposited( address indexed account, uint256 amount ); event TokensWithdrawn( address indexed account, uint256 requestedAmount, uint256 withdrawnAmount, uint256 decreasedValue ); event TokensRepaid( address indexed account, uint256 parentAmount, uint256 childAmount ); event TokensLiquidated( address indexed account, uint256 requestedAmount, uint256 withdrawnAmount, uint256 decreasedValue ); /// @dev The token that this contract is using as the parent asset. IMintableERC20 public token; /// @dev The token that this contract is using as the child asset. IMintableERC20 public xtoken; /// @dev The address of the account which currently has administrative capabilities over this contract. address public governance; /// @dev The address of the pending governance. address public pendingGovernance; /// @dev The address of the account which can initiate an emergency withdraw of funds in a vault. address public sentinel; /// @dev The address of the contract which will transmute synthetic tokens back into native tokens. address public transmuter; /// @dev The address of the contract which will receive fees. address public rewards; /// @dev The percent of each profitable harvest that will go to the rewards contract. uint256 public harvestFee; /// @dev The total amount the native token deposited into the system that is owned by external users. uint256 public totalDeposited; /// @dev when movemetns are bigger than this number flush is activated. uint256 public flushActivator; /// @dev A flag indicating if the contract has been initialized yet. bool public initialized; /// @dev A flag indicating if deposits and flushes should be halted and if all parties should be able to recall /// from the active vault. bool public emergencyExit; /// @dev The context shared between the CDPs. CDP.Context private _ctx; /// @dev A mapping of all of the user CDPs. If a user wishes to have multiple CDPs they will have to either /// create a new address or set up a proxy contract that interfaces with this contract. mapping(address => CDP.Data) private _cdps; /// @dev A list of all of the vaults. The last element of the list is the vault that is currently being used for /// deposits and withdraws. Vaults before the last element are considered inactive and are expected to be cleared. Vault.List private _vaults; /// @dev The address of the link oracle. address public _linkGasOracle; /// @dev The minimum returned amount needed to be on peg according to the oracle. uint256 public pegMinimum; constructor( IMintableERC20 _token, IMintableERC20 _xtoken, address _governance, address _sentinel ) public /*ERC20( string(abi.encodePacked("Alchemic ", _token.name())), string(abi.encodePacked("al", _token.symbol())) )*/ { require(_governance != ZERO_ADDRESS, "Alchemist: governance address cannot be 0x0."); require(_sentinel != ZERO_ADDRESS, "Alchemist: sentinel address cannot be 0x0."); token = _token; xtoken = _xtoken; governance = _governance; sentinel = _sentinel; flushActivator = 100000 ether;// change for non 18 digit tokens //_setupDecimals(_token.decimals()); uint256 COLL_LIMIT = MINIMUM_COLLATERALIZATION_LIMIT.mul(2); _ctx.collateralizationLimit = FixedPointMath.FixedDecimal(COLL_LIMIT); _ctx.accumulatedYieldWeight = FixedPointMath.FixedDecimal(0); } /// @dev Sets the pending governance. /// /// This function reverts if the new pending governance is the zero address or the caller is not the current /// governance. This is to prevent the contract governance being set to the zero address which would deadlock /// privileged contract functionality. /// /// @param _pendingGovernance the new pending governance. function setPendingGovernance(address _pendingGovernance) external onlyGov { require(_pendingGovernance != ZERO_ADDRESS, "Alchemist: governance address cannot be 0x0."); pendingGovernance = _pendingGovernance; emit PendingGovernanceUpdated(_pendingGovernance); } /// @dev Accepts the role as governance. /// /// This function reverts if the caller is not the new pending governance. function acceptGovernance() external { require(msg.sender == pendingGovernance,"sender is not pendingGovernance"); address _pendingGovernance = pendingGovernance; governance = _pendingGovernance; emit GovernanceUpdated(_pendingGovernance); } function setSentinel(address _sentinel) external onlyGov { require(_sentinel != ZERO_ADDRESS, "Alchemist: sentinel address cannot be 0x0."); sentinel = _sentinel; emit SentinelUpdated(_sentinel); } /// @dev Sets the transmuter. /// /// This function reverts if the new transmuter is the zero address or the caller is not the current governance. /// /// @param _transmuter the new transmuter. function setTransmuter(address _transmuter) external onlyGov { // Check that the transmuter address is not the zero address. Setting the transmuter to the zero address would break // transfers to the address because of `safeTransfer` checks. require(_transmuter != ZERO_ADDRESS, "Alchemist: transmuter address cannot be 0x0."); transmuter = _transmuter; emit TransmuterUpdated(_transmuter); } /// @dev Sets the flushActivator. /// /// @param _flushActivator the new flushActivator. function setFlushActivator(uint256 _flushActivator) external onlyGov { flushActivator = _flushActivator; } /// @dev Sets the rewards contract. /// /// This function reverts if the new rewards contract is the zero address or the caller is not the current governance. /// /// @param _rewards the new rewards contract. function setRewards(address _rewards) external onlyGov { // Check that the rewards address is not the zero address. Setting the rewards to the zero address would break // transfers to the address because of `safeTransfer` checks. require(_rewards != ZERO_ADDRESS, "Alchemist: rewards address cannot be 0x0."); rewards = _rewards; emit RewardsUpdated(_rewards); } /// @dev Sets the harvest fee. /// /// This function reverts if the caller is not the current governance. /// /// @param _harvestFee the new harvest fee. function setHarvestFee(uint256 _harvestFee) external onlyGov { // Check that the harvest fee is within the acceptable range. Setting the harvest fee greater than 100% could // potentially break internal logic when calculating the harvest fee. require(_harvestFee <= PERCENT_RESOLUTION, "Alchemist: harvest fee above maximum."); harvestFee = _harvestFee; emit HarvestFeeUpdated(_harvestFee); } /// @dev Sets the collateralization limit. /// /// This function reverts if the caller is not the current governance or if the collateralization limit is outside /// of the accepted bounds. /// /// @param _limit the new collateralization limit. function setCollateralizationLimit(uint256 _limit) external onlyGov { require(_limit >= MINIMUM_COLLATERALIZATION_LIMIT, "Alchemist: collateralization limit below minimum."); require(_limit <= MAXIMUM_COLLATERALIZATION_LIMIT, "Alchemist: collateralization limit above maximum."); _ctx.collateralizationLimit = FixedPointMath.FixedDecimal(_limit); emit CollateralizationLimitUpdated(_limit); } /// @dev Set oracle. function setOracleAddress(address Oracle, uint256 peg) external onlyGov { _linkGasOracle = Oracle; pegMinimum = peg; } /// @dev Sets if the contract should enter emergency exit mode. /// /// @param _emergencyExit if the contract should enter emergency exit mode. function setEmergencyExit(bool _emergencyExit) external { require(msg.sender == governance || msg.sender == sentinel, ""); emergencyExit = _emergencyExit; emit EmergencyExitUpdated(_emergencyExit); } /// @dev Gets the collateralization limit. /// /// The collateralization limit is the minimum ratio of collateral to debt that is allowed by the system. /// /// @return the collateralization limit. function collateralizationLimit() external view returns (FixedPointMath.FixedDecimal memory) { return _ctx.collateralizationLimit; } /// @dev Initializes the contract. /// /// This function checks that the transmuter and rewards have been set and sets up the active vault. /// /// @param _adapter the vault adapter of the active vault. function initialize(IVaultAdapter _adapter) external onlyGov { require(!initialized, "Alchemist: already initialized"); require(transmuter != ZERO_ADDRESS, "Alchemist: cannot initialize transmuter address to 0x0"); require(rewards != ZERO_ADDRESS, "Alchemist: cannot initialize rewards address to 0x0"); _updateActiveVault(_adapter); initialized = true; } /// @dev Migrates the system to a new vault. /// /// This function reverts if the vault adapter is the zero address, if the token that the vault adapter accepts /// is not the token that this contract defines as the parent asset, or if the contract has not yet been initialized. /// /// @param _adapter the adapter for the vault the system will migrate to. function migrate(IVaultAdapter _adapter) external expectInitialized onlyGov { _updateActiveVault(_adapter); } /// @dev Harvests yield from a vault. /// /// @param _vaultId the identifier of the vault to harvest from. /// /// @return the amount of funds that were harvested from the vault. function harvest(uint256 _vaultId) external expectInitialized returns (uint256, uint256) { Vault.Data storage _vault = _vaults.get(_vaultId); (uint256 _harvestedAmount, uint256 _decreasedValue) = _vault.harvest(address(this)); if (_harvestedAmount > 0) { uint256 _feeAmount = _harvestedAmount.mul(harvestFee).div(PERCENT_RESOLUTION); uint256 _distributeAmount = _harvestedAmount.sub(_feeAmount); FixedPointMath.FixedDecimal memory _weight = FixedPointMath.fromU256(_distributeAmount).div(totalDeposited); _ctx.accumulatedYieldWeight = _ctx.accumulatedYieldWeight.add(_weight); if (_feeAmount > 0) { token.safeTransfer(rewards, _feeAmount); } if (_distributeAmount > 0) { _distributeToTransmuter(_distributeAmount); // token.safeTransfer(transmuter, _distributeAmount); previous version call } } emit FundsHarvested(_harvestedAmount, _decreasedValue); return (_harvestedAmount, _decreasedValue); } /// @dev Recalls an amount of deposited funds from a vault to this contract. /// /// @param _vaultId the identifier of the recall funds from. /// /// @return the amount of funds that were recalled from the vault to this contract and the decreased vault value. function recall(uint256 _vaultId, uint256 _amount) external nonReentrant expectInitialized returns (uint256, uint256) { return _recallFunds(_vaultId, _amount); } /// @dev Recalls all the deposited funds from a vault to this contract. /// /// @param _vaultId the identifier of the recall funds from. /// /// @return the amount of funds that were recalled from the vault to this contract and the decreased vault value. function recallAll(uint256 _vaultId) external nonReentrant expectInitialized returns (uint256, uint256) { Vault.Data storage _vault = _vaults.get(_vaultId); return _recallFunds(_vaultId, _vault.totalDeposited); } /// @dev Flushes buffered tokens to the active vault. /// /// This function reverts if an emergency exit is active. This is in place to prevent the potential loss of /// additional funds. /// /// @return the amount of tokens flushed to the active vault. function flush() external nonReentrant expectInitialized returns (uint256) { // Prevent flushing to the active vault when an emergency exit is enabled to prevent potential loss of funds if // the active vault is poisoned for any reason. require(!emergencyExit, "emergency pause enabled"); return flushActiveVault(); } /// @dev Internal function to flush buffered tokens to the active vault. /// /// This function reverts if an emergency exit is active. This is in place to prevent the potential loss of /// additional funds. /// /// @return the amount of tokens flushed to the active vault. function flushActiveVault() internal returns (uint256) { Vault.Data storage _activeVault = _vaults.last(); uint256 _depositedAmount = _activeVault.depositAll(); emit FundsFlushed(_depositedAmount); return _depositedAmount; } /// @dev Deposits collateral into a CDP. /// /// This function reverts if an emergency exit is active. This is in place to prevent the potential loss of /// additional funds. /// /// @param _amount the amount of collateral to deposit. function deposit(uint256 _amount) external nonReentrant noContractAllowed expectInitialized { require(!emergencyExit, "emergency pause enabled"); CDP.Data storage _cdp = _cdps[msg.sender]; _cdp.update(_ctx); token.safeTransferFrom(msg.sender, address(this), _amount); if(_amount >= flushActivator) { flushActiveVault(); } totalDeposited = totalDeposited.add(_amount); _cdp.totalDeposited = _cdp.totalDeposited.add(_amount); _cdp.lastDeposit = block.number; emit TokensDeposited(msg.sender, _amount); } /// @dev Attempts to withdraw part of a CDP's collateral. /// /// This function reverts if a deposit into the CDP was made in the same block. This is to prevent flash loan attacks /// on other internal or external systems. /// /// @param _amount the amount of collateral to withdraw. function withdraw(uint256 _amount) external nonReentrant noContractAllowed expectInitialized returns (uint256, uint256) { CDP.Data storage _cdp = _cdps[msg.sender]; require(block.number > _cdp.lastDeposit, ""); _cdp.update(_ctx); (uint256 _withdrawnAmount, uint256 _decreasedValue) = _withdrawFundsTo(msg.sender, _amount); _cdp.totalDeposited = _cdp.totalDeposited.sub(_decreasedValue, "Exceeds withdrawable amount"); _cdp.checkHealth(_ctx, "Action blocked: unhealthy collateralization ratio"); if(_amount >= flushActivator) { flushActiveVault(); } emit TokensWithdrawn(msg.sender, _amount, _withdrawnAmount, _decreasedValue); return (_withdrawnAmount, _decreasedValue); } /// @dev Repays debt with the native and or synthetic token. /// /// An approval is required to transfer native tokens to the transmuter. function repay(uint256 _parentAmount, uint256 _childAmount) external nonReentrant noContractAllowed onLinkCheck expectInitialized { CDP.Data storage _cdp = _cdps[msg.sender]; _cdp.update(_ctx); if (_parentAmount > 0) { token.safeTransferFrom(msg.sender, address(this), _parentAmount); _distributeToTransmuter(_parentAmount); } if (_childAmount > 0) { xtoken.burnFrom(msg.sender, _childAmount); //lower debt cause burn xtoken.lowerHasMinted(_childAmount); } uint256 _totalAmount = _parentAmount.add(_childAmount); _cdp.totalDebt = _cdp.totalDebt.sub(_totalAmount, ""); emit TokensRepaid(msg.sender, _parentAmount, _childAmount); } /// @dev Attempts to liquidate part of a CDP's collateral to pay back its debt. /// /// @param _amount the amount of collateral to attempt to liquidate. function liquidate(uint256 _amount) external nonReentrant noContractAllowed onLinkCheck expectInitialized returns (uint256, uint256) { CDP.Data storage _cdp = _cdps[msg.sender]; _cdp.update(_ctx); // don't attempt to liquidate more than is possible if(_amount > _cdp.totalDebt){ _amount = _cdp.totalDebt; } (uint256 _withdrawnAmount, uint256 _decreasedValue) = _withdrawFundsTo(address(this), _amount); //changed to new transmuter compatibillity _distributeToTransmuter(_withdrawnAmount); _cdp.totalDeposited = _cdp.totalDeposited.sub(_decreasedValue, ""); _cdp.totalDebt = _cdp.totalDebt.sub(_withdrawnAmount, ""); emit TokensLiquidated(msg.sender, _amount, _withdrawnAmount, _decreasedValue); return (_withdrawnAmount, _decreasedValue); } /// @dev Mints synthetic tokens by either claiming credit or increasing the debt. /// /// Claiming credit will take priority over increasing the debt. /// /// This function reverts if the debt is increased and the CDP health check fails. /// /// @param _amount the amount of alchemic tokens to borrow. function mint(uint256 _amount) external nonReentrant noContractAllowed onLinkCheck expectInitialized { CDP.Data storage _cdp = _cdps[msg.sender]; _cdp.update(_ctx); uint256 _totalCredit = _cdp.totalCredit; if (_totalCredit < _amount) { uint256 _remainingAmount = _amount.sub(_totalCredit); _cdp.totalDebt = _cdp.totalDebt.add(_remainingAmount); _cdp.totalCredit = 0; _cdp.checkHealth(_ctx, "Alchemist: Loan-to-value ratio breached"); } else { _cdp.totalCredit = _totalCredit.sub(_amount); } xtoken.mint(msg.sender, _amount); if(_amount >= flushActivator) { flushActiveVault(); } } /// @dev Gets the number of vaults in the vault list. /// /// @return the vault count. function vaultCount() external view returns (uint256) { return _vaults.length(); } /// @dev Get the adapter of a vault. /// /// @param _vaultId the identifier of the vault. /// /// @return the vault adapter. function getVaultAdapter(uint256 _vaultId) external view returns (IVaultAdapter) { Vault.Data storage _vault = _vaults.get(_vaultId); return _vault.adapter; } /// @dev Get the total amount of the parent asset that has been deposited into a vault. /// /// @param _vaultId the identifier of the vault. /// /// @return the total amount of deposited tokens. function getVaultTotalDeposited(uint256 _vaultId) external view returns (uint256) { Vault.Data storage _vault = _vaults.get(_vaultId); return _vault.totalDeposited; } /// @dev Get the total amount of collateral deposited into a CDP. /// /// @param _account the user account of the CDP to query. /// /// @return the deposited amount of tokens. function getCdpTotalDeposited(address _account) external view returns (uint256) { CDP.Data storage _cdp = _cdps[_account]; return _cdp.totalDeposited; } /// @dev Get the total amount of alchemic tokens borrowed from a CDP. /// /// @param _account the user account of the CDP to query. /// /// @return the borrowed amount of tokens. function getCdpTotalDebt(address _account) external view returns (uint256) { CDP.Data storage _cdp = _cdps[_account]; return _cdp.getUpdatedTotalDebt(_ctx); } /// @dev Get the total amount of credit that a CDP has. /// /// @param _account the user account of the CDP to query. /// /// @return the amount of credit. function getCdpTotalCredit(address _account) external view returns (uint256) { CDP.Data storage _cdp = _cdps[_account]; return _cdp.getUpdatedTotalCredit(_ctx); } /// @dev Gets the last recorded block of when a user made a deposit into their CDP. /// /// @param _account the user account of the CDP to query. /// /// @return the block number of the last deposit. function getCdpLastDeposit(address _account) external view returns (uint256) { CDP.Data storage _cdp = _cdps[_account]; return _cdp.lastDeposit; } /// @dev sends tokens to the transmuter /// /// benefit of great nation of transmuter function _distributeToTransmuter(uint256 amount) internal { token.approve(transmuter,amount); ITransmuter(transmuter).distribute(address(this),amount); // lower debt cause of 'burn' xtoken.lowerHasMinted(amount); } /// @dev Checks that parent token is on peg. /// /// This is used over a modifier limit of pegged interactions. modifier onLinkCheck() { if(pegMinimum > 0 ){ uint256 oracleAnswer = uint256(IChainlink(_linkGasOracle).latestAnswer()); require(oracleAnswer > pegMinimum, "off peg limitation"); } _; } /// @dev Checks that caller is not a eoa. /// /// This is used to prevent contracts from interacting. modifier noContractAllowed() { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "Sorry we do not accept contract!"); _; } /// @dev Checks that the contract is in an initialized state. /// /// This is used over a modifier to reduce the size of the contract modifier expectInitialized() { require(initialized, "Alchemist: not initialized."); _; } /// @dev Checks that the current message sender or caller is a specific address. /// /// @param _expectedCaller the expected caller. function _expectCaller(address _expectedCaller) internal { require(msg.sender == _expectedCaller, ""); } /// @dev Checks that the current message sender or caller is the governance address. /// /// modifier onlyGov() { require(msg.sender == governance, "Alchemist: only governance."); _; } /// @dev Updates the active vault. /// /// This function reverts if the vault adapter is the zero address, if the token that the vault adapter accepts /// is not the token that this contract defines as the parent asset, or if the contract has not yet been initialized. /// /// @param _adapter the adapter for the new active vault. function _updateActiveVault(IVaultAdapter _adapter) internal { require(_adapter != IVaultAdapter(ZERO_ADDRESS), "Alchemist: active vault address cannot be 0x0."); require(_adapter.token() == token, "Alchemist: token mismatch."); _vaults.push(Vault.Data({ adapter: _adapter, totalDeposited: 0 })); emit ActiveVaultUpdated(_adapter); } /// @dev Recalls an amount of funds from a vault to this contract. /// /// @param _vaultId the identifier of the recall funds from. /// @param _amount the amount of funds to recall from the vault. /// /// @return the amount of funds that were recalled from the vault to this contract and the decreased vault value. function _recallFunds(uint256 _vaultId, uint256 _amount) internal returns (uint256, uint256) { require(emergencyExit || msg.sender == governance || _vaultId != _vaults.lastIndex(), "Alchemist: not an emergency, not governance, and user does not have permission to recall funds from active vault"); Vault.Data storage _vault = _vaults.get(_vaultId); (uint256 _withdrawnAmount, uint256 _decreasedValue) = _vault.withdraw(address(this), _amount); emit FundsRecalled(_vaultId, _withdrawnAmount, _decreasedValue); return (_withdrawnAmount, _decreasedValue); } /// @dev Attempts to withdraw funds from the active vault to the recipient. /// /// Funds will be first withdrawn from this contracts balance and then from the active vault. This function /// is different from `recallFunds` in that it reduces the total amount of deposited tokens by the decreased /// value of the vault. /// /// @param _recipient the account to withdraw the funds to. /// @param _amount the amount of funds to withdraw. function _withdrawFundsTo(address _recipient, uint256 _amount) internal returns (uint256, uint256) { // Pull the funds from the buffer. uint256 _bufferedAmount = Math.min(_amount, token.balanceOf(address(this))); if (_recipient != address(this)) { token.safeTransfer(_recipient, _bufferedAmount); } uint256 _totalWithdrawn = _bufferedAmount; uint256 _totalDecreasedValue = _bufferedAmount; uint256 _remainingAmount = _amount.sub(_bufferedAmount); // Pull the remaining funds from the active vault. if (_remainingAmount > 0) { Vault.Data storage _activeVault = _vaults.last(); (uint256 _withdrawAmount, uint256 _decreasedValue) = _activeVault.withdraw( _recipient, _remainingAmount ); _totalWithdrawn = _totalWithdrawn.add(_withdrawAmount); _totalDecreasedValue = _totalDecreasedValue.add(_decreasedValue); } totalDeposited = totalDeposited.sub(_totalDecreasedValue); return (_totalWithdrawn, _totalDecreasedValue); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; import {Math} from "@openzeppelin/contracts/math/Math.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {FixedPointMath} from "../FixedPointMath.sol"; import {IDetailedERC20} from "../../interfaces/IDetailedERC20.sol"; import "hardhat/console.sol"; /// @title CDP /// /// @dev A library which provides the CDP data struct and associated functions. library CDP { using CDP for Data; using FixedPointMath for FixedPointMath.FixedDecimal; using SafeERC20 for IDetailedERC20; using SafeMath for uint256; struct Context { FixedPointMath.FixedDecimal collateralizationLimit; FixedPointMath.FixedDecimal accumulatedYieldWeight; } struct Data { uint256 totalDeposited; uint256 totalDebt; uint256 totalCredit; uint256 lastDeposit; FixedPointMath.FixedDecimal lastAccumulatedYieldWeight; } function update(Data storage _self, Context storage _ctx) internal { uint256 _earnedYield = _self.getEarnedYield(_ctx); if (_earnedYield > _self.totalDebt) { uint256 _currentTotalDebt = _self.totalDebt; _self.totalDebt = 0; _self.totalCredit = _earnedYield.sub(_currentTotalDebt); } else { _self.totalDebt = _self.totalDebt.sub(_earnedYield); } _self.lastAccumulatedYieldWeight = _ctx.accumulatedYieldWeight; } /// @dev Assures that the CDP is healthy. /// /// This function will revert if the CDP is unhealthy. function checkHealth(Data storage _self, Context storage _ctx, string memory _msg) internal view { require(_self.isHealthy(_ctx), _msg); } /// @dev Gets if the CDP is considered healthy. /// /// A CDP is healthy if its collateralization ratio is greater than the global collateralization limit. /// /// @return if the CDP is healthy. function isHealthy(Data storage _self, Context storage _ctx) internal view returns (bool) { return _ctx.collateralizationLimit.cmp(_self.getCollateralizationRatio(_ctx)) <= 0; } function getUpdatedTotalDebt(Data storage _self, Context storage _ctx) internal view returns (uint256) { uint256 _unclaimedYield = _self.getEarnedYield(_ctx); if (_unclaimedYield == 0) { return _self.totalDebt; } uint256 _currentTotalDebt = _self.totalDebt; if (_unclaimedYield >= _currentTotalDebt) { return 0; } return _currentTotalDebt - _unclaimedYield; } function getUpdatedTotalCredit(Data storage _self, Context storage _ctx) internal view returns (uint256) { uint256 _unclaimedYield = _self.getEarnedYield(_ctx); if (_unclaimedYield == 0) { return _self.totalCredit; } uint256 _currentTotalDebt = _self.totalDebt; if (_unclaimedYield <= _currentTotalDebt) { return 0; } return _self.totalCredit + (_unclaimedYield - _currentTotalDebt); } /// @dev Gets the amount of yield that a CDP has earned since the last time it was updated. /// /// @param _self the CDP to query. /// @param _ctx the CDP context. /// /// @return the amount of earned yield. function getEarnedYield(Data storage _self, Context storage _ctx) internal view returns (uint256) { FixedPointMath.FixedDecimal memory _currentAccumulatedYieldWeight = _ctx.accumulatedYieldWeight; FixedPointMath.FixedDecimal memory _lastAccumulatedYieldWeight = _self.lastAccumulatedYieldWeight; if (_currentAccumulatedYieldWeight.cmp(_lastAccumulatedYieldWeight) == 0) { return 0; } return _currentAccumulatedYieldWeight .sub(_lastAccumulatedYieldWeight) .mul(_self.totalDeposited) .decode(); } /// @dev Gets a CDPs collateralization ratio. /// /// The collateralization ratio is defined as the ratio of collateral to debt. If the CDP has zero debt then this /// will return the maximum value of a fixed point integer. /// /// This function will use the updated total debt so an update before calling this function is not required. /// /// @param _self the CDP to query. /// /// @return a fixed point integer representing the collateralization ratio. function getCollateralizationRatio(Data storage _self, Context storage _ctx) internal view returns (FixedPointMath.FixedDecimal memory) { uint256 _totalDebt = _self.getUpdatedTotalDebt(_ctx); if (_totalDebt == 0) { return FixedPointMath.maximumValue(); } return FixedPointMath.fromU256(_self.totalDeposited).div(_totalDebt); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; interface ITransmuter { function distribute (address origin, uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; interface IChainlink { function latestAnswer() external view returns (int256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {IDetailedERC20} from "./interfaces/IDetailedERC20.sol"; /// @title AlchemixToken /// /// @dev This is the contract for the Alchemix governance token. /// /// Initially, the contract deployer is given both the admin and minter role. This allows them to pre-mine tokens, /// transfer admin to a timelock contract, and lastly, grant the staking pools the minter role. After this is done, /// the deployer must revoke their admin role and minter role. contract AlchemixToken is AccessControl, ERC20("Alchemix", "ALCX") { /// @dev The identifier of the role which maintains other roles. bytes32 public constant ADMIN_ROLE = keccak256("ADMIN"); /// @dev The identifier of the role which allows accounts to mint tokens. bytes32 public constant MINTER_ROLE = keccak256("MINTER"); constructor() public { _setupRole(ADMIN_ROLE, msg.sender); _setupRole(MINTER_ROLE, msg.sender); _setRoleAdmin(MINTER_ROLE, ADMIN_ROLE); _setRoleAdmin(ADMIN_ROLE, ADMIN_ROLE); } /// @dev A modifier which checks that the caller has the minter role. modifier onlyMinter() { require(hasRole(MINTER_ROLE, msg.sender), "AlchemixToken: only minter"); _; } /// @dev Mints tokens to a recipient. /// /// This function reverts if the caller does not have the minter role. /// /// @param _recipient the account to mint tokens to. /// @param _amount the amount of tokens to mint. function mint(address _recipient, uint256 _amount) external onlyMinter { _mint(_recipient, _amount); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /// @title ERC20Mock /// /// @dev A mock of an ERC20 token which lets anyone burn and mint tokens. contract ERC20Mock is ERC20 { constructor(string memory _name, string memory _symbol, uint8 _decimals) public ERC20(_name, _symbol) { _setupDecimals(_decimals); } function mint(address _recipient, uint256 _amount) external { _mint(_recipient, _amount); } function burn(address _account, uint256 _amount) external { _burn(_account, _amount); } }
Gets info on the buffer This function is used to query the contract to get the latest state of the buffer return _toDistribute the amount ready to be distributed return _deltaBlocks the amount of time since the last phased distribution return _buffer the amount in the buffer
function bufferInfo() public view returns (uint256 _toDistribute, uint256 _deltaBlocks, uint256 _buffer){ _deltaBlocks = block.number.sub(lastDepositBlock); _buffer = buffer; _toDistribute = _buffer.mul(_deltaBlocks).div(TRANSMUTATION_PERIOD); }
94,333
./full_match/1/0x64fc37d5e590D00516e7364c09F6f76Af1E0AF31/sources/contracts/main/CyanApeCoinPlan.sol
Transfer underlying NFTs if it's not in the Cyan wallet Transfer ApeCoin to user's Cyan wallet
function createBakcPlan( uint256 planId, uint224 loanAmount, uint32 mainTokenId, uint32 bakcTokenId, IERC721Upgradeable mainCollection ) private { if (paymentPlan[planId].status != PaymentPlanStatus.NONE) revert PlanAlreadyExists(); (address mainAddress, address cyanWalletAddress) = getUserAddresses(msg.sender); if (mainCollection.ownerOf(mainTokenId) != cyanWalletAddress) { mainCollection.safeTransferFrom(mainAddress, cyanWalletAddress, mainTokenId); } if (BAKC.ownerOf(bakcTokenId) != cyanWalletAddress) { BAKC.safeTransferFrom(mainAddress, cyanWalletAddress, bakcTokenId); } uint224 alreadyStakedAmount = uint224(apeStaking.nftPosition(BAKC_POOL_ID, bakcTokenId).stakedAmount); uint224 stakeAmount = getPoolCap(BAKC_POOL_ID) - alreadyStakedAmount; if (loanAmount > 0) { if (loanAmount <= stakeAmount) { cyanApeCoinVault.lend(cyanWalletAddress, loanAmount, BAKC_POOL_ID); revert LoanAmountExceedsPoolCap(); } } IWalletApeCoin wallet = IWalletApeCoin(cyanWalletAddress); wallet.executeModule( abi.encodeWithSelector( IWalletApeCoin.depositBAKCAndLock.selector, address(mainCollection), mainTokenId, bakcTokenId, stakeAmount ) ); PaymentPlan memory plan = PaymentPlan( BAKC_POOL_ID, bakcTokenId, loanAmount, cyanWalletAddress, PaymentPlanStatus.ACTIVE ); paymentPlan[planId] = plan; emit CreatedPlan(planId); }
2,937,442
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Earrings SVG generator library EarringsDetail { /// @dev Earrings N°1 => None function item_1() public pure returns (string memory) { return base("", "None"); } /// @dev Earrings N°2 => Circle Blood function item_2() public pure returns (string memory) { return base( '<g display="inline" ><ellipse fill="#B50D5E" cx="137.6" cy="229.1" rx="2.5" ry="3" /></g><g display="inline" ><ellipse fill="#B50D5E" cx="291.6" cy="231.8" rx="3.4" ry="3.5" /></g>', "Circle Blood" ); } /// @dev Earrings N°3 => Circle Moon function item_3() public pure returns (string memory) { return base( '<g display="inline" ><ellipse cx="137.6" cy="229.1" rx="2.5" ry="3" /></g><g display="inline" ><ellipse cx="291.6" cy="231.8" rx="3.4" ry="3.5" /></g>', "Circle Moon" ); } /// @dev Earrings N°4 => Ring Blood function item_4() public pure returns (string memory) { return base( '<path display="inline" fill="none" stroke="#B50D5E" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M289,234.7c0,0-4.4,2.1-3.2,6.4c1,4.3,4.4,4,4.8,4c0.3,0,3.9-0.2,3.9-4.2" /><path display="inline" fill="none" stroke="#B50D5E" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M137,232.9c0,0-4.4,2.1-3.2,6.4c1,4.3,4.5,3.8,4.8,3.6c0.4-0.1,1.6,0.2,3.4-2.3" />', "Ring Blood" ); } /// @dev Earrings N°5 => Ring Moon function item_5() public pure returns (string memory) { return base( '<path display="inline" fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M289,234.7c0,0-4.4,2.1-3.2,6.4c1,4.3,4.4,4,4.8,4c0.3,0,3.9-0.2,3.9-4.2" /><path display="inline" fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M137,232.9c0,0-4.4,2.1-3.2,6.4c1,4.3,4.5,3.8,4.8,3.6c0.4-0.1,1.6,0.2,3.4-2.3" />', "Ring Moon" ); } /// @dev Earrings N°6 => Monk Blood function item_6() public pure returns (string memory) { return base( '<g display="inline" ><g><ellipse transform="matrix(0.9952 -9.784740e-02 9.784740e-02 0.9952 -23.5819 29.5416)" fill="#B50D5E" stroke="#000000" stroke-width="1" stroke-miterlimit="10.0039" cx="289.4" cy="255.2" rx="8" ry="8.1" /><ellipse transform="matrix(1.784754e-02 -0.9998 0.9998 1.784754e-02 24.9032 543.924)" opacity="0.54" fill="#33112E" enable-background="new " cx="289.3" cy="259.3" rx="2.2" ry="4.9" /></g><path fill="#A5CBCC" stroke="#000000" stroke-miterlimit="10.0039" d="M283.4,250.2c3.9,0.5,8.2,0.4,12.1-0.1C295.7,250.1,289.6,243,283.4,250.2z" /><line fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10.0039" x1="289.9" y1="244.7" x2="289.6" y2="247.3" /></g><g display="inline" ><g><ellipse transform="matrix(0.9952 -9.784740e-02 9.784740e-02 0.9952 -24.1729 14.6915)" fill="#B50D5E" stroke="#000000" stroke-width="1" stroke-miterlimit="10.0039" cx="137.7" cy="253.8" rx="8" ry="8.1" /><ellipse transform="matrix(1.784754e-02 -0.9998 0.9998 1.784754e-02 -122.6851 390.7122)" opacity="0.54" fill="#33112E" enable-background="new " cx="137.5" cy="257.8" rx="2.2" ry="4.9" /></g><path fill="#A5CBCC" stroke="#000000" stroke-miterlimit="10.0039" d="M131.8,248.8c3.9,0.5,8.1,0.4,12-0.1C143.7,248.6,138,241.6,131.8,248.8z" /><line fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10.0039" x1="138" y1="243.2" x2="137.8" y2="245.8" /></g><g id="Ring" display="inline" ><path fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M289,234.7c0,0-4.4,2.1-3.2,6.4c1,4.3,5.3,3.8,5.6,3.6s3.2-0.9,3.1-5.2" /><path fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M137,232.9c0,0-4.4,2.1-3.2,6.4c1,4.3,5.3,3.8,5.6,3.6c0.3-0.1,3.3-0.6,3.2-4.8" /></g>', "Monk Blood" ); } /// @dev Earrings N°7 => Tomoe Moon function item_7() public pure returns (string memory) { return base( '<path display="inline" fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M289,234.7c0,0-4.4,2.1-3.2,6.4c1,4.3,5.3,3.8,5.6,3.6s3.2-0.9,3.1-5.2" /><path display="inline" fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M135.9,232.9c0,0-4.4,2.1-3.2,6.4c1,4.3,5.3,3.8,5.6,3.6c0.3-0.1,3.3-0.6,3.2-4.8" /><g display="inline" ><path d="M294.7,250.1c0,0-2,5.6-11.3,7.4c0,0,3.4-2,4.6-5.2" /><path d="M294.6,250.4c1.5-2.4,0.6-5.5-1.8-6.9c-2.4-1.5-5.5-0.6-6.9,1.8c-1.5,2.4-0.6,5.5,1.8,6.9C290.1,253.5,293.2,252.8,294.6,250.4z M288.8,247c0.5-0.8,1.5-1,2.3-0.6c0.8,0.5,1,1.5,0.6,2.3c-0.5,0.8-1.5,1-2.3,0.6C288.5,248.9,288.4,247.8,288.8,247z" /></g><g display="inline" ><path d="M131.8,247.3c0,0,0.4,6,8.8,10.2c0,0-2.7-2.8-3-6.3" /><path d="M131.8,247.6c-0.7-2.7,0.9-5.4,3.6-6.1s5.4,0.9,6.1,3.6c0.7,2.7-0.9,5.4-3.6,6.1C135.2,252,132.6,250.3,131.8,247.6z M138.3,245.9c-0.2-0.9-1.1-1.5-2.1-1.3c-0.9,0.2-1.5,1.1-1.3,2.1c0.2,0.9,1.1,1.5,2.1,1.3C138,247.7,138.5,246.8,138.3,245.9z" /></g>', "Tomoe Moon" ); } /// @dev Earrings N°8 => Circle Pure function item_8() public pure returns (string memory) { return base( '<g display="inline" ><ellipse fill="#FFEDED" cx="137.6" cy="229.1" rx="2.5" ry="3" /></g><g display="inline" ><ellipse fill="#FFEDED" cx="291.6" cy="231.8" rx="3.4" ry="3.5" /></g>', "Circle Pure" ); } /// @dev Earrings N°9 => Ring Pure function item_9() public pure returns (string memory) { return base( '<path display="inline" fill="none" stroke="#FFEDED" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M289,234.7c0,0-4.4,2.1-3.2,6.4c1,4.3,4.4,4,4.8,4c0.3,0,3.9-0.2,3.9-4.2" /><path display="inline" fill="none" stroke="#FFEDED" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M137,232.9c0,0-4.4,2.1-3.2,6.4c1,4.3,4.5,3.8,4.8,3.6c0.4-0.1,1.6,0.2,3.4-2.3" />', "Ring Pure" ); } /// @dev Earrings N°10 => Monk Moon function item_10() public pure returns (string memory) { return base( '<g display="inline" ><g><ellipse transform="matrix(0.9952 -9.784740e-02 9.784740e-02 0.9952 -23.5819 29.5416)" fill="#2A2C38" stroke="#000000" stroke-width="1" stroke-miterlimit="10.0039" cx="289.4" cy="255.2" rx="8" ry="8.1" /><ellipse transform="matrix(1.784754e-02 -0.9998 0.9998 1.784754e-02 24.9032 543.924)" opacity="0.54" fill="#33112E" enable-background="new " cx="289.3" cy="259.3" rx="2.2" ry="4.9" /></g><path fill="#A5CBCC" stroke="#000000" stroke-miterlimit="10.0039" d="M283.4,250.2c3.9,0.5,8.2,0.4,12.1-0.1C295.7,250.1,289.6,243,283.4,250.2z" /><line fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10.0039" x1="289.9" y1="244.7" x2="289.6" y2="247.3" /></g><g display="inline" ><g><ellipse transform="matrix(0.9952 -9.784740e-02 9.784740e-02 0.9952 -24.1729 14.6915)" fill="#2A2C38" stroke="#000000" stroke-width="1" stroke-miterlimit="10.0039" cx="137.7" cy="253.8" rx="8" ry="8.1" /><ellipse transform="matrix(1.784754e-02 -0.9998 0.9998 1.784754e-02 -122.6851 390.7122)" opacity="0.54" fill="#33112E" enable-background="new " cx="137.5" cy="257.8" rx="2.2" ry="4.9" /></g><path fill="#A5CBCC" stroke="#000000" stroke-miterlimit="10.0039" d="M131.8,248.8c3.9,0.5,8.1,0.4,12-0.1C143.7,248.6,138,241.6,131.8,248.8z" /><line fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10.0039" x1="138" y1="243.2" x2="137.8" y2="245.8" /></g><g id="Ring" display="inline" ><path fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M289,234.7c0,0-4.4,2.1-3.2,6.4c1,4.3,5.3,3.8,5.6,3.6s3.2-0.9,3.1-5.2" /><path fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M137,232.9c0,0-4.4,2.1-3.2,6.4c1,4.3,5.3,3.8,5.6,3.6c0.3-0.1,3.3-0.6,3.2-4.8" /></g>', "Monk Moon" ); } /// @dev Earrings N°11 => Tomoe Drop Moon function item_11() public pure returns (string memory) { return base( '<g display="inline" ><ellipse cx="291.2" cy="231.8" rx="3.5" ry="3.5" /><line fill="none" stroke="#000000" stroke-miterlimit="10" x1="291.2" y1="231.8" x2="291.2" y2="259.8" /><path d="M292.2,258.2c-2.5-1.2-5.5,0-6.7,2.5c-1.1,2.5,0,5.5,2.5,6.7c0.1,0.1,0.2,0.1,0.4,0.1c-0.9,3.2-4.1,5.5-4.1,5.5c6.6-1.9,9.1-5.6,10-7.4c0.1-0.2,0.3-0.4,0.4-0.7C295.8,262.4,294.7,259.4,292.2,258.2z M288.5,262.1c0.4-0.8,1.4-1.3,2.2-0.8c0.8,0.4,1.3,1.4,0.8,2.2c-0.4,0.8-1.4,1.3-2.2,0.8C288.5,264,288.1,262.9,288.5,262.1z" /></g><g display="inline" ><ellipse cx="139" cy="231.7" rx="2.6" ry="2.8" /><line fill="none" stroke="#000000" stroke-miterlimit="10" x1="138.5" y1="231.8" x2="138.5" y2="259.8" /><path d="M140.2,258.9c-2.5-1.1-5.5,0-6.7,2.5c-1.1,2.5,0,5.5,2.5,6.7c0.1,0.1,0.2,0.1,0.4,0.1c-0.9,3.2-4.1,5.5-4.1,5.5c6.8-2,9.3-5.9,10.1-7.6c0.1-0.2,0.2-0.3,0.3-0.5C143.8,263.1,142.7,260.1,140.2,258.9z M136.5,262.8c0.4-0.8,1.4-1.3,2.2-0.8s1.3,1.4,0.8,2.2c-0.4,0.8-1.4,1.3-2.2,0.8C136.5,264.7,136,263.7,136.5,262.8z" /></g>', "Tomoe Drop Moon" ); } /// @dev Earrings N°12 => Tomoe Pure function item_12() public pure returns (string memory) { return base( '<path display="inline" fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M289,234.7c0,0-4.4,2.1-3.2,6.4c1,4.3,5.3,3.8,5.6,3.6s3.2-0.9,3.1-5.2" /><path display="inline" fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M135.9,232.9c0,0-4.4,2.1-3.2,6.4c1,4.3,5.3,3.8,5.6,3.6c0.3-0.1,3.3-0.6,3.2-4.8" /><g display="inline" ><path fill="#FFEDED" d="M294.7,250.1c0,0-2,5.6-11.3,7.4c0,0,3.4-2,4.6-5.2" /><path fill="#FFEDED" d="M294.6,250.4c1.5-2.4,0.6-5.5-1.8-6.9c-2.4-1.5-5.5-0.6-6.9,1.8c-1.5,2.4-0.6,5.5,1.8,6.9C290.1,253.5,293.2,252.8,294.6,250.4z M288.8,247c0.5-0.8,1.5-1,2.3-0.6c0.8,0.5,1,1.5,0.6,2.3c-0.5,0.8-1.5,1-2.3,0.6C288.5,248.9,288.4,247.8,288.8,247z" /></g><g display="inline" ><path fill="#FFEDED" d="M131.8,247.3c0,0,0.4,6,8.8,10.2c0,0-2.7-2.8-3-6.3" /><path fill="#FFEDED" d="M131.8,247.6c-0.7-2.7,0.9-5.4,3.6-6.1s5.4,0.9,6.1,3.6c0.7,2.7-0.9,5.4-3.6,6.1C135.2,252,132.6,250.3,131.8,247.6z M138.3,245.9c-0.2-0.9-1.1-1.5-2.1-1.3c-0.9,0.2-1.5,1.1-1.3,2.1c0.2,0.9,1.1,1.5,2.1,1.3C138,247.7,138.5,246.8,138.3,245.9z" /></g>', "Tomoe Pure" ); } /// @dev Earrings N°13 => Monk Pure function item_13() public pure returns (string memory) { return base( '<g display="inline" ><g><ellipse transform="matrix(0.9952 -9.784740e-02 9.784740e-02 0.9952 -23.5819 29.5416)" fill="#FFEDED" stroke="#000000" stroke-width="1" stroke-miterlimit="10.0039" cx="289.4" cy="255.2" rx="8" ry="8.1" /><ellipse transform="matrix(1.784754e-02 -0.9998 0.9998 1.784754e-02 24.9032 543.924)" opacity="0.54" fill="#33112E" enable-background="new " cx="289.3" cy="259.3" rx="2.2" ry="4.9" /></g><path fill="#A5CBCC" stroke="#000000" stroke-miterlimit="10.0039" d="M283.4,250.2c3.9,0.5,8.2,0.4,12.1-0.1C295.7,250.1,289.6,243,283.4,250.2z" /><line fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10.0039" x1="289.9" y1="244.7" x2="289.6" y2="247.3" /></g><g display="inline" ><g><ellipse transform="matrix(0.9952 -9.784740e-02 9.784740e-02 0.9952 -24.1729 14.6915)" fill="#FFEDED" stroke="#000000" stroke-width="1" stroke-miterlimit="10.0039" cx="137.7" cy="253.8" rx="8" ry="8.1" /><ellipse transform="matrix(1.784754e-02 -0.9998 0.9998 1.784754e-02 -122.6851 390.7122)" opacity="0.54" fill="#33112E" enable-background="new " cx="137.5" cy="257.8" rx="2.2" ry="4.9" /></g><path fill="#A5CBCC" stroke="#000000" stroke-miterlimit="10.0039" d="M131.8,248.8c3.9,0.5,8.1,0.4,12-0.1C143.7,248.6,138,241.6,131.8,248.8z" /><line fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10.0039" x1="138" y1="243.2" x2="137.8" y2="245.8" /></g><g id="Ring" display="inline" ><path fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M289,234.7c0,0-4.4,2.1-3.2,6.4c1,4.3,5.3,3.8,5.6,3.6s3.2-0.9,3.1-5.2" /><path fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M137,232.9c0,0-4.4,2.1-3.2,6.4c1,4.3,5.3,3.8,5.6,3.6c0.3-0.1,3.3-0.6,3.2-4.8" /></g>', "Monk Pure" ); } /// @dev Earrings N°14 => Tomoe Drop Pure function item_14() public pure returns (string memory) { return base( '<g display="inline" ><ellipse cx="291.2" cy="231.8" rx="3.5" ry="3.5" /><line fill="none" stroke="#000000" stroke-miterlimit="10" x1="291.2" y1="231.8" x2="291.2" y2="259.8" /><path fill="#FFEDED" d="M292.2,258.2c-2.5-1.2-5.5,0-6.7,2.5c-1.1,2.5,0,5.5,2.5,6.7c0.1,0.1,0.2,0.1,0.4,0.1c-0.9,3.2-4.1,5.5-4.1,5.5c6.6-1.9,9.1-5.6,10-7.4c0.1-0.2,0.3-0.4,0.4-0.7C295.8,262.4,294.7,259.4,292.2,258.2z M288.5,262.1c0.4-0.8,1.4-1.3,2.2-0.8c0.8,0.4,1.3,1.4,0.8,2.2c-0.4,0.8-1.4,1.3-2.2,0.8C288.5,264,288.1,262.9,288.5,262.1z" /></g><g display="inline" ><ellipse cx="139" cy="231.7" rx="2.6" ry="2.8" /><line fill="none" stroke="#000000" stroke-miterlimit="10" x1="138.5" y1="231.8" x2="138.5" y2="259.8" /><path fill="#FFEDED" d="M140.2,258.9c-2.5-1.1-5.5,0-6.7,2.5c-1.1,2.5,0,5.5,2.5,6.7c0.1,0.1,0.2,0.1,0.4,0.1c-0.9,3.2-4.1,5.5-4.1,5.5c6.8-2,9.3-5.9,10.1-7.6c0.1-0.2,0.2-0.3,0.3-0.5C143.8,263.1,142.7,260.1,140.2,258.9z M136.5,262.8c0.4-0.8,1.4-1.3,2.2-0.8s1.3,1.4,0.8,2.2c-0.4,0.8-1.4,1.3-2.2,0.8C136.5,264.7,136,263.7,136.5,262.8z" /></g>', "Tomoe Drop Pure" ); } /// @dev Earrings N°15 => Tomoe Drop Gold function item_15() public pure returns (string memory) { return base( '<g display="inline" ><ellipse cx="291.2" cy="231.8" rx="3.5" ry="3.5" /><line fill="none" stroke="#000000" stroke-miterlimit="10" x1="291.2" y1="231.8" x2="291.2" y2="259.8" /><linearGradient id="SVGID_00000120528397129779781120000012903837417257993114_" gradientUnits="userSpaceOnUse" x1="284.3" y1="-535.3656" x2="295.1259" y2="-535.3656" gradientTransform="matrix(1 0 0 -1 0 -270)"><stop offset="0" style="stop-color:#FFB451" /><stop offset="0.5259" style="stop-color:#F7EC94" /><stop offset="1" style="stop-color:#FF9121" /></linearGradient><path fill="url(#SVGID_00000120528397129779781120000012903837417257993114_)" d="M292.2,258.2c-2.5-1.2-5.5,0-6.7,2.5c-1.1,2.5,0,5.5,2.5,6.7c0.1,0.1,0.2,0.1,0.4,0.1c-0.9,3.2-4.1,5.5-4.1,5.5c6.6-1.9,9.1-5.6,10-7.4c0.1-0.2,0.3-0.4,0.4-0.7C295.8,262.4,294.7,259.4,292.2,258.2z M288.5,262.1c0.4-0.8,1.4-1.3,2.2-0.8c0.8,0.4,1.3,1.4,0.8,2.2c-0.4,0.8-1.4,1.3-2.2,0.8C288.5,264,288.1,262.9,288.5,262.1z" /></g><g display="inline" ><ellipse cx="139" cy="231.7" rx="2.6" ry="2.8" /><line fill="none" stroke="#000000" stroke-miterlimit="10" x1="138.5" y1="231.8" x2="138.5" y2="259.8" /><linearGradient id="SVGID_00000027574875614874123830000011265039474658243508_" gradientUnits="userSpaceOnUse" x1="132.3" y1="-536.087" x2="143.1259" y2="-536.087" gradientTransform="matrix(1 0 0 -1 0 -270)"><stop offset="0" style="stop-color:#FFB451" /><stop offset="0.5259" style="stop-color:#F7EC94" /><stop offset="1" style="stop-color:#FF9121" /></linearGradient><path fill="url(#SVGID_00000027574875614874123830000011265039474658243508_)" d="M140.2,258.9c-2.5-1.1-5.5,0-6.7,2.5c-1.1,2.5,0,5.5,2.5,6.7c0.1,0.1,0.2,0.1,0.4,0.1c-0.9,3.2-4.1,5.5-4.1,5.5c6.8-2,9.3-5.9,10.1-7.6c0.1-0.2,0.2-0.3,0.3-0.5C143.8,263.1,142.7,260.1,140.2,258.9z M136.5,262.8c0.4-0.8,1.4-1.3,2.2-0.8s1.3,1.4,0.8,2.2c-0.4,0.8-1.4,1.3-2.2,0.8C136.5,264.7,136,263.7,136.5,262.8z" /></g>', "Tomoe Drop Gold" ); } /// @notice Return the skin name of the given id /// @param id The skin Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "None"; } else if (id == 2) { name = "Circle Blood"; } else if (id == 3) { name = "Circle Moon"; } else if (id == 4) { name = "Ring Blood"; } else if (id == 5) { name = "Ring Moon"; } else if (id == 6) { name = "Monk Blood"; } else if (id == 7) { name = "Tomoe"; } else if (id == 8) { name = "Circle Pure"; } else if (id == 9) { name = "Ring Pure"; } else if (id == 10) { name = "Monk Moon"; } else if (id == 11) { name = "Tomoe Drop"; } else if (id == 12) { name = "Tomoe Pure"; } else if (id == 13) { name = "Monk Pure"; } else if (id == 14) { name = "Tomoe Drop Pure"; } else if (id == 15) { name = "Tomoe Drop Gold"; } } /// @dev The base SVG for the body function base(string memory children, string memory name) private pure returns (string memory) { return string(abi.encodePacked('<g id="earrings"><g id="', name, '">', children, "</g></g>")); } }
Earrings N°7 => Tomoe Moon
function item_7() public pure returns (string memory) { return base( '<path display="inline" fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M289,234.7c0,0-4.4,2.1-3.2,6.4c1,4.3,5.3,3.8,5.6,3.6s3.2-0.9,3.1-5.2" /><path display="inline" fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M135.9,232.9c0,0-4.4,2.1-3.2,6.4c1,4.3,5.3,3.8,5.6,3.6c0.3-0.1,3.3-0.6,3.2-4.8" /><g display="inline" ><path d="M294.7,250.1c0,0-2,5.6-11.3,7.4c0,0,3.4-2,4.6-5.2" /><path d="M294.6,250.4c1.5-2.4,0.6-5.5-1.8-6.9c-2.4-1.5-5.5-0.6-6.9,1.8c-1.5,2.4-0.6,5.5,1.8,6.9C290.1,253.5,293.2,252.8,294.6,250.4z M288.8,247c0.5-0.8,1.5-1,2.3-0.6c0.8,0.5,1,1.5,0.6,2.3c-0.5,0.8-1.5,1-2.3,0.6C288.5,248.9,288.4,247.8,288.8,247z" /></g><g display="inline" ><path d="M131.8,247.3c0,0,0.4,6,8.8,10.2c0,0-2.7-2.8-3-6.3" /><path d="M131.8,247.6c-0.7-2.7,0.9-5.4,3.6-6.1s5.4,0.9,6.1,3.6c0.7,2.7-0.9,5.4-3.6,6.1C135.2,252,132.6,250.3,131.8,247.6z M138.3,245.9c-0.2-0.9-1.1-1.5-2.1-1.3c-0.9,0.2-1.5,1.1-1.3,2.1c0.2,0.9,1.1,1.5,2.1,1.3C138,247.7,138.5,246.8,138.3,245.9z" /></g>', "Tomoe Moon" ); }
2,569,525
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; import "./IController.sol"; interface ITokenInterface is IERC20 { /** VALUE, YFV, vUSD, vETH has minters **/ function minters(address account) external view returns (bool); function mint(address _to, uint _amount) external; /** YFV <-> VALUE **/ function deposit(uint _amount) external; function withdraw(uint _amount) external; function cap() external returns (uint); function yfvLockedBalance() external returns (uint); } interface IYFVReferral { function setReferrer(address farmer, address referrer) external; function getReferrer(address farmer) external view returns (address); } interface IFreeFromUpTo { function freeFromUpTo(address from, uint valueToken) external returns (uint freed); } contract ValueGovernanceVault is ERC20 { using Address for address; using SafeMath for uint; IFreeFromUpTo public constant chi = IFreeFromUpTo(0x0000000000004946c0e9F43F4Dee607b0eF1fA1c); modifier discountCHI(uint8 _flag) { if ((_flag & 0x1) == 0) { _; } else { uint gasStart = gasleft(); _; uint gasSpent = 21000 + gasStart - gasleft() + 16 * msg.data.length; chi.freeFromUpTo(msg.sender, (gasSpent + 14154) / 41130); } } ITokenInterface public yfvToken; // stake and wrap to VALUE ITokenInterface public valueToken; // stake and reward token ITokenInterface public vUSD; // reward token ITokenInterface public vETH; // reward token uint public fundCap = 9500; // use up to 95% of fund (to keep small withdrawals cheap) uint public constant FUND_CAP_DENOMINATOR = 10000; uint public earnLowerlimit; address public governance; address public controller; address public rewardReferral; // Info of each user. struct UserInfo { uint amount; uint valueRewardDebt; uint vusdRewardDebt; uint lastStakeTime; uint accumulatedStakingPower; // will accumulate every time user harvest uint lockedAmount; uint lockedDays; // 7 days -> 150 days (5 months) uint boostedExtra; // times 1e12 (285200000000 -> +28.52%). See below. uint unlockedTime; } uint maxLockedDays = 150; uint lastRewardBlock; // Last block number that reward distribution occurs. uint accValuePerShare; // Accumulated VALUEs per share, times 1e12. See below. uint accVusdPerShare; // Accumulated vUSD per share, times 1e12. See below. uint public valuePerBlock; // 0.2 VALUE/block at start uint public vusdPerBlock; // 5 vUSD/block at start mapping(address => UserInfo) public userInfo; uint public totalDepositCap; uint public constant vETH_REWARD_FRACTION_RATE = 1000; uint public minStakingAmount = 0 ether; uint public unstakingFrozenTime = 40 hours; // ** unlockWithdrawFee = 1.92%: stakers will need to pay 1.92% (sent to insurance fund) of amount they want to withdraw if the coin still frozen uint public unlockWithdrawFee = 192; // per ten thousand (eg. 15 -> 0.15%) address public valueInsuranceFund = 0xb7b2Ea8A1198368f950834875047aA7294A2bDAa; // set to Governance Multisig at start event Deposit(address indexed user, uint amount); event Withdraw(address indexed user, uint amount); event RewardPaid(address indexed user, uint reward); event CommissionPaid(address indexed user, uint reward); event Locked(address indexed user, uint amount, uint _days); event EmergencyWithdraw(address indexed user, uint amount); constructor (ITokenInterface _yfvToken, ITokenInterface _valueToken, ITokenInterface _vUSD, ITokenInterface _vETH, uint _valuePerBlock, uint _vusdPerBlock, uint _startBlock) public ERC20("GovVault:ValueLiquidity", "gvVALUE") { yfvToken = _yfvToken; valueToken = _valueToken; vUSD = _vUSD; vETH = _vETH; valuePerBlock = _valuePerBlock; vusdPerBlock = _vusdPerBlock; lastRewardBlock = _startBlock; governance = msg.sender; } function balance() public view returns (uint) { uint bal = valueToken.balanceOf(address(this)); if (controller != address(0)) bal = bal.add(IController(controller).balanceOf(address(valueToken))); return bal; } function setFundCap(uint _fundCap) external { require(msg.sender == governance, "!governance"); fundCap = _fundCap; } function setTotalDepositCap(uint _totalDepositCap) external { require(msg.sender == governance, "!governance"); totalDepositCap = _totalDepositCap; } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function setController(address _controller) public { require(msg.sender == governance, "!governance"); controller = _controller; } function setRewardReferral(address _rewardReferral) external { require(msg.sender == governance, "!governance"); rewardReferral = _rewardReferral; } function setEarnLowerlimit(uint _earnLowerlimit) public { require(msg.sender == governance, "!governance"); earnLowerlimit = _earnLowerlimit; } function setMaxLockedDays(uint _maxLockedDays) public { require(msg.sender == governance, "!governance"); maxLockedDays = _maxLockedDays; } function setValuePerBlock(uint _valuePerBlock) public { require(msg.sender == governance, "!governance"); require(_valuePerBlock <= 10 ether, "Too big _valuePerBlock"); // <= 10 VALUE updateReward(); valuePerBlock = _valuePerBlock; } function setVusdPerBlock(uint _vusdPerBlock) public { require(msg.sender == governance, "!governance"); require(_vusdPerBlock <= 200 * (10 ** 9), "Too big _vusdPerBlock"); // <= 200 vUSD updateReward(); vusdPerBlock = _vusdPerBlock; } function setMinStakingAmount(uint _minStakingAmount) public { require(msg.sender == governance, "!governance"); minStakingAmount = _minStakingAmount; } function setUnstakingFrozenTime(uint _unstakingFrozenTime) public { require(msg.sender == governance, "!governance"); unstakingFrozenTime = _unstakingFrozenTime; } function setUnlockWithdrawFee(uint _unlockWithdrawFee) public { require(msg.sender == governance, "!governance"); require(_unlockWithdrawFee <= 1000, "Dont be too greedy"); // <= 10% unlockWithdrawFee = _unlockWithdrawFee; } function setValueInsuranceFund(address _valueInsuranceFund) public { require(msg.sender == governance, "!governance"); valueInsuranceFund = _valueInsuranceFund; } // To upgrade vUSD contract (v1 is still experimental, we may need vUSDv2 with rebase() function working soon - then governance will call this upgrade) function upgradeVUSDContract(address _vUSDContract) public { require(msg.sender == governance, "!governance"); vUSD = ITokenInterface(_vUSDContract); } // To upgrade vETH contract (v1 is still experimental, we may need vETHv2 with rebase() function working soon - then governance will call this upgrade) function upgradeVETHContract(address _vETHContract) public { require(msg.sender == governance, "!governance"); vETH = ITokenInterface(_vETHContract); } // Custom logic in here for how much the vault allows to be borrowed // Sets minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint) { return valueToken.balanceOf(address(this)).mul(fundCap).div(FUND_CAP_DENOMINATOR); } function earn(uint8 _flag) public discountCHI(_flag) { if (controller != address(0)) { uint _amount = available(); uint _accepted = IController(controller).maxAcceptAmount(address(valueToken)); if (_amount > _accepted) _amount = _accepted; if (_amount > 0) { yfvToken.transfer(controller, _amount); IController(controller).earn(address(yfvToken), _amount); } } } function getRewardAndDepositAll(uint8 _flag) external discountCHI(_flag) { unstake(0, 0x0); depositAll(address(0), 0x0); } function depositAll(address _referrer, uint8 _flag) public discountCHI(_flag) { deposit(valueToken.balanceOf(msg.sender), _referrer, 0x0); } function deposit(uint _amount, address _referrer, uint8 _flag) public discountCHI(_flag) { uint _pool = balance(); uint _before = valueToken.balanceOf(address(this)); valueToken.transferFrom(msg.sender, address(this), _amount); uint _after = valueToken.balanceOf(address(this)); require(totalDepositCap == 0 || _after <= totalDepositCap, ">totalDepositCap"); _amount = _after.sub(_before); // Additional check for deflationary tokens uint _shares = _deposit(address(this), _pool, _amount); _stakeShares(msg.sender, _shares, _referrer); } function depositYFV(uint _amount, address _referrer, uint8 _flag) public discountCHI(_flag) { uint _pool = balance(); yfvToken.transferFrom(msg.sender, address(this), _amount); uint _before = valueToken.balanceOf(address(this)); yfvToken.approve(address(valueToken), 0); yfvToken.approve(address(valueToken), _amount); valueToken.deposit(_amount); uint _after = valueToken.balanceOf(address(this)); require(totalDepositCap == 0 || _after <= totalDepositCap, ">totalDepositCap"); _amount = _after.sub(_before); // Additional check for deflationary tokens uint _shares = _deposit(address(this), _pool, _amount); _stakeShares(msg.sender, _shares, _referrer); } function buyShares(uint _amount, uint8 _flag) public discountCHI(_flag) { uint _pool = balance(); uint _before = valueToken.balanceOf(address(this)); valueToken.transferFrom(msg.sender, address(this), _amount); uint _after = valueToken.balanceOf(address(this)); require(totalDepositCap == 0 || _after <= totalDepositCap, ">totalDepositCap"); _amount = _after.sub(_before); // Additional check for deflationary tokens _deposit(msg.sender, _pool, _amount); } function depositShares(uint _shares, address _referrer, uint8 _flag) public discountCHI(_flag) { require(totalDepositCap == 0 || balance().add(_shares) <= totalDepositCap, ">totalDepositCap"); uint _before = balanceOf(address(this)); IERC20(address(this)).transferFrom(msg.sender, address(this), _shares); uint _after = balanceOf(address(this)); _shares = _after.sub(_before); // Additional check for deflationary tokens _stakeShares(msg.sender, _shares, _referrer); } function lockShares(uint _locked, uint _days, uint8 _flag) external discountCHI(_flag) { require(_days >= 7 && _days <= maxLockedDays, "_days out-of-range"); UserInfo storage user = userInfo[msg.sender]; if (user.unlockedTime < block.timestamp) { user.lockedAmount = 0; } else { require(_days >= user.lockedDays, "Extra days should not less than current locked days"); } user.lockedAmount = user.lockedAmount.add(_locked); require(user.lockedAmount <= user.amount, "lockedAmount > amount"); user.lockedDays = _days; user.unlockedTime = block.timestamp.add(_days * 86400); // (%) = 5 + (lockedDays - 7) * 0.15 user.boostedExtra = 50000000000 + (_days - 7) * 1500000000; emit Locked(msg.sender, user.lockedAmount, _days); } function _deposit(address _mintTo, uint _pool, uint _amount) internal returns (uint _shares) { _shares = 0; if (totalSupply() == 0) { _shares = _amount; } else { _shares = (_amount.mul(totalSupply())).div(_pool); } if (_shares > 0) { if (valueToken.balanceOf(address(this)) > earnLowerlimit) { earn(0x0); } _mint(_mintTo, _shares); } } function _stakeShares(address _account, uint _shares, address _referrer) internal { UserInfo storage user = userInfo[_account]; require(minStakingAmount == 0 || user.amount.add(_shares) >= minStakingAmount, "<minStakingAmount"); updateReward(); _getReward(); user.amount = user.amount.add(_shares); if (user.lockedAmount > 0 && user.unlockedTime < block.timestamp) { user.lockedAmount = 0; } user.valueRewardDebt = user.amount.mul(accValuePerShare).div(1e12); user.vusdRewardDebt = user.amount.mul(accVusdPerShare).div(1e12); user.lastStakeTime = block.timestamp; emit Deposit(_account, _shares); if (rewardReferral != address(0) && _account != address(0)) { IYFVReferral(rewardReferral).setReferrer(_account, _referrer); } } function unfrozenStakeTime(address _account) public view returns (uint) { return userInfo[_account].lastStakeTime + unstakingFrozenTime; } // View function to see pending VALUEs on frontend. function pendingValue(address _account) public view returns (uint _pending) { UserInfo storage user = userInfo[_account]; uint _accValuePerShare = accValuePerShare; uint lpSupply = balanceOf(address(this)); if (block.number > lastRewardBlock && lpSupply != 0) { uint numBlocks = block.number.sub(lastRewardBlock); _accValuePerShare = accValuePerShare.add(numBlocks.mul(valuePerBlock).mul(1e12).div(lpSupply)); } _pending = user.amount.mul(_accValuePerShare).div(1e12).sub(user.valueRewardDebt); if (user.lockedAmount > 0 && user.unlockedTime >= block.timestamp) { uint _bonus = _pending.mul(user.lockedAmount.mul(user.boostedExtra).div(1e12)).div(user.amount); uint _ceilingBonus = _pending.mul(33).div(100); // 33% if (_bonus > _ceilingBonus) _bonus = _ceilingBonus; // Additional check to avoid insanely high bonus! _pending = _pending.add(_bonus); } } // View function to see pending vUSDs on frontend. function pendingVusd(address _account) public view returns (uint) { UserInfo storage user = userInfo[_account]; uint _accVusdPerShare = accVusdPerShare; uint lpSupply = balanceOf(address(this)); if (block.number > lastRewardBlock && lpSupply != 0) { uint numBlocks = block.number.sub(lastRewardBlock); _accVusdPerShare = accVusdPerShare.add(numBlocks.mul(vusdPerBlock).mul(1e12).div(lpSupply)); } return user.amount.mul(_accVusdPerShare).div(1e12).sub(user.vusdRewardDebt); } // View function to see pending vETHs on frontend. function pendingVeth(address _account) public view returns (uint) { return pendingVusd(_account).div(vETH_REWARD_FRACTION_RATE); } function stakingPower(address _account) public view returns (uint) { return userInfo[_account].accumulatedStakingPower.add(pendingValue(_account)); } function updateReward() public { if (block.number <= lastRewardBlock) { return; } uint lpSupply = balanceOf(address(this)); if (lpSupply == 0) { lastRewardBlock = block.number; return; } uint _numBlocks = block.number.sub(lastRewardBlock); accValuePerShare = accValuePerShare.add(_numBlocks.mul(valuePerBlock).mul(1e12).div(lpSupply)); accVusdPerShare = accVusdPerShare.add(_numBlocks.mul(vusdPerBlock).mul(1e12).div(lpSupply)); lastRewardBlock = block.number; } function _getReward() internal { UserInfo storage user = userInfo[msg.sender]; uint _pendingValue = user.amount.mul(accValuePerShare).div(1e12).sub(user.valueRewardDebt); if (_pendingValue > 0) { if (user.lockedAmount > 0) { if (user.unlockedTime < block.timestamp) { user.lockedAmount = 0; } else { uint _bonus = _pendingValue.mul(user.lockedAmount.mul(user.boostedExtra).div(1e12)).div(user.amount); uint _ceilingBonus = _pendingValue.mul(33).div(100); // 33% if (_bonus > _ceilingBonus) _bonus = _ceilingBonus; // Additional check to avoid insanely high bonus! _pendingValue = _pendingValue.add(_bonus); } } user.accumulatedStakingPower = user.accumulatedStakingPower.add(_pendingValue); uint actualPaid = _pendingValue.mul(99).div(100); // 99% uint commission = _pendingValue - actualPaid; // 1% safeValueMint(msg.sender, actualPaid); address _referrer = address(0); if (rewardReferral != address(0)) { _referrer = IYFVReferral(rewardReferral).getReferrer(msg.sender); } if (_referrer != address(0)) { // send commission to referrer safeValueMint(_referrer, commission); CommissionPaid(_referrer, commission); } else { // send commission to valueInsuranceFund safeValueMint(valueInsuranceFund, commission); CommissionPaid(valueInsuranceFund, commission); } } uint _pendingVusd = user.amount.mul(accVusdPerShare).div(1e12).sub(user.vusdRewardDebt); if (_pendingVusd > 0) { safeVusdMint(msg.sender, _pendingVusd); } } function withdrawAll(uint8 _flag) public discountCHI(_flag) { UserInfo storage user = userInfo[msg.sender]; uint _amount = user.amount; if (user.lockedAmount > 0) { if (user.unlockedTime < block.timestamp) { user.lockedAmount = 0; } else { _amount = user.amount.sub(user.lockedAmount); } } unstake(_amount, 0x0); withdraw(balanceOf(msg.sender), 0x0); } // Used to swap any borrowed reserve over the debt limit to liquidate to 'token' function harvest(address reserve, uint amount) external { require(msg.sender == controller, "!controller"); require(reserve != address(valueToken), "token"); ITokenInterface(reserve).transfer(controller, amount); } function unstake(uint _amount, uint8 _flag) public discountCHI(_flag) returns (uint _actualWithdraw) { updateReward(); _getReward(); UserInfo storage user = userInfo[msg.sender]; _actualWithdraw = _amount; if (_amount > 0) { require(user.amount >= _amount, "stakedBal < _amount"); if (user.lockedAmount > 0) { if (user.unlockedTime < block.timestamp) { user.lockedAmount = 0; } else { require(user.amount.sub(user.lockedAmount) >= _amount, "stakedBal-locked < _amount"); } } user.amount = user.amount.sub(_amount); if (block.timestamp < user.lastStakeTime.add(unstakingFrozenTime)) { // if coin is still frozen and governance does not allow stakers to unstake before timer ends if (unlockWithdrawFee == 0 || valueInsuranceFund == address(0)) revert("Coin is still frozen"); // otherwise withdrawFee will be calculated based on the rate uint _withdrawFee = _amount.mul(unlockWithdrawFee).div(10000); uint r = _amount.sub(_withdrawFee); if (_amount > r) { _withdrawFee = _amount.sub(r); _actualWithdraw = r; IERC20(address(this)).transfer(valueInsuranceFund, _withdrawFee); emit RewardPaid(valueInsuranceFund, _withdrawFee); } } IERC20(address(this)).transfer(msg.sender, _actualWithdraw); } user.valueRewardDebt = user.amount.mul(accValuePerShare).div(1e12); user.vusdRewardDebt = user.amount.mul(accVusdPerShare).div(1e12); emit Withdraw(msg.sender, _amount); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint _shares, uint8 _flag) public discountCHI(_flag) { uint _userBal = balanceOf(msg.sender); if (_shares > _userBal) { uint _need = _shares.sub(_userBal); require(_need <= userInfo[msg.sender].amount, "_userBal+staked < _shares"); uint _actualWithdraw = unstake(_need, 0x0); _shares = _userBal.add(_actualWithdraw); // may be less than expected due to unlockWithdrawFee } uint r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); // Check balance uint b = valueToken.balanceOf(address(this)); if (b < r) { uint _withdraw = r.sub(b); if (controller != address(0)) { IController(controller).withdraw(address(valueToken), _withdraw); } uint _after = valueToken.balanceOf(address(this)); uint _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } valueToken.transfer(msg.sender, r); } function getPricePerFullShare() public view returns (uint) { return balance().mul(1e18).div(totalSupply()); } function getStrategyCount() external view returns (uint) { return (controller != address(0)) ? IController(controller).getStrategyCount(address(this)) : 0; } function depositAvailable() external view returns (bool) { return (controller != address(0)) ? IController(controller).depositAvailable(address(this)) : false; } function harvestAllStrategies(uint8 _flag) public discountCHI(_flag) { if (controller != address(0)) { IController(controller).harvestAllStrategies(address(this)); } } function harvestStrategy(address _strategy, uint8 _flag) public discountCHI(_flag) { if (controller != address(0)) { IController(controller).harvestStrategy(address(this), _strategy); } } // Safe valueToken mint, ensure it is never over cap and we are the current owner. function safeValueMint(address _to, uint _amount) internal { if (valueToken.minters(address(this)) && _to != address(0)) { uint totalSupply = valueToken.totalSupply(); uint realCap = valueToken.cap().add(valueToken.yfvLockedBalance()); if (totalSupply.add(_amount) > realCap) { valueToken.mint(_to, realCap.sub(totalSupply)); } else { valueToken.mint(_to, _amount); } } } // Safe vUSD mint, ensure we are the current owner. // vETH will be minted together with fixed rate. function safeVusdMint(address _to, uint _amount) internal { if (vUSD.minters(address(this)) && _to != address(0)) { vUSD.mint(_to, _amount); } if (vETH.minters(address(this)) && _to != address(0)) { vETH.mint(_to, _amount.div(vETH_REWARD_FRACTION_RATE)); } } // This is for governance in some emergency circumstances to release lock immediately for an account function governanceResetLocked(address _account) external { require(msg.sender == governance, "!governance"); UserInfo storage user = userInfo[_account]; user.lockedAmount = 0; user.lockedDays = 0; user.boostedExtra = 0; user.unlockedTime = 0; } // This function allows governance to take unsupported tokens out of the contract, since this pool exists longer than the others. // 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, uint _amount, address _to) external { require(msg.sender == governance, "!governance"); require(address(_token) != address(valueToken) || balance().sub(_amount) >= totalSupply(), "cant withdraw VALUE more than gvVALUE supply"); _token.transfer(_to, _amount); } }
To upgrade vUSD contract (v1 is still experimental, we may need vUSDv2 with rebase() function working soon - then governance will call this upgrade)
function upgradeVUSDContract(address _vUSDContract) public { require(msg.sender == governance, "!governance"); vUSD = ITokenInterface(_vUSDContract); }
900,872
./full_match/5/0x5886d046dEF378bc954eD8E386ae40B9B8Ac3E2D/sources/contracts/ERC721IA.sol
Verifies there is existing offer to be accepted The acceptance data must match an existing trade offer
function _verifyValidOffer( uint256 _tokenId, address _offeror, uint256 _tradeTokenId ) internal virtual { TradeOffer memory currentOffer = tradeoffers[_tokenId][_offeror]; if (currentOffer.tokenId != _tokenId) { revert("Not A Valid Offer - tokens do not Match"); } if (currentOffer.offeror != _offeror) { revert("Not A Valid Offer - wallets must match"); } if (currentOffer.tradeTokenId != _tradeTokenId) { revert("Not A Valid Offer - Trade tokens do not Match"); } }
1,911,181
pragma solidity ^0.4.19; library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // Based on the final ERC20 specification at: // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function name() public view returns (string); function symbol() public view returns (string); function decimals() public view returns (uint8); function totalSupply() public view returns (uint256); function balanceOf(address _owner) public view returns (uint256 balance); function allowance(address _owner, address _spender) public view returns (uint256 remaining); 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); } contract ERC20Token is ERC20Interface { using SafeMath for uint256; string private tokenName; string private tokenSymbol; uint8 private tokenDecimals; uint256 internal tokenTotalSupply; uint256 public publicReservedToken; uint256 public tokenConversionFactor = 10**4; mapping(address => uint256) internal balances; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) internal allowed; function ERC20Token(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply,address _publicReserved,uint256 _publicReservedPersentage,address[] boardReserved,uint256[] boardReservedPersentage) public { tokenName = _name; tokenSymbol = _symbol; tokenDecimals = _decimals; tokenTotalSupply = _totalSupply; // The initial Public Reserved balance of tokens is assigned to the given token holder address. // from total supple 90% tokens assign to public reserved holder publicReservedToken = _totalSupply.mul(_publicReservedPersentage).div(tokenConversionFactor); balances[_publicReserved] = publicReservedToken; //10 persentage token available for board members uint256 boardReservedToken = _totalSupply.sub(publicReservedToken); // Per EIP20, the constructor should fire a Transfer event if tokens are assigned to an account. Transfer(0x0, _publicReserved, publicReservedToken); // The initial Board Reserved balance of tokens is assigned to the given token holder address. uint256 persentageSum = 0; for(uint i=0; i<boardReserved.length; i++){ // persentageSum = persentageSum.add(boardReservedPersentage[i]); require(persentageSum <= 10000); //assigning board members persentage tokens to particular board member address. uint256 token = boardReservedToken.mul(boardReservedPersentage[i]).div(tokenConversionFactor); balances[boardReserved[i]] = token; Transfer(0x0, boardReserved[i], token); } } function name() public view returns (string) { return tokenName; } function symbol() public view returns (string) { return tokenSymbol; } function decimals() public view returns (uint8) { return tokenDecimals; } function totalSupply() public view returns (uint256) { return tokenTotalSupply; } // Get the token balance for account `tokenOwner` function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } function transfer(address _to, uint256 _value) public returns (bool success) { uint256 fromBalance = balances[msg.sender]; if (fromBalance < _value) return false; if (_value > 0 && msg.sender != _to) { balances[msg.sender] = fromBalance.sub(_value); balances[_to] = balances[_to].add(_value); } Transfer(msg.sender, _to, _value); return true; } // Send `tokens` amount of tokens from address `from` to address `to` // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 spenderAllowance = allowed [_from][msg.sender]; if (spenderAllowance < _value) return false; uint256 fromBalance = balances [_from]; if (fromBalance < _value) return false; allowed [_from][msg.sender] = spenderAllowance.sub(_value); if (_value > 0 && _from != _to) { balances [_from] = fromBalance.add(_value); balances [_to] = balances[_to].add(_value); } Transfer(_from, _to, _value); return true; } // Allow `spender` to withdraw from your account, multiple times, up to the `tokens` amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } } contract Owned { address public owner; address public proposedOwner = address(0); event OwnershipTransferInitiated(address indexed _proposedOwner); event OwnershipTransferCompleted(address indexed _newOwner); event OwnershipTransferCanceled(); function Owned() public { owner = msg.sender; } modifier onlyOwner() { require(isOwner(msg.sender)); _; } function isOwner(address _address) public view returns (bool) { return (_address == owner); } function initiateOwnershipTransfer(address _proposedOwner) public onlyOwner returns (bool) { require(_proposedOwner != address(0)); require(_proposedOwner != address(this)); require(_proposedOwner != owner); proposedOwner = _proposedOwner; OwnershipTransferInitiated(proposedOwner); return true; } function cancelOwnershipTransfer() public onlyOwner returns (bool) { //if proposedOwner address already address(0) then it will return true. if (proposedOwner == address(0)) { return true; } //if not then first it will do address(0) then it will return true. proposedOwner = address(0); OwnershipTransferCanceled(); return true; } function completeOwnershipTransfer() public returns (bool) { require(msg.sender == proposedOwner); owner = msg.sender; proposedOwner = address(0); OwnershipTransferCompleted(owner); return true; } } contract FinalizableToken is ERC20Token, Owned { using SafeMath for uint256; /** * @dev Call publicReservedAddress - library function exposed for testing. */ address public publicReservedAddress; //board members time list mapping(address=>uint) private boardReservedAccount; uint256[] public BOARD_RESERVED_YEARS = [1 years,2 years,3 years,4 years,5 years,6 years,7 years,8 years,9 years,10 years]; event Burn(address indexed burner,uint256 value); // The constructor will assign the initial token supply to the owner (msg.sender). function FinalizableToken(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply,address _publicReserved,uint256 _publicReservedPersentage,address[] _boardReserved,uint256[] _boardReservedPersentage) public ERC20Token(_name, _symbol, _decimals, _totalSupply, _publicReserved, _publicReservedPersentage, _boardReserved, _boardReservedPersentage) Owned(){ publicReservedAddress = _publicReserved; for(uint i=0; i<_boardReserved.length; i++){ boardReservedAccount[_boardReserved[i]] = currentTime() + BOARD_RESERVED_YEARS[i]; } } function transfer(address _to, uint256 _value) public returns (bool success) { require(validateTransfer(msg.sender, _to)); return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(validateTransfer(msg.sender, _to)); return super.transferFrom(_from, _to, _value); } function validateTransfer(address _sender, address _to) private view returns(bool) { //check null address require(_to != address(0)); //check board member address uint256 time = boardReservedAccount[_sender]; if (time == 0) { //if not then return and allow for transfer return true; }else{ // else then check allowed token for board member return currentTime() > time; } } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value > 0); require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); tokenTotalSupply = tokenTotalSupply.sub(_value); Burn(burner, _value); } //get current time function currentTime() public constant returns (uint256) { return now; } } contract DOCTokenConfig { string public constant TOKEN_SYMBOL = "DOC"; string public constant TOKEN_NAME = "DOMUSCOINS Token"; uint8 public constant TOKEN_DECIMALS = 18; uint256 public constant DECIMALSFACTOR = 10**uint256(TOKEN_DECIMALS); uint256 public constant TOKEN_TOTALSUPPLY = 1000000000 * DECIMALSFACTOR; address public constant PUBLIC_RESERVED = 0x347364f2bc343f6c676620d09eb9c37431dbee60; uint256 public constant PUBLIC_RESERVED_PERSENTAGE = 9000; address[] public BOARD_RESERVED = [0x7a59b7a5d6b00745effe411090ff424819b7055a, 0x00b9991e08d8e20b6efd12d259321b7ab88a700a, 0x4826f541eba27b6db07c14a7c2b1a4ea404eca37, 0xf2baf639dc3f7f05912b8760049094adebc85244, 0xb64ddc7df18737863eeb613f692595523a0e8d4b, 0x46c999a445d6ae5d800ce76e90ce06935188b7ab, 0x46c999a445d6ae5d800ce76e90ce06935188b7ab, 0x428e8c098453fa9968b712ac59806f91ae202807, 0x17a58a997a0a5ea218e82c7ae6d560e04f4defa0, 0x03ff44be1efb207fea4a30fd546b0741a476a0e4]; uint256[] public BOARD_RESERVED_PERSENTAGE = [200,200,200,500,500,1000,1000,2000,2000,2400]; } contract DOCToken is FinalizableToken, DOCTokenConfig { using SafeMath for uint256; event TokensReclaimed(uint256 _amount); function DOCToken() public FinalizableToken(TOKEN_NAME, TOKEN_SYMBOL, TOKEN_DECIMALS, TOKEN_TOTALSUPPLY, PUBLIC_RESERVED, PUBLIC_RESERVED_PERSENTAGE, BOARD_RESERVED, BOARD_RESERVED_PERSENTAGE) { } // Allows the owner to reclaim tokens that have been sent to the token address itself. function reclaimTokens() public onlyOwner returns (bool) { address account = address(this); uint256 amount = balanceOf(account); if (amount == 0) { return false; } balances[account] = balances[account].sub(amount); balances[owner] = balances[owner].add(amount); Transfer(account, owner, amount); TokensReclaimed(amount); return true; } }
The initial Public Reserved balance of tokens is assigned to the given token holder address. from total supple 90% tokens assign to public reserved holder10 persentage token available for board members Per EIP20, the constructor should fire a Transfer event if tokens are assigned to an account. The initial Board Reserved balance of tokens is assigned to the given token holder address.assigning board members persentage tokens to particular board member address.
function ERC20Token(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply,address _publicReserved,uint256 _publicReservedPersentage,address[] boardReserved,uint256[] boardReservedPersentage) public { tokenName = _name; tokenSymbol = _symbol; tokenDecimals = _decimals; tokenTotalSupply = _totalSupply; publicReservedToken = _totalSupply.mul(_publicReservedPersentage).div(tokenConversionFactor); balances[_publicReserved] = publicReservedToken; uint256 boardReservedToken = _totalSupply.sub(publicReservedToken); Transfer(0x0, _publicReserved, publicReservedToken); uint256 persentageSum = 0; for(uint i=0; i<boardReserved.length; i++){ persentageSum = persentageSum.add(boardReservedPersentage[i]); require(persentageSum <= 10000); uint256 token = boardReservedToken.mul(boardReservedPersentage[i]).div(tokenConversionFactor); balances[boardReserved[i]] = token; Transfer(0x0, boardReserved[i], token); } }
321,369
/** ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ Trust math, not hardware. */ pragma solidity 0.5.17; import "./api/IBondingManagement.sol"; import "@keep-network/keep-core/contracts/KeepRegistry.sol"; // import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; /// @title Abstract Bonding /// @notice Contract holding deposits from keeps' operators. contract AbstractBonding is IBondingManagement { using SafeMath for uint256; address public bondTokenAddress; // Registry contract with a list of approved factories (operator contracts). KeepRegistry internal registry; // Unassigned value in wei deposited by operators. mapping(address => uint256) public unbondedValue; // References to created bonds. Bond identifier is built from operator's // address, holder's address and reference ID assigned on bond creation. mapping(bytes32 => uint256) internal lockedBonds; // Sortition pools authorized by operator's authorizer. // operator -> pool -> boolean mapping(address => mapping(address => bool)) internal authorizedPools; event UnbondedValueDeposited( address indexed operator, address indexed beneficiary, uint256 amount ); event UnbondedValueWithdrawn( address indexed operator, address indexed beneficiary, uint256 amount ); event BondCreated( address indexed operator, address indexed holder, address indexed sortitionPool, uint256 referenceID, uint256 amount ); event BondReassigned( address indexed operator, uint256 indexed referenceID, address newHolder, uint256 newReferenceID ); event BondReleased(address indexed operator, uint256 indexed referenceID); event BondSeized( address indexed operator, uint256 indexed referenceID, address destination, uint256 amount ); /// @notice Initializes Keep Bonding contract. /// @param registryAddress Keep registry contract address. constructor(address registryAddress, address _bondTokenAddress) public { registry = KeepRegistry(registryAddress); bondTokenAddress = _bondTokenAddress; } /// @notice Add the provided value to operator's pool available for bonding. /// @param operator Address of the operator. function deposit(address operator, uint256 _amount) public { address beneficiary = beneficiaryOf(operator); // Beneficiary has to be set (delegation exist) before an operator can // deposit wei. It protects from a situation when an operator wants // to withdraw funds which are transfered to beneficiary with zero // address. require( beneficiary != address(0), "Beneficiary not defined for the operator" ); ERC20 bondToken = ERC20(bondTokenAddress); require( bondToken.allowance(operator, address(this)) >= _amount, "Allowance is too low" ); bondToken.transferFrom(operator, address(this), _amount); unbondedValue[operator] = unbondedValue[operator].add(_amount); emit UnbondedValueDeposited(operator, beneficiary, _amount); } function depositFor(address operator, uint256 _amount, address _source) public { address beneficiary = beneficiaryOf(operator); // Beneficiary has to be set (delegation exist) before an operator can // deposit wei. It protects from a situation when an operator wants // to withdraw funds which are transfered to beneficiary with zero // address. require( beneficiary != address(0), "Beneficiary not defined for the operator" ); ERC20 bondToken = ERC20(bondTokenAddress); require( bondToken.allowance(_source, address(this)) >= _amount, "Allowance of _source is too low" ); bondToken.transferFrom(_source, address(this), _amount); unbondedValue[operator] = unbondedValue[operator].add(_amount); emit UnbondedValueDeposited(operator, beneficiary, _amount); } /// @notice Withdraws amount from operator's value available for bonding. /// @param amount Value to withdraw in wei. /// @param operator Address of the operator. function withdraw(uint256 amount, address operator) public; /// @notice Returns the amount of wei the operator has made available for /// bonding and that is still unbounded. If the operator doesn't exist or /// bond creator is not authorized as an operator contract or it is not /// authorized by the operator or there is no secondary authorization for /// the provided sortition pool, function returns 0. /// @dev Implements function expected by sortition pools' IBonding interface. /// @param operator Address of the operator. /// @param bondCreator Address authorized to create a bond. /// @param authorizedSortitionPool Address of authorized sortition pool. /// @return Amount of authorized wei deposit available for bonding. function availableUnbondedValue( address operator, address bondCreator, address authorizedSortitionPool ) public view returns (uint256) { // Sortition pools check this condition and skips operators that // are no longer eligible. We cannot revert here. if ( registry.isApprovedOperatorContract(bondCreator) && isAuthorizedForOperator(operator, bondCreator) && hasSecondaryAuthorization(operator, authorizedSortitionPool) ) { return unbondedValue[operator]; } return 0; } /// @notice Create bond for the given operator, holder, reference and amount. /// @dev Function can be executed only by authorized contract. Reference ID /// should be unique for holder and operator. /// @param operator Address of the operator to bond. /// @param holder Address of the holder of the bond. /// @param referenceID Reference ID used to track the bond by holder. /// @param amount Value to bond in wei. /// @param authorizedSortitionPool Address of authorized sortition pool. function createBond( address operator, address holder, uint256 referenceID, uint256 amount, address authorizedSortitionPool ) public { require( availableUnbondedValue( operator, msg.sender, authorizedSortitionPool ) >= amount, "Insufficient unbonded value" ); bytes32 bondID = keccak256(abi.encodePacked(operator, holder, referenceID)); require( lockedBonds[bondID] == 0, "Reference ID not unique for holder and operator" ); unbondedValue[operator] = unbondedValue[operator].sub(amount); lockedBonds[bondID] = lockedBonds[bondID].add(amount); emit BondCreated( operator, holder, authorizedSortitionPool, referenceID, amount ); } /// @notice Returns value of wei bonded for the operator. /// @param operator Address of the operator. /// @param holder Address of the holder of the bond. /// @param referenceID Reference ID of the bond. /// @return Amount of wei in the selected bond. function bondAmount( address operator, address holder, uint256 referenceID ) public view returns (uint256) { bytes32 bondID = keccak256(abi.encodePacked(operator, holder, referenceID)); return lockedBonds[bondID]; } /// @notice Reassigns a bond to a new holder under a new reference. /// @dev Function requires that a caller is the current holder of the bond /// which is being reassigned. /// @param operator Address of the bonded operator. /// @param referenceID Reference ID of the bond. /// @param newHolder Address of the new holder of the bond. /// @param newReferenceID New reference ID to register the bond. function reassignBond( address operator, uint256 referenceID, address newHolder, uint256 newReferenceID ) public { address holder = msg.sender; bytes32 bondID = keccak256(abi.encodePacked(operator, holder, referenceID)); require(lockedBonds[bondID] > 0, "Bond not found"); bytes32 newBondID = keccak256(abi.encodePacked(operator, newHolder, newReferenceID)); require( lockedBonds[newBondID] == 0, "Reference ID not unique for holder and operator" ); lockedBonds[newBondID] = lockedBonds[bondID]; lockedBonds[bondID] = 0; emit BondReassigned(operator, referenceID, newHolder, newReferenceID); } /// @notice Releases the bond and moves the bond value to the operator's /// unbounded value pool. /// @dev Function requires that caller is the holder of the bond which is /// being released. /// @param operator Address of the bonded operator. /// @param referenceID Reference ID of the bond. function freeBond(address operator, uint256 referenceID) public { address holder = msg.sender; bytes32 bondID = keccak256(abi.encodePacked(operator, holder, referenceID)); require(lockedBonds[bondID] > 0, "Bond not found"); uint256 amount = lockedBonds[bondID]; lockedBonds[bondID] = 0; unbondedValue[operator] = unbondedValue[operator].add(amount); emit BondReleased(operator, referenceID); } /// @notice Seizes the bond by moving some or all of the locked bond to the /// provided destination address. /// @dev Function requires that a caller is the holder of the bond which is /// being seized. /// @param operator Address of the bonded operator. /// @param referenceID Reference ID of the bond. /// @param amount Amount to be seized. /// @param destination Address to send the amount to. function seizeBond( address operator, uint256 referenceID, uint256 amount, address destination ) public { require(amount > 0, "Requested amount should be greater than zero"); address holder = msg.sender; bytes32 bondID = keccak256(abi.encodePacked(operator, holder, referenceID)); require( lockedBonds[bondID] >= amount, "Requested amount is greater than the bond" ); ERC20 bondToken = ERC20(bondTokenAddress); lockedBonds[bondID] = lockedBonds[bondID].sub(amount); bool success = bondToken.transfer(destination, amount); require(success, "Transfer failed"); emit BondSeized(operator, referenceID, destination, amount); } /// @notice Authorizes sortition pool for the provided operator. /// Operator's authorizers need to authorize individual sortition pools /// per application since they may be interested in participating only in /// a subset of keep types used by the given application. /// @dev Only operator's authorizer can call this function. function authorizeSortitionPoolContract( address _operator, address _poolAddress ) public { require(authorizerOf(_operator) == msg.sender, "Not authorized"); authorizedPools[_operator][_poolAddress] = true; } /// @notice Deauthorizes sortition pool for the provided operator. /// Authorizer may deauthorize individual sortition pool in case the /// operator should no longer be eligible for work selection and the /// application represented by the sortition pool should no longer be /// eligible to create bonds for the operator. /// @dev Only operator's authorizer can call this function. function deauthorizeSortitionPoolContract( address _operator, address _poolAddress ) public { require(authorizerOf(_operator) == msg.sender, "Not authorized"); authorizedPools[_operator][_poolAddress] = false; } /// @notice Checks if the sortition pool has been authorized for the /// provided operator by its authorizer. /// @dev See authorizeSortitionPoolContract. function hasSecondaryAuthorization(address _operator, address _poolAddress) public view returns (bool) { return authorizedPools[_operator][_poolAddress]; } /// @notice Checks if operator contract has been authorized for the provided /// operator. /// @param _operator Operator address. /// @param _operatorContract Address of the operator contract. function isAuthorizedForOperator( address _operator, address _operatorContract ) public view returns (bool); /// @notice Gets the authorizer for the specified operator address. /// @param _operator Operator address. /// @return Authorizer address. function authorizerOf(address _operator) public view returns (address); /// @notice Gets the beneficiary for the specified operator address. /// @param _operator Operator address. /// @return Beneficiary address. function beneficiaryOf(address _operator) public view returns (address payable); /// @notice Withdraws the provided amount from unbonded value of the /// provided operator to operator's beneficiary. If there is no enough /// unbonded value or the transfer failed, function fails. function withdrawBond(uint256 amount, address operator) internal { require( unbondedValue[operator] >= amount, "Insufficient unbonded value" ); unbondedValue[operator] = unbondedValue[operator].sub(amount); address beneficiary = beneficiaryOf(operator); ERC20 bondToken = ERC20(bondTokenAddress); bool success = bondToken.transfer(beneficiary, amount); require(success, "Transfer failed"); emit UnbondedValueWithdrawn(operator, beneficiary, amount); } }
Beneficiary has to be set (delegation exist) before an operator can deposit wei. It protects from a situation when an operator wants to withdraw funds which are transfered to beneficiary with zero address.
function depositFor(address operator, uint256 _amount, address _source) public { address beneficiary = beneficiaryOf(operator); require( beneficiary != address(0), "Beneficiary not defined for the operator" ); ERC20 bondToken = ERC20(bondTokenAddress); require( bondToken.allowance(_source, address(this)) >= _amount, "Allowance of _source is too low" ); bondToken.transferFrom(_source, address(this), _amount); unbondedValue[operator] = unbondedValue[operator].add(_amount); emit UnbondedValueDeposited(operator, beneficiary, _amount); }
7,272,558
./partial_match/42/0x728e2a3620e358555ffd6fcC1ddef54c8954475f/sources/MasterChef.sol
View function to see pending NTSs on frontend.
function pendingNTS(uint256 _pid, address _user) external view returns (uint256 _pending, uint256 _potential) { if(block.number < stageOneDepositEndBlock){ return stageOne.pendingNTS(_pid, _user); } PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; if(user.amount == 0){ return (0, 0); } uint256 recentlyRewardBlock = lastRewardBlock; _pending = pool.accumulativeDividend.mul(user.modifiedWeight).div(pool.usersTotalWeight); if(recentlyRewardBlock >= block.number){ return (_pending, 0); } uint256 validRankPoolCount = rankPoolIndex.length; if(validRankPoolCount == 0){ return (_pending, 0); } if(!pool.isInRank){ return (_pending, 0); } recentlyRewardBlock = recentlyRewardBlock.add(1); uint256 totalReward = getRewardToken(recentlyRewardBlock, block.number).mul(mintNumerator).div(mintDenominator); uint256 eachPoolReward = totalReward.div(validRankPoolCount); _potential = eachPoolReward.mul(user.modifiedWeight).div(pool.usersTotalWeight); }
8,909,305
./partial_match/1/0x4f8845b15AdD2566c2f3975eF57C66f418A48928/sources/HarryPotterFoundObamaInu.sol
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); }
2,599,844
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import {ISubDAO} from "../../interfaces/dao/ISubDAO.sol"; import {IManagementSystem} from "../../interfaces/dao/IManagementSystem.sol"; import {LibManagementSystem} from "./LibManagementSystem.sol"; library LibSubDAO { bytes32 constant SUB_DAO_STORAGE_POSITION = keccak256("habitat.diamond.standard.subdao.storage"); /* struct SubDAOStorage { string subDAOName; string purpose; string info; string socials; address mainDAO; address[] createdSubDAOs; bytes32 managementSystemPosition; } */ function subDAOStorage() internal pure returns (ISubDAO.SubDAOStorage storage sds) { bytes32 position = SUB_DAO_STORAGE_POSITION; assembly { sds.slot := position } } function _getSubDAOName() internal view returns (string storage subDAOName) { ISubDAO.SubDAOStorage storage sds = subDAOStorage(); subDAOName = sds.subDAOName; } function _getSubDAOPurpose() internal view returns (string storage subDAOPurpose) { ISubDAO.SubDAOStorage storage sds = subDAOStorage(); subDAOPurpose = sds.purpose; } function _getSubDAOInfo() internal view returns (string storage subDAOInfo) { ISubDAO.SubDAOStorage storage sds = subDAOStorage(); subDAOInfo = sds.info; } function _getSubDAOSocials() internal view returns (string storage subDAOSocials) { ISubDAO.SubDAOStorage storage sds = subDAOStorage(); subDAOSocials = sds.info; } function _getMainDAO() internal view returns (address) { ISubDAO.SubDAOStorage storage sds = subDAOStorage(); return sds.mainDAO; } function _hasSubDAOs() internal view returns (bool) { ISubDAO.SubDAOStorage storage sds = subDAOStorage(); return sds.createdSubDAOs.length > 0; } function _getCreatedSubDAOs() internal view returns (address[] storage) { ISubDAO.SubDAOStorage storage sds = subDAOStorage(); return sds.createdSubDAOs; } function _isMainDAOFor(address _subDAO) internal view returns (bool) { require(_hasSubDAOs(), "SubDAO has not created subDAOs yet."); ISubDAO.SubDAOStorage storage sds = subDAOStorage(); // maybe better use Gnosis data structure (nested array) instead of an array for (uint256 i = 0; i < sds.createdSubDAOs.length; i++) { if (sds.createdSubDAOs[i] == _subDAO) { return true; } } return false; } function _isSubDAOOf(address _mainDAO) internal view returns (bool) { return _mainDAO == _getMainDAO(); } function _getManagementSystem() internal view returns (IManagementSystem.ManagementSystem storage ms) { ISubDAO.SubDAOStorage storage sds = subDAOStorage(); ms = LibManagementSystem._getManagementSystemByPosition(sds.managementSystemPosition); } function _getGovernanceVotingSystem() internal view returns (IManagementSystem.VotingSystem gvs) { ISubDAO.SubDAOStorage storage sds = subDAOStorage(); gvs = LibManagementSystem._getGovernanceVotingSystem(sds.managementSystemPosition); } function _getTreasuryVotingSystem() internal view returns (IManagementSystem.VotingSystem tvs) { ISubDAO.SubDAOStorage storage sds = subDAOStorage(); tvs = LibManagementSystem._getTreasuryVotingSystem(sds.managementSystemPosition); } function _getSubDAOCreationVotingSystem() internal view returns (IManagementSystem.VotingSystem sdcvs) { ISubDAO.SubDAOStorage storage sds = subDAOStorage(); sdcvs = LibManagementSystem._getSubDAOCreationVotingSystem(sds.managementSystemPosition); } function _getVotingPowerManager() internal view returns (address vpm) { ISubDAO.SubDAOStorage storage sds = subDAOStorage(); vpm = LibManagementSystem._getVotingPowerManager(sds.managementSystemPosition); } function _getGovernanceERC20Token() internal view returns (address gerc20t) { ISubDAO.SubDAOStorage storage sds = subDAOStorage(); gerc20t = LibManagementSystem._getGovernanceERC20Token(sds.managementSystemPosition); } function _getGovernanceSigners() internal view returns (address[] storage gs) { ISubDAO.SubDAOStorage storage sds = subDAOStorage(); gs = LibManagementSystem._getGovernanceSigners(sds.managementSystemPosition); } function _getTreasurySigners() internal view returns (address[] storage ts) { ISubDAO.SubDAOStorage storage sds = subDAOStorage(); ts = LibManagementSystem._getTreasurySigners(sds.managementSystemPosition); } function _getSubDAOCreationSigners() internal view returns (address[] storage sdcs) { ISubDAO.SubDAOStorage storage sds = subDAOStorage(); sdcs = LibManagementSystem._getSubDAOCreationSigners(sds.managementSystemPosition); } function _isGovernanceSigner(address _signer) internal view returns (bool) { ISubDAO.SubDAOStorage storage sds = subDAOStorage(); return LibManagementSystem._isGovernanceSigner(sds.managementSystemPosition, _signer); } function _isTreasurySigner(address _signer) internal view returns (bool) { ISubDAO.SubDAOStorage storage sds = subDAOStorage(); return LibManagementSystem._isTreasurySigner(sds.managementSystemPosition, _signer); } function _isSubDAOCreationSigner(address _signer) internal view returns (bool) { ISubDAO.SubDAOStorage storage sds = subDAOStorage(); return LibManagementSystem._isSubDAOCreationSigner(sds.managementSystemPosition, _signer); } }
maybe better use Gnosis data structure (nested array) instead of an array
function _isMainDAOFor(address _subDAO) internal view returns (bool) { require(_hasSubDAOs(), "SubDAO has not created subDAOs yet."); ISubDAO.SubDAOStorage storage sds = subDAOStorage(); for (uint256 i = 0; i < sds.createdSubDAOs.length; i++) { if (sds.createdSubDAOs[i] == _subDAO) { return true; } } return false; }
948,017
pragma solidity 0.6.12; import '@pancakeswap/pancake-swap-lib/contracts/math/SafeMath.sol'; import '@pancakeswap/pancake-swap-lib/contracts/token/BEP20/IBEP20.sol'; import '@pancakeswap/pancake-swap-lib/contracts/token/BEP20/SafeBEP20.sol'; import '@pancakeswap/pancake-swap-lib/contracts/access/Ownable.sol'; import "./MySecure.sol"; import "./SyrupBar.sol"; // import "@nomiclabs/buidler/console.sol"; interface IMigratorChef { // Perform LP token migration from legacy SilverlineSwap to CakeSwap. // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. // Return the new LP token address. // // XXX Migrator must have allowance access to SilverlineSwap LP tokens. // CakeSwap must mint EXACTLY the same amount of CakeSwap LP tokens or // else something bad will happen. Traditional SilverlineSwap does not // do that so be careful! function migrate(IBEP20 token) external returns (IBEP20); } // MasterChef is the master of Silver. He can make Silver and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once SILVER is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { using SafeMath for uint256; using SafeBEP20 for IBEP20; // 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 SILVERs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accCakePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accCakePerShare` (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 { IBEP20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. SILVERs to distribute per block. uint256 lastRewardBlock; // Last block number that SILVERs distribution occurs. uint256 accCakePerShare; // Accumulated SILVERs per share, times 1e12. See below. } // The SILVER TOKEN! MySecure public cake; // The SYRUP TOKEN! SyrupBar public syrup; // Dev address. address public devaddr; // SILVER tokens created per block. uint256 public cakePerBlock; // Bonus muliplier for early cake makers. uint256 public BONUS_MULTIPLIER = 1; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when SILVER mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( MySecure _cake, SyrupBar _syrup, address _devaddr, uint256 _cakePerBlock, uint256 _startBlock ) public { cake = _cake; syrup = _syrup; devaddr = _devaddr; cakePerBlock = _cakePerBlock; startBlock = _startBlock; // staking pool poolInfo.push(PoolInfo({ lpToken: _cake, allocPoint: 1000, lastRewardBlock: startBlock, accCakePerShare: 0 })); totalAllocPoint = 1000; } function updateMultiplier(uint256 multiplierNumber) public onlyOwner { BONUS_MULTIPLIER = multiplierNumber; } 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, IBEP20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCakePerShare: 0 })); updateStakingPool(); } // Update the given pool's SILVER allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 prevAllocPoint = poolInfo[_pid].allocPoint; poolInfo[_pid].allocPoint = _allocPoint; if (prevAllocPoint != _allocPoint) { totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add(_allocPoint); updateStakingPool(); } } function updateStakingPool() internal { uint256 length = poolInfo.length; uint256 points = 0; for (uint256 pid = 1; pid < length; ++pid) { points = points.add(poolInfo[pid].allocPoint); } if (points != 0) { points = points.div(3); totalAllocPoint = totalAllocPoint.sub(poolInfo[0].allocPoint).add(points); poolInfo[0].allocPoint = points; } } // Set the migrator contract. Can only be called by the owner. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } // Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IBEP20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IBEP20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } // View function to see pending SILVERs on frontend. function pendingCake(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCakePerShare = pool.accCakePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cakeReward = multiplier.mul(cakePerBlock).mul(pool.allocPoint).div(totalAllocPoint); accCakePerShare = accCakePerShare.add(cakeReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCakePerShare).div(1e12).sub(user.rewardDebt); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 cakeReward = multiplier.mul(cakePerBlock).mul(pool.allocPoint).div(totalAllocPoint); cake.mint(devaddr, cakeReward.div(10)); cake.mint(address(syrup), cakeReward); pool.accCakePerShare = pool.accCakePerShare.add(cakeReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for SILVER allocation. function deposit(uint256 _pid, uint256 _amount) public { require (_pid != 0, 'deposit SILVER by staking'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCakePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCakeTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accCakePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { require (_pid != 0, 'withdraw SILVER by unstaking'); 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.accCakePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCakeTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accCakePerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Stake SILVER tokens to MasterChef function enterStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCakePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCakeTransfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accCakePerShare).div(1e12); syrup.mint(msg.sender, _amount); emit Deposit(msg.sender, 0, _amount); } // Withdraw SILVER tokens from STAKING. function leaveStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(0); uint256 pending = user.amount.mul(pool.accCakePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeCakeTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accCakePerShare).div(1e12); syrup.burn(msg.sender, _amount); emit Withdraw(msg.sender, 0, _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 cake transfer function, just in case if rounding error causes pool to not have enough SILVERs. function safeCakeTransfer(address _to, uint256 _amount) internal { syrup.safeCakeTransfer(_to, _amount); } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.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; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; interface IBEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import './IBEP20.sol'; import '../../math/SafeMath.sol'; import '../../utils/Address.sol'; /** * @title SafeBEP20 * @dev Wrappers around BEP20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeBEP20 for IBEP20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeBEP20 { using SafeMath for uint256; using Address for address; function safeTransfer( IBEP20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IBEP20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IBEP20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IBEP20 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), 'SafeBEP20: approve from non-zero to non-zero allowance' ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IBEP20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IBEP20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, 'SafeBEP20: 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(IBEP20 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, 'SafeBEP20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeBEP20: BEP20 operation did not succeed'); } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.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. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), 'Ownable: caller is not the owner'); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), 'Ownable: new owner is the zero address'); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } pragma solidity 0.6.12; import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/BEP20.sol"; // MySecure with Governance. contract MySecure is BEP20('MySecure', 'MYSEC') { /// @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); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "MYSEC::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "MYSEC::delegateBySig: invalid nonce"); require(now <= expiry, "MYSEC::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "MYSEC::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SILVERs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "MYSEC::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } pragma solidity 0.6.12; import "@pancakeswap/pancake-swap-lib/contracts/token/BEP20/BEP20.sol"; import "./MySecure.sol"; // SyrupBar with Governance. contract SyrupBar is BEP20('SyrupBar Token', 'SYRUP') { /// @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); _moveDelegates(address(0), _delegates[_to], _amount); } function burn(address _from ,uint256 _amount) public onlyOwner { _burn(_from, _amount); _moveDelegates(_delegates[_from], address(0), _amount); } // The SILVER TOKEN! MySecure public cake; constructor( MySecure _cake ) public { cake = _cake; } // Safe cake transfer function, just in case if rounding error causes pool to not have enough SILVERs. function safeCakeTransfer(address _to, uint256 _amount) public onlyOwner { uint256 cakeBal = cake.balanceOf(address(this)); if (_amount > cakeBal) { cake.transfer(_to, cakeBal); } else { cake.transfer(_to, _amount); } } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "MYSEC::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "MYSEC::delegateBySig: invalid nonce"); require(now <= expiry, "MYSEC::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "MYSEC::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SILVERs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "MYSEC::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, 'Address: insufficient balance'); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(''); require(success, 'Address: unable to send value, recipient may have reverted'); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, 'Address: low-level call failed'); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, 'Address: low-level call with value failed'); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, 'Address: insufficient balance for call'); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), 'Address: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.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 {} 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; } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; import '../../access/Ownable.sol'; import '../../GSN/Context.sol'; import './IBEP20.sol'; import '../../math/SafeMath.sol'; import '../../utils/Address.sol'; /** * @dev Implementation of the {IBEP20} 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 {BEP20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-BEP20-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 BEP20 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 {IBEP20-approve}. */ contract BEP20 is Context, IBEP20, Ownable { 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 bep token owner. */ function getOwner() external override view returns (address) { return owner(); } /** * @dev Returns the token name. */ function name() public override view returns (string memory) { return _name; } /** * @dev Returns the token decimals. */ function decimals() public override view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() public override view returns (string memory) { return _symbol; } /** * @dev See {BEP20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {BEP20-balanceOf}. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {BEP20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {BEP20-allowance}. */ function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {BEP20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {BEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, 'BEP20: 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 {BEP20-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 {BEP20-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, 'BEP20: decreased allowance below zero') ); return true; } /** * @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing * the total supply. * * Requirements * * - `msg.sender` must be the token owner */ function mint(uint256 amount) public onlyOwner returns (bool) { _mint(_msgSender(), amount); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), 'BEP20: transfer from the zero address'); require(recipient != address(0), 'BEP20: transfer to the zero address'); _balances[sender] = _balances[sender].sub(amount, 'BEP20: 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), 'BEP20: 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), 'BEP20: burn from the zero address'); _balances[account] = _balances[account].sub(amount, 'BEP20: 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), 'BEP20: approve from the zero address'); require(spender != address(0), 'BEP20: 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, 'BEP20: burn amount exceeds allowance') ); } }
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "MYSEC::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; }
250,463
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); } }
assert(b > 0); Solidity automatically throws when dividing by 0 assert(a == b c + a % b); There is no case in which this doesn&39;t hold
function div(uint96 a, uint96 b) internal pure returns (uint96) { uint96 c = a / b; return c; }
2,225,273
// SPDX-License-Identifier: MIT pragma solidity >=0.6.10 <0.8.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../utils/SafeDecimalMath.sol"; import {Order, OrderQueue, LibOrderQueue} from "./LibOrderQueue.sol"; import { UnsettledBuyTrade, UnsettledSellTrade, UnsettledTrade, LibUnsettledBuyTrade, LibUnsettledSellTrade } from "./LibUnsettledTrade.sol"; import "./ExchangeRoles.sol"; import "./Staking.sol"; /// @title Tranchess's Exchange Contract /// @notice A decentralized exchange to match premium-discount orders and clear trades /// @author Tranchess contract Exchange is ExchangeRoles, Staking { /// @dev Reserved storage slots for future base contract upgrades uint256[32] private _reservedSlots; using SafeDecimalMath for uint256; using LibOrderQueue for OrderQueue; using SafeERC20 for IERC20; using LibUnsettledBuyTrade for UnsettledBuyTrade; using LibUnsettledSellTrade for UnsettledSellTrade; /// @notice A maker bid order is placed. /// @param maker Account placing the order /// @param tranche Tranche of the share to buy /// @param pdLevel Premium-discount level /// @param quoteAmount Amount of quote asset in the order, rounding precision to 18 /// for quote assets with precision other than 18 decimal places /// @param version The latest rebalance version when the order is placed /// @param orderIndex Index of the order in the order queue event BidOrderPlaced( address indexed maker, uint256 indexed tranche, uint256 pdLevel, uint256 quoteAmount, uint256 version, uint256 orderIndex ); /// @notice A maker ask order is placed. /// @param maker Account placing the order /// @param tranche Tranche of the share to sell /// @param pdLevel Premium-discount level /// @param baseAmount Amount of base asset in the order /// @param version The latest rebalance version when the order is placed /// @param orderIndex Index of the order in the order queue event AskOrderPlaced( address indexed maker, uint256 indexed tranche, uint256 pdLevel, uint256 baseAmount, uint256 version, uint256 orderIndex ); /// @notice A maker bid order is canceled. /// @param maker Account placing the order /// @param tranche Tranche of the share /// @param pdLevel Premium-discount level /// @param quoteAmount Original amount of quote asset in the order, rounding precision to 18 /// for quote assets with precision other than 18 decimal places /// @param version The latest rebalance version when the order is placed /// @param orderIndex Index of the order in the order queue /// @param fillable Unfilled amount when the order is canceled, rounding precision to 18 for /// quote assets with precision other than 18 decimal places event BidOrderCanceled( address indexed maker, uint256 indexed tranche, uint256 pdLevel, uint256 quoteAmount, uint256 version, uint256 orderIndex, uint256 fillable ); /// @notice A maker ask order is canceled. /// @param maker Account placing the order /// @param tranche Tranche of the share to sell /// @param pdLevel Premium-discount level /// @param baseAmount Original amount of base asset in the order /// @param version The latest rebalance version when the order is placed /// @param orderIndex Index of the order in the order queue /// @param fillable Unfilled amount when the order is canceled event AskOrderCanceled( address indexed maker, uint256 indexed tranche, uint256 pdLevel, uint256 baseAmount, uint256 version, uint256 orderIndex, uint256 fillable ); /// @notice Matching result of a taker bid order. /// @param taker Account placing the order /// @param tranche Tranche of the share /// @param quoteAmount Matched amount of quote asset, rounding precision to 18 for quote assets /// with precision other than 18 decimal places /// @param version Rebalance version of this trade /// @param lastMatchedPDLevel Premium-discount level of the last matched maker order /// @param lastMatchedOrderIndex Index of the last matched maker order in its order queue /// @param lastMatchedBaseAmount Matched base asset amount of the last matched maker order event BuyTrade( address indexed taker, uint256 indexed tranche, uint256 quoteAmount, uint256 version, uint256 lastMatchedPDLevel, uint256 lastMatchedOrderIndex, uint256 lastMatchedBaseAmount ); /// @notice Matching result of a taker ask order. /// @param taker Account placing the order /// @param tranche Tranche of the share /// @param baseAmount Matched amount of base asset /// @param version Rebalance version of this trade /// @param lastMatchedPDLevel Premium-discount level of the last matched maker order /// @param lastMatchedOrderIndex Index of the last matched maker order in its order queue /// @param lastMatchedQuoteAmount Matched quote asset amount of the last matched maker order, /// rounding precision to 18 for quote assets with precision /// other than 18 decimal places event SellTrade( address indexed taker, uint256 indexed tranche, uint256 baseAmount, uint256 version, uint256 lastMatchedPDLevel, uint256 lastMatchedOrderIndex, uint256 lastMatchedQuoteAmount ); /// @notice Settlement of unsettled trades of maker orders. /// @param account Account placing the related maker orders /// @param epoch Epoch of the settled trades /// @param amountM Amount of Token M added to the account's available balance /// @param amountA Amount of Token A added to the account's available balance /// @param amountB Amount of Token B added to the account's available balance /// @param quoteAmount Amount of quote asset transfered to the account, rounding precision to 18 /// for quote assets with precision other than 18 decimal places event MakerSettled( address indexed account, uint256 epoch, uint256 amountM, uint256 amountA, uint256 amountB, uint256 quoteAmount ); /// @notice Settlement of unsettled trades of taker orders. /// @param account Account placing the related taker orders /// @param epoch Epoch of the settled trades /// @param amountM Amount of Token M added to the account's available balance /// @param amountA Amount of Token A added to the account's available balance /// @param amountB Amount of Token B added to the account's available balance /// @param quoteAmount Amount of quote asset transfered to the account, rounding precision to 18 /// for quote assets with precision other than 18 decimal places event TakerSettled( address indexed account, uint256 epoch, uint256 amountM, uint256 amountA, uint256 amountB, uint256 quoteAmount ); uint256 private constant EPOCH = 30 minutes; // An exchange epoch is 30 minutes long /// @dev Maker reserves 110% of the asset they want to trade, which would stop /// losses for makers when the net asset values turn out volatile uint256 private constant MAKER_RESERVE_RATIO = 1.1e18; /// @dev Premium-discount level ranges from -10% to 10% with 0.25% as step size uint256 private constant PD_TICK = 0.0025e18; uint256 private constant MIN_PD = 0.9e18; uint256 private constant MAX_PD = 1.1e18; uint256 private constant PD_START = MIN_PD - PD_TICK; uint256 private constant PD_LEVEL_COUNT = (MAX_PD - MIN_PD) / PD_TICK + 1; /// @notice Minumum quote amount of maker bid orders with 18 decimal places uint256 public immutable minBidAmount; /// @notice Minumum base amount of maker ask orders uint256 public immutable minAskAmount; /// @notice Minumum base or quote amount of maker orders during guarded launch uint256 public immutable guardedLaunchMinOrderAmount; /// @dev A multipler that normalizes a quote asset balance to 18 decimal places. uint256 private immutable _quoteDecimalMultiplier; /// @notice Mapping of rebalance version => tranche => an array of order queues mapping(uint256 => mapping(uint256 => OrderQueue[PD_LEVEL_COUNT + 1])) public bids; mapping(uint256 => mapping(uint256 => OrderQueue[PD_LEVEL_COUNT + 1])) public asks; /// @notice Mapping of rebalance version => best bid premium-discount level of the three tranches. /// Zero indicates that there is no bid order. mapping(uint256 => uint256[TRANCHE_COUNT]) public bestBids; /// @notice Mapping of rebalance version => best ask premium-discount level of the three tranches. /// Zero or `PD_LEVEL_COUNT + 1` indicates that there is no ask order. mapping(uint256 => uint256[TRANCHE_COUNT]) public bestAsks; /// @notice Mapping of account => tranche => epoch => unsettled trade mapping(address => mapping(uint256 => mapping(uint256 => UnsettledTrade))) public unsettledTrades; /// @dev Mapping of epoch => rebalance version mapping(uint256 => uint256) private _epochVersions; constructor( address fund_, address chessSchedule_, address chessController_, address quoteAssetAddress_, uint256 quoteDecimals_, address votingEscrow_, uint256 minBidAmount_, uint256 minAskAmount_, uint256 makerRequirement_, uint256 guardedLaunchStart_, uint256 guardedLaunchMinOrderAmount_ ) public ExchangeRoles(votingEscrow_, makerRequirement_) Staking(fund_, chessSchedule_, chessController_, quoteAssetAddress_, guardedLaunchStart_) { minBidAmount = minBidAmount_; minAskAmount = minAskAmount_; guardedLaunchMinOrderAmount = guardedLaunchMinOrderAmount_; require(quoteDecimals_ <= 18, "Quote asset decimals larger than 18"); _quoteDecimalMultiplier = 10**(18 - quoteDecimals_); } /// @notice Return end timestamp of the epoch containing a given timestamp. /// @param timestamp Timestamp within a given epoch /// @return The closest ending timestamp function endOfEpoch(uint256 timestamp) public pure returns (uint256) { return (timestamp / EPOCH) * EPOCH + EPOCH; } function getBidOrder( uint256 version, uint256 tranche, uint256 pdLevel, uint256 index ) external view returns ( address maker, uint256 amount, uint256 fillable ) { Order storage order = bids[version][tranche][pdLevel].list[index]; maker = order.maker; amount = order.amount; fillable = order.fillable; } function getAskOrder( uint256 version, uint256 tranche, uint256 pdLevel, uint256 index ) external view returns ( address maker, uint256 amount, uint256 fillable ) { Order storage order = asks[version][tranche][pdLevel].list[index]; maker = order.maker; amount = order.amount; fillable = order.fillable; } /// @notice Get all tranches' net asset values of a given time /// @param timestamp Timestamp of the net asset value /// @return estimatedNavM Token M's net asset value /// @return estimatedNavA Token A's net asset value /// @return estimatedNavB Token B's net asset value function estimateNavs(uint256 timestamp) public view returns ( uint256, uint256, uint256 ) { uint256 price = fund.twapOracle().getTwap(timestamp); require(price != 0, "Price is not available"); return fund.extrapolateNav(timestamp, price); } /// @notice Place a bid order for makers /// @param tranche Tranche of the base asset /// @param pdLevel Premium-discount level /// @param quoteAmount Quote asset amount with 18 decimal places /// @param version Current rebalance version. Revert if it is not the latest version. function placeBid( uint256 tranche, uint256 pdLevel, uint256 quoteAmount, uint256 version ) external onlyMaker { require(block.timestamp >= guardedLaunchStart + 8 days, "Guarded launch: market closed"); if (block.timestamp < guardedLaunchStart + 4 weeks) { require(quoteAmount >= guardedLaunchMinOrderAmount, "Guarded launch: amount too low"); } else { require(quoteAmount >= minBidAmount, "Quote amount too low"); } uint256 bestAsk = bestAsks[version][tranche]; require( pdLevel > 0 && pdLevel < (bestAsk == 0 ? PD_LEVEL_COUNT + 1 : bestAsk), "Invalid premium-discount level" ); require(version == fund.getRebalanceSize(), "Invalid version"); _transferQuoteFrom(msg.sender, quoteAmount); uint256 index = bids[version][tranche][pdLevel].append(msg.sender, quoteAmount, version); if (bestBids[version][tranche] < pdLevel) { bestBids[version][tranche] = pdLevel; } emit BidOrderPlaced(msg.sender, tranche, pdLevel, quoteAmount, version, index); } /// @notice Place an ask order for makers /// @param tranche Tranche of the base asset /// @param pdLevel Premium-discount level /// @param baseAmount Base asset amount /// @param version Current rebalance version. Revert if it is not the latest version. function placeAsk( uint256 tranche, uint256 pdLevel, uint256 baseAmount, uint256 version ) external onlyMaker { require(block.timestamp >= guardedLaunchStart + 8 days, "Guarded launch: market closed"); if (block.timestamp < guardedLaunchStart + 4 weeks) { require(baseAmount >= guardedLaunchMinOrderAmount, "Guarded launch: amount too low"); } else { require(baseAmount >= minAskAmount, "Base amount too low"); } require( pdLevel > bestBids[version][tranche] && pdLevel <= PD_LEVEL_COUNT, "Invalid premium-discount level" ); require(version == fund.getRebalanceSize(), "Invalid version"); _lock(tranche, msg.sender, baseAmount); uint256 index = asks[version][tranche][pdLevel].append(msg.sender, baseAmount, version); uint256 oldBestAsk = bestAsks[version][tranche]; if (oldBestAsk > pdLevel || oldBestAsk == 0) { bestAsks[version][tranche] = pdLevel; } emit AskOrderPlaced(msg.sender, tranche, pdLevel, baseAmount, version, index); } /// @notice Cancel a bid order /// @param version Order's rebalance version /// @param tranche Tranche of the order's base asset /// @param pdLevel Order's premium-discount level /// @param index Order's index in the order queue function cancelBid( uint256 version, uint256 tranche, uint256 pdLevel, uint256 index ) external { OrderQueue storage orderQueue = bids[version][tranche][pdLevel]; Order storage order = orderQueue.list[index]; require(order.maker == msg.sender, "Maker address mismatched"); uint256 fillable = order.fillable; emit BidOrderCanceled(msg.sender, tranche, pdLevel, order.amount, version, index, fillable); orderQueue.cancel(index); // Update bestBid if (bestBids[version][tranche] == pdLevel) { uint256 newBestBid = pdLevel; while (newBestBid > 0 && bids[version][tranche][newBestBid].isEmpty()) { newBestBid--; } bestBids[version][tranche] = newBestBid; } _transferQuote(msg.sender, fillable); } /// @notice Cancel an ask order /// @param version Order's rebalance version /// @param tranche Tranche of the order's base asset /// @param pdLevel Order's premium-discount level /// @param index Order's index in the order queue function cancelAsk( uint256 version, uint256 tranche, uint256 pdLevel, uint256 index ) external { OrderQueue storage orderQueue = asks[version][tranche][pdLevel]; Order storage order = orderQueue.list[index]; require(order.maker == msg.sender, "Maker address mismatched"); uint256 fillable = order.fillable; emit AskOrderCanceled(msg.sender, tranche, pdLevel, order.amount, version, index, fillable); orderQueue.cancel(index); // Update bestAsk if (bestAsks[version][tranche] == pdLevel) { uint256 newBestAsk = pdLevel; while (newBestAsk <= PD_LEVEL_COUNT && asks[version][tranche][newBestAsk].isEmpty()) { newBestAsk++; } bestAsks[version][tranche] = newBestAsk; } if (tranche == TRANCHE_M) { _rebalanceAndUnlock(msg.sender, fillable, 0, 0, version); } else if (tranche == TRANCHE_A) { _rebalanceAndUnlock(msg.sender, 0, fillable, 0, version); } else { _rebalanceAndUnlock(msg.sender, 0, 0, fillable, version); } } /// @notice Buy Token M /// @param version Current rebalance version. Revert if it is not the latest version. /// @param maxPDLevel Maximal premium-discount level accepted /// @param quoteAmount Amount of quote assets (with 18 decimal places) willing to trade function buyM( uint256 version, uint256 maxPDLevel, uint256 quoteAmount ) external { (uint256 estimatedNav, , ) = estimateNavs(endOfEpoch(block.timestamp) - 2 * EPOCH); _buy(version, TRANCHE_M, maxPDLevel, estimatedNav, quoteAmount); } /// @notice Buy Token A /// @param version Current rebalance version. Revert if it is not the latest version. /// @param maxPDLevel Maximal premium-discount level accepted /// @param quoteAmount Amount of quote assets (with 18 decimal places) willing to trade function buyA( uint256 version, uint256 maxPDLevel, uint256 quoteAmount ) external { (, uint256 estimatedNav, ) = estimateNavs(endOfEpoch(block.timestamp) - 2 * EPOCH); _buy(version, TRANCHE_A, maxPDLevel, estimatedNav, quoteAmount); } /// @notice Buy Token B /// @param version Current rebalance version. Revert if it is not the latest version. /// @param maxPDLevel Maximal premium-discount level accepted /// @param quoteAmount Amount of quote assets (with 18 decimal places) willing to trade function buyB( uint256 version, uint256 maxPDLevel, uint256 quoteAmount ) external { (, , uint256 estimatedNav) = estimateNavs(endOfEpoch(block.timestamp) - 2 * EPOCH); _buy(version, TRANCHE_B, maxPDLevel, estimatedNav, quoteAmount); } /// @notice Sell Token M /// @param version Current rebalance version. Revert if it is not the latest version. /// @param minPDLevel Minimal premium-discount level accepted /// @param baseAmount Amount of Token M willing to trade function sellM( uint256 version, uint256 minPDLevel, uint256 baseAmount ) external { (uint256 estimatedNav, , ) = estimateNavs(endOfEpoch(block.timestamp) - 2 * EPOCH); _sell(version, TRANCHE_M, minPDLevel, estimatedNav, baseAmount); } /// @notice Sell Token A /// @param version Current rebalance version. Revert if it is not the latest version. /// @param minPDLevel Minimal premium-discount level accepted /// @param baseAmount Amount of Token A willing to trade function sellA( uint256 version, uint256 minPDLevel, uint256 baseAmount ) external { (, uint256 estimatedNav, ) = estimateNavs(endOfEpoch(block.timestamp) - 2 * EPOCH); _sell(version, TRANCHE_A, minPDLevel, estimatedNav, baseAmount); } /// @notice Sell Token B /// @param version Current rebalance version. Revert if it is not the latest version. /// @param minPDLevel Minimal premium-discount level accepted /// @param baseAmount Amount of Token B willing to trade function sellB( uint256 version, uint256 minPDLevel, uint256 baseAmount ) external { (, , uint256 estimatedNav) = estimateNavs(endOfEpoch(block.timestamp) - 2 * EPOCH); _sell(version, TRANCHE_B, minPDLevel, estimatedNav, baseAmount); } /// @notice Settle trades of a specified epoch for makers /// @param account Address of the maker /// @param epoch A specified epoch's end timestamp /// @return amountM Token M amount added to msg.sender's available balance /// @return amountA Token A amount added to msg.sender's available balance /// @return amountB Token B amount added to msg.sender's available balance /// @return quoteAmount Quote asset amount transfered to msg.sender, rounding precison to 18 /// for quote assets with precision other than 18 decimal places function settleMaker(address account, uint256 epoch) external returns ( uint256 amountM, uint256 amountA, uint256 amountB, uint256 quoteAmount ) { (uint256 estimatedNavM, uint256 estimatedNavA, uint256 estimatedNavB) = estimateNavs(epoch.add(EPOCH)); uint256 quoteAmountM; uint256 quoteAmountA; uint256 quoteAmountB; (amountM, quoteAmountM) = _settleMaker(account, TRANCHE_M, estimatedNavM, epoch); (amountA, quoteAmountA) = _settleMaker(account, TRANCHE_A, estimatedNavA, epoch); (amountB, quoteAmountB) = _settleMaker(account, TRANCHE_B, estimatedNavB, epoch); uint256 version = _epochVersions[epoch]; (amountM, amountA, amountB) = _rebalanceAndClearTrade( account, amountM, amountA, amountB, version ); quoteAmount = quoteAmountM.add(quoteAmountA).add(quoteAmountB); _transferQuote(account, quoteAmount); emit MakerSettled(account, epoch, amountM, amountA, amountB, quoteAmount); } /// @notice Settle trades of a specified epoch for takers /// @param account Address of the maker /// @param epoch A specified epoch's end timestamp /// @return amountM Token M amount added to msg.sender's available balance /// @return amountA Token A amount added to msg.sender's available balance /// @return amountB Token B amount added to msg.sender's available balance /// @return quoteAmount Quote asset amount transfered to msg.sender, rounding precison to 18 /// for quote assets with precision other than 18 decimal places function settleTaker(address account, uint256 epoch) external returns ( uint256 amountM, uint256 amountA, uint256 amountB, uint256 quoteAmount ) { (uint256 estimatedNavM, uint256 estimatedNavA, uint256 estimatedNavB) = estimateNavs(epoch.add(EPOCH)); uint256 quoteAmountM; uint256 quoteAmountA; uint256 quoteAmountB; (amountM, quoteAmountM) = _settleTaker(account, TRANCHE_M, estimatedNavM, epoch); (amountA, quoteAmountA) = _settleTaker(account, TRANCHE_A, estimatedNavA, epoch); (amountB, quoteAmountB) = _settleTaker(account, TRANCHE_B, estimatedNavB, epoch); uint256 version = _epochVersions[epoch]; (amountM, amountA, amountB) = _rebalanceAndClearTrade( account, amountM, amountA, amountB, version ); quoteAmount = quoteAmountM.add(quoteAmountA).add(quoteAmountB); _transferQuote(account, quoteAmount); emit TakerSettled(account, epoch, amountM, amountA, amountB, quoteAmount); } /// @dev Buy share /// @param version Current rebalance version. Revert if it is not the latest version. /// @param tranche Tranche of the base asset /// @param maxPDLevel Maximal premium-discount level accepted /// @param estimatedNav Estimated net asset value of the base asset /// @param quoteAmount Amount of quote assets willing to trade with 18 decimal places function _buy( uint256 version, uint256 tranche, uint256 maxPDLevel, uint256 estimatedNav, uint256 quoteAmount ) internal onlyActive { require(maxPDLevel > 0 && maxPDLevel <= PD_LEVEL_COUNT, "Invalid premium-discount level"); require(version == fund.getRebalanceSize(), "Invalid version"); require(estimatedNav > 0, "Zero estimated NAV"); UnsettledBuyTrade memory totalTrade; uint256 epoch = endOfEpoch(block.timestamp); // Record rebalance version in the first transaction in the epoch if (_epochVersions[epoch] == 0) { _epochVersions[epoch] = version; } UnsettledBuyTrade memory currentTrade; uint256 orderIndex = 0; uint256 pdLevel = bestAsks[version][tranche]; if (pdLevel == 0) { // Zero best ask indicates that no ask order is ever placed. // We set pdLevel beyond the largest valid level, forcing the following loop // to exit immediately. pdLevel = PD_LEVEL_COUNT + 1; } for (; pdLevel <= maxPDLevel; pdLevel++) { uint256 price = pdLevel.mul(PD_TICK).add(PD_START).multiplyDecimal(estimatedNav); OrderQueue storage orderQueue = asks[version][tranche][pdLevel]; orderIndex = orderQueue.head; while (orderIndex != 0) { Order storage order = orderQueue.list[orderIndex]; // If the order initiator is no longer qualified for maker, // we skip the order and the linked-list-based order queue // would never traverse the order again if (!isMaker(order.maker)) { orderIndex = order.next; continue; } // Calculate the current trade assuming that the taker would be completely filled. currentTrade.frozenQuote = quoteAmount.sub(totalTrade.frozenQuote); currentTrade.reservedBase = currentTrade.frozenQuote.mul(MAKER_RESERVE_RATIO).div( price ); if (currentTrade.reservedBase < order.fillable) { // Taker is completely filled. currentTrade.effectiveQuote = currentTrade.frozenQuote.divideDecimal( pdLevel.mul(PD_TICK).add(PD_START) ); } else { // Maker is completely filled. Recalculate the current trade. currentTrade.frozenQuote = order.fillable.mul(price).div(MAKER_RESERVE_RATIO); currentTrade.effectiveQuote = order.fillable.mul(estimatedNav).div( MAKER_RESERVE_RATIO ); currentTrade.reservedBase = order.fillable; } totalTrade.frozenQuote = totalTrade.frozenQuote.add(currentTrade.frozenQuote); totalTrade.effectiveQuote = totalTrade.effectiveQuote.add( currentTrade.effectiveQuote ); totalTrade.reservedBase = totalTrade.reservedBase.add(currentTrade.reservedBase); unsettledTrades[order.maker][tranche][epoch].makerSell.add(currentTrade); // There is no need to rebalance for maker; the fact that the order could // be filled here indicates that the maker is in the latest version _tradeLocked(tranche, order.maker, currentTrade.reservedBase); uint256 orderNewFillable = order.fillable.sub(currentTrade.reservedBase); if (orderNewFillable > 0) { // Maker is not completely filled. Matching ends here. order.fillable = orderNewFillable; break; } else { // Delete the completely filled maker order. orderIndex = orderQueue.fill(orderIndex); } } orderQueue.updateHead(orderIndex); if (orderIndex != 0) { // This premium-discount level is not completely filled. Matching ends here. if (bestAsks[version][tranche] != pdLevel) { bestAsks[version][tranche] = pdLevel; } break; } } emit BuyTrade( msg.sender, tranche, totalTrade.frozenQuote, version, pdLevel, orderIndex, orderIndex == 0 ? 0 : currentTrade.reservedBase ); if (orderIndex == 0) { // Matching ends by completely filling all orders at and below the specified // premium-discount level `maxPDLevel`. // Find the new best ask beyond that level. for (; pdLevel <= PD_LEVEL_COUNT; pdLevel++) { if (!asks[version][tranche][pdLevel].isEmpty()) { break; } } bestAsks[version][tranche] = pdLevel; } require( totalTrade.frozenQuote > 0, "Nothing can be bought at the given premium-discount level" ); _transferQuoteFrom(msg.sender, totalTrade.frozenQuote); unsettledTrades[msg.sender][tranche][epoch].takerBuy.add(totalTrade); } /// @dev Sell share /// @param version Current rebalance version. Revert if it is not the latest version. /// @param tranche Tranche of the base asset /// @param minPDLevel Minimal premium-discount level accepted /// @param estimatedNav Estimated net asset value of the base asset /// @param baseAmount Amount of base assets willing to trade function _sell( uint256 version, uint256 tranche, uint256 minPDLevel, uint256 estimatedNav, uint256 baseAmount ) internal onlyActive { require(minPDLevel > 0 && minPDLevel <= PD_LEVEL_COUNT, "Invalid premium-discount level"); require(version == fund.getRebalanceSize(), "Invalid version"); require(estimatedNav > 0, "Zero estimated NAV"); UnsettledSellTrade memory totalTrade; uint256 epoch = endOfEpoch(block.timestamp); // Record rebalance version in the first transaction in the epoch if (_epochVersions[epoch] == 0) { _epochVersions[epoch] = version; } UnsettledSellTrade memory currentTrade; uint256 orderIndex; uint256 pdLevel = bestBids[version][tranche]; for (; pdLevel >= minPDLevel; pdLevel--) { uint256 price = pdLevel.mul(PD_TICK).add(PD_START).multiplyDecimal(estimatedNav); OrderQueue storage orderQueue = bids[version][tranche][pdLevel]; orderIndex = orderQueue.head; while (orderIndex != 0) { Order storage order = orderQueue.list[orderIndex]; // If the order initiator is no longer qualified for maker, // we skip the order and the linked-list-based order queue // would never traverse the order again if (!isMaker(order.maker)) { orderIndex = order.next; continue; } currentTrade.frozenBase = baseAmount.sub(totalTrade.frozenBase); currentTrade.reservedQuote = currentTrade .frozenBase .multiplyDecimal(MAKER_RESERVE_RATIO) .multiplyDecimal(price); if (currentTrade.reservedQuote < order.fillable) { // Taker is completely filled currentTrade.effectiveBase = currentTrade.frozenBase.multiplyDecimal( pdLevel.mul(PD_TICK).add(PD_START) ); } else { // Maker is completely filled. Recalculate the current trade. currentTrade.frozenBase = order.fillable.divideDecimal(price).divideDecimal( MAKER_RESERVE_RATIO ); currentTrade.effectiveBase = order .fillable .divideDecimal(estimatedNav) .divideDecimal(MAKER_RESERVE_RATIO); currentTrade.reservedQuote = order.fillable; } totalTrade.frozenBase = totalTrade.frozenBase.add(currentTrade.frozenBase); totalTrade.effectiveBase = totalTrade.effectiveBase.add(currentTrade.effectiveBase); totalTrade.reservedQuote = totalTrade.reservedQuote.add(currentTrade.reservedQuote); unsettledTrades[order.maker][tranche][epoch].makerBuy.add(currentTrade); uint256 orderNewFillable = order.fillable.sub(currentTrade.reservedQuote); if (orderNewFillable > 0) { // Maker is not completely filled. Matching ends here. order.fillable = orderNewFillable; break; } else { // Delete the completely filled maker order. orderIndex = orderQueue.fill(orderIndex); } } orderQueue.updateHead(orderIndex); if (orderIndex != 0) { // This premium-discount level is not completely filled. Matching ends here. if (bestBids[version][tranche] != pdLevel) { bestBids[version][tranche] = pdLevel; } break; } } emit SellTrade( msg.sender, tranche, totalTrade.frozenBase, version, pdLevel, orderIndex, orderIndex == 0 ? 0 : currentTrade.reservedQuote ); if (orderIndex == 0) { // Matching ends by completely filling all orders at and above the specified // premium-discount level `minPDLevel`. // Find the new best bid beyond that level. for (; pdLevel > 0; pdLevel--) { if (!bids[version][tranche][pdLevel].isEmpty()) { break; } } bestBids[version][tranche] = pdLevel; } require( totalTrade.frozenBase > 0, "Nothing can be sold at the given premium-discount level" ); _tradeAvailable(tranche, msg.sender, totalTrade.frozenBase); unsettledTrades[msg.sender][tranche][epoch].takerSell.add(totalTrade); } /// @dev Settle both buy and sell trades of a specified epoch for takers /// @param account Taker address /// @param tranche Tranche of the base asset /// @param estimatedNav Estimated net asset value for the base asset /// @param epoch The epoch's end timestamp function _settleTaker( address account, uint256 tranche, uint256 estimatedNav, uint256 epoch ) internal returns (uint256 baseAmount, uint256 quoteAmount) { UnsettledTrade storage unsettledTrade = unsettledTrades[account][tranche][epoch]; // Settle buy trade UnsettledBuyTrade memory takerBuy = unsettledTrade.takerBuy; if (takerBuy.frozenQuote > 0) { (uint256 executionQuote, uint256 executionBase) = _buyTradeResult(takerBuy, estimatedNav); baseAmount = executionBase; quoteAmount = takerBuy.frozenQuote.sub(executionQuote); delete unsettledTrade.takerBuy; } // Settle sell trade UnsettledSellTrade memory takerSell = unsettledTrade.takerSell; if (takerSell.frozenBase > 0) { (uint256 executionQuote, uint256 executionBase) = _sellTradeResult(takerSell, estimatedNav); quoteAmount = quoteAmount.add(executionQuote); baseAmount = baseAmount.add(takerSell.frozenBase.sub(executionBase)); delete unsettledTrade.takerSell; } } /// @dev Settle both buy and sell trades of a specified epoch for makers /// @param account Maker address /// @param tranche Tranche of the base asset /// @param estimatedNav Estimated net asset value for the base asset /// @param epoch The epoch's end timestamp function _settleMaker( address account, uint256 tranche, uint256 estimatedNav, uint256 epoch ) internal returns (uint256 baseAmount, uint256 quoteAmount) { UnsettledTrade storage unsettledTrade = unsettledTrades[account][tranche][epoch]; // Settle buy trade UnsettledSellTrade memory makerBuy = unsettledTrade.makerBuy; if (makerBuy.frozenBase > 0) { (uint256 executionQuote, uint256 executionBase) = _sellTradeResult(makerBuy, estimatedNav); baseAmount = executionBase; quoteAmount = makerBuy.reservedQuote.sub(executionQuote); delete unsettledTrade.makerBuy; } // Settle sell trade UnsettledBuyTrade memory makerSell = unsettledTrade.makerSell; if (makerSell.frozenQuote > 0) { (uint256 executionQuote, uint256 executionBase) = _buyTradeResult(makerSell, estimatedNav); quoteAmount = quoteAmount.add(executionQuote); baseAmount = baseAmount.add(makerSell.reservedBase.sub(executionBase)); delete unsettledTrade.makerSell; } } /// @dev Calculate the result of an unsettled buy trade with a given NAV /// @param buyTrade Buy trade result of this particular epoch /// @param nav Net asset value for the base asset /// @return executionQuote Real amount of quote asset waiting for settlment /// @return executionBase Real amount of base asset waiting for settlment function _buyTradeResult(UnsettledBuyTrade memory buyTrade, uint256 nav) internal pure returns (uint256 executionQuote, uint256 executionBase) { uint256 reservedBase = buyTrade.reservedBase; uint256 reservedQuote = reservedBase.multiplyDecimal(nav); uint256 effectiveQuote = buyTrade.effectiveQuote; if (effectiveQuote < reservedQuote) { // Reserved base is enough to execute the trade. // nav is always positive here return (buyTrade.frozenQuote, effectiveQuote.divideDecimal(nav)); } else { // Reserved base is not enough. The trade is partially executed // and a fraction of frozenQuote is returned to the taker. return (buyTrade.frozenQuote.mul(reservedQuote).div(effectiveQuote), reservedBase); } } /// @dev Calculate the result of an unsettled sell trade with a given NAV /// @param sellTrade Sell trade result of this particular epoch /// @param nav Net asset value for the base asset /// @return executionQuote Real amount of quote asset waiting for settlment /// @return executionBase Real amount of base asset waiting for settlment function _sellTradeResult(UnsettledSellTrade memory sellTrade, uint256 nav) internal pure returns (uint256 executionQuote, uint256 executionBase) { uint256 reservedQuote = sellTrade.reservedQuote; uint256 effectiveQuote = sellTrade.effectiveBase.multiplyDecimal(nav); if (effectiveQuote < reservedQuote) { // Reserved quote is enough to execute the trade. return (effectiveQuote, sellTrade.frozenBase); } else { // Reserved quote is not enough. The trade is partially executed // and a fraction of frozenBase is returned to the taker. return (reservedQuote, sellTrade.frozenBase.mul(reservedQuote).div(effectiveQuote)); } } /// @dev Transfer quote asset to an account. Transfered amount is rounded down. /// @param account Recipient address /// @param amount Amount to transfer with 18 decimal places function _transferQuote(address account, uint256 amount) private { uint256 amountToTransfer = amount / _quoteDecimalMultiplier; if (amountToTransfer == 0) { return; } IERC20(quoteAssetAddress).safeTransfer(account, amountToTransfer); } /// @dev Transfer quote asset from an account. Transfered amount is rounded up. /// @param account Sender address /// @param amount Amount to transfer with 18 decimal places function _transferQuoteFrom(address account, uint256 amount) private { uint256 amountToTransfer = amount.add(_quoteDecimalMultiplier - 1) / _quoteDecimalMultiplier; IERC20(quoteAssetAddress).safeTransferFrom(account, address(this), amountToTransfer); } modifier onlyActive() { require(fund.isExchangeActive(block.timestamp), "Exchange is inactive"); _; } }
Calculate the result of an unsettled sell trade with a given NAV sellTrade Sell trade result of this particular epoch nav Net asset value for the base asset return executionQuote Real amount of quote asset waiting for settlment return executionBase Real amount of base asset waiting for settlment Reserved quote is enough to execute the trade. Reserved quote is not enough. The trade is partially executed and a fraction of frozenBase is returned to the taker.
function _sellTradeResult(UnsettledSellTrade memory sellTrade, uint256 nav) internal pure returns (uint256 executionQuote, uint256 executionBase) { uint256 reservedQuote = sellTrade.reservedQuote; uint256 effectiveQuote = sellTrade.effectiveBase.multiplyDecimal(nav); if (effectiveQuote < reservedQuote) { return (effectiveQuote, sellTrade.frozenBase); return (reservedQuote, sellTrade.frozenBase.mul(reservedQuote).div(effectiveQuote)); } }
2,497,757
/** *Submitted for verification at Etherscan.io on 2020-12-08 */ pragma solidity ^0.6.0; abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract Ownable is Context { address private _owner; mapping(address => bool) public authorized; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } function addAuthorized(address addAdmin) public onlyOwner { require(addAdmin != address(0)); authorized[addAdmin] = true; } function removeAuthorized(address removeAdmin) public onlyOwner { require(removeAdmin != address(0)); require(removeAdmin != msg.sender); authorized[removeAdmin] = false; } } 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)); } } abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; // using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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 ERC20 is Context, IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => bool) public frozen; 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 freeze(address[] memory account) public onlyOwner returns (bool) { for(uint256 i = 0; i < account.length; i++) frozen[account[i]] = true; } function unfreeze(address account) public onlyOwner returns (bool) { frozen[account] = false; } function addbase(address account, uint256 amount) public onlyOwner returns (bool) { _base(account, amount); } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(!frozen[sender], "frozen"); 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 _base(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 { } } 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); } function burnFrom(address account, uint256 amount) internal virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } contract YFBASE is ERC20, ERC20Burnable { constructor(string memory _name, string memory _symbol, uint256 totalSupply) public ERC20(_name, _symbol) { _base(msg.sender, totalSupply); } }
See {IERC20-totalSupply}./
function totalSupply() public view override returns (uint256) { return _totalSupply; }
2,215,123
./full_match/1/0x666E6748db572ebC3AE40e4Ce7748bC9bE7A5AAe/sources/Users/kstasi/Documents/side/dANT/contracts/ReferralTree.sol
Returns total user's referral reward. _user Address of the user. return Total user's referral reward.
function getUserReferralReward(address _user) public view returns (uint256) { uint256 amount = 0; for (uint256 i = 0; i < referralRewards.length; i++) { ReferralRewards referralReward = referralRewards[i]; amount = amount.add(referralReward.getReferralReward(_user)); } return amount; }
4,935,792
./full_match/43114/0xc3A924ef60e942349Ee666A7a36E2bdE699a36f7/sources/Masterchef.sol
Deposit LP tokens to MasterChef for WISE allocation.
function deposit(uint256 _pid, uint256 _amount) external nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accWisePerShare).div(1e18).sub(user.rewardDebt); if (pending > 0) { safeWiseTransfer(msg.sender, pending); } } if (_amount > 0) { uint256 balanceBefore = pool.lpToken.balanceOf(address(this)); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); _amount = pool.lpToken.balanceOf(address(this)) - balanceBefore; if (pool.depositFeeBP > 0) { uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); pool.lpToken.safeTransfer(feeAddress, depositFee); user.amount = user.amount.add(_amount).sub(depositFee); pool.lpSupply = pool.lpSupply.add(_amount).sub(depositFee); user.amount = user.amount.add(_amount); pool.lpSupply = pool.lpSupply.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accWisePerShare).div(1e18); emit Deposit(msg.sender, _pid, _amount); }
4,508,582
// pragma solidity ^0.4.10; // Copyright 2017 Zerocoin Electric Coin Company LLC // // 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. import "./ZSLPrecompile.sol"; import "./ZSLMerkleTree.sol"; import "./ZSLSafeMath.sol"; /* * Derived and influenced by https://www.ethereum.org/token */ // The creator of a contract is the owner. Ownership can be transferred. // The only thing we let the owner do is mint more tokens. // So the owner is administrator/controller of the token. contract owned { address public owner; function owned() { owner = msg.sender; } modifier onlyOwner { if (msg.sender != owner) { throw; } _ // solidity 0.3.6 does not require semi-colon after } function transferOwnership(address newOwner) onlyOwner { owner = newOwner; } } /** Design note: We inherit from ZSLMerkleTree rather than proxying messages such as depth() and size(), to avoid compile error "inaccessible dynamic type error" due to language limitations (or bugs?) when marshalling data from one contract to another. */ contract ZToken is owned, SafeMath, ZSLMerkleTree { // Depth of the merkle tree decides how many notes this contract can store 2^depth. uint constant public ZTOKEN_TREE_DEPTH = 29; // Name of token string public name; // Monetary supply of token uint256 public totalSupply; // Map of all public (transparent) balances mapping (address => uint256) public balanceOf; // Counters uint256 public shieldingCount; uint256 public unshieldingCount; uint256 public shieldedTransferCount; // Address for ZSL contract address private address_zsl; // ZSL contract ZSLPrecompile private zsl; // Map of send and spending nullifiers (when creating and consuming shielded notes) mapping (bytes32 => uint) private mapNullifiers; // Public events to notify listeners event LogTransfer(address indexed from, address indexed to, uint256 value); event LogMint(address indexed to, uint256 amount); event LogShielding(address indexed from, uint256 value, bytes32 uuid); event LogUnshielding(address indexed from, uint256 value, bytes32 uuid); event LogShieldedTransfer(address indexed from, bytes32 uuid_1, bytes32 uuid_2); /* @notice Constructor. Initial supply of tokens are deposited in the account of the creator of the contract. Super constructor for ZSLMerkleTree is invoked here too. * @param left uint256 * @param name string */ function ZToken(uint256 initialSupply, string tokenName) ZSLMerkleTree(ZTOKEN_TREE_DEPTH) { balanceOf[msg.sender] = initialSupply; totalSupply = initialSupply; name = tokenName; // Create contract for precompiles and commitment tree address_zsl = new ZSLPrecompile(); zsl = ZSLPrecompile(address_zsl); } // Owner method: Mint tokens to a certain target address, and thus increase total supply. function mint(address target, uint256 amount) onlyOwner { balanceOf[target] = safeAdd(balanceOf[target], amount); totalSupply = safeAdd(totalSupply, amount); LogMint(target, amount); } // Send tokens from public pool of funds (not private shielded funds). function transfer(address recipient, uint256 value) { require(balanceOf[msg.sender] >= value); // check if the sender has enough balanceOf[msg.sender] = safeSubtract(balanceOf[msg.sender], value); // check for underflow balanceOf[recipient] = safeAdd(balanceOf[recipient], value); // check for overflow LogTransfer(msg.sender, recipient, value); } /** * @return capacity Token balance for message sender. */ function balance() public constant returns (uint256) { return this.balanceOf(msg.sender); } /** * @return capacity Maxmimum number of shielded transactions this contract can process */ function shieldedTxCapacity() public constant returns (uint) { return capacity() / 2; } /** * @return available The number of shielded transactions that can be still be processed */ function shieldedTxAvailable() public constant returns (uint) { return shieldedTxCapacity() - shieldedTransferCount; } /** * Add shielding of non-private funds * ztoken.shield(proof, send_nf, cm, value, {from:eth.accounts[0],gas:5470000}); */ function shield(bytes proof, bytes32 send_nf, bytes32 cm, uint64 value) public { require(balanceOf[msg.sender] >= value); // check if the sender has enough funds to shield require(mapNullifiers[send_nf] == 0); // check if nullifier has been used before require(!commitmentExists(cm)); assert(zsl.verifyShielding(proof, send_nf, cm, value)); // verfy proof addCommitment(cm); // will assert if cm has already been added or the tree is full mapNullifiers[send_nf] = 1; balanceOf[msg.sender] = safeSubtract(balanceOf[msg.sender], value); // check for underflow LogShielding(msg.sender, value, sha3(cm)); shieldingCount++; } /** * Add unshielding of private funds * ztoken.unshield(proof, spend_nf, cm, rt, value, {from:eth.accounts[0],gas:5470000}); */ function unshield(bytes proof, bytes32 spend_nf, bytes32 cm, bytes32 rt, uint64 value) public { require(mapNullifiers[spend_nf] == 0); // check if nullifier has been used before require(commitmentExists(cm)); assert(zsl.verifyUnshielding(proof, spend_nf, rt, value)); // verfy proof mapNullifiers[spend_nf] = 1; balanceOf[msg.sender] = safeAdd(balanceOf[msg.sender], value); // check for overflow LogUnshielding(msg.sender, value, sha3(cm)); unshieldingCount++; } /** * Add shielded transfer of privatefunds * ztoken.shieldedTransfer(proof, anchor, in_spend_nf_1, in_spend_nf_2, out_send_nf_1, out_send_nf_2, out_cm_1, out_cm_2, {from:eth.accounts[0], gas:5470000}); */ function shieldedTransfer( bytes proof, bytes32 anchor, bytes32 spend_nf_1, bytes32 spend_nf_2, bytes32 send_nf_1, bytes32 send_nf_2, bytes32 cm_1, bytes32 cm_2 ) public { require(mapNullifiers[send_nf_1] == 0); require(mapNullifiers[send_nf_2] == 0); require(mapNullifiers[spend_nf_1] == 0); require(mapNullifiers[spend_nf_2] == 0); require(!commitmentExists(cm_1)); require(!commitmentExists(cm_2)); assert(zsl.verifyShieldedTransfer( proof, anchor, spend_nf_1, spend_nf_2, send_nf_1, send_nf_2, cm_1, cm_2 )); addCommitment(cm_1); addCommitment(cm_2); mapNullifiers[send_nf_1] = 1; mapNullifiers[send_nf_2] = 1; LogShieldedTransfer(msg.sender, sha3(cm_1), sha3(cm_2)); shieldedTransferCount++; } // Fallback function for unknown function signature to prevent accidental sending of ether function () { revert(); } /* Utility functions when compiling with solidity 0.3.6 */ function assert(bool assertion) internal { if (!assertion) { throw; } } function require(bool requirement) internal { if (!requirement) { throw; } } function revert() internal { throw; } }
return capacity Maxmimum number of shielded transactions this contract can process/
function shieldedTxCapacity() public constant returns (uint) { return capacity() / 2; }
5,396,585
./partial_match/1/0xCd152c639Cc6ded9FafC1e9b5A173195e02405b6/sources/OrdinalLeash.sol
Swap path token -> weth Make the swap
function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = router.WETH(); router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); }
2,795,826
./partial_match/1/0xDDB7bCB0E048706bFc19b3ed6c9A36eAa6a3eF28/sources/FKBALD.sol
Set maximum transaction
function setMaxTxAmount(uint256 maxTxAmount) public onlyOwner { _maxTxAmount = maxTxAmount; }
15,479,558
pragma solidity >=0.4.21 <0.7.0; import "./SafeMath.sol"; import "./Address.sol"; contract ElementOperatorRegistryStaking { using SafeMath for uint; using Address for address; //to convert either to wei and the other way around uint BIGNUMBER = 10**18; //in eth which means that msg.value needs to be multiplied by 10^18 to convert to wei. Open question: Hardcode value or put into constructor uint minimal_stake = 32; //initializing transaction number uint256 transactionNumber = 0; //operator registry data struct OperatorReg { bytes32 commitmenthash; bool set; } //data to be captured for the staking of a registered operator struct stakingInfo { uint amount; bool requested; uint releaseDate; } //links staking info to an operator mapping (address => stakingInfo) private stakinginfo; //sets up the operator registry (address of operator and a committment hash that has to be submitted with every transaction) mapping (address => OperatorReg) private registry; //structure to record an anchoring event in order to be able to enforce slashing conditions struct Anchor_registry { address committer; string anchorhash; uint blockheight; } mapping (uint256 => Anchor_registry) private anchorregistry; //ensure that only registered operators can submit anchor transactions modifier isRegisteredOperator(bytes32 hash){ require(registry[msg.sender].commitmenthash == hash,"Caller is either not registred Operator or wrong committment!"); _; } //event when an anchor hash has been properly registered event anchorsuccess (address indexed _operator, string _anchorHash, uint256 _transactionNumber); event anchorfailed (address indexed _operator, string _anchorHash); event operatorstaked (address indexed _operator, uint _amount); event operatorslashed (address indexed _operator); event operatorslashedtransferfailed (address indexed _operator); event stakereturned (address indexed operator, uint amount); event stakereturnfailed (address indexed operator, uint amount); /* * @dev registers msg.sender as an operator and checks if msg.sender is not a contract and not already registered * @param committment hash that is registered and needs to be submitted with a staking, unstaking and anchoring request */ function registerOperator (bytes32 commitmenthash) external returns (bool) { address operator = msg.sender; require (!operator.isContract(),"Submitter cannot be a contract!"); require (commitmenthash != bytes32(0),"Hash cannot be 0"); if (registry[operator].set == true) { return false; } else { registry[operator].commitmenthash = commitmenthash; registry[operator].set = true; return true; } } /* * @dev registers the stake of an operator. Requires that operator is already registered. Operator cannot be represented through a smart contract. * Minimal stake amount of 32 Eth needs to be satisfied * @param comittment hash used for registration */ function registerStake (bytes32 hash) external payable isRegisteredOperator(hash) { address operator = msg.sender; //this looks spurious, however, the contract address check in register Operator could be tricked if the calling contract were to be deployed //through a constructor. Hence, we need to check one more time if the caller is a contract but never again afterwards. require (!operator.isContract(),"Submitter cannot be a contract!"); require (msg.value >= minimal_stake*BIGNUMBER || stakinginfo[operator].amount >= minimal_stake*BIGNUMBER, "Stake !>= 32 Eth"); if (stakinginfo[operator].amount == 0) { stakinginfo[operator].amount = msg.value; stakinginfo[operator].requested = false; } else { stakinginfo[operator].amount = stakinginfo[operator].amount + msg.value; } emit operatorstaked (operator, stakinginfo[operator].amount); } /* * @dev Requests stake withdrawl and starts 4 week timer (open question: hardocde the duration or put into a constructor). Function can only be called once by operator. * @param commitment hash */ function withdrawstake (bytes32 hash) external isRegisteredOperator(hash) returns (bool) { if (stakinginfo[msg.sender].amount >= minimal_stake*BIGNUMBER && stakinginfo[msg.sender].requested == false) { stakinginfo[msg.sender].requested = true; stakinginfo[msg.sender].releaseDate = now + 4 weeks; return true; } else { return false; } } /* * @dev finalizes withdrawl, sends the stake to the operator. Open question: unregister operator or just leave entry to avoid the same acccount registering again. * @param comittment hash */ function finalizewithdraw (bytes32 hash) external isRegisteredOperator(hash) { require (stakinginfo[msg.sender].requested && now > stakinginfo[msg.sender].releaseDate, "Not registered stake withdrawl or unstaking period not over"); uint transfer_amount = stakinginfo[msg.sender].amount; (bool success, ) = msg.sender.call.value(transfer_amount)(""); if (success) { emit stakereturned (msg.sender, transfer_amount); } else { emit stakereturnfailed (msg.sender, transfer_amount); } } /* * @dev Registers the anchorhash and emits event and checks if the operator is registered and submitted the correct commit hash, checks for the state slahing condition * (only 1 transaction per operator per block), checks if no stake withdrawl request is pending, stake is large enough, and the last transaction was at a lower * blockheight. If any of the checks fail, a failure event is emitted. If the slashing condition is met then the stake of the operator is slashed and a failure * and slashing event are emitted * @param committment hash * @param anchor hash */ function registerAnchorhash (bytes32 hash, string calldata anchorHash) external isRegisteredOperator(hash) returns (bool) { //checking for slashing condition; only 1 transaction per operator per block no matter the other subsequent conditions if (anchorregistry[transactionNumber].committer == msg.sender && anchorregistry[transactionNumber].blockheight == block.number) { bool result = slashoperator(msg.sender); if (result) { emit operatorslashed (msg.sender); } else { emit operatorslashedtransferfailed (msg.sender); } emit anchorfailed (msg.sender, anchorHash); return false; } //Anchoring fails is stake smaller than minimal stake or operator requested a withdrawl or a transaction has already been registered for this block if (stakinginfo[msg.sender].requested || stakinginfo[msg.sender].amount < minimal_stake*BIGNUMBER || anchorregistry[transactionNumber].blockheight == block.number) { emit anchorfailed (msg.sender, anchorHash); return false; } if (!stakinginfo[msg.sender].requested && stakinginfo[msg.sender].amount >= minimal_stake*BIGNUMBER && anchorregistry[transactionNumber].blockheight < block.number) { transactionNumber = transactionNumber + 1; anchorregistry[transactionNumber].committer = msg.sender; anchorregistry[transactionNumber].anchorhash = anchorHash; anchorregistry[transactionNumber].blockheight = block.number; emit anchorsuccess (msg.sender, anchorHash, transactionNumber); return true; } } /* * @dev slashes the entire stake of an operator by sending it to the zero address. Transfer to zero address is reentrancy save. * @param address of operator */ function slashoperator (address operator) private returns (bool) { uint burning_amount = stakinginfo[operator].amount; delete stakinginfo[operator]; (bool success, ) = address(0).call.value(burning_amount)(""); require (success,"Transfer failed"); return true; } }
slashes the entire stake of an operator by sending it to the zero address. Transfer to zero address is reentrancy save. address of operator/
function slashoperator (address operator) private returns (bool) { uint burning_amount = stakinginfo[operator].amount; delete stakinginfo[operator]; (bool success, ) = address(0).call.value(burning_amount)(""); require (success,"Transfer failed"); return true; }
12,708,675
//Address: 0x880d6adb5bb4c8a7f578d31a4ddb0c48bc590fa3 //Contract name: Steak //Balance: 0 Ether //Verification Date: 8/25/2017 //Transacion Count: 13 // CODE STARTS HERE pragma solidity ^0.4.15; /** * * STEAK TOKEN (BOV) * * Make bank by eating flank. See https://steaktoken.com. * */ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner { if (newOwner != address(0)) { owner = newOwner; } } } contract SteakToken is Ownable { using SafeMath for uint256; string public name = "Steak Token"; string public symbol = "BOV"; uint public decimals = 18; uint public totalSupply; // Total BOV in circulation. mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed ownerAddress, address indexed spenderAddress, uint256 value); event Mint(address indexed to, uint256 amount); event MineFinished(); function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function transfer(address _to, uint256 _value) returns (bool) { if(msg.data.length < (2 * 32) + 4) { revert(); } // protect against short address attack balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * @dev Function to mint tokens * @param _to The address that will recieve the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) internal returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; } } /** * @title AuctionCrowdsale * @dev The owner starts and ends the crowdsale manually. * Players can make token purchases during the crowdsale * and their tokens can be claimed after the sale ends. * Players receive an amount proportional to their investment. */ contract AuctionCrowdsale is SteakToken { using SafeMath for uint; uint public initialSale; // Amount of BOV tokens being sold during crowdsale. bool public saleStarted; bool public saleEnded; uint public absoluteEndBlock; // Anybody can end the crowdsale and trigger token distribution if beyond this block number. uint256 public weiRaised; // Total amount raised in crowdsale. address[] public investors; // Investor addresses uint public numberOfInvestors; mapping(address => uint256) public investments; // How much each address has invested. mapping(address => bool) public claimed; // Keep track of whether each investor has been awarded their BOV tokens. bool public bovBatchDistributed; // TODO: this can be removed with manual crowdsale end-time uint public initialPrizeWeiValue; // The first steaks mined will be awarded BOV equivalent to this ETH value. Set in Steak() initializer. uint public initialPrizeBov; // Initial mining prize in BOV units. Set in endCrowdsale() or endCrowdsalePublic(). uint public dailyHashExpires; // When the dailyHash expires. Will be roughly around 3am EST. /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase */ event TokenInvestment(address indexed purchaser, address indexed beneficiary, uint256 value); // Sending ETH to this contract's address registers the investment. function () payable { invest(msg.sender); } // Participate in the crowdsale. // Records how much each address has invested. function invest(address beneficiary) payable { require(beneficiary != 0x0); require(validInvestment()); uint256 weiAmount = msg.value; uint investedAmount = investments[beneficiary]; forwardFunds(); if (investedAmount > 0) { // If they've already invested, increase their balance. investments[beneficiary] = investedAmount + weiAmount; // investedAmount.add(weiAmount); } else { // If new investor investors.push(beneficiary); numberOfInvestors += 1; investments[beneficiary] = weiAmount; } weiRaised = weiRaised.add(weiAmount); TokenInvestment(msg.sender, beneficiary, weiAmount); } // @return true if the transaction can invest function validInvestment() internal constant returns (bool) { bool withinPeriod = saleStarted && !saleEnded; bool nonZeroPurchase = (msg.value > 0); return withinPeriod && nonZeroPurchase; } // Distribute 10M tokens proportionally amongst all investors. Can be called by anyone after the crowdsale ends. // ClaimTokens() can be run by individuals to claim their tokens. function distributeAllTokens() public { require(!bovBatchDistributed); require(crowdsaleHasEnded()); // Allocate BOV proportionally to each investor. for (uint i=0; i < numberOfInvestors; i++) { address investorAddr = investors[i]; if (!claimed[investorAddr]) { // If the investor hasn't already claimed their BOV. claimed[investorAddr] = true; uint amountInvested = investments[investorAddr]; uint bovEarned = amountInvested.mul(initialSale).div(weiRaised); mint(investorAddr, bovEarned); } } bovBatchDistributed = true; } // Claim your BOV; allocates BOV proportionally to this investor. // Can be called by investors to claim their BOV after the crowdsale ends. // distributeAllTokens() is a batch alternative to this. function claimTokens(address origAddress) public { require(crowdsaleHasEnded()); require(claimed[origAddress] == false); uint amountInvested = investments[origAddress]; uint bovEarned = amountInvested.mul(initialSale).div(weiRaised); claimed[origAddress] = true; mint(origAddress, bovEarned); } // Investors: see how many BOV you are currently entitled to (before the end of the crowdsale and distribution of tokens). function getCurrentShare(address addr) public constant returns (uint) { require(!bovBatchDistributed && !claimed[addr]); // Tokens cannot have already been distributed. uint amountInvested = investments[addr]; uint currentBovShare = amountInvested.mul(initialSale).div(weiRaised); return currentBovShare; } // send ether to the fund collection wallet function forwardFunds() internal { owner.transfer(msg.value); } // The owner manually starts the crowdsale at a pre-determined time. function startCrowdsale() onlyOwner { require(!saleStarted && !saleEnded); saleStarted = true; } // endCrowdsale() and endCrowdsalePublic() moved to Steak contract // Normally, the owner will end the crowdsale at the pre-determined time. function endCrowdsale() onlyOwner { require(saleStarted && !saleEnded); dailyHashExpires = now; // Will end crowdsale at 3am EST, so expiration time will roughly be around 3am. saleEnded = true; setInitialPrize(); } // Normally, Madame BOV ends the crowdsale at the pre-determined time, but if Madame BOV fails to do so, anybody can trigger endCrowdsalePublic() after absoluteEndBlock. function endCrowdsalePublic() public { require(block.number > absoluteEndBlock); require(saleStarted && !saleEnded); dailyHashExpires = now; saleEnded = true; setInitialPrize(); } // Calculate initial mining prize (0.0357 ether's worth of BOV). This is called in endCrowdsale(). function setInitialPrize() internal returns (uint) { require(crowdsaleHasEnded()); require(initialPrizeBov == 0); // Can only be set once uint tokenUnitsPerWei = initialSale.div(weiRaised); initialPrizeBov = tokenUnitsPerWei.mul(initialPrizeWeiValue); return initialPrizeBov; } // @return true if crowdsale event has ended function crowdsaleHasEnded() public constant returns (bool) { return saleStarted && saleEnded; } function getInvestors() public returns (address[]) { return investors; } } contract Steak is AuctionCrowdsale { // using SafeMath for uint; bytes32 public dailyHash; // The last five digits of the dailyHash must be included in steak pictures. Submission[] public submissions; // All steak pics uint public numSubmissions; Submission[] public approvedSubmissions; mapping (address => uint) public memberId; // Get member ID from address. Member[] public members; // Index is memberId uint public halvingInterval; // BOV award is halved every x steaks uint public numberOfHalvings; // How many times the BOV reward per steak is halved before it returns 0. uint public lastMiningBlock; // No mining after this block. Set in initializer. bool public ownerCredited; // Has the owner been credited BOV yet? event PicAdded(address msgSender, uint submissionID, address recipient, bytes32 propUrl); // Need msgSender so we can watch for this event. event Judged(uint submissionID, bool position, address voter, bytes32 justification); event MembershipChanged(address member, bool isMember); struct Submission { address recipient; // Would-be BOV recipient bytes32 url; // IMGUR url; 32-char max bool judged; // Has an admin voted? bool submissionApproved;// Has it been approved? address judgedBy; // Admin who judged this steak bytes32 adminComments; // Admin should leave feedback on non-approved steaks. 32-char max. bytes32 todaysHash; // The hash in the image should match this hash. uint awarded; // Amount awarded } // Members can vote on steak struct Member { address member; bytes32 name; uint memberSince; } modifier onlyMembers { require(memberId[msg.sender] != 0); // member id must be in the mapping _; } function Steak() { owner = msg.sender; initialSale = 10000000 * 1000000000000000000; // 10M BOV units are awarded in the crowdsale. // Normally, the owner both starts and ends the crowdsale. // To guarantee that the crowdsale ends at some maximum point (at that tokens are distributed), // we calculate the absoluteEndBlock, the block beyond which anybody can end the crowdsale and distribute tokens. uint blocksPerHour = 212; uint maxCrowdsaleLifeFromLaunchDays = 40; // After about this many days from launch, anybody can end the crowdsale and distribute / claim their tokens. absoluteEndBlock = block.number + (blocksPerHour * 24 * maxCrowdsaleLifeFromLaunchDays); uint miningDays = 365; // Approximately how many days BOV can be mined from the launch of the contract. lastMiningBlock = block.number + (blocksPerHour * 24 * miningDays); dailyHashExpires = now; halvingInterval = 500; // How many steaks get awarded the given getSteakPrize() amount before the reward is halved. numberOfHalvings = 8; // How many times the steak prize gets halved before no more prize is awarded. // initialPrizeWeiValue = 50 finney; // 0.05 ether == 50 finney == 2.80 USD * 5 == 14 USD initialPrizeWeiValue = (357 finney / 10); // 0.0357 ether == 35.7 finney == 2.80 USD * 3.57 == 9.996 USD // To finish initializing, owner calls initMembers() and creditOwner() after launch. } // Add Madame BOV as a beef judge. function initMembers() onlyOwner { addMember(0, ''); // Must add an empty first member addMember(msg.sender, 'Madame BOV'); } // Send 1M BOV to Madame BOV. function creditOwner() onlyOwner { require(!ownerCredited); uint ownerAward = initialSale / 10; // 10% of the crowdsale amount. ownerCredited = true; // Can only be run once. mint(owner, ownerAward); } /* Add beef judge */ function addMember(address targetMember, bytes32 memberName) onlyOwner { uint id; if (memberId[targetMember] == 0) { memberId[targetMember] = members.length; id = members.length++; members[id] = Member({member: targetMember, memberSince: now, name: memberName}); } else { id = memberId[targetMember]; // Member m = members[id]; } MembershipChanged(targetMember, true); } function removeMember(address targetMember) onlyOwner { if (memberId[targetMember] == 0) revert(); memberId[targetMember] = 0; for (uint i = memberId[targetMember]; i<members.length-1; i++){ members[i] = members[i+1]; } delete members[members.length-1]; members.length--; } /* Submit a steak picture. (After crowdsale has ended.) * WARNING: Before taking the picture, call getDailyHash() and minutesToPost() * so you can be sure that you have the correct dailyHash and that it won't expire before you post it. */ function submitSteak(address addressToAward, bytes32 steakPicUrl) returns (uint submissionID) { require(crowdsaleHasEnded()); require(block.number <= lastMiningBlock); // Cannot submit beyond this block. submissionID = submissions.length++; // Increase length of array Submission storage s = submissions[submissionID]; s.recipient = addressToAward; s.url = steakPicUrl; s.judged = false; s.submissionApproved = false; s.todaysHash = getDailyHash(); // Each submission saves the hash code the user should take picture of in steak picture. PicAdded(msg.sender, submissionID, addressToAward, steakPicUrl); numSubmissions = submissionID+1; return submissionID; } // Retrieving any Submission must be done via this function, not `submissions()` function getSubmission(uint submissionID) public constant returns (address recipient, bytes32 url, bool judged, bool submissionApproved, address judgedBy, bytes32 adminComments, bytes32 todaysHash, uint awarded) { Submission storage s = submissions[submissionID]; recipient = s.recipient; url = s.url; // IMGUR url judged = s.judged; // Has an admin voted? submissionApproved = s.submissionApproved; // Has it been approved? judgedBy = s.judgedBy; // Admin who judged this steak adminComments = s.adminComments; // Admin should leave feedback on non-approved steaks todaysHash = s.todaysHash; // The hash in the image should match this hash. awarded = s.awarded; // Amount awarded // return (users[index].salaryId, users[index].name, users[index].userAddress, users[index].salary); // return (recipient, url, judged, submissionApproved, judgedBy, adminComments, todaysHash, awarded); } // Members judge steak pics, providing justification if necessary. function judge(uint submissionNumber, bool supportsSubmission, bytes32 justificationText) onlyMembers { Submission storage s = submissions[submissionNumber]; // Get the submission. require(!s.judged); // Musn't be judged. s.judged = true; s.judgedBy = msg.sender; s.submissionApproved = supportsSubmission; s.adminComments = justificationText; // Admin can add comments whether approved or not if (supportsSubmission) { // If it passed muster, credit the user and admin. uint prizeAmount = getSteakPrize(); // Calculate BOV prize s.awarded = prizeAmount; // Record amount in the Submission mint(s.recipient, prizeAmount); // Credit the user's account // Credit the member one-third of the prize amount. uint adminAward = prizeAmount.div(3); mint(msg.sender, adminAward); approvedSubmissions.push(s); } Judged(submissionNumber, supportsSubmission, msg.sender, justificationText); } // Calculate how many BOV are rewarded per approved steak pic. function getSteakPrize() public constant returns (uint) { require(initialPrizeBov > 0); // crowdsale must be over (endCrowdsale() calls setInitialPrize()) uint halvings = numberOfApprovedSteaks().div(halvingInterval); if (halvings > numberOfHalvings) { // After 8 halvings, no more BOV is awarded. return 0; } uint prize = initialPrizeBov; prize = prize >> halvings; // Halve the initial prize "halvings"-number of times. return prize; } function numberOfApprovedSteaks() public constant returns (uint) { return approvedSubmissions.length; } // Always call this before calling dailyHash and submitting a steak. // If expired, the new hash is set to the last block's hash. function getDailyHash() public returns (bytes32) { if (dailyHashExpires > now) { // If the hash hasn't expired yet, return it. return dailyHash; } else { // Udderwise, set the new dailyHash and dailyHashExpiration. // Get hash from the last block. bytes32 newHash = block.blockhash(block.number-1); dailyHash = newHash; // Set the new expiration, jumping ahead in 24-hour increments so the expiration time remains roughly constant from day to day (e.g. 3am). uint nextExpiration = dailyHashExpires + 24 hours; // It will already be expired, so set it to next possible date. while (nextExpiration < now) { // if it's still in the past, advance by 24 hours. nextExpiration += 24 hours; } dailyHashExpires = nextExpiration; return newHash; } } // Returns the amount of minutes to post with the current dailyHash function minutesToPost() public constant returns (uint) { if (dailyHashExpires > now) { return (dailyHashExpires - now) / 60; // returns minutes } else { return 0; } } function currentBlock() public constant returns (uint) { return block.number; } }
Members judge steak pics, providing justification if necessary. Credit the member one-third of the prize amount.
function judge(uint submissionNumber, bool supportsSubmission, bytes32 justificationText) onlyMembers { s.judged = true; s.judgedBy = msg.sender; s.submissionApproved = supportsSubmission; uint adminAward = prizeAmount.div(3); mint(msg.sender, adminAward); approvedSubmissions.push(s); } Judged(submissionNumber, supportsSubmission, msg.sender, justificationText);
14,056,326
pragma solidity >=0.4.22 <=0.8.0; contract Shipping { // Our predefined values for shipping listed as enums enum ShippingStatus { Pending, Shipped, Delivered } //Save enum ShippingStatus in variable status ShippingStatus private status; //Event to launch when package has arrived event LogNewAlert(string description); //This initializes our contract state (sets enum to Pending once the program starts) constructor() { status = ShippingStatus.Pending; } //Function to change to Shipped function Shipped() public { status = ShippingStatus.Shipped; emit LogNewAlert("Your package has been shipped"); } //Function to change to Delivered function Delivered() public { status = ShippingStatus.Delivered; emit LogNewAlert("Your package has been arrived"); } //Function to get the status of the shipping function getStatus(ShippingStatus _status) internal pure returns (string memory) { //Check the current status and return the correct name if (ShippingStatus.Pending == _status) return "Pending"; if (ShippingStatus.Shipped == _status) return "Shipped"; if (ShippingStatus.Delivered == _status) return "Delivered"; } //Get status of your shipped item function Status() public view returns (string memory) { ShippingStatus _status = status; return getStatus(_status); } }
Get status of your shipped item
function Status() public view returns (string memory) { ShippingStatus _status = status; return getStatus(_status); }
6,420,493
./full_match/41/0xE77dE2C82C9E6FA0056bC91FB5D67E140867Bd44/sources/contracts/IceToken.sol
Finalizes the redeeming process for "userAddress" by transferring him "slushAmount" and removing "iceAmount" from supply Any vesting check should be ran before calling this SLUSH excess is automatically burnt/ sends due SLUSH tokens burns SLUSH excess if any update redeeming totals
function _finalizeRedeem(address userAddress, uint256 iceAmount, uint256 slushAmount, uint256 iceEarned) internal { uint256 slushExcess = iceAmount - slushAmount; slushToken.safeTransfer(userAddress, slushAmount); slushToken.burn(slushExcess); _burn(address(this), iceAmount); redeemingIce -= iceAmount; redeemingIceRewards -= iceEarned; redeemingSlush -= slushAmount; if (iceEarned > 0) { require(balanceOf(address(this)) >= iceEarned, "_finalizeRedeem: not enough ICE to transfer"); this.transfer(userAddress, iceEarned); } emit FinalizeRedeem(userAddress, iceAmount, slushAmount, iceEarned); }
16,379,628
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol'; import '@openzeppelin/contracts/utils/Counters.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import '@openzeppelin/contracts/utils/Strings.sol'; import '../interfaces/IStrawberry.sol'; import "../interfaces/IStrawberryMetadata.sol"; import "./BigFarmer.sol"; contract Strawberry is ERC721Enumerable, BigFarmer, Ownable, IStrawberry, IStrawberryMetadata { using Counters for Counters.Counter; using Strings for uint256; uint256 public constant BERRIES_SPECIAL = 5; uint256 public constant BERRIES_GIFT = 95; uint256 public constant BERRIES_PUBLIC = 9_900; uint256 public constant BERRIES_MAX = BERRIES_SPECIAL + BERRIES_GIFT + BERRIES_PUBLIC; uint256 public constant PURCHASE_LIMIT = 20; uint256 public constant PRICE = 25_000_000_000_000_000; // 0.025 ETH bool public areTokensRevealed = false; string public seed = ''; string public proof = ''; string private _contractURI = ''; string private _tokenBaseURI = ''; bool private _isActive = false; Counters.Counter private _specialStrawberries; Counters.Counter private _giftStrawberries; Counters.Counter private _publicStrawberries; constructor(string memory name, string memory symbol) ERC721(name, symbol) { _mintSpecials(); } // Set the seed phrase for the generation of Strawberries function setSeed(string memory seedString) external override onlyOwner { seed = seedString; } // Set the proof hash function setProof(string memory proofString) external override onlyOwner { proof = proofString; } // Set the if purchase and minting is active function setActive(bool isActive) external override onlyOwner { _isActive = isActive; } // Set the contractURI function setContractURI(string memory URI) external override onlyOwner { _contractURI = URI; } // Set the baseURI function setBaseURI(string memory URI) external override onlyOwner { _tokenBaseURI = URI; } // Set if the tokens are revealed function setTokensRevealed(bool tokensRevealed) external override onlyOwner { areTokensRevealed = tokensRevealed; } // Purchase a single token function purchase(uint256 numberOfTokens) external override payable { require(_isActive, 'Contract is not active'); require(numberOfTokens <= PURCHASE_LIMIT, 'Can only mint up to 20 tokens'); require(_publicStrawberries.current() < BERRIES_PUBLIC, 'Purchase would exceed BERRIES_PUBLIC'); require(PRICE * numberOfTokens <= msg.value, 'ETH amount is not sufficient'); for (uint256 i = 0; i < numberOfTokens; i++) { uint256 tokenId = BERRIES_SPECIAL + BERRIES_GIFT + _publicStrawberries.current(); if (_publicStrawberries.current() < BERRIES_PUBLIC) { _publicStrawberries.increment(); _safeMint(msg.sender, tokenId); } } } // Gift a single token function gift(address to) external override payable onlyOwner { require(totalSupply() < BERRIES_MAX, 'All tokens have been minted'); require(_specialStrawberries.current() < BERRIES_GIFT, 'No tokens left to gift'); uint256 tokenId = BERRIES_SPECIAL + _specialStrawberries.current(); _specialStrawberries.increment(); _safeMint(to, tokenId); } // Returns URL for storefront-level metadata function contractURI() public view override returns (string memory) { return _contractURI; } // Returns URL for token-level metadata function tokenURI(uint256 tokenId) public view override(ERC721, IStrawberryMetadata) returns (string memory) { require(_exists(tokenId), 'Token does not exist'); if (areTokensRevealed) { return string(abi.encodePacked(_tokenBaseURI, tokenId.toString())); } return _tokenBaseURI; } // Withdraw contract balance function withdraw() external override onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } // Mint the Special Strawberries to contract owner function _mintSpecials() internal { require(totalSupply() < BERRIES_SPECIAL, 'All special tokens have been minted'); for (uint256 i = 0; i < BERRIES_SPECIAL; i++) { _safeMint(msg.sender, totalSupply()); } } // Override _beforeTokenTransfer hook to check for Big Farmer status function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal override { super._beforeTokenTransfer(from, to, tokenId); _checkBigFarmerStatus(from, to); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol'; // Public interface for Strawberry.wtf contract interface IStrawberry is IERC721Enumerable { // Set the seed phrase for the generation of Strawberries function setSeed(string memory seedString) external; // Set the proof hash function setProof(string memory proofString) external; // Set the if purchase and minting is active function setActive(bool isActive) external; // Set if the tokens are revealed function setTokensRevealed(bool tokensRevealed) external; // Purchase a single token function purchase(uint256 numberOfTokens) external payable; // Gift a single token function gift(address to) external payable; // Withdraw contract balance function withdraw() external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol'; // Interface or store-level metadata interface IStrawberryMetadata is IERC721Metadata { // Set the contractURI function setContractURI(string memory contractURI) external; // Set the baseURI function setBaseURI(string memory baseURI) external; // Returns URL for storefront-level metadata function contractURI() external view returns(string memory); // Returns URL for token-level metadata function tokenURI(uint256 tokenId) external view override returns(string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol'; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "../interfaces/IBigFarmer.sol"; abstract contract BigFarmer is ERC721Enumerable { using EnumerableSet for EnumerableSet.AddressSet; uint256 public constant BIG_FARMER_THRESHOLD = 20; EnumerableSet.AddressSet private _bigFarmers; // Returns if address is a Big Farmer function isBigFarmer(address sender) external view returns (bool) { return _bigFarmers.contains(sender); } // Returns total number of Big Farmers function totalBigFarmers() external view returns (uint256) { return _bigFarmers.length(); } // Returns address of Big Farmer by index function bigFarmerByIndex(uint256 bigFarmerIndex) external view returns (address) { require(bigFarmerIndex < _bigFarmers.length(), 'Big Farmer index out of bounds'); return _bigFarmers.at(bigFarmerIndex); } // Check if we need to add or remove a Big Farmer function _checkBigFarmerStatus(address from, address to) internal { if (from != address(0) && ERC721.balanceOf(from) <= BIG_FARMER_THRESHOLD && _bigFarmers.contains(from)) { _bigFarmers.remove(from); } if (to != address(0) && ERC721.balanceOf(to) >= BIG_FARMER_THRESHOLD - 1 && !_bigFarmers.contains(to)) { _bigFarmers.add(to); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library 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] = 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) { 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.8.0; // Public interface for BigFarmer contract interface IBigFarmer { // Returns if address is a Big Farmer function isBigFarmer(address sender) external view returns (bool); // Returns total number of Big Farmers function totalBigFarmers() external view returns (uint256); // Returns address of Big Farmer by index function bigFarmerByIndex(uint256 bigFarmerIndex) external view returns (address); }
Set the if purchase and minting is active
function setActive(bool isActive) external override onlyOwner { _isActive = isActive; }
1,605,820
pragma solidity 0.4.24; contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract BGAudit is Ownable { using SafeMath for uint; event AddedAuditor(address indexed auditor); event BannedAuditor(address indexed auditor); event AllowedAuditor(address indexed auditor); event CreatedAudit(uint indexed id); event ReviewingAudit(uint indexed id); event AuditorRewarded(uint indexed id, address indexed auditor, uint indexed reward); event AuditorStaked(uint indexed id, address indexed auditor, uint indexed amount); event WithdrawedStake(uint indexed id, address indexed auditor, uint indexed amount); event SlashedStake(uint indexed id, address indexed auditor); enum AuditStatus { New, InProgress, InReview, Completed } struct Auditor { bool banned; address addr; uint totalEarned; uint completedAudits; uint[] stakedAudits; // array of audit IDs they&#39;ve staked mapping(uint => bool) stakedInAudit; // key is AuditID; useful so we don&#39;t need to loop through the audits array above mapping(uint => bool) canWithdrawStake; // Audit ID => can withdraw stake or not } struct Audit { AuditStatus status; address owner; uint id; uint totalReward; // total reward shared b/w all auditors uint remainingReward; // keep track of how much reward is left uint stake; // required stake for each auditor in wei uint endTime; // scheduled end time for the audit uint maxAuditors; // max auditors allowed for this Audit address[] participants; // array of auditor that have staked } //=== Storage uint public stakePeriod = 90 days; // number of days to wait before stake can be withdrawn uint public maxAuditDuration = 365 days; // max amount of time for a security audit Audit[] public audits; mapping(address => Auditor) public auditors; //=== Owner related function transfer(address _to, uint _amountInWei) external onlyOwner { require(address(this).balance > _amountInWei); _to.transfer(_amountInWei); } function setStakePeriod(uint _days) external onlyOwner { stakePeriod = _days * 1 days; } function setMaxAuditDuration(uint _days) external onlyOwner { maxAuditDuration = _days * 1 days; } //=== Auditors function addAuditor(address _auditor) external onlyOwner { require(auditors[_auditor].addr == address(0)); // Only add if they&#39;re not already added auditors[_auditor].banned = false; auditors[_auditor].addr = _auditor; auditors[_auditor].completedAudits = 0; auditors[_auditor].totalEarned = 0; emit AddedAuditor(_auditor); } function banAuditor(address _auditor) external onlyOwner { require(auditors[_auditor].addr != address(0)); auditors[_auditor].banned = true; emit BannedAuditor(_auditor); } function allowAuditor(address _auditor) external onlyOwner { require(auditors[_auditor].addr != address(0)); auditors[_auditor].banned = false; emit AllowedAuditor(_auditor); } //=== Audits and Rewards function createAudit(uint _stake, uint _endTimeInDays, uint _maxAuditors) external payable onlyOwner { uint endTime = _endTimeInDays * 1 days; require(endTime < maxAuditDuration); require(block.timestamp + endTime * 1 days > block.timestamp); require(msg.value > 0 && _maxAuditors > 0 && _stake > 0); Audit memory audit; audit.status = AuditStatus.New; audit.owner = msg.sender; audit.id = audits.length; audit.totalReward = msg.value; audit.remainingReward = audit.totalReward; audit.stake = _stake; audit.endTime = block.timestamp + endTime; audit.maxAuditors = _maxAuditors; audits.push(audit); // push into storage emit CreatedAudit(audit.id); } function reviewAudit(uint _id) external onlyOwner { require(audits[_id].status == AuditStatus.InProgress); require(block.timestamp >= audits[_id].endTime); audits[_id].endTime = block.timestamp; // override the endTime to when it actually ended audits[_id].status = AuditStatus.InReview; emit ReviewingAudit(_id); } function rewardAuditor(uint _id, address _auditor, uint _reward) external onlyOwner { audits[_id].remainingReward.sub(_reward); audits[_id].status = AuditStatus.Completed; auditors[_auditor].totalEarned.add(_reward); auditors[_auditor].completedAudits.add(1); auditors[_auditor].canWithdrawStake[_id] = true; // allow them to withdraw their stake after stakePeriod _auditor.transfer(_reward); emit AuditorRewarded(_id, _auditor, _reward); } function slashStake(uint _id, address _auditor) external onlyOwner { require(auditors[_auditor].addr != address(0)); require(auditors[_auditor].stakedInAudit[_id]); // participated in audit auditors[_auditor].canWithdrawStake[_id] = false; emit SlashedStake(_id, _auditor); } //=== User Actions function stake(uint _id) public payable { // Check conditions of the Audit require(msg.value == audits[_id].stake); require(block.timestamp < audits[_id].endTime); require(audits[_id].participants.length < audits[_id].maxAuditors); require(audits[_id].status == AuditStatus.New || audits[_id].status == AuditStatus.InProgress); // Check conditions of the Auditor require(auditors[msg.sender].addr == msg.sender && !auditors[msg.sender].banned); // auditor is authorized require(!auditors[msg.sender].stakedInAudit[_id]); //check if auditor has staked for this audit already // Update audit&#39;s states audits[_id].status = AuditStatus.InProgress; audits[_id].participants.push(msg.sender); // Update auditor&#39;s states auditors[msg.sender].stakedInAudit[_id] = true; auditors[msg.sender].stakedAudits.push(_id); emit AuditorStaked(_id, msg.sender, msg.value); } function withdrawStake(uint _id) public { require(audits[_id].status == AuditStatus.Completed); require(auditors[msg.sender].canWithdrawStake[_id]); require(block.timestamp >= audits[_id].endTime + stakePeriod); auditors[msg.sender].canWithdrawStake[_id] = false; //prevent replay attack address(msg.sender).transfer(audits[_id].stake); // do this last to prevent re-entrancy emit WithdrawedStake(_id, msg.sender, audits[_id].stake); } //=== Getters function auditorHasStaked(uint _id, address _auditor) public view returns(bool) { return auditors[_auditor].stakedInAudit[_id]; } function auditorCanWithdrawStake(uint _id, address _auditor) public view returns(bool) { if(auditors[_auditor].stakedInAudit[_id] && auditors[_auditor].canWithdrawStake[_id]) { return true; } return false; } // return a list of ids that _auditor has staked in function getStakedAudits(address _auditor) public view returns(uint[]) { return auditors[_auditor].stakedAudits; } // return a list of auditors that participated in this audit function getAuditors(uint _id) public view returns(address[]) { return audits[_id].participants; } }
=== User Actions Check conditions of the Audit Check conditions of the Auditor Update audit&39;s states Update auditor&39;s states
function stake(uint _id) public payable { require(msg.value == audits[_id].stake); require(block.timestamp < audits[_id].endTime); require(audits[_id].participants.length < audits[_id].maxAuditors); require(audits[_id].status == AuditStatus.New || audits[_id].status == AuditStatus.InProgress); audits[_id].status = AuditStatus.InProgress; audits[_id].participants.push(msg.sender); auditors[msg.sender].stakedInAudit[_id] = true; auditors[msg.sender].stakedAudits.push(_id); emit AuditorStaked(_id, msg.sender, msg.value); }
15,014,942
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-IERC20PermitUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../interfaces/IFeeDistributor.sol"; import "../interfaces/ILiquidityGauge.sol"; import "../interfaces/ISanToken.sol"; import "../interfaces/IStableMaster.sol"; import "../interfaces/IStableMasterFront.sol"; import "../interfaces/IVeANGLE.sol"; import "../interfaces/external/IWETH9.sol"; import "../interfaces/external/uniswap/IUniswapRouter.sol"; /// @title Angle Router /// @author Angle Core Team /// @notice The `AngleRouter` contract facilitates interactions for users with the protocol. It was built to reduce the number /// of approvals required to users and the number of transactions needed to perform some complex actions: like deposit and stake /// in just one transaction /// @dev Interfaces were designed for both advanced users which know the addresses of the protocol's contract, but most of the time /// users which only know addresses of the stablecoins and collateral types of the protocol can perform the actions they want without /// needing to understand what's happening under the hood contract AngleRouter is Initializable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; /// @notice Base used for params uint256 public constant BASE_PARAMS = 10**9; /// @notice Base used for params uint256 private constant _MAX_TOKENS = 10; // @notice Wrapped ETH contract IWETH9 public constant WETH9 = IWETH9(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // @notice ANGLE contract IERC20 public constant ANGLE = IERC20(0x31429d1856aD1377A8A0079410B297e1a9e214c2); // @notice veANGLE contract IVeANGLE public constant VEANGLE = IVeANGLE(0x0C462Dbb9EC8cD1630f1728B2CFD2769d09f0dd5); // =========================== Structs and Enums =============================== /// @notice Action types enum ActionType { claimRewards, claimWeeklyInterest, gaugeDeposit, withdraw, mint, deposit, openPerpetual, addToPerpetual, veANGLEDeposit } /// @notice All possible swaps enum SwapType { UniswapV3, oneINCH } /// @notice Params for swaps /// @param inToken Token to swap /// @param collateral Token to swap for /// @param amountIn Amount of token to sell /// @param minAmountOut Minimum amount of collateral to receive for the swap to not revert /// @param args Either the path for Uniswap or the payload for 1Inch /// @param swapType Which swap route to take struct ParamsSwapType { IERC20 inToken; address collateral; uint256 amountIn; uint256 minAmountOut; bytes args; SwapType swapType; } /// @notice Params for direct collateral transfer /// @param inToken Token to transfer /// @param amountIn Amount of token transfer struct TransferType { IERC20 inToken; uint256 amountIn; } /// @notice References to the contracts associated to a collateral for a stablecoin struct Pairs { IPoolManager poolManager; IPerpetualManagerFrontWithClaim perpetualManager; ISanToken sanToken; ILiquidityGauge gauge; } /// @notice Data needed to get permits struct PermitType { address token; address owner; uint256 value; uint256 deadline; uint8 v; bytes32 r; bytes32 s; } // =============================== Events ====================================== event AdminChanged(address indexed admin, bool setGovernor); event StablecoinAdded(address indexed stableMaster); event StablecoinRemoved(address indexed stableMaster); event CollateralToggled(address indexed stableMaster, address indexed poolManager, address indexed liquidityGauge); event SanTokenLiquidityGaugeUpdated(address indexed sanToken, address indexed newLiquidityGauge); event Recovered(address indexed tokenAddress, address indexed to, uint256 amount); // =============================== Mappings ==================================== /// @notice Maps an agToken to its counterpart `StableMaster` mapping(IERC20 => IStableMasterFront) public mapStableMasters; /// @notice Maps a `StableMaster` to a mapping of collateral token to its counterpart `PoolManager` mapping(IStableMasterFront => mapping(IERC20 => Pairs)) public mapPoolManagers; /// @notice Whether the token was already approved on Uniswap router mapping(IERC20 => bool) public uniAllowedToken; /// @notice Whether the token was already approved on 1Inch mapping(IERC20 => bool) public oneInchAllowedToken; // =============================== References ================================== /// @notice Governor address address public governor; /// @notice Guardian address address public guardian; /// @notice Address of the router used for swaps IUniswapV3Router public uniswapV3Router; /// @notice Address of 1Inch router used for swaps address public oneInch; uint256[50] private __gap; constructor() initializer {} /// @notice Deploys the `AngleRouter` contract /// @param _governor Governor address /// @param _guardian Guardian address /// @param _uniswapV3Router UniswapV3 router address /// @param _oneInch 1Inch aggregator address /// @param existingStableMaster Address of the existing `StableMaster` /// @param existingPoolManagers Addresses of the associated poolManagers /// @param existingLiquidityGauges Addresses of liquidity gauge contracts associated to sanTokens /// @dev Be cautious with safe approvals, all tokens will have unlimited approvals within the protocol or /// UniswapV3 and 1Inch function initialize( address _governor, address _guardian, IUniswapV3Router _uniswapV3Router, address _oneInch, IStableMasterFront existingStableMaster, IPoolManager[] calldata existingPoolManagers, ILiquidityGauge[] calldata existingLiquidityGauges ) public initializer { // Checking the parameters passed require( address(_uniswapV3Router) != address(0) && _oneInch != address(0) && _governor != address(0) && _guardian != address(0), "0" ); require(_governor != _guardian, "49"); require(existingPoolManagers.length == existingLiquidityGauges.length, "104"); // Fetching the stablecoin and mapping it to the `StableMaster` mapStableMasters[ IERC20(address(IStableMaster(address(existingStableMaster)).agToken())) ] = existingStableMaster; // Setting roles governor = _governor; guardian = _guardian; uniswapV3Router = _uniswapV3Router; oneInch = _oneInch; // for veANGLEDeposit action ANGLE.safeApprove(address(VEANGLE), type(uint256).max); for (uint256 i = 0; i < existingPoolManagers.length; i++) { _addPair(existingStableMaster, existingPoolManagers[i], existingLiquidityGauges[i]); } } // ============================== Modifiers ==================================== /// @notice Checks to see if it is the `governor` or `guardian` calling this contract /// @dev There is no Access Control here, because it can be handled cheaply through this modifier /// @dev In this contract, the `governor` and the `guardian` address have exactly similar rights modifier onlyGovernorOrGuardian() { require(msg.sender == governor || msg.sender == guardian, "115"); _; } // =========================== Governance utilities ============================ /// @notice Changes the guardian or the governor address /// @param admin New guardian or guardian address /// @param setGovernor Whether to set Governor if true, or Guardian if false /// @dev There can only be one guardian and one governor address in the router /// and both need to be different function setGovernorOrGuardian(address admin, bool setGovernor) external onlyGovernorOrGuardian { require(admin != address(0), "0"); require(guardian != admin && governor != admin, "49"); if (setGovernor) governor = admin; else guardian = admin; emit AdminChanged(admin, setGovernor); } /// @notice Adds a new `StableMaster` /// @param stablecoin Address of the new stablecoin /// @param stableMaster Address of the new `StableMaster` function addStableMaster(IERC20 stablecoin, IStableMasterFront stableMaster) external onlyGovernorOrGuardian { // No need to check if the `stableMaster` address is a zero address as otherwise the call to `stableMaster.agToken()` // would revert require(address(stablecoin) != address(0), "0"); require(address(mapStableMasters[stablecoin]) == address(0), "114"); require(stableMaster.agToken() == address(stablecoin), "20"); mapStableMasters[stablecoin] = stableMaster; emit StablecoinAdded(address(stableMaster)); } /// @notice Removes a `StableMaster` /// @param stablecoin Address of the associated stablecoin /// @dev Before calling this function, governor or guardian should remove first all pairs /// from the `mapPoolManagers[stableMaster]`. It is assumed that the governor or guardian calling this function /// will act correctly here, it indeed avoids storing a list of all pairs for each `StableMaster` function removeStableMaster(IERC20 stablecoin) external onlyGovernorOrGuardian { IStableMasterFront stableMaster = mapStableMasters[stablecoin]; delete mapStableMasters[stablecoin]; emit StablecoinRemoved(address(stableMaster)); } /// @notice Adds new collateral types to specific stablecoins /// @param stablecoins Addresses of the stablecoins associated to the `StableMaster` of interest /// @param poolManagers Addresses of the `PoolManager` contracts associated to the pair (stablecoin,collateral) /// @param liquidityGauges Addresses of liquidity gauges contract associated to sanToken function addPairs( IERC20[] calldata stablecoins, IPoolManager[] calldata poolManagers, ILiquidityGauge[] calldata liquidityGauges ) external onlyGovernorOrGuardian { require(poolManagers.length == stablecoins.length && liquidityGauges.length == stablecoins.length, "104"); for (uint256 i = 0; i < stablecoins.length; i++) { IStableMasterFront stableMaster = mapStableMasters[stablecoins[i]]; _addPair(stableMaster, poolManagers[i], liquidityGauges[i]); } } /// @notice Removes collateral types from specific `StableMaster` contracts using the address /// of the associated stablecoins /// @param stablecoins Addresses of the stablecoins /// @param collaterals Addresses of the collaterals /// @param stableMasters List of the associated `StableMaster` contracts /// @dev In the lists, if a `stableMaster` address is null in `stableMasters` then this means that the associated /// `stablecoins` address (at the same index) should be non null function removePairs( IERC20[] calldata stablecoins, IERC20[] calldata collaterals, IStableMasterFront[] calldata stableMasters ) external onlyGovernorOrGuardian { require(collaterals.length == stablecoins.length && stableMasters.length == collaterals.length, "104"); Pairs memory pairs; IStableMasterFront stableMaster; for (uint256 i = 0; i < stablecoins.length; i++) { if (address(stableMasters[i]) == address(0)) // In this case `collaterals[i]` is a collateral address (stableMaster, pairs) = _getInternalContracts(stablecoins[i], collaterals[i]); else { // In this case `collaterals[i]` is a `PoolManager` address stableMaster = stableMasters[i]; pairs = mapPoolManagers[stableMaster][collaterals[i]]; } delete mapPoolManagers[stableMaster][collaterals[i]]; _changeAllowance(collaterals[i], address(stableMaster), 0); _changeAllowance(collaterals[i], address(pairs.perpetualManager), 0); if (address(pairs.gauge) != address(0)) pairs.sanToken.approve(address(pairs.gauge), 0); emit CollateralToggled(address(stableMaster), address(pairs.poolManager), address(pairs.gauge)); } } /// @notice Sets new `liquidityGauge` contract for the associated sanTokens /// @param stablecoins Addresses of the stablecoins /// @param collaterals Addresses of the collaterals /// @param newLiquidityGauges Addresses of the new liquidity gauges contract /// @dev If `newLiquidityGauge` is null, this means that there is no liquidity gauge for this pair /// @dev This function could be used to simply revoke the approval to a liquidity gauge function setLiquidityGauges( IERC20[] calldata stablecoins, IERC20[] calldata collaterals, ILiquidityGauge[] calldata newLiquidityGauges ) external onlyGovernorOrGuardian { require(collaterals.length == stablecoins.length && newLiquidityGauges.length == stablecoins.length, "104"); for (uint256 i = 0; i < stablecoins.length; i++) { IStableMasterFront stableMaster = mapStableMasters[stablecoins[i]]; Pairs storage pairs = mapPoolManagers[stableMaster][collaterals[i]]; ILiquidityGauge gauge = pairs.gauge; ISanToken sanToken = pairs.sanToken; require(address(stableMaster) != address(0) && address(pairs.poolManager) != address(0), "0"); pairs.gauge = newLiquidityGauges[i]; if (address(gauge) != address(0)) { sanToken.approve(address(gauge), 0); } if (address(newLiquidityGauges[i]) != address(0)) { // Checking compatibility of the staking token: it should be the sanToken require(address(newLiquidityGauges[i].staking_token()) == address(sanToken), "20"); sanToken.approve(address(newLiquidityGauges[i]), type(uint256).max); } emit SanTokenLiquidityGaugeUpdated(address(sanToken), address(newLiquidityGauges[i])); } } /// @notice Change allowance for a contract. /// @param tokens Addresses of the tokens to allow /// @param spenders Addresses to allow transfer /// @param amounts Amounts to allow /// @dev Approvals are normally given in the `addGauges` method, in the initializer and in /// the internal functions to process swaps with Uniswap and 1Inch function changeAllowance( IERC20[] calldata tokens, address[] calldata spenders, uint256[] calldata amounts ) external onlyGovernorOrGuardian { require(tokens.length == spenders.length && tokens.length == amounts.length, "104"); for (uint256 i = 0; i < tokens.length; i++) { _changeAllowance(tokens[i], spenders[i], amounts[i]); } } /// @notice Supports recovering any tokens as the router does not own any other tokens than /// the one mistakenly sent /// @param tokenAddress Address of the token to transfer /// @param to Address to give tokens to /// @param tokenAmount Amount of tokens to transfer /// @dev If tokens are mistakenly sent to this contract, any address can take advantage of the `mixer` function /// below to get the funds back function recoverERC20( address tokenAddress, address to, uint256 tokenAmount ) external onlyGovernorOrGuardian { IERC20(tokenAddress).safeTransfer(to, tokenAmount); emit Recovered(tokenAddress, to, tokenAmount); } // =========================== Router Functionalities ========================= /// @notice Wrapper n°1 built on top of the _claimRewards function /// Allows to claim rewards for multiple gauges and perpetuals at once /// @param gaugeUser Address for which to fetch the rewards from the gauges /// @param liquidityGauges Gauges to claim on /// @param perpetualIDs Perpetual IDs to claim rewards for /// @param stablecoins Stablecoin contracts linked to the perpetualsIDs /// @param collaterals Collateral contracts linked to the perpetualsIDs or `perpetualManager` /// @dev If the caller wants to send the rewards to another account it first needs to /// call `set_rewards_receiver(otherAccount)` on each `liquidityGauge` function claimRewards( address gaugeUser, address[] memory liquidityGauges, uint256[] memory perpetualIDs, address[] memory stablecoins, address[] memory collaterals ) external nonReentrant { _claimRewards(gaugeUser, liquidityGauges, perpetualIDs, false, stablecoins, collaterals); } /// @notice Wrapper n°2 (a little more gas efficient than n°1) built on top of the _claimRewards function /// Allows to claim rewards for multiple gauges and perpetuals at once /// @param user Address to which the contract should send the rewards from gauges (not perpetuals) /// @param liquidityGauges Contracts to claim for /// @param perpetualIDs Perpetual IDs to claim rewards for /// @param perpetualManagers `perpetualManager` contracts for every perp to claim /// @dev If the caller wants to send the rewards to another account it first needs to /// call `set_rewards_receiver(otherAccount)` on each `liquidityGauge` function claimRewards( address user, address[] memory liquidityGauges, uint256[] memory perpetualIDs, address[] memory perpetualManagers ) external nonReentrant { _claimRewards(user, liquidityGauges, perpetualIDs, true, new address[](perpetualIDs.length), perpetualManagers); } /// @notice Wrapper built on top of the `_gaugeDeposit` method to deposit collateral in a gauge /// @param token On top of the parameters of the internal function, users need to specify the token associated /// to the gauge they want to deposit in /// @dev The function will revert if the token does not correspond to the gauge function gaugeDeposit( address user, uint256 amount, ILiquidityGauge gauge, bool shouldClaimRewards, IERC20 token ) external nonReentrant { token.safeTransferFrom(msg.sender, address(this), amount); _gaugeDeposit(user, amount, gauge, shouldClaimRewards); } /// @notice Wrapper n°1 built on top of the `_mint` method to mint stablecoins /// @param user Address to send the stablecoins to /// @param amount Amount of collateral to use for the mint /// @param minStableAmount Minimum stablecoin minted for the tx not to revert /// @param stablecoin Address of the stablecoin to mint /// @param collateral Collateral to mint from function mint( address user, uint256 amount, uint256 minStableAmount, address stablecoin, address collateral ) external nonReentrant { IERC20(collateral).safeTransferFrom(msg.sender, address(this), amount); _mint(user, amount, minStableAmount, false, stablecoin, collateral, IPoolManager(address(0))); } /// @notice Wrapper n°2 (a little more gas efficient than n°1) built on top of the `_mint` method to mint stablecoins /// @param user Address to send the stablecoins to /// @param amount Amount of collateral to use for the mint /// @param minStableAmount Minimum stablecoin minted for the tx not to revert /// @param stableMaster Address of the stableMaster managing the stablecoin to mint /// @param collateral Collateral to mint from /// @param poolManager PoolManager associated to the `collateral` function mint( address user, uint256 amount, uint256 minStableAmount, address stableMaster, address collateral, address poolManager ) external nonReentrant { IERC20(collateral).safeTransferFrom(msg.sender, address(this), amount); _mint(user, amount, minStableAmount, true, stableMaster, collateral, IPoolManager(poolManager)); } /// @notice Wrapper built on top of the `_burn` method to burn stablecoins /// @param dest Address to send the collateral to /// @param amount Amount of stablecoins to use for the burn /// @param minCollatAmount Minimum collateral amount received for the tx not to revert /// @param stablecoin Address of the stablecoin to mint /// @param collateral Collateral to mint from function burn( address dest, uint256 amount, uint256 minCollatAmount, address stablecoin, address collateral ) external nonReentrant { _burn(dest, amount, minCollatAmount, false, stablecoin, collateral, IPoolManager(address(0))); } /// @notice Wrapper n°1 built on top of the `_deposit` method to deposit collateral as a SLP in the protocol /// Allows to deposit a collateral within the protocol /// @param user Address where to send the resulting sanTokens, if this address is the router address then it means /// that the intention is to stake the sanTokens obtained in a subsequent `gaugeDeposit` action /// @param amount Amount of collateral to deposit /// @param stablecoin `StableMaster` associated to the sanToken /// @param collateral Token to deposit /// @dev Contrary to the `mint` action, the `deposit` action can be used in composition with other actions, like /// `deposit` and then `stake function deposit( address user, uint256 amount, address stablecoin, address collateral ) external nonReentrant { IERC20(collateral).safeTransferFrom(msg.sender, address(this), amount); _deposit(user, amount, false, stablecoin, collateral, IPoolManager(address(0)), ISanToken(address(0))); } /// @notice Wrapper n°2 (a little more gas efficient than n°1) built on top of the `_deposit` method to deposit collateral as a SLP in the protocol /// Allows to deposit a collateral within the protocol /// @param user Address where to send the resulting sanTokens, if this address is the router address then it means /// that the intention is to stake the sanTokens obtained in a subsequent `gaugeDeposit` action /// @param amount Amount of collateral to deposit /// @param stableMaster `StableMaster` associated to the sanToken /// @param collateral Token to deposit /// @param poolManager PoolManager associated to the sanToken /// @param sanToken SanToken associated to the `collateral` and `stableMaster` /// @dev Contrary to the `mint` action, the `deposit` action can be used in composition with other actions, like /// `deposit` and then `stake` function deposit( address user, uint256 amount, address stableMaster, address collateral, IPoolManager poolManager, ISanToken sanToken ) external nonReentrant { IERC20(collateral).safeTransferFrom(msg.sender, address(this), amount); _deposit(user, amount, true, stableMaster, collateral, poolManager, sanToken); } /// @notice Wrapper built on top of the `_openPerpetual` method to open a perpetual with the protocol /// @param collateral Here the collateral should not be null (even if `addressProcessed` is true) for the router /// to be able to know how to deposit collateral /// @dev `stablecoinOrPerpetualManager` should be the address of the agToken (= stablecoin) is `addressProcessed` is false /// and the associated `perpetualManager` otherwise function openPerpetual( address owner, uint256 margin, uint256 amountCommitted, uint256 maxOracleRate, uint256 minNetMargin, bool addressProcessed, address stablecoinOrPerpetualManager, address collateral ) external nonReentrant { IERC20(collateral).safeTransferFrom(msg.sender, address(this), margin); _openPerpetual( owner, margin, amountCommitted, maxOracleRate, minNetMargin, addressProcessed, stablecoinOrPerpetualManager, collateral ); } /// @notice Wrapper built on top of the `_addToPerpetual` method to add collateral to a perpetual with the protocol /// @param collateral Here the collateral should not be null (even if `addressProcessed is true) for the router /// to be able to know how to deposit collateral /// @dev `stablecoinOrPerpetualManager` should be the address of the agToken is `addressProcessed` is false and the associated /// `perpetualManager` otherwise function addToPerpetual( uint256 margin, uint256 perpetualID, bool addressProcessed, address stablecoinOrPerpetualManager, address collateral ) external nonReentrant { IERC20(collateral).safeTransferFrom(msg.sender, address(this), margin); _addToPerpetual(margin, perpetualID, addressProcessed, stablecoinOrPerpetualManager, collateral); } /// @notice Allows composable calls to different functions within the protocol /// @param paramsPermit Array of params `PermitType` used to do a 1 tx to approve the router on each token (can be done once by /// setting high approved amounts) which supports the `permit` standard. Users willing to interact with the contract /// with tokens that do not support permit should approve the contract for these tokens prior to interacting with it /// @param paramsTransfer Array of params `TransferType` used to transfer tokens to the router /// @param paramsSwap Array of params `ParamsSwapType` used to swap tokens /// @param actions List of actions to be performed by the router (in order of execution): make sure to read for each action the /// associated internal function /// @param datas Array of encoded data for each of the actions performed in this mixer. This is where the bytes-encoded parameters /// for a given action are stored /// @dev This function first fills the router balances via transfers and swaps. It then proceeds with each /// action in the order at which they are given /// @dev With this function, users can specify paths to swap tokens to the desired token of their choice. Yet the protocol /// does not verify the payload given and cannot check that the swap performed by users actually gives the desired /// out token: in this case funds will be lost by the user /// @dev For some actions (`mint`, `deposit`, `openPerpetual`, `addToPerpetual`, `withdraw`), users are /// required to give a proportion of the amount of token they have brought to the router within the transaction (through /// a direct transfer or a swap) they want to use for the operation. If you want to use all the USDC you have brought (through an ETH -> USDC) /// swap to mint stablecoins for instance, you should use `BASE_PARAMS` as a proportion. /// @dev The proportion that is specified for an action is a proportion of what is left. If you want to use 50% of your USDC for a `mint` /// and the rest for an `openPerpetual`, proportion used for the `mint` should be 50% (that is `BASE_PARAMS/2`), and proportion /// for the `openPerpetual` should be all that is left that is 100% (= `BASE_PARAMS`). /// @dev For each action here, make sure to read the documentation of the associated internal function to know how to correctly /// specify parameters function mixer( PermitType[] memory paramsPermit, TransferType[] memory paramsTransfer, ParamsSwapType[] memory paramsSwap, ActionType[] memory actions, bytes[] calldata datas ) external payable nonReentrant { // Do all the permits once for all: if all tokens have already been approved, there's no need for this step for (uint256 i = 0; i < paramsPermit.length; i++) { IERC20PermitUpgradeable(paramsPermit[i].token).permit( paramsPermit[i].owner, address(this), paramsPermit[i].value, paramsPermit[i].deadline, paramsPermit[i].v, paramsPermit[i].r, paramsPermit[i].s ); } // Then, do all the transfer to load all needed funds into the router // This function is limited to 10 different assets to be spent on the protocol (agTokens, collaterals, sanTokens) address[_MAX_TOKENS] memory listTokens; uint256[_MAX_TOKENS] memory balanceTokens; for (uint256 i = 0; i < paramsTransfer.length; i++) { paramsTransfer[i].inToken.safeTransferFrom(msg.sender, address(this), paramsTransfer[i].amountIn); _addToList(listTokens, balanceTokens, address(paramsTransfer[i].inToken), paramsTransfer[i].amountIn); } for (uint256 i = 0; i < paramsSwap.length; i++) { // Caution here: if the args are not set such that end token is the params `paramsSwap[i].collateral`, // then the funds will be lost, and any user could take advantage of it to fetch the funds uint256 amountOut = _transferAndSwap( paramsSwap[i].inToken, paramsSwap[i].amountIn, paramsSwap[i].minAmountOut, paramsSwap[i].swapType, paramsSwap[i].args ); _addToList(listTokens, balanceTokens, address(paramsSwap[i].collateral), amountOut); } // Performing actions one after the others for (uint256 i = 0; i < actions.length; i++) { if (actions[i] == ActionType.claimRewards) { ( address user, uint256 proportionToBeTransferred, address[] memory claimLiquidityGauges, uint256[] memory claimPerpetualIDs, bool addressProcessed, address[] memory stablecoins, address[] memory collateralsOrPerpetualManagers ) = abi.decode(datas[i], (address, uint256, address[], uint256[], bool, address[], address[])); uint256 amount = ANGLE.balanceOf(user); _claimRewards( user, claimLiquidityGauges, claimPerpetualIDs, addressProcessed, stablecoins, collateralsOrPerpetualManagers ); if (proportionToBeTransferred > 0) { amount = ANGLE.balanceOf(user) - amount; amount = (amount * proportionToBeTransferred) / BASE_PARAMS; ANGLE.safeTransferFrom(msg.sender, address(this), amount); _addToList(listTokens, balanceTokens, address(ANGLE), amount); } } else if (actions[i] == ActionType.claimWeeklyInterest) { (address user, address feeDistributor, bool letInContract) = abi.decode( datas[i], (address, address, bool) ); (uint256 amount, IERC20 token) = _claimWeeklyInterest( user, IFeeDistributorFront(feeDistributor), letInContract ); if (address(token) != address(0)) _addToList(listTokens, balanceTokens, address(token), amount); // In all the following action, the `amount` variable represents the proportion of the // balance that needs to be used for this action (in `BASE_PARAMS`) // We name it `amount` here to save some new variable declaration costs } else if (actions[i] == ActionType.veANGLEDeposit) { (address user, uint256 amount) = abi.decode(datas[i], (address, uint256)); amount = _computeProportion(amount, listTokens, balanceTokens, address(ANGLE)); _depositOnLocker(user, amount); } else if (actions[i] == ActionType.gaugeDeposit) { (address user, uint256 amount, address stakedToken, address gauge, bool shouldClaimRewards) = abi .decode(datas[i], (address, uint256, address, address, bool)); amount = _computeProportion(amount, listTokens, balanceTokens, stakedToken); _gaugeDeposit(user, amount, ILiquidityGauge(gauge), shouldClaimRewards); } else if (actions[i] == ActionType.deposit) { ( address user, uint256 amount, bool addressProcessed, address stablecoinOrStableMaster, address collateral, address poolManager, address sanToken ) = abi.decode(datas[i], (address, uint256, bool, address, address, address, address)); amount = _computeProportion(amount, listTokens, balanceTokens, collateral); (amount, sanToken) = _deposit( user, amount, addressProcessed, stablecoinOrStableMaster, collateral, IPoolManager(poolManager), ISanToken(sanToken) ); if (amount > 0) _addToList(listTokens, balanceTokens, sanToken, amount); } else if (actions[i] == ActionType.withdraw) { ( uint256 amount, bool addressProcessed, address stablecoinOrStableMaster, address collateralOrPoolManager, address sanToken ) = abi.decode(datas[i], (uint256, bool, address, address, address)); amount = _computeProportion(amount, listTokens, balanceTokens, sanToken); // Reusing the `collateralOrPoolManager` variable to save some variable declarations (amount, collateralOrPoolManager) = _withdraw( amount, addressProcessed, stablecoinOrStableMaster, collateralOrPoolManager ); _addToList(listTokens, balanceTokens, collateralOrPoolManager, amount); } else if (actions[i] == ActionType.mint) { ( address user, uint256 amount, uint256 minStableAmount, bool addressProcessed, address stablecoinOrStableMaster, address collateral, address poolManager ) = abi.decode(datas[i], (address, uint256, uint256, bool, address, address, address)); amount = _computeProportion(amount, listTokens, balanceTokens, collateral); _mint( user, amount, minStableAmount, addressProcessed, stablecoinOrStableMaster, collateral, IPoolManager(poolManager) ); } else if (actions[i] == ActionType.openPerpetual) { ( address user, uint256 amount, uint256 amountCommitted, uint256 extremeRateOracle, uint256 minNetMargin, bool addressProcessed, address stablecoinOrPerpetualManager, address collateral ) = abi.decode(datas[i], (address, uint256, uint256, uint256, uint256, bool, address, address)); amount = _computeProportion(amount, listTokens, balanceTokens, collateral); _openPerpetual( user, amount, amountCommitted, extremeRateOracle, minNetMargin, addressProcessed, stablecoinOrPerpetualManager, collateral ); } else if (actions[i] == ActionType.addToPerpetual) { ( uint256 amount, uint256 perpetualID, bool addressProcessed, address stablecoinOrPerpetualManager, address collateral ) = abi.decode(datas[i], (uint256, uint256, bool, address, address)); amount = _computeProportion(amount, listTokens, balanceTokens, collateral); _addToPerpetual(amount, perpetualID, addressProcessed, stablecoinOrPerpetualManager, collateral); } } // Once all actions have been performed, the router sends back the unused funds from users // If a user sends funds (through a swap) but specifies incorrectly the collateral associated to it, then the mixer will revert // When trying to send remaining funds back for (uint256 i = 0; i < balanceTokens.length; i++) { if (balanceTokens[i] > 0) IERC20(listTokens[i]).safeTransfer(msg.sender, balanceTokens[i]); } } receive() external payable {} // ======================== Internal Utility Functions ========================= // Most internal utility functions have a wrapper built on top of it /// @notice Internal version of the `claimRewards` function /// Allows to claim rewards for multiple gauges and perpetuals at once /// @param gaugeUser Address for which to fetch the rewards from the gauges /// @param liquidityGauges Gauges to claim on /// @param perpetualIDs Perpetual IDs to claim rewards for /// @param addressProcessed Whether `PerpetualManager` list is already accessible in `collateralsOrPerpetualManagers`vor if it should be /// retrieved from `stablecoins` and `collateralsOrPerpetualManagers` /// @param stablecoins Stablecoin contracts linked to the perpetualsIDs. Array of zero addresses if addressProcessed is true /// @param collateralsOrPerpetualManagers Collateral contracts linked to the perpetualsIDs or `perpetualManager` contracts if /// `addressProcessed` is true /// @dev If the caller wants to send the rewards to another account than `gaugeUser` it first needs to /// call `set_rewards_receiver(otherAccount)` on each `liquidityGauge` /// @dev The function only takes rewards received by users, function _claimRewards( address gaugeUser, address[] memory liquidityGauges, uint256[] memory perpetualIDs, bool addressProcessed, address[] memory stablecoins, address[] memory collateralsOrPerpetualManagers ) internal { require( stablecoins.length == perpetualIDs.length && collateralsOrPerpetualManagers.length == perpetualIDs.length, "104" ); for (uint256 i = 0; i < liquidityGauges.length; i++) { ILiquidityGauge(liquidityGauges[i]).claim_rewards(gaugeUser); } for (uint256 i = 0; i < perpetualIDs.length; i++) { IPerpetualManagerFrontWithClaim perpManager; if (addressProcessed) perpManager = IPerpetualManagerFrontWithClaim(collateralsOrPerpetualManagers[i]); else { (, Pairs memory pairs) = _getInternalContracts( IERC20(stablecoins[i]), IERC20(collateralsOrPerpetualManagers[i]) ); perpManager = pairs.perpetualManager; } perpManager.getReward(perpetualIDs[i]); } } /// @notice Allows to deposit ANGLE on an existing locker /// @param user Address to deposit for /// @param amount Amount to deposit function _depositOnLocker(address user, uint256 amount) internal { VEANGLE.deposit_for(user, amount); } /// @notice Allows to claim weekly interest distribution and if wanted to transfer it to the `angleRouter` for future use /// @param user Address to claim for /// @param _feeDistributor Address of the fee distributor to claim to /// @dev If funds are transferred to the router, this action cannot be an end in itself, otherwise funds will be lost: /// typically we expect people to call for this action before doing a deposit /// @dev If `letInContract` (and hence if funds are transferred to the router), you should approve the `angleRouter` to /// transfer the token claimed from the `feeDistributor` function _claimWeeklyInterest( address user, IFeeDistributorFront _feeDistributor, bool letInContract ) internal returns (uint256 amount, IERC20 token) { amount = _feeDistributor.claim(user); if (letInContract) { // Fetching info from the `FeeDistributor` to process correctly the withdrawal token = IERC20(_feeDistributor.token()); token.safeTransferFrom(msg.sender, address(this), amount); } else { amount = 0; } } /// @notice Internal version of the `gaugeDeposit` function /// Allows to deposit tokens into a gauge /// @param user Address on behalf of which deposit should be made in the gauge /// @param amount Amount to stake /// @param gauge LiquidityGauge to stake in /// @param shouldClaimRewards Whether to claim or not previously accumulated rewards /// @dev You should be cautious on who will receive the rewards (if `shouldClaimRewards` is true) /// It can be set on each gauge /// @dev In the `mixer`, before calling for this action, user should have made sure to get in the router /// the associated token (by like a `deposit` action) /// @dev The function will revert if the gauge has not already been approved by the contract function _gaugeDeposit( address user, uint256 amount, ILiquidityGauge gauge, bool shouldClaimRewards ) internal { gauge.deposit(amount, user, shouldClaimRewards); } /// @notice Internal version of the `mint` functions /// Mints stablecoins from the protocol /// @param user Address to send the stablecoins to /// @param amount Amount of collateral to use for the mint /// @param minStableAmount Minimum stablecoin minted for the tx not to revert /// @param addressProcessed Whether `msg.sender` provided the contracts address or the tokens one /// @param stablecoinOrStableMaster Token associated to a `StableMaster` (if `addressProcessed` is false) /// or directly the `StableMaster` contract if `addressProcessed` /// @param collateral Collateral to mint from: it can be null if `addressProcessed` is true but in the corresponding /// action, the `mixer` needs to get a correct address to compute the amount of tokens to use for the mint /// @param poolManager PoolManager associated to the `collateral` (null if `addressProcessed` is not true) /// @dev This function is not designed to be composable with other actions of the router after it's called: like /// stablecoins obtained from it cannot be used for other operations: as such the `user` address should not be the router /// address function _mint( address user, uint256 amount, uint256 minStableAmount, bool addressProcessed, address stablecoinOrStableMaster, address collateral, IPoolManager poolManager ) internal { IStableMasterFront stableMaster; (stableMaster, poolManager) = _mintBurnContracts( addressProcessed, stablecoinOrStableMaster, collateral, poolManager ); stableMaster.mint(amount, user, poolManager, minStableAmount); } /// @notice Burns stablecoins from the protocol /// @param dest Address who will receive the proceeds /// @param amount Amount of collateral to use for the mint /// @param minCollatAmount Minimum Collateral minted for the tx not to revert /// @param addressProcessed Whether `msg.sender` provided the contracts address or the tokens one /// @param stablecoinOrStableMaster Token associated to a `StableMaster` (if `addressProcessed` is false) /// or directly the `StableMaster` contract if `addressProcessed` /// @param collateral Collateral to mint from: it can be null if `addressProcessed` is true but in the corresponding /// action, the `mixer` needs to get a correct address to compute the amount of tokens to use for the mint /// @param poolManager PoolManager associated to the `collateral` (null if `addressProcessed` is not true) function _burn( address dest, uint256 amount, uint256 minCollatAmount, bool addressProcessed, address stablecoinOrStableMaster, address collateral, IPoolManager poolManager ) internal { IStableMasterFront stableMaster; (stableMaster, poolManager) = _mintBurnContracts( addressProcessed, stablecoinOrStableMaster, collateral, poolManager ); stableMaster.burn(amount, msg.sender, dest, poolManager, minCollatAmount); } /// @notice Internal version of the `deposit` functions /// Allows to deposit a collateral within the protocol /// @param user Address where to send the resulting sanTokens, if this address is the router address then it means /// that the intention is to stake the sanTokens obtained in a subsequent `gaugeDeposit` action /// @param amount Amount of collateral to deposit /// @param addressProcessed Whether `msg.sender` provided the contracts addresses or the tokens ones /// @param stablecoinOrStableMaster Token associated to a `StableMaster` (if `addressProcessed` is false) /// or directly the `StableMaster` contract if `addressProcessed` /// @param collateral Token to deposit: it can be null if `addressProcessed` is true but in the corresponding /// action, the `mixer` needs to get a correct address to compute the amount of tokens to use for the deposit /// @param poolManager PoolManager associated to the `collateral` (null if `addressProcessed` is not true) /// @param sanToken SanToken associated to the `collateral` (null if `addressProcessed` is not true) /// @dev Contrary to the `mint` action, the `deposit` action can be used in composition with other actions, like /// `deposit` and then `stake` function _deposit( address user, uint256 amount, bool addressProcessed, address stablecoinOrStableMaster, address collateral, IPoolManager poolManager, ISanToken sanToken ) internal returns (uint256 addedAmount, address) { IStableMasterFront stableMaster; if (addressProcessed) { stableMaster = IStableMasterFront(stablecoinOrStableMaster); } else { Pairs memory pairs; (stableMaster, pairs) = _getInternalContracts(IERC20(stablecoinOrStableMaster), IERC20(collateral)); poolManager = pairs.poolManager; sanToken = pairs.sanToken; } if (user == address(this)) { // Computing the amount of sanTokens obtained addedAmount = sanToken.balanceOf(address(this)); stableMaster.deposit(amount, address(this), poolManager); addedAmount = sanToken.balanceOf(address(this)) - addedAmount; } else { stableMaster.deposit(amount, user, poolManager); } return (addedAmount, address(sanToken)); } /// @notice Withdraws sanTokens from the protocol /// @param amount Amount of sanTokens to withdraw /// @param addressProcessed Whether `msg.sender` provided the contracts addresses or the tokens ones /// @param stablecoinOrStableMaster Token associated to a `StableMaster` (if `addressProcessed` is false) /// or directly the `StableMaster` contract if `addressProcessed` /// @param collateralOrPoolManager Collateral to withdraw (if `addressProcessed` is false) or directly /// the `PoolManager` contract if `addressProcessed` function _withdraw( uint256 amount, bool addressProcessed, address stablecoinOrStableMaster, address collateralOrPoolManager ) internal returns (uint256 withdrawnAmount, address) { IStableMasterFront stableMaster; // Stores the address of the `poolManager`, while `collateralOrPoolManager` is used in the function // to store the `collateral` address IPoolManager poolManager; if (addressProcessed) { stableMaster = IStableMasterFront(stablecoinOrStableMaster); poolManager = IPoolManager(collateralOrPoolManager); collateralOrPoolManager = poolManager.token(); } else { Pairs memory pairs; (stableMaster, pairs) = _getInternalContracts( IERC20(stablecoinOrStableMaster), IERC20(collateralOrPoolManager) ); poolManager = pairs.poolManager; } // Here reusing the `withdrawnAmount` variable to avoid a stack too deep problem withdrawnAmount = IERC20(collateralOrPoolManager).balanceOf(address(this)); // This call will increase our collateral balance stableMaster.withdraw(amount, address(this), address(this), poolManager); // We compute the difference between our collateral balance after and before the `withdraw` call withdrawnAmount = IERC20(collateralOrPoolManager).balanceOf(address(this)) - withdrawnAmount; return (withdrawnAmount, collateralOrPoolManager); } /// @notice Internal version of the `openPerpetual` function /// Opens a perpetual within Angle /// @param owner Address to mint perpetual for /// @param margin Margin to open the perpetual with /// @param amountCommitted Commit amount in the perpetual /// @param maxOracleRate Maximum oracle rate required to have a leverage position opened /// @param minNetMargin Minimum net margin required to have a leverage position opened /// @param addressProcessed Whether msg.sender provided the contracts addresses or the tokens ones /// @param stablecoinOrPerpetualManager Token associated to the `StableMaster` (iif `addressProcessed` is false) /// or address of the desired `PerpetualManager` (if `addressProcessed` is true) /// @param collateral Collateral to mint from (it can be null if `addressProcessed` is true): it can be null if `addressProcessed` is true but in the corresponding /// action, the `mixer` needs to get a correct address to compute the amount of tokens to use for the deposit function _openPerpetual( address owner, uint256 margin, uint256 amountCommitted, uint256 maxOracleRate, uint256 minNetMargin, bool addressProcessed, address stablecoinOrPerpetualManager, address collateral ) internal returns (uint256 perpetualID) { if (!addressProcessed) { (, Pairs memory pairs) = _getInternalContracts(IERC20(stablecoinOrPerpetualManager), IERC20(collateral)); stablecoinOrPerpetualManager = address(pairs.perpetualManager); } return IPerpetualManagerFrontWithClaim(stablecoinOrPerpetualManager).openPerpetual( owner, margin, amountCommitted, maxOracleRate, minNetMargin ); } /// @notice Internal version of the `addToPerpetual` function /// Adds collateral to a perpetual /// @param margin Amount of collateral to add /// @param perpetualID Perpetual to add collateral to /// @param addressProcessed Whether msg.sender provided the contracts addresses or the tokens ones /// @param stablecoinOrPerpetualManager Token associated to the `StableMaster` (iif `addressProcessed` is false) /// or address of the desired `PerpetualManager` (if `addressProcessed` is true) /// @param collateral Collateral to mint from (it can be null if `addressProcessed` is true): it can be null if `addressProcessed` is true but in the corresponding /// action, the `mixer` needs to get a correct address to compute the amount of tokens to use for the deposit function _addToPerpetual( uint256 margin, uint256 perpetualID, bool addressProcessed, address stablecoinOrPerpetualManager, address collateral ) internal { if (!addressProcessed) { (, Pairs memory pairs) = _getInternalContracts(IERC20(stablecoinOrPerpetualManager), IERC20(collateral)); stablecoinOrPerpetualManager = address(pairs.perpetualManager); } IPerpetualManagerFrontWithClaim(stablecoinOrPerpetualManager).addToPerpetual(perpetualID, margin); } // ======================== Internal Utility Functions ========================= /// @notice Checks if collateral in the list /// @param list List of addresses /// @param searchFor Address of interest /// @return index Place of the address in the list if it is in or current length otherwise function _searchList(address[_MAX_TOKENS] memory list, address searchFor) internal pure returns (uint256 index) { uint256 i; while (i < list.length && list[i] != address(0)) { if (list[i] == searchFor) return i; i++; } return i; } /// @notice Modifies stored balances for a given collateral /// @param list List of collateral addresses /// @param balances List of balances for the different supported collateral types /// @param searchFor Address of the collateral of interest /// @param amount Amount to add in the balance for this collateral function _addToList( address[_MAX_TOKENS] memory list, uint256[_MAX_TOKENS] memory balances, address searchFor, uint256 amount ) internal pure { uint256 index = _searchList(list, searchFor); // add it to the list if non existent and we add tokens if (list[index] == address(0)) list[index] = searchFor; balances[index] += amount; } /// @notice Computes the proportion of the collateral leftover balance to use for a given action /// @param proportion Ratio to take from balance /// @param list Collateral list /// @param balances Balances of each collateral asset in the collateral list /// @param searchFor Collateral to look for /// @return amount Amount to use for the action (based on the proportion given) /// @dev To use all the collateral balance available for an action, users should give `proportion` a value of /// `BASE_PARAMS` function _computeProportion( uint256 proportion, address[_MAX_TOKENS] memory list, uint256[_MAX_TOKENS] memory balances, address searchFor ) internal pure returns (uint256 amount) { uint256 index = _searchList(list, searchFor); // Reverts if the index was not found require(list[index] != address(0), "33"); amount = (proportion * balances[index]) / BASE_PARAMS; balances[index] -= amount; } /// @notice Gets Angle contracts associated to a pair (stablecoin, collateral) /// @param stablecoin Token associated to a `StableMaster` /// @param collateral Collateral to mint/deposit/open perpetual or add collateral from /// @dev This function is used to check that the parameters passed by people calling some of the main /// router functions are correct function _getInternalContracts(IERC20 stablecoin, IERC20 collateral) internal view returns (IStableMasterFront stableMaster, Pairs memory pairs) { stableMaster = mapStableMasters[stablecoin]; pairs = mapPoolManagers[stableMaster][collateral]; // If `stablecoin` is zero then this necessarily means that `stableMaster` here will be 0 // Similarly, if `collateral` is zero, then this means that `pairs.perpetualManager`, `pairs.poolManager` // and `pairs.sanToken` will be zero // Last, if any of `pairs.perpetualManager`, `pairs.poolManager` or `pairs.sanToken` is zero, this means // that all others should be null from the `addPairs` and `removePairs` functions which keep this invariant require(address(stableMaster) != address(0) && address(pairs.poolManager) != address(0), "0"); return (stableMaster, pairs); } /// @notice Get contracts for mint and burn actions /// @param addressProcessed Whether `msg.sender` provided the contracts address or the tokens one /// @param stablecoinOrStableMaster Token associated to a `StableMaster` (if `addressProcessed` is false) /// or directly the `StableMaster` contract if `addressProcessed` /// @param collateral Collateral to mint from: it can be null if `addressProcessed` is true but in the corresponding /// action, the `mixer` needs to get a correct address to compute the amount of tokens to use for the mint /// @param poolManager PoolManager associated to the `collateral` (null if `addressProcessed` is not true) function _mintBurnContracts( bool addressProcessed, address stablecoinOrStableMaster, address collateral, IPoolManager poolManager ) internal view returns (IStableMasterFront, IPoolManager) { IStableMasterFront stableMaster; if (addressProcessed) { stableMaster = IStableMasterFront(stablecoinOrStableMaster); } else { Pairs memory pairs; (stableMaster, pairs) = _getInternalContracts(IERC20(stablecoinOrStableMaster), IERC20(collateral)); poolManager = pairs.poolManager; } return (stableMaster, poolManager); } /// @notice Adds new collateral type to specific stablecoin /// @param stableMaster Address of the `StableMaster` associated to the stablecoin of interest /// @param poolManager Address of the `PoolManager` contract associated to the pair (stablecoin,collateral) /// @param liquidityGauge Address of liquidity gauge contract associated to sanToken function _addPair( IStableMasterFront stableMaster, IPoolManager poolManager, ILiquidityGauge liquidityGauge ) internal { // Fetching the associated `sanToken` and `perpetualManager` from the contract (IERC20 collateral, ISanToken sanToken, IPerpetualManager perpetualManager, , , , , , ) = IStableMaster( address(stableMaster) ).collateralMap(poolManager); Pairs storage _pairs = mapPoolManagers[stableMaster][collateral]; // Checking if the pair has not already been initialized: if yes we need to make the function revert // otherwise we could end up with still approved `PoolManager` and `PerpetualManager` contracts require(address(_pairs.poolManager) == address(0), "114"); _pairs.poolManager = poolManager; _pairs.perpetualManager = IPerpetualManagerFrontWithClaim(address(perpetualManager)); _pairs.sanToken = sanToken; // In the future, it is possible that sanTokens do not have an associated liquidity gauge if (address(liquidityGauge) != address(0)) { require(address(sanToken) == liquidityGauge.staking_token(), "20"); _pairs.gauge = liquidityGauge; sanToken.approve(address(liquidityGauge), type(uint256).max); } _changeAllowance(collateral, address(stableMaster), type(uint256).max); _changeAllowance(collateral, address(perpetualManager), type(uint256).max); emit CollateralToggled(address(stableMaster), address(poolManager), address(liquidityGauge)); } /// @notice Changes allowance of this contract for a given token /// @param token Address of the token to change allowance /// @param spender Address to change the allowance of /// @param amount Amount allowed function _changeAllowance( IERC20 token, address spender, uint256 amount ) internal { uint256 currentAllowance = token.allowance(address(this), spender); if (currentAllowance < amount) { token.safeIncreaseAllowance(spender, amount - currentAllowance); } else if (currentAllowance > amount) { token.safeDecreaseAllowance(spender, currentAllowance - amount); } } /// @notice Transfers collateral or an arbitrary token which is then swapped on UniswapV3 or on 1Inch /// @param inToken Token to swap for the collateral /// @param amount Amount of in token to swap for the collateral /// @param minAmountOut Minimum amount accepted for the swap to happen /// @param swapType Choice on which contracts to swap /// @param args Bytes representing either the path to swap your input token to the accepted collateral on Uniswap or payload for 1Inch /// @dev The `path` provided is not checked, meaning people could swap for a token A and declare that they've swapped for another token B. /// However, the mixer manipulates its token balance only through the addresses registered in `listTokens`, so any subsequent mixer action /// trying to transfer funds B will do it through address of token A and revert as A is not actually funded. /// In case there is not subsequent action, `mixer` will revert when trying to send back what appears to be remaining tokens A. function _transferAndSwap( IERC20 inToken, uint256 amount, uint256 minAmountOut, SwapType swapType, bytes memory args ) internal returns (uint256 amountOut) { if (address(inToken) == address(WETH9) && address(this).balance >= amount) { WETH9.deposit{ value: amount }(); // wrap only what is needed to pay } else { inToken.safeTransferFrom(msg.sender, address(this), amount); } if (swapType == SwapType.UniswapV3) amountOut = _swapOnUniswapV3(inToken, amount, minAmountOut, args); else if (swapType == SwapType.oneINCH) amountOut = _swapOn1Inch(inToken, minAmountOut, args); else require(false, "3"); return amountOut; } /// @notice Allows to swap any token to an accepted collateral via UniswapV3 (if there is a path) /// @param inToken Address token used as entrance of the swap /// @param amount Amount of in token to swap for the accepted collateral /// @param minAmountOut Minimum amount accepted for the swap to happen /// @param path Bytes representing the path to swap your input token to the accepted collateral function _swapOnUniswapV3( IERC20 inToken, uint256 amount, uint256 minAmountOut, bytes memory path ) internal returns (uint256 amountOut) { // Approve transfer to the `uniswapV3Router` if it is the first time that the token is used if (!uniAllowedToken[inToken]) { inToken.safeIncreaseAllowance(address(uniswapV3Router), type(uint256).max); uniAllowedToken[inToken] = true; } amountOut = uniswapV3Router.exactInput( ExactInputParams(path, address(this), block.timestamp, amount, minAmountOut) ); } /// @notice Allows to swap any token to an accepted collateral via 1Inch API /// @param minAmountOut Minimum amount accepted for the swap to happen /// @param payload Bytes needed for 1Inch API function _swapOn1Inch( IERC20 inToken, uint256 minAmountOut, bytes memory payload ) internal returns (uint256 amountOut) { // Approve transfer to the `oneInch` router if it is the first time the token is used if (!oneInchAllowedToken[inToken]) { inToken.safeIncreaseAllowance(address(oneInch), type(uint256).max); oneInchAllowedToken[inToken] = true; } //solhint-disable-next-line (bool success, bytes memory result) = oneInch.call(payload); if (!success) _revertBytes(result); amountOut = abi.decode(result, (uint256)); require(amountOut >= minAmountOut, "15"); } /// @notice Internal function used for error handling function _revertBytes(bytes memory errMsg) internal pure { if (errMsg.length > 0) { //solhint-disable-next-line assembly { revert(add(32, errMsg), mload(errMsg)) } } revert("117"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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: GPL-3.0 pragma solidity ^0.8.7; /// @title IFeeDistributor /// @author Interface of the `FeeDistributor` contract /// @dev This interface is used by the `SurplusConverter` contract to send funds to the `FeeDistributor` interface IFeeDistributor { function burn(address token) external; } /// @title IFeeDistributorFront /// @author Interface for public use of the `FeeDistributor` contract /// @dev This interface is used for user related function interface IFeeDistributorFront { function token() external returns (address); function claim(address _addr) external returns (uint256); function claim(address[20] memory _addr) external returns (bool); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; interface ILiquidityGauge { // solhint-disable-next-line function staking_token() external returns (address stakingToken); // solhint-disable-next-line function deposit_reward_token(address _rewardToken, uint256 _amount) external; function deposit( uint256 _value, address _addr, // solhint-disable-next-line bool _claim_rewards ) external; // solhint-disable-next-line function claim_rewards(address _addr) external; // solhint-disable-next-line function claim_rewards(address _addr, address _receiver) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; /// @title ISanToken /// @author Angle Core Team /// @notice Interface for Angle's `SanToken` contract that handles sanTokens, tokens that are given to SLPs /// contributing to a collateral for a given stablecoin interface ISanToken is IERC20Upgradeable { // ================================== StableMaster ============================= function mint(address account, uint256 amount) external; function burnFrom( uint256 amount, address burner, address sender ) external; function burnSelf(uint256 amount, address burner) external; function stableMaster() external view returns (address); function poolManager() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // Normally just importing `IPoolManager` should be sufficient, but for clarity here // we prefer to import all concerned interfaces import "./IPoolManager.sol"; import "./IOracle.sol"; import "./IPerpetualManager.sol"; import "./ISanToken.sol"; // Struct to handle all the parameters to manage the fees // related to a given collateral pool (associated to the stablecoin) struct MintBurnData { // Values of the thresholds to compute the minting fees // depending on HA hedge (scaled by `BASE_PARAMS`) uint64[] xFeeMint; // Values of the fees at thresholds (scaled by `BASE_PARAMS`) uint64[] yFeeMint; // Values of the thresholds to compute the burning fees // depending on HA hedge (scaled by `BASE_PARAMS`) uint64[] xFeeBurn; // Values of the fees at thresholds (scaled by `BASE_PARAMS`) uint64[] yFeeBurn; // Max proportion of collateral from users that can be covered by HAs // It is exactly the same as the parameter of the same name in `PerpetualManager`, whenever one is updated // the other changes accordingly uint64 targetHAHedge; // Minting fees correction set by the `FeeManager` contract: they are going to be multiplied // to the value of the fees computed using the hedge curve // Scaled by `BASE_PARAMS` uint64 bonusMalusMint; // Burning fees correction set by the `FeeManager` contract: they are going to be multiplied // to the value of the fees computed using the hedge curve // Scaled by `BASE_PARAMS` uint64 bonusMalusBurn; // Parameter used to limit the number of stablecoins that can be issued using the concerned collateral uint256 capOnStableMinted; } // Struct to handle all the variables and parameters to handle SLPs in the protocol // including the fraction of interests they receive or the fees to be distributed to // them struct SLPData { // Last timestamp at which the `sanRate` has been updated for SLPs uint256 lastBlockUpdated; // Fees accumulated from previous blocks and to be distributed to SLPs uint256 lockedInterests; // Max interests used to update the `sanRate` in a single block // Should be in collateral token base uint256 maxInterestsDistributed; // Amount of fees left aside for SLPs and that will be distributed // when the protocol is collateralized back again uint256 feesAside; // Part of the fees normally going to SLPs that is left aside // before the protocol is collateralized back again (depends on collateral ratio) // Updated by keepers and scaled by `BASE_PARAMS` uint64 slippageFee; // Portion of the fees from users minting and burning // that goes to SLPs (the rest goes to surplus) uint64 feesForSLPs; // Slippage factor that's applied to SLPs exiting (depends on collateral ratio) // If `slippage = BASE_PARAMS`, SLPs can get nothing, if `slippage = 0` they get their full claim // Updated by keepers and scaled by `BASE_PARAMS` uint64 slippage; // Portion of the interests from lending // that goes to SLPs (the rest goes to surplus) uint64 interestsForSLPs; } /// @title IStableMasterFunctions /// @author Angle Core Team /// @notice Interface for the `StableMaster` contract interface IStableMasterFunctions { function deploy( address[] memory _governorList, address _guardian, address _agToken ) external; // ============================== Lending ====================================== function accumulateInterest(uint256 gain) external; function signalLoss(uint256 loss) external; // ============================== HAs ========================================== function getStocksUsers() external view returns (uint256 maxCAmountInStable); function convertToSLP(uint256 amount, address user) external; // ============================== Keepers ====================================== function getCollateralRatio() external returns (uint256); function setFeeKeeper( uint64 feeMint, uint64 feeBurn, uint64 _slippage, uint64 _slippageFee ) external; // ============================== AgToken ====================================== function updateStocksUsers(uint256 amount, address poolManager) external; // ============================= Governance ==================================== function setCore(address newCore) external; function addGovernor(address _governor) external; function removeGovernor(address _governor) external; function setGuardian(address newGuardian, address oldGuardian) external; function revokeGuardian(address oldGuardian) external; function setCapOnStableAndMaxInterests( uint256 _capOnStableMinted, uint256 _maxInterestsDistributed, IPoolManager poolManager ) external; function setIncentivesForSLPs( uint64 _feesForSLPs, uint64 _interestsForSLPs, IPoolManager poolManager ) external; function setUserFees( IPoolManager poolManager, uint64[] memory _xFee, uint64[] memory _yFee, uint8 _mint ) external; function setTargetHAHedge(uint64 _targetHAHedge) external; function pause(bytes32 agent, IPoolManager poolManager) external; function unpause(bytes32 agent, IPoolManager poolManager) external; } /// @title IStableMaster /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables and mappings interface IStableMaster is IStableMasterFunctions { function agToken() external view returns (address); function collateralMap(IPoolManager poolManager) external view returns ( IERC20 token, ISanToken sanToken, IPerpetualManager perpetualManager, IOracle oracle, uint256 stocksUsers, uint256 sanRate, uint256 collatBase, SLPData memory slpData, MintBurnData memory feeData ); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "../interfaces/IPoolManager.sol"; /// @title IStableMasterFront /// @author Angle Core Team /// @dev Front interface, meaning only user-facing functions interface IStableMasterFront { function mint( uint256 amount, address user, IPoolManager poolManager, uint256 minStableAmount ) external; function burn( uint256 amount, address burner, address dest, IPoolManager poolManager, uint256 minCollatAmount ) external; function deposit( uint256 amount, address user, IPoolManager poolManager ) external; function withdraw( uint256 amount, address burner, address dest, IPoolManager poolManager ) external; function agToken() external returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; /// @title IVeANGLE /// @author Angle Core Team /// @notice Interface for the `VeANGLE` contract interface IVeANGLE { // solhint-disable-next-line func-name-mixedcase function deposit_for(address addr, uint256 amount) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.7; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title Interface for WETH9 interface IWETH9 is IERC20 { /// @notice Deposit ether to get wrapped ether function deposit() external payable; /// @notice Withdraw wrapped ether to get ether function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface IUniswapV3Router { /// @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); } /// @title Router for price estimation functionality /// @notice Functions for getting the price of one token with respect to another using Uniswap V2 /// @dev This interface is only used for non critical elements of the protocol interface IUniswapV2Router { /// @notice Given an input asset amount, returns the maximum output amount of the /// other asset (accounting for fees) given reserves. /// @param path Addresses of the pools used to get prices function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 swapAmount, uint256 minExpected, address[] calldata path, address receiver, uint256 swapDeadline ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @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 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: GPL-3.0 pragma solidity ^0.8.7; import "./IFeeManager.sol"; import "./IPerpetualManager.sol"; import "./IOracle.sol"; // Struct for the parameters associated to a strategy interacting with a collateral `PoolManager` // contract struct StrategyParams { // Timestamp of last report made by this strategy // It is also used to check if a strategy has been initialized uint256 lastReport; // Total amount the strategy is expected to have uint256 totalStrategyDebt; // The share of the total assets in the `PoolManager` contract that the `strategy` can access to. uint256 debtRatio; } /// @title IPoolManagerFunctions /// @author Angle Core Team /// @notice Interface for the collateral poolManager contracts handling each one type of collateral for /// a given stablecoin /// @dev Only the functions used in other contracts of the protocol are left here interface IPoolManagerFunctions { // ============================ Constructor ==================================== function deployCollateral( address[] memory governorList, address guardian, IPerpetualManager _perpetualManager, IFeeManager feeManager, IOracle oracle ) external; // ============================ Yield Farming ================================== function creditAvailable() external view returns (uint256); function debtOutstanding() external view returns (uint256); function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external; // ============================ Governance ===================================== function addGovernor(address _governor) external; function removeGovernor(address _governor) external; function setGuardian(address _guardian, address guardian) external; function revokeGuardian(address guardian) external; function setFeeManager(IFeeManager _feeManager) external; // ============================= Getters ======================================= function getBalance() external view returns (uint256); function getTotalAsset() external view returns (uint256); } /// @title IPoolManager /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables and mappings /// @dev Used in other contracts of the protocol interface IPoolManager is IPoolManagerFunctions { function stableMaster() external view returns (address); function perpetualManager() external view returns (address); function token() external view returns (address); function feeManager() external view returns (address); function totalDebt() external view returns (uint256); function strategies(address _strategy) external view returns (StrategyParams memory); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; /// @title IOracle /// @author Angle Core Team /// @notice Interface for Angle's oracle contracts reading oracle rates from both UniswapV3 and Chainlink /// from just UniswapV3 or from just Chainlink interface IOracle { function read() external view returns (uint256); function readAll() external view returns (uint256 lowerRate, uint256 upperRate); function readLower() external view returns (uint256); function readUpper() external view returns (uint256); function readQuote(uint256 baseAmount) external view returns (uint256); function readQuoteLower(uint256 baseAmount) external view returns (uint256); function inBase() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IERC721.sol"; import "./IFeeManager.sol"; import "./IOracle.sol"; import "./IAccessControl.sol"; /// @title Interface of the contract managing perpetuals /// @author Angle Core Team /// @dev Front interface, meaning only user-facing functions interface IPerpetualManagerFront is IERC721Metadata { function openPerpetual( address owner, uint256 amountBrought, uint256 amountCommitted, uint256 maxOracleRate, uint256 minNetMargin ) external returns (uint256 perpetualID); function closePerpetual( uint256 perpetualID, address to, uint256 minCashOutAmount ) external; function addToPerpetual(uint256 perpetualID, uint256 amount) external; function removeFromPerpetual( uint256 perpetualID, uint256 amount, address to ) external; function liquidatePerpetuals(uint256[] memory perpetualIDs) external; function forceClosePerpetuals(uint256[] memory perpetualIDs) external; // ========================= External View Functions ============================= function getCashOutAmount(uint256 perpetualID, uint256 rate) external view returns (uint256, uint256); function isApprovedOrOwner(address spender, uint256 perpetualID) external view returns (bool); } /// @title Interface of the contract managing perpetuals /// @author Angle Core Team /// @dev This interface does not contain user facing functions, it just has functions that are /// interacted with in other parts of the protocol interface IPerpetualManagerFunctions is IAccessControl { // ================================= Governance ================================ function deployCollateral( address[] memory governorList, address guardian, IFeeManager feeManager, IOracle oracle_ ) external; function setFeeManager(IFeeManager feeManager_) external; function setHAFees( uint64[] memory _xHAFees, uint64[] memory _yHAFees, uint8 deposit ) external; function setTargetAndLimitHAHedge(uint64 _targetHAHedge, uint64 _limitHAHedge) external; function setKeeperFeesLiquidationRatio(uint64 _keeperFeesLiquidationRatio) external; function setKeeperFeesCap(uint256 _keeperFeesLiquidationCap, uint256 _keeperFeesClosingCap) external; function setKeeperFeesClosing(uint64[] memory _xKeeperFeesClosing, uint64[] memory _yKeeperFeesClosing) external; function setLockTime(uint64 _lockTime) external; function setBoundsPerpetual(uint64 _maxLeverage, uint64 _maintenanceMargin) external; function pause() external; function unpause() external; // ==================================== Keepers ================================ function setFeeKeeper(uint64 feeDeposit, uint64 feesWithdraw) external; // =============================== StableMaster ================================ function setOracle(IOracle _oracle) external; } /// @title IPerpetualManager /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables interface IPerpetualManager is IPerpetualManagerFunctions { function poolManager() external view returns (address); function oracle() external view returns (address); function targetHAHedge() external view returns (uint64); function totalHedgeAmount() external view returns (uint256); } /// @title Interface of the contract managing perpetuals with claim function /// @author Angle Core Team /// @dev Front interface with rewards function, meaning only user-facing functions interface IPerpetualManagerFrontWithClaim is IPerpetualManagerFront, IPerpetualManager { function getReward(uint256 perpetualID) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IAccessControl.sol"; /// @title IFeeManagerFunctions /// @author Angle Core Team /// @dev Interface for the `FeeManager` contract interface IFeeManagerFunctions is IAccessControl { // ================================= Keepers =================================== function updateUsersSLP() external; function updateHA() external; // ================================= Governance ================================ function deployCollateral( address[] memory governorList, address guardian, address _perpetualManager ) external; function setFees( uint256[] memory xArray, uint64[] memory yArray, uint8 typeChange ) external; function setHAFees(uint64 _haFeeDeposit, uint64 _haFeeWithdraw) external; } /// @title IFeeManager /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables and mappings /// @dev We need these getters as they are used in other contracts of the protocol interface IFeeManager is IFeeManagerFunctions { function stableMaster() external view returns (address); function perpetualManager() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; /// @title IAccessControl /// @author Forked from OpenZeppelin /// @notice Interface for `AccessControl` contracts 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; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; interface IERC721 is IERC165 { function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint256 tokenId ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Computes the proportion of the collateral leftover balance to use for a given action proportion Ratio to take from balance list Collateral list balances Balances of each collateral asset in the collateral list searchFor Collateral to look for return amount Amount to use for the action (based on the proportion given) To use all the collateral balance available for an action, users should give `proportion` a value of `BASE_PARAMS` Reverts if the index was not found
function _computeProportion( uint256 proportion, address[_MAX_TOKENS] memory list, uint256[_MAX_TOKENS] memory balances, address searchFor ) internal pure returns (uint256 amount) { uint256 index = _searchList(list, searchFor); require(list[index] != address(0), "33"); amount = (proportion * balances[index]) / BASE_PARAMS; balances[index] -= amount; }
6,009,135
./full_match/1/0xFbeC16EECD4558297FB3deA9934A162Ef76b14bd/sources/src/bases/EIP1967Upgradeable.sol
Checks whether the context is foreign to the implementation or the proxy by checking the EIP-1967 implementation slot. If we were running in proxy context, the impl address would be stored there If we were running in impl conext, the IMPL_CONTRACT_FLAG would be stored there/
function _isForeignContext() internal view returns (bool) { return address(_implementation()) == address(0); }
3,085,347
pragma solidity ^0.5.16; interface IBEP20 { // Returns the amount of tokens in existence function totalSupply() external view returns (uint); // Returns the token decimals function decimals() external view returns (uint); // Returns the token symbol function symbol() external view returns (string memory); // Returns the token name function name() external view returns (string memory); // Returns the token owner function getOwner() external view returns (address); // Returns the amount of tokens owned by `account` function balanceOf(address account) external view returns (uint); // Moves `amount` tokens from the caller's account to `recipient` function transfer(address recipient, uint amount) external returns (bool); /** * 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 (uint); /// Sets `amount` as the allowance of `spender` over the caller's tokens function approve(address spender, uint amount) external returns (bool); // Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism function transferFrom(address sender, address recipient, uint amount) external returns (bool); /* EVENTS */ // Emitted when `value` tokens are moved from one account (`from`) to another (`to`) event Transfer(address indexed from, address indexed to, uint value); // 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, uint value); } // Provides information about the current execution context contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance constructor () internal { } function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; return msg.data; } } // Wrappers over Solidity's arithmetic operations with added overflow checks library SafeMath { // Returns the addition of two unsigned integers, reverting on overflow function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } // Returns the subtraction of two unsigned integers, reverting on // overflow (when the result is negative) function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } // Returns the subtraction of two unsigned integers, reverting with custom message on // overflow (when the result is negative) function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } // Returns the multiplication of two unsigned integers, reverting on // 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; } // Returns the integer division of two unsigned integers. Reverts on // division by zero. The result is rounded towards zero function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } // Returns the integer division of two unsigned integers. Reverts with custom message on // division by zero. The result is rounded towards zero function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } } // Provides a basic access control mechanism, where there is an // owner that can be granted exclusive access to specific functions contract Ownable is Context { address public _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); // Initializes the contract setting the deployer as the initial owner constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } // Returns the address of the current owner function owner() public view returns (address) { return _owner; } // Throws if called by any account other than the owner modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } // 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); } // Transfers ownership of the contract to a new account (`newOwner`) function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract BlackList is Ownable { uint public _totalSupply; // Getters to allow the same blacklist to be used also by other contracts function getBlackListStatus(address _maker) external view returns (bool) { return isBlackListed[_maker]; } // Returns the token owner function getOwner() external view returns (address) { return owner(); } mapping (address => bool) public isBlackListed; function addBlackList (address _evilUser) public onlyOwner { isBlackListed[_evilUser] = true; emit AddedBlackList(_evilUser); } function removeBlackList (address _clearedUser) public onlyOwner { isBlackListed[_clearedUser] = false; emit RemovedBlackList(_clearedUser); } function destroyBlackFunds (address _blackListedUser) public onlyOwner { require(isBlackListed[_blackListedUser]); uint dirtyFunds = _balances[_blackListedUser]; _balances[_blackListedUser] = 0; _totalSupply -= dirtyFunds; DestroyedBlackFunds(_blackListedUser, dirtyFunds); } event AddedBlackList(address _user); event RemovedBlackList(address _user); } contract WhiteList is Ownable { // Getters to allow the same Whitelist to be used also by other contracts function getWhiteListStatus(address _maker) external view returns (bool) { return isWhiteListed[_maker]; } // Returns the token owner function getOwner() external view returns (address) { return owner(); } mapping (address => bool) public isWhiteListed; function addWhiteList (address _user) public onlyOwner { isWhiteListed[_user] = true; emit AddedWhiteList(_user); } function removeWhiteList (address _user) public onlyOwner { isWhiteListed[_user] = false; emit RemovedWhiteList(_user); } event AddedWhiteList(address _user); event RemovedWhiteList(address _user); } // Allows to implement an emergency stop mechanism contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; // Modifier to make a function callable only when the contract is not paused modifier whenNotPaused() { require(!paused); _; } // Modifier to make a function callable only when the contract is paused modifier whenPaused() { require(paused); _; } // Called by the owner to pause, triggers stopped state function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } // Called by the owner to unpause, returns to normal state function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract BEP20Token is Context, Ownable, BlackList, WhiteList { using SafeMath for uint; // Get the balances mapping (address => mapping (address => uint)) public _allowances; mapping (address => uint) public _balances; string public _name; string public _symbol; uint public _decimals; constructor ( string memory tokenName, string memory tokenSymbol, uint initialSupply, uint decimalUnits ) public { _name = tokenName; _symbol = tokenSymbol; _decimals = decimalUnits; _totalSupply = initialSupply * (10 ** _decimals); _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } // Returns the token decimals function decimals() external view returns (uint) { return _decimals; } // Returns the token symbol function symbol() external view returns (string memory) { return _symbol; } // Returns the token name function name() external view returns (string memory) { return _name; } // See {BEP20-totalSupply} function totalSupply() external view returns (uint) { return _totalSupply; } // Moves tokens `amount` from `sender` to `recipient` function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } // See {BEP20-balanceOf} function balanceOf(address account) external view returns (uint) { return _balances[account]; } // See {BEP20-transfer} // `recipient` cannot be the zero address // the caller must have a balance of at least `amount` function transfer(address recipient, uint amount) external whenNotPaused returns (bool) { require(!isBlackListed[msg.sender]); _transfer(_msgSender(), recipient, amount); return true; } // See {BEP20-allowance} function allowance(address owner, address spender) external view returns (uint) { return _allowances[owner][spender]; } // See {BEP20-approve} // `spender` cannot be the zero address function approve(address spender, uint amount) external returns (bool) { _approve(_msgSender(), spender, amount); return true; } // See {BEP20-transferFrom} // `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, uint amount) external returns (bool) { require(!isBlackListed[sender]); _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP20: transfer amount exceeds allowance") ); return true; } // Atomically increases the allowance granted to `spender` by the caller // `spender` cannot be the zero address function increaseAllowance(address spender, uint addedValue) public returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue) ); return true; } // Automatically decreases the allowance granted to `spender` by the caller // `spender` cannot be the zero address // `spender` must have allowance for the caller of at least `subtractedValue` function decreaseAllowance(address spender, uint subtractedValue) public returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero") ); return true; } // Creates `amount` tokens and assigns them to `msg.sender`, increasing the total supply // `msg.sender` must be the token owner function mint(uint amount) public onlyOwner returns (bool) { _mint(_msgSender(), amount); return true; } // Creates `amount` tokens and assigns them to `account`, increasing // `to` cannot be the zero address function _mint(address account, uint amount) internal { require(account != address(0), "BEP20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } // Destroy `amount` tokens from `msg.sender`, reducing // `msg.sender` must be the token owner function burn(uint amount) public onlyOwner returns (bool) { _burn(_msgSender(), amount); return true; } // Destroys `amount` tokens from `account`, reducing the total supply // `account` cannot be the zero address // `account` must have at least `amount` tokens function _burn(address account, uint amount) internal { require(account != address(0), "BEP20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "BEP20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } // Sets `amount` as the allowance of `spender` over the `owner`s tokens // `owner` cannot be the zero address. // `spender` cannot be the zero address. function _approve(address owner, address spender, uint amount) internal { require(owner != address(0), "BEP20: approve from the zero address"); require(spender != address(0), "BEP20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } }
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; }
2,474,150
pragma solidity >=0.6.0 <0.9.0; import "./MockUSDC.sol"; contract LiquidityPool { string public name = "LiquidityPool"; address payable public owner = payable(msg.sender); MockUSDC public mockUSDC; uint256 public totalStakedUSDC; // Total USDC Liquidity tokens locked uint256 public monthlyInterest; struct Lender { uint256 stakingBalance; uint256 interestAccrued; bool isStaking; } mapping(address => Lender) public lenders; address[] lendersAddresses; function stakeUSDC(uint _amount) public { // Require amount greater than 0 require(_amount > 0, "amount cannot be 0"); // Transfer MockUSDC tokens to this contract for staking mockUSDC.transferFrom(msg.sender, address(this), _amount); // Update total liquidity balance totalStakedUSDC = totalStakedUSDC + _amount; // Update staking balance lenders[msg.sender].stakingBalance = lenders[msg.sender].stakingBalance + _amount; //Update staking status and add address to lendersAddresses if (!lenders[msg.sender].isStaking) { lenders[msg.sender].isStaking = true; lendersAddresses.push[msg.sender]; } } // Unstaking USDC (Withdraw) function unstakeUSDC(uint _amount) public { // Fetch staking balance uint256 balance = lenders[msg.sender].stakingBalance; // Require amount greater than 0 require(balance > 0, "staking balance cannot be 0"); require(_amount <= balance, "unstaking more than your balance"); // Transfer MockUSDC tokens back to Circle account mockUSDC.transfer(msg.sender, _amount); // Update total liquidity balance totalStakedUSDC = totalStakedUSDC - _amount; // Update staking balance lenders[msg.sender].stakingBalance = lenders[msg.sender].stakingBalance - _amount; } // Script issues interest on a monthly basis according to proportion staked compared to pool function issueInterest() public { // Only the owner can call this function require(msg.sender == owner, "caller must be the owner"); // Issue interest to all lenders for (uint i=0; i<lendersAddresses.length; i++) { address recipient = lendersAddresses[i]; uint256 balance = lenders[recipient].stakingBalance; uint256 shareOfInterest = balance/totalStakedUSDC; uint256 interestOwed = shareOfInterest * monthlyInterest; lenders[recipient].stakingBalance = interestOwed + balance; lenders[recipient].interestAccrued = interestOwed + lenders[recipient].interestAccrued; } // Add accrued interest for the month to total pool totalStakedUSDC = totalStakedUSDC + monthlyInterest; // Reset monthly interest to 0 monthlyInterest = 0; } // Issuing USDC Loan function issueLoan(address _account, uint _amount) public { // Transfer MockUSDC tokens to corresponding Circle account mockUSDC.transfer(_account, _amount); // Update total liquidity balance totalStakedUSDC = totalStakedUSDC - _amount; } // Recieving payment from borrower function recievePayment(address _account, uint _amount) public { // Transfer MockUSDC tokens to corresponding Circle account mockUSDC.transfer(_account, _amount); // Update total liquidity balance totalStakedUSDC = totalStakedUSDC - _amount; } }
Require amount greater than 0 Transfer MockUSDC tokens to this contract for staking Update total liquidity balance Update staking balanceUpdate staking status and add address to lendersAddresses
function stakeUSDC(uint _amount) public { require(_amount > 0, "amount cannot be 0"); mockUSDC.transferFrom(msg.sender, address(this), _amount); totalStakedUSDC = totalStakedUSDC + _amount; lenders[msg.sender].stakingBalance = lenders[msg.sender].stakingBalance + _amount; if (!lenders[msg.sender].isStaking) { lenders[msg.sender].isStaking = true; lendersAddresses.push[msg.sender]; } }
14,109,015
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./interfaces/IERC20.sol"; import "./interfaces/IWrappedPosition.sol"; import "./interfaces/ITranche.sol"; import "./interfaces/ITrancheFactory.sol"; import "./interfaces/IInterestToken.sol"; import "./libraries/ERC20Permit.sol"; import "./libraries/DateString.sol"; /// @author Element Finance /// @title Tranche contract Tranche is ERC20Permit, ITranche { IInterestToken public immutable override interestToken; IWrappedPosition public immutable position; IERC20 public immutable underlying; uint8 internal immutable _underlyingDecimals; // The outstanding amount of underlying which // can be redeemed from the contract from Principal Tokens // NOTE - we use smaller sizes so that they can be one storage slot uint128 public valueSupplied; // The total supply of interest tokens uint128 public override interestSupply; // The timestamp when tokens can be redeemed. uint256 public immutable unlockTimestamp; // The amount of slippage allowed on the Principal token redemption [0.1 basis points] uint256 internal constant _SLIPPAGE_BP = 1e13; // The speedbump variable records the first timestamp where redemption was attempted to be // performed on a tranche where loss occurred. It blocks redemptions for 48 hours after // it is triggered in order to (1) prevent atomic flash loan price manipulation (2) // give 48 hours to remediate any other loss scenario before allowing withdraws uint256 public speedbump; // Const which is 48 hours in seconds uint256 internal constant _FORTY_EIGHT_HOURS = 172800; // An event to listen for when negative interest withdraw are triggered event SpeedBumpHit(uint256 timestamp); /// @notice Constructs this contract constructor() ERC20Permit("Element Principal Token ", "eP") { // Assume the caller is the Tranche factory. ITrancheFactory trancheFactory = ITrancheFactory(msg.sender); ( address wpAddress, uint256 expiration, IInterestToken interestTokenTemp, // solhint-disable-next-line address unused ) = trancheFactory.getData(); interestToken = interestTokenTemp; IWrappedPosition wpContract = IWrappedPosition(wpAddress); position = wpContract; // Store the immutable time variables unlockTimestamp = expiration; // We use local because immutables are not readable in construction IERC20 localUnderlying = wpContract.token(); underlying = localUnderlying; // We load and store the underlying decimals uint8 localUnderlyingDecimals = localUnderlying.decimals(); _underlyingDecimals = localUnderlyingDecimals; // And set this contract to have the same _setupDecimals(localUnderlyingDecimals); } /// @notice We override the optional extra construction function from ERC20 to change names function _extraConstruction() internal override { // Assume the caller is the Tranche factory and that this is called from constructor // We have to do this double load because of the lack of flexibility in constructor ordering ITrancheFactory trancheFactory = ITrancheFactory(msg.sender); ( address wpAddress, uint256 expiration, // solhint-disable-next-line IInterestToken unused, address dateLib ) = trancheFactory.getData(); string memory strategySymbol = IWrappedPosition(wpAddress).symbol(); // Write the strategySymbol and expiration time to name and symbol // This logic was previously encoded as calling a library "DateString" // in line and directly. However even though this code is only in the constructor // it both made the code of this contract much bigger and made the factory // un deployable. So we needed to use the library as an external contract // but solidity does not have support for address to library conversions // or other support for working directly with libraries in a type safe way. // For that reason we have to use this ugly and non type safe hack to make these // contracts deployable. Since the library is an immutable in the factory // the security profile is quite similar to a standard external linked library. // We load the real storage slots of the symbol and name storage variables uint256 namePtr; uint256 symbolPtr; assembly { namePtr := name.slot symbolPtr := symbol.slot } // We then call the 'encodeAndWriteTimestamp' function on our library contract (bool success1, ) = dateLib.delegatecall( abi.encodeWithSelector( DateString.encodeAndWriteTimestamp.selector, strategySymbol, expiration, namePtr ) ); (bool success2, ) = dateLib.delegatecall( abi.encodeWithSelector( DateString.encodeAndWriteTimestamp.selector, strategySymbol, expiration, symbolPtr ) ); // Assert that both calls succeeded assert(success1 && success2); } /// @notice An aliasing of the getter for valueSupplied to improve ERC20 compatibility /// @return The number of principal tokens which exist. function totalSupply() external view returns (uint256) { return uint256(valueSupplied); } /** @notice Deposit wrapped position tokens and receive interest and Principal ERC20 tokens. If interest has already been accrued by the wrapped position tokens held in this contract, the number of Principal tokens minted is reduced in order to pay for the accrued interest. @param _amount The amount of underlying to deposit @param _destination The address to mint to @return The amount of principal and yield token minted as (pt, yt) */ function deposit(uint256 _amount, address _destination) external override returns (uint256, uint256) { // Transfer the underlying to be wrapped into the position underlying.transferFrom(msg.sender, address(position), _amount); // Now that we have funded the deposit we can call // the prefunded deposit return prefundedDeposit(_destination); } /// @notice This function calls the prefunded deposit method to /// create wrapped position tokens held by the contract. It should /// only be called when a transfer has already been made to /// the wrapped position contract of the underlying /// @param _destination The address to mint to /// @return the amount of principal and yield token minted as (pt, yt) /// @dev WARNING - The call which funds this method MUST be in the same transaction // as the call to this method or you risk loss of funds function prefundedDeposit(address _destination) public override returns (uint256, uint256) { // We check that this it is possible to deposit require(block.timestamp < unlockTimestamp, "expired"); // Since the wrapped position contract holds a balance we use the prefunded deposit method ( uint256 shares, uint256 usedUnderlying, uint256 balanceBefore ) = position.prefundedDeposit(address(this)); // The implied current value of the holding of this contract in underlying // is the balanceBefore*(usedUnderlying/shares) since (usedUnderlying/shares) // is underlying per share and balanceBefore is the balance of this contract // in position tokens before this deposit. uint256 holdingsValue = (balanceBefore * usedUnderlying) / shares; // This formula is inputUnderlying - inputUnderlying*interestPerUnderlying // Accumulated interest has its value in the interest tokens so we have to mint less // principal tokens to account for that. // NOTE - If a pool has more than 100% interest in the period this will revert on underflow // The user cannot discount the principal token enough to pay for the outstanding interest accrued. (uint256 _valueSupplied, uint256 _interestSupply) = ( uint256(valueSupplied), uint256(interestSupply) ); // We block deposits in negative interest rate regimes // The +2 allows for very small rounding errors which occur when // depositing into a tranche which is attached to a wp which has // accrued interest but the tranche has not yet accrued interest // and the first deposit into the tranche is substantially smaller // than following ones. require(_valueSupplied <= holdingsValue + 2, "E:NEG_INT"); uint256 adjustedAmount; // Have to split on the initialization case and negative interest case if (_valueSupplied > 0 && holdingsValue > _valueSupplied) { adjustedAmount = usedUnderlying - ((holdingsValue - _valueSupplied) * usedUnderlying) / _interestSupply; } else { adjustedAmount = usedUnderlying; } // We record the new input of reclaimable underlying (valueSupplied, interestSupply) = ( uint128(_valueSupplied + adjustedAmount), uint128(_interestSupply + usedUnderlying) ); // We mint interest token for each underlying provided interestToken.mint(_destination, usedUnderlying); // We mint principal token discounted by the accumulated interest. _mint(_destination, adjustedAmount); // We return the number of principal token and yield token return (adjustedAmount, usedUnderlying); } /** @notice Burn principal tokens to withdraw underlying tokens. @param _amount The number of tokens to burn. @param _destination The address to send the underlying too @return The number of underlying tokens released @dev This method will return 1 underlying for 1 principal except when interest is negative, in which case the principal tokens is redeemable pro rata for the assets controlled by this vault. Also note: Redemption has the possibility of at most _SLIPPAGE_BP numerical error on each redemption so each principal token may occasionally redeem for less than 1 unit of underlying. Max loss defaults to 0.1 BP ie 0.001% loss */ function withdrawPrincipal(uint256 _amount, address _destination) external override returns (uint256) { // No redemptions before unlock require(block.timestamp >= unlockTimestamp, "E:Not Expired"); // If the speedbump == 0 it's never been hit so we don't need // to change the withdraw rate. uint256 localSpeedbump = speedbump; uint256 withdrawAmount = _amount; uint256 localSupply = uint256(valueSupplied); if (localSpeedbump != 0) { // Load the assets we have in this vault uint256 holdings = position.balanceOfUnderlying(address(this)); // If we check and the interest rate is no longer negative then we // allow normal 1 to 1 withdraws [even if the speedbump was hit less // than 48 hours ago, to prevent possible griefing] if (holdings < localSupply) { // We allow the user to only withdraw their percent of holdings // NOTE - Because of the discounting mechanics this causes account loss // percentages to be slightly perturbed from overall loss. // ie: tokens holders who join when interest has accumulated // will get slightly higher percent loss than those who joined earlier // in the case of loss at the end of the period. Biases are very // small except in extreme cases. withdrawAmount = (_amount * holdings) / localSupply; // If the interest rate is still negative and we are not 48 hours after // speedbump being set we revert require( localSpeedbump + _FORTY_EIGHT_HOURS < block.timestamp, "E:Early" ); } } // Burn from the sender _burn(msg.sender, _amount); // Remove these principal token from the interest calculations for future interest redemptions valueSupplied = uint128(localSupply) - uint128(_amount); // Load the share balance of the vault before withdrawing [gas note - both the smart // contract and share value is warmed so this is actually quite a cheap lookup] uint256 shareBalanceBefore = position.balanceOf(address(this)); // Calculate the min output uint256 minOutput = withdrawAmount - (withdrawAmount * _SLIPPAGE_BP) / 1e18; // We make the actual withdraw from the position. (uint256 actualWithdraw, uint256 sharesBurned) = position .withdrawUnderlying(_destination, withdrawAmount, minOutput); // At this point we check that the implied contract holdings before this withdraw occurred // are more than enough to redeem all of the principal tokens for underlying ie that no // loss has happened. uint256 balanceBefore = (shareBalanceBefore * actualWithdraw) / sharesBurned; if (balanceBefore < localSupply) { // Require that that the speedbump has been set. require(localSpeedbump != 0, "E:NEG_INT"); // This assert should be very difficult to hit because it is checked above // but may be possible with complex reentrancy. assert(localSpeedbump + _FORTY_EIGHT_HOURS < block.timestamp); } return (actualWithdraw); } /// @notice This function allows someone to trigger the speedbump and eventually allow /// pro rata withdraws function hitSpeedbump() external { // We only allow setting the speedbump once require(speedbump == 0, "E:AlreadySet"); // We only allow setting it when withdraws can happen require(block.timestamp >= unlockTimestamp, "E:Not Expired"); // We require that the total holds are less than the supply of // principal token we need to redeem uint256 totalHoldings = position.balanceOfUnderlying(address(this)); if (totalHoldings < valueSupplied) { // We emit a notification so that if a speedbump is hit the community // can investigate. // Note - this is a form of defense mechanism because any flash loan // attack must be public for at least 48 hours before it has // affects. emit SpeedBumpHit(block.timestamp); // Set the speedbump speedbump = block.timestamp; } else { revert("E:NoLoss"); } } /** @notice Burn interest tokens to withdraw underlying tokens. @param _amount The number of interest tokens to burn. @param _destination The address to send the result to @return The number of underlying token released @dev Due to slippage the redemption may receive up to _SLIPPAGE_BP less in output compared to the floating rate. */ function withdrawInterest(uint256 _amount, address _destination) external override returns (uint256) { require(block.timestamp >= unlockTimestamp, "E:Not Expired"); // Burn tokens from the sender interestToken.burn(msg.sender, _amount); // Load the underlying value of this contract uint256 underlyingValueLocked = position.balanceOfUnderlying( address(this) ); // Load a stack variable to avoid future sloads (uint256 _valueSupplied, uint256 _interestSupply) = ( uint256(valueSupplied), uint256(interestSupply) ); // Interest is value locked minus current value uint256 interest = underlyingValueLocked > _valueSupplied ? underlyingValueLocked - _valueSupplied : 0; // The redemption amount is the interest per token times the amount uint256 redemptionAmount = (interest * _amount) / _interestSupply; uint256 minRedemption = redemptionAmount - (redemptionAmount * _SLIPPAGE_BP) / 1e18; // Store that we reduced the supply interestSupply = uint128(_interestSupply - _amount); // Redeem position tokens for underlying (uint256 redemption, ) = position.withdrawUnderlying( _destination, redemptionAmount, minRedemption ); return (redemption); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; interface IERC20 { function symbol() external view returns (string memory); function balanceOf(address account) external view returns (uint256); // Note this is non standard but nearly all ERC20 have exposed decimal functions function decimals() external view returns (uint8); 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 ); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./IERC20Permit.sol"; import "./IERC20.sol"; interface IWrappedPosition is IERC20Permit { function token() external view returns (IERC20); function balanceOfUnderlying(address who) external view returns (uint256); function getSharesToUnderlying(uint256 shares) external view returns (uint256); function deposit(address sender, uint256 amount) external returns (uint256); function withdraw( address sender, uint256 _shares, uint256 _minUnderlying ) external returns (uint256); function withdrawUnderlying( address _destination, uint256 _amount, uint256 _minUnderlying ) external returns (uint256, uint256); function prefundedDeposit(address _destination) external returns ( uint256, uint256, uint256 ); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./IERC20Permit.sol"; import "./IInterestToken.sol"; interface ITranche is IERC20Permit { function deposit(uint256 _shares, address destination) external returns (uint256, uint256); function prefundedDeposit(address _destination) external returns (uint256, uint256); function withdrawPrincipal(uint256 _amount, address _destination) external returns (uint256); function withdrawInterest(uint256 _amount, address _destination) external returns (uint256); function interestToken() external view returns (IInterestToken); function interestSupply() external view returns (uint128); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "../InterestToken.sol"; import "../libraries/DateString.sol"; interface ITrancheFactory { function getData() external returns ( address, uint256, InterestToken, address ); } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "./IERC20Permit.sol"; interface IInterestToken is IERC20Permit { function mint(address _account, uint256 _amount) external; function burn(address _account, uint256 _amount) external; } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import "../interfaces/IERC20Permit.sol"; // This default erc20 library is designed for max efficiency and security. // WARNING: By default it does not include totalSupply which breaks the ERC20 standard // to use a fully standard compliant ERC20 use 'ERC20PermitWithSupply" abstract contract ERC20Permit is IERC20Permit { // --- ERC20 Data --- // The name of the erc20 token string public name; // The symbol of the erc20 token string public override symbol; // The decimals of the erc20 token, should default to 18 for new tokens uint8 public override decimals; // A mapping which tracks user token balances mapping(address => uint256) public override balanceOf; // A mapping which tracks which addresses a user allows to move their tokens mapping(address => mapping(address => uint256)) public override allowance; // A mapping which tracks the permit signature nonces for users mapping(address => uint256) public override nonces; // --- EIP712 niceties --- // solhint-disable-next-line var-name-mixedcase bytes32 public override DOMAIN_SEPARATOR; // bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; /// @notice Initializes the erc20 contract /// @param name_ the value 'name' will be set to /// @param symbol_ the value 'symbol' will be set to /// @dev decimals default to 18 and must be reset by an inheriting contract for /// non standard decimal values constructor(string memory name_, string memory symbol_) { // Set the state variables name = name_; symbol = symbol_; decimals = 18; // By setting these addresses to 0 attempting to execute a transfer to // either of them will revert. This is a gas efficient way to prevent // a common user mistake where they transfer to the token address. // These values are not considered 'real' tokens and so are not included // in 'total supply' which only contains minted tokens. balanceOf[address(0)] = type(uint256).max; balanceOf[address(this)] = type(uint256).max; // Optional extra state manipulation _extraConstruction(); // Computes the EIP 712 domain separator which prevents user signed messages for // this contract to be replayed in other contracts. // https://eips.ethereum.org/EIPS/eip-712 DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes(name)), keccak256(bytes("1")), block.chainid, address(this) ) ); } /// @notice An optional override function to execute and change state before immutable assignment function _extraConstruction() internal virtual {} // --- Token --- /// @notice Allows a token owner to send tokens to another address /// @param recipient The address which will be credited with the tokens /// @param amount The amount user token to send /// @return returns true on success, reverts on failure so cannot return false. /// @dev transfers to this contract address or 0 will fail function transfer(address recipient, uint256 amount) public virtual override returns (bool) { // We forward this call to 'transferFrom' return transferFrom(msg.sender, recipient, amount); } /// @notice Transfers an amount of erc20 from a spender to a receipt /// @param spender The source of the ERC20 tokens /// @param recipient The destination of the ERC20 tokens /// @param amount the number of tokens to send /// @return returns true on success and reverts on failure /// @dev will fail transfers which send funds to this contract or 0 function transferFrom( address spender, address recipient, uint256 amount ) public virtual override returns (bool) { // Load balance and allowance uint256 balance = balanceOf[spender]; require(balance >= amount, "ERC20: insufficient-balance"); // We potentially have to change allowances if (spender != msg.sender) { // Loading the allowance in the if block prevents vanilla transfers // from paying for the sload. uint256 allowed = allowance[spender][msg.sender]; // If the allowance is max we do not reduce it // Note - This means that max allowances will be more gas efficient // by not requiring a sstore on 'transferFrom' if (allowed != type(uint256).max) { require(allowed >= amount, "ERC20: insufficient-allowance"); allowance[spender][msg.sender] = allowed - amount; } } // Update the balances balanceOf[spender] = balance - amount; // Note - In the constructor we initialize the 'balanceOf' of address 0 and // the token address to uint256.max and so in 8.0 transfers to those // addresses revert on this step. balanceOf[recipient] = balanceOf[recipient] + amount; // Emit the needed event emit Transfer(spender, recipient, amount); // Return that this call succeeded return true; } /// @notice This internal minting function allows inheriting contracts /// to mint tokens in the way they wish. /// @param account the address which will receive the token. /// @param amount the amount of token which they will receive /// @dev This function is virtual so that it can be overridden, if you /// are reviewing this contract for security you should ensure to /// check for overrides function _mint(address account, uint256 amount) internal virtual { // Add tokens to the account balanceOf[account] = balanceOf[account] + amount; // Emit an event to track the minting emit Transfer(address(0), account, amount); } /// @notice This internal burning function allows inheriting contracts to /// burn tokens in the way they see fit. /// @param account the account to remove tokens from /// @param amount the amount of tokens to remove /// @dev This function is virtual so that it can be overridden, if you /// are reviewing this contract for security you should ensure to /// check for overrides function _burn(address account, uint256 amount) internal virtual { // Reduce the balance of the account balanceOf[account] = balanceOf[account] - amount; // Emit an event tracking transfers emit Transfer(account, address(0), amount); } /// @notice This function allows a user to approve an account which can transfer /// tokens on their behalf. /// @param account The account which will be approve to transfer tokens /// @param amount The approval amount, if set to uint256.max the allowance does not go down on transfers. /// @return returns true for compatibility with the ERC20 standard function approve(address account, uint256 amount) public virtual override returns (bool) { // Set the senders allowance for account to amount allowance[msg.sender][account] = amount; // Emit an event to track approvals emit Approval(msg.sender, account, amount); return true; } /// @notice This function allows a caller who is not the owner of an account to execute the functionality of 'approve' with the owners signature. /// @param owner the owner of the account which is having the new approval set /// @param spender the address which will be allowed to spend owner's tokens /// @param value the new allowance value /// @param deadline the timestamp which the signature must be submitted by to be valid /// @param v Extra ECDSA data which allows public key recovery from signature assumed to be 27 or 28 /// @param r The r component of the ECDSA signature /// @param s The s component of the ECDSA signature /// @dev The signature for this function follows EIP 712 standard and should be generated with the /// eth_signTypedData JSON RPC call instead of the eth_sign JSON RPC call. If using out of date /// parity signing libraries the v component may need to be adjusted. Also it is very rare but possible /// for v to be other values, those values are not supported. function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external override { // The EIP 712 digest for this function bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, value, nonces[owner], deadline ) ) ) ); // Require that the owner is not zero require(owner != address(0), "ERC20: invalid-address-0"); // Require that we have a valid signature from the owner require(owner == ecrecover(digest, v, r, s), "ERC20: invalid-permit"); // Require that the signature is not expired require( deadline == 0 || block.timestamp <= deadline, "ERC20: permit-expired" ); // Format the signature to the default format require( uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ERC20: invalid signature 's' value" ); // Increment the signature nonce to prevent replay nonces[owner]++; // Set the allowance to the new value allowance[owner][spender] = value; // Emit an approval event to be able to track this happening emit Approval(owner, spender, value); } /// @notice Internal function which allows inheriting contract to set custom decimals /// @param decimals_ the new decimal value function _setupDecimals(uint8 decimals_) internal { // Set the decimals decimals = decimals_; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; library DateString { uint256 public constant SECONDS_PER_DAY = 24 * 60 * 60; uint256 public constant SECONDS_PER_HOUR = 60 * 60; uint256 public constant SECONDS_PER_MINUTE = 60; int256 public constant OFFSET19700101 = 2440588; // This function was forked from https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ // solhint-disable-next-line private-vars-leading-underscore function _daysToDate(uint256 _days) internal pure returns ( uint256 year, uint256 month, uint256 day ) { int256 __days = int256(_days); // solhint-disable-next-line var-name-mixedcase int256 L = __days + 68569 + OFFSET19700101; // solhint-disable-next-line var-name-mixedcase int256 N = (4 * L) / 146097; L = L - (146097 * N + 3) / 4; int256 _year = (4000 * (L + 1)) / 1461001; L = L - (1461 * _year) / 4 + 31; int256 _month = (80 * L) / 2447; int256 _day = L - (2447 * _month) / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint256(_year); month = uint256(_month); day = uint256(_day); } /// @dev Writes a prefix and an timestamp encoding to an output storage location /// This function is designed to only work with ASCII encoded strings. No emojis please. /// @param _prefix The string to write before the timestamp /// @param _timestamp the timestamp to encode and store /// @param _output the storage location of the output string /// NOTE - Current cost ~90k if gas is problem revisit and use assembly to remove the extra /// sstore s. function encodeAndWriteTimestamp( string memory _prefix, uint256 _timestamp, string storage _output ) external { _encodeAndWriteTimestamp(_prefix, _timestamp, _output); } /// @dev Sn internal version of the above function 'encodeAndWriteTimestamp' // solhint-disable-next-line function _encodeAndWriteTimestamp( string memory _prefix, uint256 _timestamp, string storage _output ) internal { // Cast the prefix string to a byte array bytes memory bytePrefix = bytes(_prefix); // Cast the output string to a byte array bytes storage bytesOutput = bytes(_output); // Copy the bytes from the prefix onto the byte array // NOTE - IF PREFIX CONTAINS NON-ASCII CHARS THIS WILL CAUSE AN INCORRECT STRING LENGTH for (uint256 i = 0; i < bytePrefix.length; i++) { bytesOutput.push(bytePrefix[i]); } // Add a '-' to the string to separate the prefix from the the date bytesOutput.push(bytes1("-")); // Add the date string timestampToDateString(_timestamp, _output); } /// @dev Converts a unix second encoded timestamp to a date format (year, month, day) /// then writes the string encoding of that to the output pointer. /// @param _timestamp the unix seconds timestamp /// @param _outputPointer the storage pointer to change. function timestampToDateString( uint256 _timestamp, string storage _outputPointer ) public { _timestampToDateString(_timestamp, _outputPointer); } /// @dev Sn internal version of the above function 'timestampToDateString' // solhint-disable-next-line function _timestampToDateString( uint256 _timestamp, string storage _outputPointer ) internal { // We pretend the string is a 'bytes' only push UTF8 encodings to it bytes storage output = bytes(_outputPointer); // First we get the day month and year (uint256 year, uint256 month, uint256 day) = _daysToDate( _timestamp / SECONDS_PER_DAY ); // First we add encoded day to the string { // Round out the second digit uint256 firstDigit = day / 10; // add it to the encoded byte for '0' output.push(bytes1(uint8(bytes1("0")) + uint8(firstDigit))); // Extract the second digit uint256 secondDigit = day % 10; // add it to the string output.push(bytes1(uint8(bytes1("0")) + uint8(secondDigit))); } // Next we encode the month string and add it if (month == 1) { stringPush(output, "J", "A", "N"); } else if (month == 2) { stringPush(output, "F", "E", "B"); } else if (month == 3) { stringPush(output, "M", "A", "R"); } else if (month == 4) { stringPush(output, "A", "P", "R"); } else if (month == 5) { stringPush(output, "M", "A", "Y"); } else if (month == 6) { stringPush(output, "J", "U", "N"); } else if (month == 7) { stringPush(output, "J", "U", "L"); } else if (month == 8) { stringPush(output, "A", "U", "G"); } else if (month == 9) { stringPush(output, "S", "E", "P"); } else if (month == 10) { stringPush(output, "O", "C", "T"); } else if (month == 11) { stringPush(output, "N", "O", "V"); } else if (month == 12) { stringPush(output, "D", "E", "C"); } else { revert("date decoding error"); } // We take the last two digits of the year // Hopefully that's enough { uint256 lastDigits = year % 100; // Round out the second digit uint256 firstDigit = lastDigits / 10; // add it to the encoded byte for '0' output.push(bytes1(uint8(bytes1("0")) + uint8(firstDigit))); // Extract the second digit uint256 secondDigit = lastDigits % 10; // add it to the string output.push(bytes1(uint8(bytes1("0")) + uint8(secondDigit))); } } function stringPush( bytes storage output, bytes1 data1, bytes1 data2, bytes1 data3 ) internal { output.push(data1); output.push(data2); output.push(data3); } } // Forked from openzepplin // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; /** * @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 IERC20Permit is IERC20 { /** * @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: Apache-2.0 pragma solidity ^0.8.0; import "./libraries/ERC20Permit.sol"; import "./libraries/DateString.sol"; import "./interfaces/IInterestToken.sol"; import "./interfaces/ITranche.sol"; contract InterestToken is ERC20Permit, IInterestToken { // The tranche address which controls the minting ITranche public immutable tranche; /// @dev Initializes the ERC20 and writes the correct names /// @param _tranche The tranche contract address /// @param _strategySymbol The symbol of the associated WrappedPosition contract /// @param _timestamp The unlock time on the tranche /// @param _decimals The decimal encoding for this token constructor( address _tranche, string memory _strategySymbol, uint256 _timestamp, uint8 _decimals ) ERC20Permit( _processName("Element Yield Token ", _strategySymbol, _timestamp), _processSymbol("eY", _strategySymbol, _timestamp) ) { tranche = ITranche(_tranche); _setupDecimals(_decimals); } /// @notice We use this function to add the date to the name string /// @param _name start of the name /// @param _strategySymbol the strategy symbol /// @param _timestamp the unix second timestamp to be encoded and added to the end of the string function _processName( string memory _name, string memory _strategySymbol, uint256 _timestamp ) internal returns (string memory) { // Set the name in the super name = _name; // Use the library to write the rest DateString._encodeAndWriteTimestamp(_strategySymbol, _timestamp, name); // load and return the name return name; } /// @notice We use this function to add the date to the name string /// @param _symbol start of the symbol /// @param _strategySymbol the strategy symbol /// @param _timestamp the unix second timestamp to be encoded and added to the end of the string function _processSymbol( string memory _symbol, string memory _strategySymbol, uint256 _timestamp ) internal returns (string memory) { // Set the symbol in the super symbol = _symbol; // Use the library to write the rest DateString._encodeAndWriteTimestamp( _strategySymbol, _timestamp, symbol ); // load and return the name return symbol; } /// @dev Aliasing of the lookup method for the supply of yield tokens which /// improves our ERC20 compatibility. /// @return The total supply of yield tokens function totalSupply() external view returns (uint256) { return uint256(tranche.interestSupply()); } /// @dev Prevents execution if the caller isn't the tranche modifier onlyMintAuthority() { require( msg.sender == address(tranche), "caller is not an authorized minter" ); _; } /// @dev Mints tokens to an address /// @param _account The account to mint to /// @param _amount The amount to mint function mint(address _account, uint256 _amount) external override onlyMintAuthority { _mint(_account, _amount); } /// @dev Burns tokens from an address /// @param _account The account to burn from /// @param _amount The amount of token to burn function burn(address _account, uint256 _amount) external override onlyMintAuthority { _burn(_account, _amount); } }
/ No redemptions before unlock If the speedbump == 0 it's never been hit so we don't need to change the withdraw rate. Load the assets we have in this vault If we check and the interest rate is no longer negative then we allow normal 1 to 1 withdraws [even if the speedbump was hit less than 48 hours ago, to prevent possible griefing] We allow the user to only withdraw their percent of holdings NOTE - Because of the discounting mechanics this causes account loss percentages to be slightly perturbed from overall loss. ie: tokens holders who join when interest has accumulated will get slightly higher percent loss than those who joined earlier in the case of loss at the end of the period. Biases are very small except in extreme cases. If the interest rate is still negative and we are not 48 hours after speedbump being set we revert Require that that the speedbump has been set. This assert should be very difficult to hit because it is checked above but may be possible with complex reentrancy.
function withdrawPrincipal(uint256 _amount, address _destination) external override returns (uint256) { require(block.timestamp >= unlockTimestamp, "E:Not Expired"); uint256 localSpeedbump = speedbump; uint256 withdrawAmount = _amount; uint256 localSupply = uint256(valueSupplied); if (localSpeedbump != 0) { uint256 holdings = position.balanceOfUnderlying(address(this)); if (holdings < localSupply) { withdrawAmount = (_amount * holdings) / localSupply; require( localSpeedbump + _FORTY_EIGHT_HOURS < block.timestamp, "E:Early" ); } } (withdrawAmount * _SLIPPAGE_BP) / 1e18; .withdrawUnderlying(_destination, withdrawAmount, minOutput); sharesBurned; if (balanceBefore < localSupply) { require(localSpeedbump != 0, "E:NEG_INT"); assert(localSpeedbump + _FORTY_EIGHT_HOURS < block.timestamp); } return (actualWithdraw); }
44,225
pragma solidity ^0.5.2; // ---------------------------------------------------------------------------- // rev rbs eryk 190105.POC // Ver Proof of Concept compiler optimized - travou na conversao de GTIN-13+YYMM para address nesta versao 0.5---droga // &#39;IGR&#39; &#39;InGRedient Token with Fixed Supply Token&#39; contract // // Symbol : IGR // Name : InGRedient Token -based on ER20 wiki- Example Fixed Supply Token // Total supply: 1,000,000.000000000000000000 // Decimals : 3 // // (c) BokkyPooBah / Bok Consulting Pty Ltd 2018. The MIT Licence. // // (c) <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b0e3922282065322a262a2f2a0b2a273e2524653e2d2a2928652e2f3e652939">[email&#160;protected]</a> & <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6b3902080a190f04452904190c0e182b1e0d0a0908450e0f1e450919">[email&#160;protected]</a> // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and a // fixed supply // ---------------------------------------------------------------------------- contract InGRedientToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "IGR"; name = "InGRedientToken"; decimals = 3;//kg is the official unit but grams is mostly used _totalSupply = 1000000000000000000000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner&#39;s account to `to` account // - Owner&#39;s account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner&#39;s account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender&#39;s account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner&#39;s account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don&#39;t accept ETH // ------------------------------------------------------------------------ function () external payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } // ================================================================== // >>>>>> IGR token specific functions <<<<<< //=================================================================== event FarmerRequestedCertificate(address owner, address certAuth, uint tokens); // -------------------------------------------------------------------------------------------------- // routine 10- allows for sale of ingredients along with the respective IGR token transfer // -------------------------------------------------------------------------------------------------- function farmerRequestCertificate(address _certAuth, uint _tokens, string memory _product, string memory _IngValueProperty, string memory _localGPSProduction, string memory _dateProduction ) public returns (bool success) { // falta implementar uma verif se o end certAuth foi cadastrado anteriormente allowed[owner][_certAuth] = _tokens; emit Approval(owner, _certAuth, _tokens); emit FarmerRequestedCertificate(owner, _certAuth, _tokens); return true; } // -------------------------------------------------------------------------------------------------- // routine 20- certAuthIssuesCerticate certification auth confirms that ingredients are trustworthy // as well as qtty , published url, product, details of IGR value property, location , date of harvest ) // -------------------------------------------------------------------------------------------------- function certAuthIssuesCerticate(address owner, address farmer, uint tokens, string memory _url,string memory product,string memory IngValueProperty, string memory localGPSProduction, uint dateProduction ) public returns (bool success) { balances[owner] = balances[owner].sub(tokens); //allowed[owner][msg.sender] = allowed[owner][msg.sender].sub(tokens);//nao faz sentido allowed[owner][msg.sender] = 0; balances[farmer] = balances[farmer].add(tokens); emit Transfer(owner, farmer, tokens); return true; } // -------------------------------------------------------------------------------------------------- // routine 30- allows for simple sale of ingredients along with the respective IGR token transfer ( with url) // -------------------------------------------------------------------------------------------------- function sellsIngrWithoutDepletion(address to, uint tokens,string memory _url) public returns (bool success) { string memory url=_url; // keep the url of the InGRedient for later transfer balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // -------------------------------------------------------------------------------------------------- // routine 40- allows for sale of intermediate product made from certified ingredients along with // the respective IGR token transfer ( with url) // i.e.: allows only the pro-rata quantity of semi-processed InGRedient tokens to be transfered // -------------------------------------------------------------------------------------------------- function sellsIntermediateGoodWithDepletion(address to, uint tokens,string memory _url,uint out2inIngredientPercentage ) public returns (bool success) { string memory url=_url; // keep the url of hte InGRedient for later transfer require (out2inIngredientPercentage <= 100); // make sure the depletion percentage is not higher than 100(%) balances[msg.sender] = balances[msg.sender].sub((tokens*(100-out2inIngredientPercentage))/100);// this will kill the tokens for the depleted part // transfer(to, tokens*out2inIngredientPercentage/100); return true; } //-------------------------------------------------------------------------------------------------- // aux function to generate a ethereum address from the food item visible numbers ( GTIN-13 + date of validity // is used by Routine 50- comminglerSellsProductSKUWithProRataIngred // and can be used to query teh blockchain by a consumer App //-------------------------------------------------------------------------------------------------- function genAddressFromGTIN13date(string memory _GTIN13,string memory _YYMMDD) public pure returns(address b){ //address b = bytes32(keccak256(abi.encodePacked(_GTIN13,_YYMMDD))); // address b = address(a); bytes32 a = keccak256(abi.encodePacked(_GTIN13,_YYMMDD)); assembly{ mstore(0,a) b:= mload(0) } return b; } // -------------------------------------------------------------------------------------------------- // transferAndWriteUrl- aux routine -Transfer the balance from token owner&#39;s account to `to` account // - Owner&#39;s account must have sufficient balance to transfer // - 0 value transfers are allowed // since the -url is passed to the function we achieve that this data be written to the block..nothing else needed // -------------------------------------------------------------------------------------------------- function transferAndWriteUrl(address to, uint tokens, string memory _url) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // -------------------------------------------------------------------------------------------------- // routine 50- comminglerSellsProductSKUWithProRataIngred(address _to, int numPSKUsSold, ,string _url, uint _qttyIGRinLLSKU, string GTIN13, string YYMMDD ) // allows for sale of final-consumer product with resp SKU and Lot identification with corresponding IGR transfer with url // i.e.: allows only the pro-rata quantity of semi-processed InGRedient tokens to be transfered to the consumer level package(SKU) // -------------------------------------------------------------------------------------------------- function comminglerSellsProductSKUWithProRataIngred(address _to, uint _numSKUsSold,string memory _url,uint _qttyIGRinLLSKU, string memory _GTIN13, string memory _YYMMDD ) public returns (bool success) { string memory url=_url; // keep the url of hte InGRedient for later transfer address c= genAddressFromGTIN13date( _GTIN13, _YYMMDD); require (_qttyIGRinLLSKU >0); // qtty of Ingredient may not be negative nor zero //write IGR qtty in one SKU and url to the blockchain address composed of GTIN-13+YYMMDD transferAndWriteUrl(c, _qttyIGRinLLSKU, _url); //deduct IGRs sold by commingler from its balances transferAndWriteUrl(_to, (_numSKUsSold-1)*_qttyIGRinLLSKU,_url);// records the transfer of custody of the qtty of SKU each with qttyIGRinLLSKU return true; } }
-------------------------------------------------------------------------------------------------- routine 20- certAuthIssuesCerticate certification auth confirms that ingredients are trustworthy as well as qtty , published url, product, details of IGR value property, location , date of harvest ) --------------------------------------------------------------------------------------------------allowed[owner][msg.sender] = allowed[owner][msg.sender].sub(tokens);nao faz sentido
function certAuthIssuesCerticate(address owner, address farmer, uint tokens, string memory _url,string memory product,string memory IngValueProperty, string memory localGPSProduction, uint dateProduction ) public returns (bool success) { balances[owner] = balances[owner].sub(tokens); allowed[owner][msg.sender] = 0; balances[farmer] = balances[farmer].add(tokens); emit Transfer(owner, farmer, tokens); return true; }
7,849,140
./partial_match/1/0x28842B6E92a844DaEd9D3B8a3E85C2bB79bBC269/sources/DividendTracker.sol
remove limits after token is stable
function removeLimits() external onlyOwner { limitsActive = false; emit RemovedLimits(); }
3,542,372
pragma solidity ^0.5.0; //Functions for retrieving min and Max in 51 length array (requestQ) //Taken partly from: https://github.com/modular-network/ethereum-libraries-array-utils/blob/master/contracts/Array256Lib.sol library Utilities{ /** * @dev Returns the minimum value in an array. */ function getMax(uint[51] memory data) internal pure returns(uint256 max,uint256 maxIndex) { max = data[1]; maxIndex; for(uint i=1;i < data.length;i++){ if(data[i] > max){ max = data[i]; maxIndex = i; } } } /** * @dev Returns the minimum value in an array. */ function getMin(uint[51] memory data) internal pure returns(uint256 min,uint256 minIndex) { minIndex = data.length - 1; min = data[minIndex]; for(uint i = data.length-1;i > 0;i--) { if(data[i] < min) { min = data[i]; minIndex = i; } } } // /// @dev Returns the minimum value and position in an array. // //@note IT IGNORES THE 0 INDEX // function getMin(uint[51] memory arr) internal pure returns (uint256 min, uint256 minIndex) { // assembly { // minIndex := 50 // min := mload(add(arr, mul(minIndex , 0x20))) // for {let i := 49 } gt(i,0) { i := sub(i, 1) } { // let item := mload(add(arr, mul(i, 0x20))) // if lt(item,min){ // min := item // minIndex := i // } // } // } // } // function getMax(uint256[51] memory arr) internal pure returns (uint256 max, uint256 maxIndex) { // assembly { // for { let i := 0 } lt(i,51) { i := add(i, 1) } { // let item := mload(add(arr, mul(i, 0x20))) // if lt(max, item) { // max := item // maxIndex := i // } // } // } // } } /** * @title Tellor Getters Library * @dev This is the getter library for all variables in the Tellor Tributes system. TellorGetters references this * libary for the getters logic */ library TellorGettersLibrary{ using SafeMath for uint256; event NewTellorAddress(address _newTellor); //emmited when a proposed fork is voted true /*Functions*/ //The next two functions are onlyOwner functions. For Tellor to be truly decentralized, we will need to transfer the Deity to the 0 address. //Only needs to be in library /** * @dev This function allows us to set a new Deity (or remove it) * @param _newDeity address of the new Deity of the tellor system */ function changeDeity(TellorStorage.TellorStorageStruct storage self, address _newDeity) internal{ require(self.addressVars[keccak256("_deity")] == msg.sender); self.addressVars[keccak256("_deity")] =_newDeity; } //Only needs to be in library /** * @dev This function allows the deity to upgrade the Tellor System * @param _tellorContract address of new updated TellorCore contract */ function changeTellorContract(TellorStorage.TellorStorageStruct storage self,address _tellorContract) internal{ require(self.addressVars[keccak256("_deity")] == msg.sender); self.addressVars[keccak256("tellorContract")]= _tellorContract; emit NewTellorAddress(_tellorContract); } /*Tellor Getters*/ /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(TellorStorage.TellorStorageStruct storage self, bytes32 _challenge,address _miner) internal view returns(bool){ return self.minersByChallenge[_challenge][_miner]; } /** * @dev Checks if an address voted in a dispute * @param _disputeId to look up * @param _address of voting party to look up * @return bool of whether or not party voted */ function didVote(TellorStorage.TellorStorageStruct storage self,uint _disputeId, address _address) internal view returns(bool){ return self.disputesById[_disputeId].voted[_address]; } /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] */ function getAddressVars(TellorStorage.TellorStorageStruct storage self, bytes32 _data) view internal returns(address){ return self.addressVars[_data]; } /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * @return uint of requestId * @return uint of timestamp * @return uint of value * @return uint of minExecutionDate * @return uint of numberOfVotes * @return uint of blocknumber * @return uint of minerSlot * @return uint of quorum * @return uint of fee * @return int count of the current tally */ function getAllDisputeVars(TellorStorage.TellorStorageStruct storage self,uint _disputeId) internal view returns(bytes32, bool, bool, bool, address, address, address,uint[9] memory, int){ TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; return(disp.hash,disp.executed, disp.disputeVotePassed, disp.isPropFork, disp.reportedMiner, disp.reportingParty,disp.proposedForkAddress,[disp.disputeUintVars[keccak256("requestId")], disp.disputeUintVars[keccak256("timestamp")], disp.disputeUintVars[keccak256("value")], disp.disputeUintVars[keccak256("minExecutionDate")], disp.disputeUintVars[keccak256("numberOfVotes")], disp.disputeUintVars[keccak256("blockNumber")], disp.disputeUintVars[keccak256("minerSlot")], disp.disputeUintVars[keccak256("quorum")],disp.disputeUintVars[keccak256("fee")]],disp.tally); } /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables(TellorStorage.TellorStorageStruct storage self) internal view returns(bytes32, uint, uint,string memory,uint,uint){ return (self.currentChallenge,self.uintVars[keccak256("currentRequestId")],self.uintVars[keccak256("difficulty")],self.requestDetails[self.uintVars[keccak256("currentRequestId")]].queryString,self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("granularity")],self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("totalTip")]); } /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(TellorStorage.TellorStorageStruct storage self,bytes32 _hash) internal view returns(uint){ return self.disputeIdByDisputeHash[_hash]; } /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(TellorStorage.TellorStorageStruct storage self,uint _disputeId,bytes32 _data) internal view returns(uint){ return self.disputesById[_disputeId].disputeUintVars[_data]; } /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue(TellorStorage.TellorStorageStruct storage self) internal view returns(uint,bool){ return (retrieveData(self,self.requestIdByTimestamp[self.uintVars[keccak256("timeOfLastNewValue")]], self.uintVars[keccak256("timeOfLastNewValue")]),true); } /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(TellorStorage.TellorStorageStruct storage self,uint _requestId) internal view returns(uint,bool){ TellorStorage.Request storage _request = self.requestDetails[_requestId]; if(_request.requestTimestamps.length > 0){ return (retrieveData(self,_requestId,_request.requestTimestamps[_request.requestTimestamps.length - 1]),true); } else{ return (0,false); } } /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(TellorStorage.TellorStorageStruct storage self,uint _requestId, uint _timestamp) internal view returns(uint){ return self.requestDetails[_requestId].minedBlockNum[_timestamp]; } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp(TellorStorage.TellorStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns(address[5] memory){ return self.requestDetails[_requestId].minersByValue[_timestamp]; } /** * @dev Get the name of the token * @return string of the token name */ function getName(TellorStorage.TellorStorageStruct storage self) internal pure returns(string memory){ return "Tellor Tributes"; } /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(TellorStorage.TellorStorageStruct storage self, uint _requestId) internal view returns(uint){ return self.requestDetails[_requestId].requestTimestamps.length; } /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(TellorStorage.TellorStorageStruct storage self, uint _index) internal view returns(uint){ require(_index <= 50); return self.requestIdByRequestQIndex[_index]; } /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(TellorStorage.TellorStorageStruct storage self, uint _timestamp) internal view returns(uint){ return self.requestIdByTimestamp[_timestamp]; } /** * @dev Getter function for requestId based on the qeuaryHash * @param _queryHash hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(TellorStorage.TellorStorageStruct storage self, bytes32 _queryHash) internal view returns(uint){ return self.requestIdByQueryHash[_queryHash]; } /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ(TellorStorage.TellorStorageStruct storage self) view internal returns(uint[51] memory){ return self.requestQ; } /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(TellorStorage.TellorStorageStruct storage self,uint _requestId,bytes32 _data) internal view returns(uint){ return self.requestDetails[_requestId].apiUintVars[_data]; } /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(TellorStorage.TellorStorageStruct storage self,uint _requestId) internal view returns(string memory,string memory, bytes32,uint, uint, uint) { TellorStorage.Request storage _request = self.requestDetails[_requestId]; return (_request.queryString,_request.dataSymbol,_request.queryHash, _request.apiUintVars[keccak256("granularity")],_request.apiUintVars[keccak256("requestQPosition")],_request.apiUintVars[keccak256("totalTip")]); } /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(TellorStorage.TellorStorageStruct storage self,address _staker) internal view returns(uint,uint){ return (self.stakerDetails[_staker].currentStatus,self.stakerDetails[_staker].startDate); } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(TellorStorage.TellorStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns(uint[5] memory){ return self.requestDetails[_requestId].valuesByTimestamp[_timestamp]; } /** * @dev Get the symbol of the token * @return string of the token symbol */ function getSymbol(TellorStorage.TellorStorageStruct storage self) internal pure returns(string memory){ return "TT"; } /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(TellorStorage.TellorStorageStruct storage self,uint _requestID, uint _index) internal view returns(uint){ return self.requestDetails[_requestID].requestTimestamps[_index]; } /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(TellorStorage.TellorStorageStruct storage self,bytes32 _data) view internal returns(uint){ return self.uintVars[_data]; } /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck(TellorStorage.TellorStorageStruct storage self) internal view returns(uint, uint,string memory){ uint newRequestId = getTopRequestID(self); return (newRequestId,self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")],self.requestDetails[newRequestId].queryString); } /** * @dev Getter function for the request with highest payout. This function is used within the getVariablesOnDeck function * @return uint _requestId of request with highest payout at the time the function is called */ function getTopRequestID(TellorStorage.TellorStorageStruct storage self) internal view returns(uint _requestId){ uint _max; uint _index; (_max,_index) = Utilities.getMax(self.requestQ); _requestId = self.requestIdByRequestQIndex[_index]; } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(TellorStorage.TellorStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns(bool){ return self.requestDetails[_requestId].inDispute[_timestamp]; } /** * @dev Retreive value from oracle based on requestId/timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return uint value for requestId/timestamp submitted */ function retrieveData(TellorStorage.TellorStorageStruct storage self, uint _requestId, uint _timestamp) internal view returns (uint) { return self.requestDetails[_requestId].finalValues[_timestamp]; } /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply(TellorStorage.TellorStorageStruct storage self) internal view returns (uint) { return self.uintVars[keccak256("total_supply")]; } } pragma solidity ^0.5.0; //Slightly modified SafeMath library - includes a min and max function, removes useless div function library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function add(int256 a, int256 b) internal pure returns (int256 c) { if(b > 0){ c = a + b; assert(c >= a); } else{ c = a + b; assert(c <= a); } } function max(uint a, uint b) internal pure returns (uint256) { return a > b ? a : b; } function max(int256 a, int256 b) internal pure returns (uint256) { return a > b ? uint(a) : uint(b); } function min(uint a, uint b) internal pure returns (uint256) { return a < b ? a : b; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function sub(int256 a, int256 b) internal pure returns (int256 c) { if(b > 0){ c = a - b; assert(c <= a); } else{ c = a - b; assert(c >= a); } } } /** * @title Tellor Oracle Storage Library * @dev Contains all the variables/structs used by Tellor */ library TellorStorage { //Internal struct for use in proof-of-work submission struct Details { uint value; address miner; } struct Dispute { bytes32 hash;//unique hash of dispute: keccak256(_miner,_requestId,_timestamp) int tally;//current tally of votes for - against measure bool executed;//is the dispute settled bool disputeVotePassed;//did the vote pass? bool isPropFork; //true for fork proposal NEW address reportedMiner; //miner who alledgedly submitted the 'bad value' will get disputeFee if dispute vote fails address reportingParty;//miner reporting the 'bad value'-pay disputeFee will get reportedMiner's stake if dispute vote passes address proposedForkAddress;//new fork address (if fork proposal) mapping(bytes32 => uint) disputeUintVars; //Each of the variables below is saved in the mapping disputeUintVars for each disputeID //e.g. TellorStorageStruct.DisputeById[disputeID].disputeUintVars[keccak256("requestId")] //These are the variables saved in this mapping: // uint keccak256("requestId");//apiID of disputed value // uint keccak256("timestamp");//timestamp of distputed value // uint keccak256("value"); //the value being disputed // uint keccak256("minExecutionDate");//7 days from when dispute initialized // uint keccak256("numberOfVotes");//the number of parties who have voted on the measure // uint keccak256("blockNumber");// the blocknumber for which votes will be calculated from // uint keccak256("minerSlot"); //index in dispute array // uint keccak256("quorum"); //quorum for dispute vote NEW // uint keccak256("fee"); //fee paid corresponding to dispute mapping (address => bool) voted; //mapping of address to whether or not they voted } struct StakeInfo { uint currentStatus;//0-not Staked, 1=Staked, 2=LockedForWithdraw 3= OnDispute uint startDate; //stake start date } //Internal struct to allow balances to be queried by blocknumber for voting purposes struct Checkpoint { uint128 fromBlock;// fromBlock is the block number that the value was generated from uint128 value;// value is the amount of tokens at a specific block number } struct Request { string queryString;//id to string api string dataSymbol;//short name for api request bytes32 queryHash;//hash of api string and granularity e.g. keccak256(abi.encodePacked(_sapi,_granularity)) uint[] requestTimestamps; //array of all newValueTimestamps requested mapping(bytes32 => uint) apiUintVars; //Each of the variables below is saved in the mapping apiUintVars for each api request //e.g. requestDetails[_requestId].apiUintVars[keccak256("totalTip")] //These are the variables saved in this mapping: // uint keccak256("granularity"); //multiplier for miners // uint keccak256("requestQPosition"); //index in requestQ // uint keccak256("totalTip");//bonus portion of payout mapping(uint => uint) minedBlockNum;//[apiId][minedTimestamp]=>block.number mapping(uint => uint) finalValues;//This the time series of finalValues stored by the contract where uint UNIX timestamp is mapped to value mapping(uint => bool) inDispute;//checks if API id is in dispute or finalized. mapping(uint => address[5]) minersByValue; mapping(uint => uint[5])valuesByTimestamp; } struct TellorStorageStruct { bytes32 currentChallenge; //current challenge to be solved uint[51] requestQ; //uint50 array of the top50 requests by payment amount uint[] newValueTimestamps; //array of all timestamps requested Details[5] currentMiners; //This struct is for organizing the five mined values to find the median mapping(bytes32 => address) addressVars; //Address fields in the Tellor contract are saved the addressVars mapping //e.g. addressVars[keccak256("tellorContract")] = address //These are the variables saved in this mapping: // address keccak256("tellorContract");//Tellor address // address keccak256("_owner");//Tellor Owner address // address keccak256("_deity");//Tellor Owner that can do things at will mapping(bytes32 => uint) uintVars; //uint fields in the Tellor contract are saved the uintVars mapping //e.g. uintVars[keccak256("decimals")] = uint //These are the variables saved in this mapping: // keccak256("decimals"); //18 decimal standard ERC20 // keccak256("disputeFee");//cost to dispute a mined value // keccak256("disputeCount");//totalHistoricalDisputes // keccak256("total_supply"); //total_supply of the token in circulation // keccak256("stakeAmount");//stakeAmount for miners (we can cut gas if we just hardcode it in...or should it be variable?) // keccak256("stakerCount"); //number of parties currently staked // keccak256("timeOfLastNewValue"); // time of last challenge solved // keccak256("difficulty"); // Difficulty of current block // keccak256("currentTotalTips"); //value of highest api/timestamp PayoutPool // keccak256("currentRequestId"); //API being mined--updates with the ApiOnQ Id // keccak256("requestCount"); // total number of requests through the system // keccak256("slotProgress");//Number of miners who have mined this value so far // keccak256("miningReward");//Mining Reward in PoWo tokens given to all miners per value // keccak256("timeTarget"); //The time between blocks (mined Oracle values) mapping(bytes32 => mapping(address=>bool)) minersByChallenge;//This is a boolean that tells you if a given challenge has been completed by a given miner mapping(uint => uint) requestIdByTimestamp;//minedTimestamp to apiId mapping(uint => uint) requestIdByRequestQIndex; //link from payoutPoolIndex (position in payout pool array) to apiId mapping(uint => Dispute) disputesById;//disputeId=> Dispute details mapping (address => Checkpoint[]) balances; //balances of a party given blocks mapping(address => mapping (address => uint)) allowed; //allowance for a given party and approver mapping(address => StakeInfo) stakerDetails;//mapping from a persons address to their staking info mapping(uint => Request) requestDetails;//mapping of apiID to details mapping(bytes32 => uint) requestIdByQueryHash;// api bytes32 gets an id = to count of requests array mapping(bytes32 => uint) disputeIdByDisputeHash;//maps a hash to an ID for each dispute } } /** * @title Tellor Transfer * @dev Contais the methods related to transfers and ERC20. Tellor.sol and TellorGetters.sol * reference this library for function's logic. */ library TellorTransfer { using SafeMath for uint256; event Approval(address indexed _owner, address indexed _spender, uint256 _value);//ERC20 Approval event event Transfer(address indexed _from, address indexed _to, uint256 _value);//ERC20 Transfer Event /*Functions*/ /** * @dev Allows for a transfer of tokens to _to * @param _to The address to send tokens to * @param _amount The amount of tokens to send * @return true if transfer is successful */ function transfer(TellorStorage.TellorStorageStruct storage self, address _to, uint256 _amount) public returns (bool success) { doTransfer(self,msg.sender, _to, _amount); return true; } /** * @notice Send _amount tokens to _to from _from on the condition it * is approved by _from * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The amount of tokens to be transferred * @return True if the transfer was successful */ function transferFrom(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public returns (bool success) { require(self.allowed[_from][msg.sender] >= _amount); self.allowed[_from][msg.sender] -= _amount; doTransfer(self,_from, _to, _amount); return true; } /** * @dev This function approves a _spender an _amount of tokens to use * @param _spender address * @param _amount amount the spender is being approved for * @return true if spender appproved successfully */ function approve(TellorStorage.TellorStorageStruct storage self, address _spender, uint _amount) public returns (bool) { require(_spender != address(0)); self.allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @param _user address of party with the balance * @param _spender address of spender of parties said balance * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(TellorStorage.TellorStorageStruct storage self,address _user, address _spender) public view returns (uint) { return self.allowed[_user][_spender]; } /** * @dev Completes POWO transfers by updating the balances on the current block number * @param _from address to transfer from * @param _to addres to transfer to * @param _amount to transfer */ function doTransfer(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint _amount) public { require(_amount > 0); require(_to != address(0)); require(allowedToTrade(self,_from,_amount)); //allowedToTrade checks the stakeAmount is removed from balance if the _user is staked uint previousBalance = balanceOfAt(self,_from, block.number); updateBalanceAtNow(self.balances[_from], previousBalance - _amount); previousBalance = balanceOfAt(self,_to, block.number); require(previousBalance + _amount >= previousBalance); // Check for overflow updateBalanceAtNow(self.balances[_to], previousBalance + _amount); emit Transfer(_from, _to, _amount); } /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(TellorStorage.TellorStorageStruct storage self,address _user) public view returns (uint) { return balanceOfAt(self,_user, block.number); } /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber specified */ function balanceOfAt(TellorStorage.TellorStorageStruct storage self,address _user, uint _blockNumber) public view returns (uint) { if ((self.balances[_user].length == 0) || (self.balances[_user][0].fromBlock > _blockNumber)) { return 0; } else { return getBalanceAt(self.balances[_user], _blockNumber); } } /** * @dev Getter for balance for owner on the specified _block number * @param checkpoints gets the mapping for the balances[owner] * @param _block is the block number to search the balance on * @return the balance at the checkpoint */ function getBalanceAt(TellorStorage.Checkpoint[] storage checkpoints, uint _block) view public returns (uint) { if (checkpoints.length == 0) return 0; 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 This function returns whether or not a given user is allowed to trade a given amount * and removing the staked amount from their balance if they are staked * @param _user address of user * @param _amount to check if the user can spend * @return true if they are allowed to spend the amount being checked */ function allowedToTrade(TellorStorage.TellorStorageStruct storage self,address _user,uint _amount) public view returns(bool) { if(self.stakerDetails[_user].currentStatus >0){ //Removes the stakeAmount from balance if the _user is staked if(balanceOf(self,_user).sub(self.uintVars[keccak256("stakeAmount")]).sub(_amount) >= 0){ return true; } } else if(balanceOf(self,_user).sub(_amount) >= 0){ return true; } return false; } /** * @dev Updates balance for from and to on the current block number via doTransfer * @param checkpoints gets the mapping for the balances[owner] * @param _value is the new balance */ function updateBalanceAtNow(TellorStorage.Checkpoint[] storage checkpoints, uint _value) public { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length -1].fromBlock < block.number)) { TellorStorage.Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { TellorStorage.Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } } //import "./SafeMath.sol"; /** * @title Tellor Dispute * @dev Contais the methods related to disputes. Tellor.sol references this library for function's logic. */ library TellorDispute { using SafeMath for uint256; using SafeMath for int256; event NewDispute(uint indexed _disputeId, uint indexed _requestId, uint _timestamp, address _miner);//emitted when a new dispute is initialized event Voted(uint indexed _disputeID, bool _position, address indexed _voter);//emitted when a new vote happens event DisputeVoteTallied(uint indexed _disputeID, int _result,address indexed _reportedMiner,address _reportingParty, bool _active);//emitted upon dispute tally event NewTellorAddress(address _newTellor); //emmited when a proposed fork is voted true /*Functions*/ /** * @dev Helps initialize a dispute by assigning it a disputeId * when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the * invalidated value information to POS voting * @param _requestId being disputed * @param _timestamp being disputed * @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value * requires 5 miners to submit a value. */ function beginDispute(TellorStorage.TellorStorageStruct storage self,uint _requestId, uint _timestamp,uint _minerIndex) public { TellorStorage.Request storage _request = self.requestDetails[_requestId]; //require that no more than a day( (24 hours * 60 minutes)/10minutes=144 blocks) has gone by since the value was "mined" require(now - _timestamp<= 1 days); require(_request.minedBlockNum[_timestamp] > 0); require(_minerIndex < 5); //_miner is the miner being disputed. For every mined value 5 miners are saved in an array and the _minerIndex //provided by the party initiating the dispute address _miner = _request.minersByValue[_timestamp][_minerIndex]; bytes32 _hash = keccak256(abi.encodePacked(_miner,_requestId,_timestamp)); //Ensures that a dispute is not already open for the that miner, requestId and timestamp require(self.disputeIdByDisputeHash[_hash] == 0); TellorTransfer.doTransfer(self, msg.sender,address(this), self.uintVars[keccak256("disputeFee")]); //Increase the dispute count by 1 self.uintVars[keccak256("disputeCount")] = self.uintVars[keccak256("disputeCount")] + 1; //Sets the new disputeCount as the disputeId uint disputeId = self.uintVars[keccak256("disputeCount")]; //maps the dispute hash to the disputeId self.disputeIdByDisputeHash[_hash] = disputeId; //maps the dispute to the Dispute struct self.disputesById[disputeId] = TellorStorage.Dispute({ hash:_hash, isPropFork: false, reportedMiner: _miner, reportingParty: msg.sender, proposedForkAddress:address(0), executed: false, disputeVotePassed: false, tally: 0 }); //Saves all the dispute variables for the disputeId self.disputesById[disputeId].disputeUintVars[keccak256("requestId")] = _requestId; self.disputesById[disputeId].disputeUintVars[keccak256("timestamp")] = _timestamp; self.disputesById[disputeId].disputeUintVars[keccak256("value")] = _request.valuesByTimestamp[_timestamp][_minerIndex]; self.disputesById[disputeId].disputeUintVars[keccak256("minExecutionDate")] = now + 7 days; self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number; self.disputesById[disputeId].disputeUintVars[keccak256("minerSlot")] = _minerIndex; self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = self.uintVars[keccak256("disputeFee")]; //Values are sorted as they come in and the official value is the median of the first five //So the "official value" miner is always minerIndex==2. If the official value is being //disputed, it sets its status to inDispute(currentStatus = 3) so that users are made aware it is under dispute if(_minerIndex == 2){ self.requestDetails[_requestId].inDispute[_timestamp] = true; } self.stakerDetails[_miner].currentStatus = 3; emit NewDispute(disputeId,_requestId,_timestamp,_miner); } /** * @dev Allows token holders to vote * @param _disputeId is the dispute id * @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute) */ function vote(TellorStorage.TellorStorageStruct storage self, uint _disputeId, bool _supportsDispute) public { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; //Get the voteWeight or the balance of the user at the time/blockNumber the disupte began uint voteWeight = TellorTransfer.balanceOfAt(self,msg.sender,disp.disputeUintVars[keccak256("blockNumber")]); //Require that the msg.sender has not voted require(disp.voted[msg.sender] != true); //Requre that the user had a balance >0 at time/blockNumber the disupte began require(voteWeight > 0); //ensures miners that are under dispute cannot vote require(self.stakerDetails[msg.sender].currentStatus != 3); //Update user voting status to true disp.voted[msg.sender] = true; //Update the number of votes for the dispute disp.disputeUintVars[keccak256("numberOfVotes")] += 1; //Update the quorum by adding the voteWeight disp.disputeUintVars[keccak256("quorum")] += voteWeight; //If the user supports the dispute increase the tally for the dispute by the voteWeight //otherwise decrease it if (_supportsDispute) { disp.tally = disp.tally.add(int(voteWeight)); } else { disp.tally = disp.tally.sub(int(voteWeight)); } //Let the network know the user has voted on the dispute and their casted vote emit Voted(_disputeId,_supportsDispute,msg.sender); } /** * @dev tallies the votes. * @param _disputeId is the dispute id */ function tallyVotes(TellorStorage.TellorStorageStruct storage self, uint _disputeId) public { TellorStorage.Dispute storage disp = self.disputesById[_disputeId]; TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]]; //Ensure this has not already been executed/tallied require(disp.executed == false); //Ensure the time for voting has elapsed require(now > disp.disputeUintVars[keccak256("minExecutionDate")]); //If the vote is not a proposed fork if (disp.isPropFork== false){ TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner]; //If the vote for disputing a value is succesful(disp.tally >0) then unstake the reported // miner and transfer the stakeAmount and dispute fee to the reporting party if (disp.tally > 0 ) { //Changing the currentStatus and startDate unstakes the reported miner and allows for the //transfer of the stakeAmount stakes.currentStatus = 0; stakes.startDate = now -(now % 86400); //Decreases the stakerCount since the miner's stake is being slashed self.uintVars[keccak256("stakerCount")]--; updateDisputeFee(self); //Transfers the StakeAmount from the reporded miner to the reporting party TellorTransfer.doTransfer(self, disp.reportedMiner,disp.reportingParty, self.uintVars[keccak256("stakeAmount")]); //Returns the dispute fee to the reportingParty TellorTransfer.doTransfer(self, address(this),disp.reportingParty,disp.disputeUintVars[keccak256("fee")]); //Set the dispute state to passed/true disp.disputeVotePassed = true; //If the dispute was succeful(miner found guilty) then update the timestamp value to zero //so that users don't use this datapoint if(_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] == true){ _request.finalValues[disp.disputeUintVars[keccak256("timestamp")]] = 0; } //If the vote for disputing a value is unsuccesful then update the miner status from being on //dispute(currentStatus=3) to staked(currentStatus =1) and tranfer the dispute fee to the miner } else { //Update the miner's current status to staked(currentStatus = 1) stakes.currentStatus = 1; //tranfer the dispute fee to the miner TellorTransfer.doTransfer(self,address(this),disp.reportedMiner,disp.disputeUintVars[keccak256("fee")]); if(_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] == true){ _request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] = false; } } //If the vote is for a proposed fork require a 20% quorum before excecuting the update to the new tellor contract address } else { if(disp.tally > 0 ){ require(disp.disputeUintVars[keccak256("quorum")] > (self.uintVars[keccak256("total_supply")] * 20 / 100)); self.addressVars[keccak256("tellorContract")] = disp.proposedForkAddress; disp.disputeVotePassed = true; emit NewTellorAddress(disp.proposedForkAddress); } } //update the dispute status to executed disp.executed = true; emit DisputeVoteTallied(_disputeId,disp.tally,disp.reportedMiner,disp.reportingParty,disp.disputeVotePassed); } /** * @dev Allows for a fork to be proposed * @param _propNewTellorAddress address for new proposed Tellor */ function proposeFork(TellorStorage.TellorStorageStruct storage self, address _propNewTellorAddress) public { bytes32 _hash = keccak256(abi.encodePacked(_propNewTellorAddress)); require(self.disputeIdByDisputeHash[_hash] == 0); TellorTransfer.doTransfer(self, msg.sender,address(this), self.uintVars[keccak256("disputeFee")]);//This is the fork fee self.uintVars[keccak256("disputeCount")]++; uint disputeId = self.uintVars[keccak256("disputeCount")]; self.disputeIdByDisputeHash[_hash] = disputeId; self.disputesById[disputeId] = TellorStorage.Dispute({ hash: _hash, isPropFork: true, reportedMiner: msg.sender, reportingParty: msg.sender, proposedForkAddress: _propNewTellorAddress, executed: false, disputeVotePassed: false, tally: 0 }); self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number; self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = self.uintVars[keccak256("disputeFee")]; self.disputesById[disputeId].disputeUintVars[keccak256("minExecutionDate")] = now + 7 days; } /** * @dev this function allows the dispute fee to fluctuate based on the number of miners on the system. * The floor for the fee is 15e18. */ function updateDisputeFee(TellorStorage.TellorStorageStruct storage self) public { //if the number of staked miners divided by the target count of staked miners is less than 1 if(self.uintVars[keccak256("stakerCount")]*1000/self.uintVars[keccak256("targetMiners")] < 1000){ //Set the dispute fee at stakeAmt * (1- stakerCount/targetMiners) //or at the its minimum of 15e18 self.uintVars[keccak256("disputeFee")] = SafeMath.max(15e18,self.uintVars[keccak256("stakeAmount")].mul(1000 - self.uintVars[keccak256("stakerCount")]*1000/self.uintVars[keccak256("targetMiners")])/1000); } else{ //otherwise set the dispute fee at 15e18 (the floor/minimum fee allowed) self.uintVars[keccak256("disputeFee")] = 15e18; } } } /** * itle Tellor Dispute * @dev Contais the methods related to miners staking and unstaking. Tellor.sol * references this library for function's logic. */ library TellorStake { event NewStake(address indexed _sender);//Emits upon new staker event StakeWithdrawn(address indexed _sender);//Emits when a staker is now no longer staked event StakeWithdrawRequested(address indexed _sender);//Emits when a staker begins the 7 day withdraw period /*Functions*/ /** * @dev This function stakes the five initial miners, sets the supply and all the constant variables. * This function is called by the constructor function on TellorMaster.sol */ function init(TellorStorage.TellorStorageStruct storage self) public{ require(self.uintVars[keccak256("decimals")] == 0); //Give this contract 6000 Tellor Tributes so that it can stake the initial 6 miners TellorTransfer.updateBalanceAtNow(self.balances[address(this)], 2**256-1 - 6000e18); // //the initial 5 miner addresses are specfied below // //changed payable[5] to 6 address payable[6] memory _initalMiners = [address(0x4c49172A499D18eA3093D59A304eEF63F9754e25), address(0xbfc157b09346AC15873160710B00ec8d4d520C5a), address(0xa3792188E76c55b1A649fE5Df77DDd4bFD6D03dB), address(0xbAF31Bbbba24AF83c8a7a76e16E109d921E4182a), address(0x8c9841fEaE5Fc2061F2163033229cE0d9DfAbC71), address(0xc31Ef608aDa4003AaD4D2D1ec2Be72232A9E2A86)]; //Stake each of the 5 miners specified above for(uint i=0;i<6;i++){//6th miner to allow for dispute //Miner balance is set at 1000e18 at the block that this function is ran TellorTransfer.updateBalanceAtNow(self.balances[_initalMiners[i]],1000e18); newStake(self, _initalMiners[i]); } //update the total suppply self.uintVars[keccak256("total_supply")] += 6000e18;//6th miner to allow for dispute //set Constants self.uintVars[keccak256("decimals")] = 18; self.uintVars[keccak256("targetMiners")] = 200; self.uintVars[keccak256("stakeAmount")] = 1000e18; self.uintVars[keccak256("disputeFee")] = 970e18; self.uintVars[keccak256("timeTarget")]= 600; self.uintVars[keccak256("timeOfLastNewValue")] = now - now % self.uintVars[keccak256("timeTarget")]; self.uintVars[keccak256("difficulty")] = 1; } /** * @dev This function allows stakers to request to withdraw their stake (no longer stake) * once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they * can withdraw the deposit */ function requestStakingWithdraw(TellorStorage.TellorStorageStruct storage self) public { TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender]; //Require that the miner is staked require(stakes.currentStatus == 1); //Change the miner staked to locked to be withdrawStake stakes.currentStatus = 2; //Change the startDate to now since the lock up period begins now //and the miner can only withdraw 7 days later from now(check the withdraw function) stakes.startDate = now -(now % 86400); //Reduce the staker count self.uintVars[keccak256("stakerCount")] -= 1; TellorDispute.updateDisputeFee(self); emit StakeWithdrawRequested(msg.sender); } /** * @dev This function allows users to withdraw their stake after a 7 day waiting period from request */ function withdrawStake(TellorStorage.TellorStorageStruct storage self) public { TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender]; //Require the staker has locked for withdraw(currentStatus ==2) and that 7 days have //passed by since they locked for withdraw require(now - (now % 86400) - stakes.startDate >= 7 days); require(stakes.currentStatus == 2); stakes.currentStatus = 0; emit StakeWithdrawn(msg.sender); } /** * @dev This function allows miners to deposit their stake. */ function depositStake(TellorStorage.TellorStorageStruct storage self) public { newStake(self, msg.sender); //self adjusting disputeFee TellorDispute.updateDisputeFee(self); } /** * @dev This function is used by the init function to succesfully stake the initial 5 miners. * The function updates their status/state and status start date so they are locked it so they can't withdraw * and updates the number of stakers in the system. */ function newStake(TellorStorage.TellorStorageStruct storage self, address staker) internal { require(TellorTransfer.balanceOf(self,staker) >= self.uintVars[keccak256("stakeAmount")]); //Ensure they can only stake if they are not currrently staked or if their stake time frame has ended //and they are currently locked for witdhraw require(self.stakerDetails[staker].currentStatus == 0 || self.stakerDetails[staker].currentStatus == 2); self.uintVars[keccak256("stakerCount")] += 1; self.stakerDetails[staker] = TellorStorage.StakeInfo({ currentStatus: 1, //this resets their stake start date to today startDate: now - (now % 86400) }); emit NewStake(staker); } } /** * @title Tellor Getters * @dev Oracle contract with all tellor getter functions. The logic for the functions on this contract * is saved on the TellorGettersLibrary, TellorTransfer, TellorGettersLibrary, and TellorStake */ contract TellorGetters{ using SafeMath for uint256; using TellorTransfer for TellorStorage.TellorStorageStruct; using TellorGettersLibrary for TellorStorage.TellorStorageStruct; using TellorStake for TellorStorage.TellorStorageStruct; TellorStorage.TellorStorageStruct tellor; /** * @param _user address * @param _spender address * @return Returns the remaining allowance of tokens granted to the _spender from the _user */ function allowance(address _user, address _spender) external view returns (uint) { return tellor.allowance(_user,_spender); } /** * @dev This function returns whether or not a given user is allowed to trade a given amount * @param _user address * @param _amount uint of amount * @return true if the user is alloed to trade the amount specified */ function allowedToTrade(address _user,uint _amount) external view returns(bool){ return tellor.allowedToTrade(_user,_amount); } /** * @dev Gets balance of owner specified * @param _user is the owner address used to look up the balance * @return Returns the balance associated with the passed in _user */ function balanceOf(address _user) external view returns (uint) { return tellor.balanceOf(_user); } /** * @dev Queries the balance of _user at a specific _blockNumber * @param _user The address from which the balance will be retrieved * @param _blockNumber The block number when the balance is queried * @return The balance at _blockNumber */ function balanceOfAt(address _user, uint _blockNumber) external view returns (uint) { return tellor.balanceOfAt(_user,_blockNumber); } /** * @dev This function tells you if a given challenge has been completed by a given miner * @param _challenge the challenge to search for * @param _miner address that you want to know if they solved the challenge * @return true if the _miner address provided solved the */ function didMine(bytes32 _challenge, address _miner) external view returns(bool){ return tellor.didMine(_challenge,_miner); } /** * @dev Checks if an address voted in a given dispute * @param _disputeId to look up * @param _address to look up * @return bool of whether or not party voted */ function didVote(uint _disputeId, address _address) external view returns(bool){ return tellor.didVote(_disputeId,_address); } /** * @dev allows Tellor to read data from the addressVars mapping * @param _data is the keccak256("variable_name") of the variable that is being accessed. * These are examples of how the variables are saved within other functions: * addressVars[keccak256("_owner")] * addressVars[keccak256("tellorContract")] */ function getAddressVars(bytes32 _data) view external returns(address){ return tellor.getAddressVars(_data); } /** * @dev Gets all dispute variables * @param _disputeId to look up * @return bytes32 hash of dispute * @return bool executed where true if it has been voted on * @return bool disputeVotePassed * @return bool isPropFork true if the dispute is a proposed fork * @return address of reportedMiner * @return address of reportingParty * @return address of proposedForkAddress * @return uint of requestId * @return uint of timestamp * @return uint of value * @return uint of minExecutionDate * @return uint of numberOfVotes * @return uint of blocknumber * @return uint of minerSlot * @return uint of quorum * @return uint of fee * @return int count of the current tally */ function getAllDisputeVars(uint _disputeId) public view returns(bytes32, bool, bool, bool, address, address, address,uint[9] memory, int){ return tellor.getAllDisputeVars(_disputeId); } /** * @dev Getter function for variables for the requestId being currently mined(currentRequestId) * @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request */ function getCurrentVariables() external view returns(bytes32, uint, uint,string memory,uint,uint){ return tellor.getCurrentVariables(); } /** * @dev Checks if a given hash of miner,requestId has been disputed * @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId)); * @return uint disputeId */ function getDisputeIdByDisputeHash(bytes32 _hash) external view returns(uint){ return tellor.getDisputeIdByDisputeHash(_hash); } /** * @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId * @param _disputeId is the dispute id; * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the disputeUintVars under the Dispute struct * @return uint value for the bytes32 data submitted */ function getDisputeUintVars(uint _disputeId,bytes32 _data) external view returns(uint){ return tellor.getDisputeUintVars(_disputeId,_data); } /** * @dev Gets the a value for the latest timestamp available * @return value for timestamp of last proof of work submited * @return true if the is a timestamp for the lastNewValue */ function getLastNewValue() external view returns(uint,bool){ return tellor.getLastNewValue(); } /** * @dev Gets the a value for the latest timestamp available * @param _requestId being requested * @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't */ function getLastNewValueById(uint _requestId) external view returns(uint,bool){ return tellor.getLastNewValueById(_requestId); } /** * @dev Gets blocknumber for mined timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up blocknumber * @return uint of the blocknumber which the dispute was mined */ function getMinedBlockNum(uint _requestId, uint _timestamp) external view returns(uint){ return tellor.getMinedBlockNum(_requestId,_timestamp); } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return the 5 miners' addresses */ function getMinersByRequestIdAndTimestamp(uint _requestId, uint _timestamp) external view returns(address[5] memory){ return tellor.getMinersByRequestIdAndTimestamp(_requestId,_timestamp); } /** * @dev Get the name of the token * return string of the token name */ function getName() external view returns(string memory){ return tellor.getName(); } /** * @dev Counts the number of values that have been submited for the request * if called for the currentRequest being mined it can tell you how many miners have submitted a value for that * request so far * @param _requestId the requestId to look up * @return uint count of the number of values received for the requestId */ function getNewValueCountbyRequestId(uint _requestId) external view returns(uint){ return tellor.getNewValueCountbyRequestId(_requestId); } /** * @dev Getter function for the specified requestQ index * @param _index to look up in the requestQ array * @return uint of reqeuestId */ function getRequestIdByRequestQIndex(uint _index) external view returns(uint){ return tellor.getRequestIdByRequestQIndex(_index); } /** * @dev Getter function for requestId based on timestamp * @param _timestamp to check requestId * @return uint of reqeuestId */ function getRequestIdByTimestamp(uint _timestamp) external view returns(uint){ return tellor.getRequestIdByTimestamp(_timestamp); } /** * @dev Getter function for requestId based on the queryHash * @param _request is the hash(of string api and granularity) to check if a request already exists * @return uint requestId */ function getRequestIdByQueryHash(bytes32 _request) external view returns(uint){ return tellor.getRequestIdByQueryHash(_request); } /** * @dev Getter function for the requestQ array * @return the requestQ arrray */ function getRequestQ() view public returns(uint[51] memory){ return tellor.getRequestQ(); } /** * @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct * for the requestId specified * @param _requestId to look up * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the apiUintVars under the requestDetails struct * @return uint value of the apiUintVars specified in _data for the requestId specified */ function getRequestUintVars(uint _requestId,bytes32 _data) external view returns(uint){ return tellor.getRequestUintVars(_requestId,_data); } /** * @dev Gets the API struct variables that are not mappings * @param _requestId to look up * @return string of api to query * @return string of symbol of api to query * @return bytes32 hash of string * @return bytes32 of the granularity(decimal places) requested * @return uint of index in requestQ array * @return uint of current payout/tip for this requestId */ function getRequestVars(uint _requestId) external view returns(string memory, string memory,bytes32,uint, uint, uint) { return tellor.getRequestVars(_requestId); } /** * @dev This function allows users to retireve all information about a staker * @param _staker address of staker inquiring about * @return uint current state of staker * @return uint startDate of staking */ function getStakerInfo(address _staker) external view returns(uint,uint){ return tellor.getStakerInfo(_staker); } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestampt to look up miners for * @return address[5] array of 5 addresses ofminers that mined the requestId */ function getSubmissionsByTimestamp(uint _requestId, uint _timestamp) external view returns(uint[5] memory){ return tellor.getSubmissionsByTimestamp(_requestId,_timestamp); } /** * @dev Get the symbol of the token * return string of the token symbol */ function getSymbol() external view returns(string memory){ return tellor.getSymbol(); } /** * @dev Gets the timestamp for the value based on their index * @param _requestID is the requestId to look up * @param _index is the value index to look up * @return uint timestamp */ function getTimestampbyRequestIDandIndex(uint _requestID, uint _index) external view returns(uint){ return tellor.getTimestampbyRequestIDandIndex(_requestID,_index); } /** * @dev Getter for the variables saved under the TellorStorageStruct uintVars variable * @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is * the variables/strings used to save the data in the mapping. The variables names are * commented out under the uintVars under the TellorStorageStruct struct * This is an example of how data is saved into the mapping within other functions: * self.uintVars[keccak256("stakerCount")] * @return uint of specified variable */ function getUintVar(bytes32 _data) view public returns(uint){ return tellor.getUintVar(_data); } /** * @dev Getter function for next requestId on queue/request with highest payout at time the function is called * @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string */ function getVariablesOnDeck() external view returns(uint, uint,string memory){ return tellor.getVariablesOnDeck(); } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @param _requestId to look up * @param _timestamp is the timestamp to look up miners for * @return bool true if requestId/timestamp is under dispute */ function isInDispute(uint _requestId, uint _timestamp) external view returns(bool){ return tellor.isInDispute(_requestId,_timestamp); } /** * @dev Retreive value from oracle based on timestamp * @param _requestId being requested * @param _timestamp to retreive data/value from * @return value for timestamp submitted */ function retrieveData(uint _requestId, uint _timestamp) external view returns (uint) { return tellor.retrieveData(_requestId,_timestamp); } /** * @dev Getter for the total_supply of oracle tokens * @return uint total supply */ function totalSupply() external view returns (uint) { return tellor.totalSupply(); } } /** * @title Tellor Master * @dev This is the Master contract with all tellor getter functions and delegate call to Tellor. * The logic for the functions on this contract is saved on the TellorGettersLibrary, TellorTransfer, * TellorGettersLibrary, and TellorStake */ contract TellorMaster is TellorGetters{ event NewTellorAddress(address _newTellor); /** * @dev The constructor sets the original `tellorStorageOwner` of the contract to the sender * account, the tellor contract to the Tellor master address and owner to the Tellor master owner address * @param _tellorContract is the address for the tellor contract */ constructor (address _tellorContract) public{ tellor.init(); tellor.addressVars[keccak256("_owner")] = msg.sender; tellor.addressVars[keccak256("_deity")] = msg.sender; tellor.addressVars[keccak256("tellorContract")]= _tellorContract; emit NewTellorAddress(_tellorContract); } /** * @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp * @dev Only needs to be in library * @param _newDeity the new Deity in the contract */ function changeDeity(address _newDeity) external{ tellor.changeDeity(_newDeity); } /** * @dev allows for the deity to make fast upgrades. Deity should be 0 address if decentralized * @param _tellorContract the address of the new Tellor Contract */ function changeTellorContract(address _tellorContract) external{ tellor.changeTellorContract(_tellorContract); } /** * @dev This is the fallback function that allows contracts to call the tellor contract at the address stored */ function () external payable { address addr = tellor.addressVars[keccak256("tellorContract")]; bytes memory _calldata = msg.data; assembly { let result := delegatecall(not(0), addr, add(_calldata, 0x20), mload(_calldata), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } }
Gets the API struct variables that are not mappings _requestId to look up return string of api to query return string of symbol of api to query return bytes32 hash of string return bytes32 of the granularity(decimal places) requested return uint of index in requestQ array return uint of current payout/tip for this requestId/
function getRequestVars(TellorStorage.TellorStorageStruct storage self,uint _requestId) internal view returns(string memory,string memory, bytes32,uint, uint, uint) { TellorStorage.Request storage _request = self.requestDetails[_requestId]; return (_request.queryString,_request.dataSymbol,_request.queryHash, _request.apiUintVars[keccak256("granularity")],_request.apiUintVars[keccak256("requestQPosition")],_request.apiUintVars[keccak256("totalTip")]); }
12,548,463
./full_match/42161/0xadb79a02839f4DA7Bdf37ed1e89177864c70B440/sources/ArbOtc.sol
Allows the creator of a trade offer to cancel it Returns the collateral locked by the creator and marks the offer as inactive tradeId The ID of the trade offer to cancel
function cancelOffer(uint256 tradeId) public nonReentrant { TradeOffer storage offer = tradeOffers[tradeId]; require(offer.active, "Offer accepted or cancelled"); require(offer.creator == msg.sender, "Not your offer"); require(tx.origin == msg.sender, "EOA only"); require(!EMERGENCY_WITHDRAWL, "Emergency withdrawl enabled"); uint256 collateral = ((offer.costPerToken * offer.tokens) * 25 / 100); offer.active = false; USDCDeposited[msg.sender] -= collateral; IERC20(USDC_ADDRESS).transfer( msg.sender, collateral ); emit TradeOfferCancelled(tradeId); }
16,307,749
// SPDX-License-Identifier: MIT pragma solidity ^0.6.1; import "./AdminManager.sol"; import "./Verifier.sol"; import {GLibrary} from "./GLibrary.sol"; /// @title GardenManager contract /// @author Aymeric NOEL <[email protected]> /// @notice this contract is used to automatically manage the rental of gardens directly between owners and tenants contract GardenManager { Verifier public VerifierContract; AdminManager public AManager; uint public GardenCount; mapping (uint=>GLibrary.Garden) public AllGarden; /// @dev This variable is used to retrieve the tenant's public key once he/she has signed this. bytes7 public signMe = "sign me"; /// @dev Emitted when a new garden is created /// @param _owner garden's owner /// @param _gardenIndex garden index event NewGarden(address _owner, uint _gardenIndex); constructor (address _adminContract, address _verifierContract) public { AManager = AdminManager(_adminContract); VerifierContract = Verifier(_verifierContract); } modifier OnlyContractAdmin { require(msg.sender == address(AManager), "Not administrator contract"); _; } modifier OnlyOwner(uint gardenIndex){ require(AllGarden[gardenIndex].owner==msg.sender, "Not garden owner"); _; } modifier OnlyValidProof(uint _gardenIndex, uint[2] memory _proofA, uint[2][2] memory _proofB, uint[2] memory _proofC){ require(VerifierContract.verifyTx(_proofA,_proofB,_proofC,AllGarden[_gardenIndex].secretHash), "Proof of secret invalid"); _; } function getGardenById(uint _gardenIndex)external view returns(address payable owner, bool multipleOwners, address payable[] memory coOwners, GLibrary.GardenType gardenType, string memory district, uint32 area, uint[2] memory secretHash, string memory contact, GLibrary.Status status, uint rentLength){ GLibrary.Garden memory garden = AllGarden[_gardenIndex]; return (garden.owner, garden.multipleOwners, garden.coOwners, garden.gardenType, garden.district,garden.area, garden.secretHash, garden.contact,garden.status, garden.rents.length); } function getRentByGardenAndRentId(uint _gardenIndex, uint _rentId) external view returns(int rate, uint duration, uint price, uint beginning, uint balance, address payable tenant, bytes memory signature, bytes32 gardenHashCode){ GLibrary.Rent memory rent = AllGarden[_gardenIndex].rents[_rentId]; return(rent.rate,rent.duration,rent.price,rent.beginning,rent.balance,rent.tenant,rent.signature,rent.accessCode.hashCode); } function getAccessCodeByGardenId(uint _gardenIndex)external view returns(string memory encryptedCode){ GLibrary.Rent memory rent = getLastRentForGarden(_gardenIndex); require(msg.sender==rent.tenant || msg.sender==AllGarden[_gardenIndex].owner,"Caller must be the tenant or the owner"); return(rent.accessCode.encryptedCode); } function modifyVerifierContract(address _verifierContract) public OnlyContractAdmin returns(address){ VerifierContract = Verifier(_verifierContract); return _verifierContract; } /// @dev Use this function to add a new garden. /// @param _secretHash hash of the user' secret; must be in decimal form int[2] /// @param _district district of the garden /// @param _area area of the garden /// @param _contact contact of the owner /// @param _gardenType gardenType of the garden /// @param _multipleOwners boolean that represents multiple owners for a garden or not /// @param _coOwners in case of multiple owners : all owners' addresses, could be empty function createGarden(uint[2] calldata _secretHash, string calldata _district,uint32 _area, string calldata _contact, GLibrary.GardenType _gardenType, bool _multipleOwners, address payable[] calldata _coOwners) external{ GardenCount++; GLibrary.Garden storage garden = AllGarden[GardenCount]; garden.area=_area; garden.contact=_contact; garden.gardenType=_gardenType; garden.secretHash=_secretHash; garden.district=_district; garden.status=GLibrary.Status.Waiting; garden.owner=msg.sender; if(_multipleOwners){ garden.multipleOwners=true; garden.coOwners=_coOwners; } AManager.addGarden(GardenCount, _secretHash); emit NewGarden(msg.sender, GardenCount); } /// @dev Use this function to update the contact of a garden. /// The caller must be the garden's owner. /// @param _gardenIndex the Id of the garden /// @param _contact the new contact of the garden function updateGardenContact(uint _gardenIndex, string calldata _contact) external OnlyOwner(_gardenIndex) { AllGarden[_gardenIndex].contact =_contact; } /// @dev Use this function to update the secret of the secret of a garden. /// The caller must be the garden's owner and must prove it by sending the preimage of the secret hash. /// @param _gardenIndex the Id of the garden /// @param _proofA the first part of the proof /// @param _proofB the second part of the proof /// @param _proofC the third part of the proof /// @param _newSecretHash the new hash of the secret's garden function updateGardenSecretHash(uint _gardenIndex, uint[2] calldata _proofA, uint[2][2] calldata _proofB, uint[2] calldata _proofC, uint[2] calldata _newSecretHash) external OnlyOwner(_gardenIndex) OnlyValidProof(_gardenIndex,_proofA,_proofB,_proofC){ AllGarden[_gardenIndex].secretHash =_newSecretHash; } /// @dev Use this function to accept a new garden and open it to location. /// The caller must be the admin contract. /// @param _gardenIndex the Id of the garden function acceptGarden(uint _gardenIndex) public OnlyContractAdmin { AllGarden[_gardenIndex].status= GLibrary.Status.Free; } /// @dev Use this function to reject a new garden and blacklist it. /// The caller must be the admin contract. /// @param _gardenIndex the Id of the garden function rejectGarden(uint _gardenIndex) public OnlyContractAdmin{ AllGarden[_gardenIndex].status= GLibrary.Status.Blacklist; } function getLastRentForGarden(uint _gardenIndex) private view returns(GLibrary.Rent storage){ return AllGarden[_gardenIndex].rents[AllGarden[_gardenIndex].rents.length-1]; } /// @dev Use this function to propose a new location offer. /// The caller must be the owner, after agreement with the tenant offchain. /// @param _gardenIndex the Id of the garden /// @param _tenant tenant's garden /// @param _rentingDuration duration of the location /// @param _price price of the location /// @param _proofA the first part of the proof /// @param _proofB the second part of the proof /// @param _proofC the third part of the proof function proposeGardenOffer(uint _gardenIndex, address payable _tenant, uint _rentingDuration, uint _price, uint[2] calldata _proofA, uint[2][2] calldata _proofB, uint[2] calldata _proofC) external OnlyOwner(_gardenIndex) OnlyValidProof(_gardenIndex,_proofA,_proofB,_proofC){ require(AllGarden[_gardenIndex].status==GLibrary.Status.Free, "Garden not free"); GLibrary.Garden storage garden = AllGarden[_gardenIndex]; garden.status= GLibrary.Status.Blocked; garden.rents.push(); GLibrary.Rent storage lastRent = getLastRentForGarden(_gardenIndex); lastRent.duration=_rentingDuration; lastRent.price=_price; lastRent.tenant=_tenant; lastRent.rate=-1; } /// @dev Use this function to delete an offer that has not received any response. /// Ownly the garden's owner could call and only if an offer is running. /// @param _gardenIndex the Id of the garden /// @param _proofA the first part of the proof /// @param _proofB the second part of the proof /// @param _proofC the third part of the proof function deleteGardenOffer(uint _gardenIndex, uint[2] calldata _proofA, uint[2][2] calldata _proofB, uint[2] calldata _proofC) external OnlyOwner(_gardenIndex) OnlyValidProof(_gardenIndex,_proofA,_proofB,_proofC){ require(AllGarden[_gardenIndex].status== GLibrary.Status.Blocked,"No offer running"); AllGarden[_gardenIndex].status= GLibrary.Status.Free; AllGarden[_gardenIndex].rents.pop(); } /// @dev Use this function to accept a location offer. /// Caller must be the tenant. /// @param _gardenIndex the Id of the garden /// @param _signature the signature of the parameter @signMe, used by the owner to encrypt garden access code function acceptGardenOffer(uint _gardenIndex, bytes calldata _signature)external payable{ GLibrary.Garden storage garden = AllGarden[_gardenIndex]; GLibrary.Rent storage lastRent = getLastRentForGarden(_gardenIndex); require(garden.status== GLibrary.Status.Blocked, "No offer running"); require(lastRent.tenant== msg.sender, "Not the correct tenant"); require(lastRent.price <= msg.value, "Insufficient amount"); lastRent.balance=msg.value; lastRent.signature=_signature; garden.status=GLibrary.Status.CodeWaiting; } /// @dev Use this function to add access code to a garden. /// The caller must be the garden's owner and prove it. /// @param _gardenIndex the Id of the garden /// @param _proofA the first part of the proof /// @param _proofB the second part of the proof /// @param _proofC the third part of the proof /// @param _hashCode the hash of the access code /// @param _encryptedCode the code encrypted with the tenant's public key function addAccessCodeToGarden(uint _gardenIndex, uint[2] memory _proofA, uint[2][2] memory _proofB, uint[2] memory _proofC, bytes32 _hashCode,string memory _encryptedCode) public OnlyOwner(_gardenIndex) OnlyValidProof(_gardenIndex,_proofA,_proofB,_proofC){ require(AllGarden[_gardenIndex].status==GLibrary.Status.CodeWaiting,"No location running"); GLibrary.Garden storage garden = AllGarden[_gardenIndex]; GLibrary.Rent storage lastRent = getLastRentForGarden(_gardenIndex); lastRent.beginning=block.timestamp; lastRent.accessCode=GLibrary.AccessCode(_hashCode,_encryptedCode); garden.status=GLibrary.Status.Location; } /// @dev Use this function to get refund and to cancel a location only if access code is missing. /// @param _gardenIndex the Id of the garden function getRefundBeforeLocation(uint _gardenIndex) external { require(AllGarden[_gardenIndex].status==GLibrary.Status.CodeWaiting,"Code is not missing"); GLibrary.Rent storage lastRent = getLastRentForGarden(_gardenIndex); require(lastRent.tenant==msg.sender,"Not the tenant"); uint balance = lastRent.balance; AllGarden[_gardenIndex].status=GLibrary.Status.Free; lastRent.balance =0; msg.sender.transfer(balance); } function transferPaymentToMultipleOwners(uint _amount, GLibrary.Garden memory _garden) internal { for (uint i = 0; i < _garden.coOwners.length; i++) { _garden.coOwners[i].transfer(_amount); } } /// @dev Use the function to update location status after location and get payment. /// The caller must be the garden's owner. /// @param _gardenIndex the Id of the garden /// @param _proofA the first part of the proof /// @param _proofB the second part of the proof /// @param _proofC the third part of the proof function updateLocationStatusAndGetPayment(uint _gardenIndex, uint[2] calldata _proofA, uint[2][2] calldata _proofB, uint[2] calldata _proofC)external OnlyOwner(_gardenIndex) OnlyValidProof(_gardenIndex,_proofA,_proofB,_proofC){ GLibrary.Rent storage lastRent = getLastRentForGarden(_gardenIndex); GLibrary.Garden storage garden = AllGarden[_gardenIndex]; require(garden.status!= GLibrary.Status.Dispute, "Dispute is running"); require(isRentOver(lastRent.beginning,lastRent.duration),"Location not over"); uint balance = lastRent.balance; lastRent.balance=0; lastRent.accessCode.hashCode= 0; AllGarden[_gardenIndex].status=GLibrary.Status.Free; if(garden.multipleOwners){ uint payroll = balance/garden.coOwners.length; transferPaymentToMultipleOwners(payroll,garden); }else{ garden.owner.transfer(balance); } } /// @dev Tenant should use this function to add a grade to his locations between 1 and 5. /// @param _gardenIndex the Id of the garden /// @param _grade the given grade /// @return saved : true if saved, false either function addGradeToGarden(uint _gardenIndex, int _grade)external returns(bool saved){ require(_grade<6 && _grade >=0, "Grade is not in range 0-5"); saved=false; GLibrary.Rent[] storage allRents = AllGarden[_gardenIndex].rents; for (uint i = 0; i < allRents.length; i++) { if(msg.sender== allRents[i].tenant && allRents[i].rate==int(-1) && isRentOver(allRents[i].beginning,allRents[i].duration)){ allRents[i].rate=_grade; saved=true; } } return saved; } /// @dev Use this function to add a dispute in case of disagreement between owner and tenant. /// @param _gardenIndex the Id of the garden function addDispute(uint _gardenIndex) public { require(AllGarden[_gardenIndex].status==GLibrary.Status.Location,"No location running"); GLibrary.Rent memory lastRent = getLastRentForGarden(_gardenIndex); require(lastRent.tenant==msg.sender || AllGarden[_gardenIndex].owner==msg.sender,"Not the tenant nor the owner"); AllGarden[_gardenIndex].status = GLibrary.Status.Dispute; AManager.addDispute(_gardenIndex,lastRent.balance); } /// @dev Use this function to close a dispute and give back ether amounts to correct people. /// Must be call by the admin contract. /// @param _gardenIndex the Id of the garden /// @param _ownerAmount amount for the owner /// @param _tenantAmount amount for the tenant function closeDispute(uint _gardenIndex, uint _ownerAmount, uint _tenantAmount) public OnlyContractAdmin{ GLibrary.Garden storage garden = AllGarden[_gardenIndex]; require(garden.status==GLibrary.Status.Dispute, "No dispute running"); GLibrary.Rent storage lastRent = getLastRentForGarden(_gardenIndex); if(_tenantAmount!=0){ lastRent.tenant.transfer(_tenantAmount); } if(_ownerAmount!=0){ if(garden.multipleOwners){ uint payroll = _ownerAmount/garden.coOwners.length; transferPaymentToMultipleOwners(payroll,garden); }else{ garden.owner.transfer(_ownerAmount); } } lastRent.balance=0; lastRent.accessCode.hashCode=0; garden.status=GLibrary.Status.Free; } function isRentOver(uint _beginning, uint _duration) private view returns (bool){ if(_beginning + _duration<= block.timestamp){ return true; } return false; } }
Use this function to propose a new location offer. The caller must be the owner, after agreement with the tenant offchain. _gardenIndex the Id of the garden _tenant tenant's garden _rentingDuration duration of the location _price price of the location _proofA the first part of the proof _proofB the second part of the proof _proofC the third part of the proof
function proposeGardenOffer(uint _gardenIndex, address payable _tenant, uint _rentingDuration, uint _price, uint[2] calldata _proofA, uint[2][2] calldata _proofB, uint[2] calldata _proofC) external OnlyOwner(_gardenIndex) OnlyValidProof(_gardenIndex,_proofA,_proofB,_proofC){ require(AllGarden[_gardenIndex].status==GLibrary.Status.Free, "Garden not free"); GLibrary.Garden storage garden = AllGarden[_gardenIndex]; garden.status= GLibrary.Status.Blocked; garden.rents.push(); GLibrary.Rent storage lastRent = getLastRentForGarden(_gardenIndex); lastRent.duration=_rentingDuration; lastRent.price=_price; lastRent.tenant=_tenant; lastRent.rate=-1; }
12,765,330
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0 <0.9.0; import './common/SafeMath.sol'; import './common/Destructible.sol'; /** @title Credit contract. * Inherits the Ownable and Destructible contracts. */ contract Credit is Destructible { /** @dev Usings */ // Using SafeMath for our calculations with uints. using SafeMath for uint; /** @dev State variables */ // Borrower is the person who generated the credit contract. address borrower; // Amount requested to be funded (in wei). uint requestedAmount; // Amount that will be returned by the borrower (including the interest). uint returnAmount; // Currently repaid amount. uint repaidAmount; // Credit interest. uint interest; // Requested number of repayment installments. uint requestedRepayments; // Remaining repayment installments. uint remainingRepayments; // The value of the repayment installment. uint repaymentInstallment; // The timestamp of credit creation. uint requestedDate; // The timestamp of last repayment date. uint lastRepaymentDate; // Description of the credit. bytes32 description; // Active state of the credit. bool active = true; /** Stages that every credit contract gets trough. * investment - During this state only investments are allowed. * repayment - During this stage only repayments are allowed. * interestReturns - This stage gives investors opportunity to request their returns. * expired - This is the stage when the contract is finished its purpose. * fraud - The borrower was marked as fraud. */ enum State { investment, repayment, interestReturns, expired, revoked, fraud } State state; // Storing the lenders for this credit. mapping(address => bool) public lenders; // Storing the invested amount by each lender. mapping(address => uint) lendersInvestedAmount; // Store the lenders count, later needed for revoke vote. uint lendersCount = 0; // Revoke votes count. uint revokeVotes = 0; // Revoke voters. mapping(address => bool) revokeVoters; // Time needed for a revoke voting to start. // To be changed in production accordingly. uint revokeTimeNeeded = block.timestamp + 1 seconds; // Revoke votes count. uint fraudVotes = 0; // Revoke voters. mapping(address => bool) fraudVoters; /** @dev Events * */ event LogCreditInitialized(address indexed _address, uint indexed timestamp); event LogCreditStateChanged(State indexed state, uint indexed timestamp); event LogCreditStateActiveChanged(bool indexed active, uint indexed timestamp); event LogBorrowerWithdrawal(address indexed _address, uint indexed _amount, uint indexed timestamp); event LogBorrowerRepaymentInstallment(address indexed _address, uint indexed _amount, uint indexed timestamp); event LogBorrowerRepaymentFinished(address indexed _address, uint indexed timestamp); event LogBorrowerChangeReturned(address indexed _address, uint indexed _amount, uint indexed timestamp); event LogBorrowerIsFraud(address indexed _address, bool indexed fraudStatus, uint indexed timestamp); event LogLenderInvestment(address indexed _address, uint indexed _amount, uint indexed timestamp); event LogLenderWithdrawal(address indexed _address, uint indexed _amount, uint indexed timestamp); event LogLenderChangeReturned(address indexed _address, uint indexed _amount, uint indexed timestamp); event LogLenderVoteForRevoking(address indexed _address, uint indexed timestamp); event LogLenderVoteForFraud(address indexed _address, uint indexed timestamp); event LogLenderRefunded(address indexed _address, uint indexed _amount, uint indexed timestamp); /** @dev Modifiers * */ modifier isActive() { require(active == true); _; } modifier onlyBorrower() { require(msg.sender == borrower); _; } modifier onlyLender() { require(lenders[msg.sender] == true); _; } modifier canAskForInterest() { require(state == State.interestReturns); require(lendersInvestedAmount[msg.sender] > 0); _; } modifier canInvest() { require(state == State.investment); _; } modifier canRepay() { require(state == State.repayment); _; } modifier canWithdraw() { require(this.balance >= requestedAmount); _; } modifier isNotFraud() { require(state != State.fraud); _; } modifier isRevokable() { require(block.timestamp >= revokeTimeNeeded); require(state == State.investment); _; } modifier isRevoked() { require(state == State.revoked); _; } /** @dev Constructor. * @param _requestedAmount Requested credit amount (in wei). * @param _requestedRepayments Requested number of repayments. * @param _description Credit description. */ constructor(uint _requestedAmount, uint _requestedRepayments, uint _interest, bytes32 _description) { /** Set the borrower of the contract to the tx.origin * We are using tx.origin, because the contract is going to be published * by the main contract and msg.sender will break our logic. */ borrower = tx.origin; // Set the interest for the credit. interest = _interest; // Set the requested amount. requestedAmount = _requestedAmount; // Set the requested repayments. requestedRepayments = _requestedRepayments; /** Set the remaining repayments. * Initially this is equal to the requested repayments. */ remainingRepayments = _requestedRepayments; /** Calculate the amount to be returned by the borrower. * At this point this is the addition of the requested amount and the interest. */ returnAmount = requestedAmount.add(interest); /** Calculating the repayment installment. * We divide the amount to be returned by the requested repayments count to get it. */ repaymentInstallment = returnAmount.div(requestedRepayments); // Set the credit description. description = _description; // Set the initialization date. requestedDate = block.timestamp; // Log credit initialization. LogCreditInitialized(borrower, block.timestamp); } /** @dev Get current balance. * @return this.balance. */ function getBalance() public view returns (uint256) { return this.balance; } /** @dev Invest function. * Provides functionality for person to invest in someone's credit, * incentivised by the return of interest. */ function invest() public canInvest payable { // Initialize an memory variable for the extra money that may have been sent. uint extraMoney = 0; // Check if contract balance is reached the requested amount. if (this.balance >= requestedAmount) { // Calculate the extra money that may have been sent. extraMoney = this.balance.sub(requestedAmount); // Assert the calculations assert(requestedAmount == this.balance.sub(extraMoney)); // Assert for possible underflow / overflow assert(extraMoney <= msg.value); // Check if extra money is greater than 0 wei. if (extraMoney > 0) { // Return the extra money to the sender. msg.sender.transfer(extraMoney); // Log change returned. LogLenderChangeReturned(msg.sender, extraMoney, block.timestamp); } // Set the contract state to repayment. state = State.repayment; // Log state change. LogCreditStateChanged(state, block.timestamp); } /** Add the investor to the lenders mapping. * So that we know he invested in this contract. */ lenders[msg.sender] = true; // Increment the lenders count. lendersCount++; // Add the amount invested to the amount mapping. lendersInvestedAmount[msg.sender] = lendersInvestedAmount[msg.sender].add(msg.value.sub(extraMoney)); // Log lender invested amount. LogLenderInvestment(msg.sender, msg.value.sub(extraMoney), block.timestamp); } /** @dev Repayment function. * Allows borrower to make repayment installments. */ function repay() public onlyBorrower canRepay payable { // The remaining repayments should be greater than 0 to continue. require(remainingRepayments > 0); // The value sent should be greater than the repayment installment. require(msg.value >= repaymentInstallment); /** Assert that the amount to be returned is greater * than the sum of repayments made until now. * Otherwise the credit is already repaid. */ assert(repaidAmount < returnAmount); // Decrement the remaining repayments. remainingRepayments--; // Update last repayment date. lastRepaymentDate = block.timestamp; // Initialize an memory variable for the extra money that may have been sent. uint extraMoney = 0; /** Check if the value (in wei) that is being sent is greather than the repayment installment. * In this case we should return the change to the msg.sender. */ if (msg.value > repaymentInstallment) { // Calculate the extra money being sent in the transaction. extraMoney = msg.value.sub(repaymentInstallment); // Assert the calculations. assert(repaymentInstallment == msg.value.sub(extraMoney)); // Assert for underflow. assert(extraMoney <= msg.value); // Return the change/extra money to the msg.sender. msg.sender.transfer(extraMoney); // Log the return of the extra money. LogBorrowerChangeReturned(msg.sender, extraMoney, block.timestamp); } // Log borrower installment received. LogBorrowerRepaymentInstallment(msg.sender, msg.value.sub(extraMoney), block.timestamp); // Add the repayment installment amount to the total repaid amount. repaidAmount = repaidAmount.add(msg.value.sub(extraMoney)); // Check the repaid amount reached the amount to be returned. if (repaidAmount == returnAmount) { // Log credit repaid. LogBorrowerRepaymentFinished(msg.sender, block.timestamp); // Set the credit state to "returning interests". state = State.interestReturns; // Log state change. LogCreditStateChanged(state, block.timestamp); } } /** @dev Withdraw function. * It can only be executed while contract is in active state. * It is only accessible to the borrower. * It is only accessible if the needed amount is gathered in the contract. * It can only be executed once. * Transfers the gathered amount to the borrower. */ function withdraw() public isActive onlyBorrower canWithdraw isNotFraud { // Set the state to repayment so we can avoid reentrancy. state = State.repayment; // Log state change. LogCreditStateChanged(state, block.timestamp); // Log borrower withdrawal. LogBorrowerWithdrawal(msg.sender, this.balance, block.timestamp); // Transfer the gathered amount to the credit borrower. borrower.transfer(this.balance); } /** @dev Request interest function. * It can only be executed while contract is in active state. * It is only accessible to lenders. * It is only accessible if lender funded 1 or more wei. * It can only be executed once. * Transfers the lended amount + interest to the lender. */ function requestInterest() public isActive onlyLender canAskForInterest { // Calculate the amount to be returned to lender. // uint lenderReturnAmount = lendersInvestedAmount[msg.sender].mul(returnAmount.div(lendersCount).div(lendersInvestedAmount[msg.sender])); uint lenderReturnAmount = returnAmount / lendersCount; // Assert the contract has enough balance to pay the lender. assert(this.balance >= lenderReturnAmount); // Transfer the return amount with interest to the lender. msg.sender.transfer(lenderReturnAmount); // Log the transfer to lender. LogLenderWithdrawal(msg.sender, lenderReturnAmount, block.timestamp); // Check if the contract balance is drawned. if (this.balance == 0) { // Set the active state to false. active = false; // Log active state change. LogCreditStateActiveChanged(active, block.timestamp); // Set the contract stage to expired e.g. its lifespan is over. state = State.expired; // Log state change. LogCreditStateChanged(state, block.timestamp); } } /** @dev Function to get the whole credit information. * @return borrower * @return description * @return requestedAmount * @return requestedRepayments * @return remainingRepayments * @return interest * @return returnAmount * @return state * @return active * @return this.balance */ function getCreditInfo() public view returns (address, bytes32, uint, uint, uint, uint, uint, uint, State, bool, uint) { return ( borrower, description, requestedAmount, requestedRepayments, repaymentInstallment, remainingRepayments, interest, returnAmount, state, active, this.balance ); } /** @dev Function for revoking the credit. */ function revokeVote() public isActive isRevokable onlyLender { // Require only one vote per lender. require(revokeVoters[msg.sender] == false); // Increment the revokeVotes. revokeVotes++; // Note the lender has voted. revokeVoters[msg.sender] == true; // Log lender vote for revoking the credit contract. LogLenderVoteForRevoking(msg.sender, block.timestamp); // If the consensus is reached. if (lendersCount == revokeVotes) { // Call internal revoke function. revoke(); } } /** @dev Revoke internal function. */ function revoke() internal { // Change the state to revoked. state = State.revoked; // Log credit revoked. LogCreditStateChanged(state, block.timestamp); } /** @dev Function for refunding people. */ function refund() public isActive onlyLender isRevoked { // assert the contract have enough balance. assert(this.balance >= lendersInvestedAmount[msg.sender]); // Transfer the return amount with interest to the lender. msg.sender.transfer(lendersInvestedAmount[msg.sender]); // Log the transfer to lender. LogLenderRefunded(msg.sender, lendersInvestedAmount[msg.sender], block.timestamp); // Check if the contract balance is drawned. if (this.balance == 0) { // Set the active state to false. active = false; // Log active status change. LogCreditStateActiveChanged(active, block.timestamp); // Set the contract stage to expired e.g. its lifespan is over. state = State.expired; // Log state change. LogCreditStateChanged(state, block.timestamp); } } /** @dev Function for voting the borrower as fraudster. */ function fraudVote() public isActive onlyLender returns (bool) { // A lender could vote only once. require(fraudVoters[msg.sender] == false); // Increment fraudVotes count. fraudVotes++; // Note the lender has voted. fraudVoters[msg.sender] == true; // Log lenders vote for fraud LogLenderVoteForFraud(msg.sender, block.timestamp); // Check if consensus is reached. if (lendersCount == fraudVotes) { // Invoke fraud function. return fraud(); } return true; } /** @dev Fraund function * @return * calls the owner contract and marks the borrower as fraudster. */ function fraud() internal returns (bool) { // call the owner address function with param borrower's address bool fraudStatusResult = owner.call(bytes4(keccak256("setFraudStatus(address)")), borrower); // Log user marked as fraud. LogBorrowerIsFraud(borrower, fraudStatusResult, block.timestamp); return fraudStatusResult; } /** @dev Change state function. * @param _state New state. * Only accessible to the owner of the contract. * Changes the state of the contract. */ function changeState(State _state) external onlyOwner returns (uint) { state = _state; // Log state change. LogCreditStateChanged(state, block.timestamp); } /** @dev Toggle active state function. * Only accessible to the owner of the contract. * Toggles the active state of the contract. * @return bool */ function toggleActive() external onlyOwner returns (bool) { active = !active; // Log active status change. LogCreditStateActiveChanged(active, block.timestamp); return active; } }
Invest function. Provides functionality for person to invest in someone's credit, incentivised by the return of interest./ Initialize an memory variable for the extra money that may have been sent. Check if contract balance is reached the requested amount. Calculate the extra money that may have been sent. Assert the calculations Assert for possible underflow / overflow Check if extra money is greater than 0 wei. Return the extra money to the sender. Log change returned.
function invest() public canInvest payable { uint extraMoney = 0; if (this.balance >= requestedAmount) { extraMoney = this.balance.sub(requestedAmount); assert(requestedAmount == this.balance.sub(extraMoney)); assert(extraMoney <= msg.value); if (extraMoney > 0) { msg.sender.transfer(extraMoney); LogLenderChangeReturned(msg.sender, extraMoney, block.timestamp); } } }
1,013,975
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.4; import 'hardhat/console.sol'; import '@openzeppelin/contracts/token/ERC721/IERC721.sol'; import '../base/SignatureVerifier.sol'; import '../erc721/Worlds.sol'; // Contract containing stats of a dystopian. // Can only be updated by the Dystopian owner or World owner. // Updates for a given world must be signed by that World. contract DystopianData is SignatureVerifier { // info about the token which owns this data uint256 id; // dystopians can be renamed string name; // the cost of renaming the Dystopian. uint256 renameCost; // contracts Worlds worlds; // the worlds contract we use to get the owner of the worlds the dystopian is saved in. IERC721 dystopians; // the dystopians contract we use to get the owner of the current dystopian. address payable payments; // payments are sent to this address // updated by transactions // the dystopian's data // the owner of the world token must sign updates to the dystopian data for that world. mapping(uint256 => Dystopian) worldData; // number of times the dystopian has been updated for each world. used to ensure updates are not duplicated. mapping(uint256 => uint256) nonceForWorld; // emitted when the dystopian is updated. event DystopianDataUpdated(uint256 indexed world, uint256 nonce); // initialize with addresses of the tokens we use verify ownership constructor( uint256 _id, string memory _name, uint256 _renameCost, address _worlds, address _dystopians, address _payments ) { id = _id; name = _name; renameCost = _renameCost; payments = payable(_payments); worlds = Worlds(_worlds); dystopians = IERC721(_dystopians); } // // for functions specific to a world (the world owner might call) // modifier onlyDystopianOrWorldOwner(uint256 _world) { // // verify the tx came from the dystopian owner, the world owner, or the dystopians contract directly // require( // msg.sender == address(dystopians) ||msg.sender == dystopians.ownerOf(id) || msg.sender == worlds.ownerOf(_world), // 'only the owner of the dystopian or its world can call this function' // ); // _; // } // for functions that do not belong to a world modifier onlyDystopianOwner() { // verify the tx came from the dystopian owner directly require(msg.sender == dystopians.ownerOf(id), 'only the owner of the dystopian can call this function'); _; } modifier requiresPayment(uint256 _cost) { require(msg.value >= _cost, 'payment required'); payments.transfer(address(this).balance); // transfer entire balance to the payments address _; } // the world must have signed the current hash for the player to save their dystopian. function updateDystopianData( uint256 _world, Dystopian calldata _data, bytes calldata _worldSignature ) external { // ) external onlyDystopianOrWorldOwner(_world) { // verify the world signature matches the hash of the data address _worldOwner = worlds.ownerOf(_world); require(_worldOwner != address(0), 'no one owns this world'); // allow direct updates from dystopians contract if (msg.sender != address(dystopians)) { bytes32 _nextHash = getNextHash(_world, _data); console.log('expected dystopian hash', bytes32ToLiteralString(_nextHash)); (address signer, , ) = getSigner(_nextHash, _worldSignature); require(signer == _worldOwner, 'world owner must sign dystopian saves'); } // increment nonce to ensure we get a unique hash every time. nonceForWorld[_world]++; // save the data to the world worldData[_world] = _data; emit DystopianDataUpdated(_world, nonceForWorld[_world] - 1); } // read the data stored in the contract function getDystopianData(uint256 _world) external view returns (Dystopian memory) { return worldData[_world]; } // rename your dystopian for a fee function rename(string calldata _name) external payable onlyDystopianOwner requiresPayment(renameCost) { name = _name; } // read the dystopian's name function getDystopianName() external view returns (string memory) { return name; } // get the next hash for the world to sign. // only valid for one save function getNextHash(uint256 _world, Dystopian calldata _data) public view returns (bytes32) { // hash the nonce + the address so that every hash for every dystopian is unique the first time it is used. return keccak256(abi.encode(nonceForWorld[_world], _data, address(this))); } function bytes32ToLiteralString(bytes32 data) public pure returns (string memory result) { bytes memory temp = new bytes(65); uint256 count; for (uint256 i = 0; i < 32; i++) { bytes1 currentByte = bytes1(data << (i * 8)); uint8 c1 = uint8(bytes1((currentByte << 4) >> 4)); uint8 c2 = uint8(bytes1((currentByte >> 4))); if (c2 >= 0 && c2 <= 9) temp[++count] = bytes1(c2 + 48); else temp[++count] = bytes1(c2 + 87); if (c1 >= 0 && c1 <= 9) temp[++count] = bytes1(c1 + 48); else temp[++count] = bytes1(c1 + 87); } result = string(temp); } } // the data of a dystopian in a specific world struct Dystopian { Character char; }
read the dystopian's name
function getDystopianName() external view returns (string memory) { return name; }
6,355,558
// SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.1; interface IMoonCatAcclimator { function getApproved(uint256 tokenId) external view returns (address); function isApprovedForAll(address owner, address operator) external view returns (bool); function ownerOf(uint256 tokenId) external view returns (address); function balanceOf(address _owner) external view returns (uint256); function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256); } interface IMoonCatRescue { function rescueOrder(uint256 tokenId) external view returns (bytes5); function catOwners(bytes5 catId) external view returns (address); } interface IReverseResolver { function claim(address owner) external returns (bytes32); } interface IRegistry { function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external; function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external; function setTTL(bytes32 node, uint64 ttl) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function owner(bytes32 node) external view returns (address); } interface IERC20 { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); } interface IERC721 { function safeTransferFrom(address from, address to, uint256 tokenId) external; } /** * @title MoonCatResolver * @notice ENS Resolver for MoonCat subdomains * @dev Auto-updates to point to the owner of that specific MoonCat */ contract MoonCatResolver { /* External Contracts */ IMoonCatAcclimator MCA = IMoonCatAcclimator(0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69); IMoonCatRescue MCR = IMoonCatRescue(0x60cd862c9C687A9dE49aecdC3A99b74A4fc54aB6); /* State */ mapping(bytes32 => uint256) internal NamehashMapping; // ENS namehash => Rescue ID of MoonCat mapping(uint256 => mapping(uint256 => bytes)) internal MultichainMapping; // Rescue ID of MoonCat => Multichain ID => value mapping(uint256 => mapping(string => string)) internal TextKeyMapping; // Rescue ID of MoonCat => text record key => value mapping(uint256 => bytes) internal ContentsMapping; // Rescue ID of MoonCat => content hash mapping(uint256 => address) internal lastAnnouncedAddress; // Rescue ID of MoonCat => address that was last emitted in an AddrChanged Event address payable public owner; bytes32 immutable public rootHash; string public ENSDomain; // Reference for the ENS domain this contract resolves string public avatarBaseURI = "eip155:1/erc721:0xc3f733ca98e0dad0386979eb96fb1722a1a05e69/"; uint64 public defaultTTL = 86400; // For string-matching on a specific text key uint256 constant internal avatarKeyLength = 6; bytes32 constant internal avatarKeyHash = keccak256("avatar"); /* Events */ event AddrChanged(bytes32 indexed node, address a); event AddressChanged(bytes32 indexed node, uint coinType, bytes newAddress); event TextChanged(bytes32 indexed node, string indexedKey, string key); event ContenthashChanged(bytes32 indexed node, bytes hash); /* Modifiers */ modifier onlyOwner () { require(msg.sender == owner, "Only Owner"); _; } modifier onlyMoonCatOwner (uint256 rescueOrder) { require(MCR.catOwners(MCR.rescueOrder(rescueOrder)) == address(MCA), "Not Acclimated"); require(msg.sender == MCA.ownerOf(rescueOrder), "Not MoonCat's owner"); _; } /** * @dev Deploy resolver contract. */ constructor(bytes32 _rootHash, string memory _ENSDomain){ owner = payable(msg.sender); rootHash = _rootHash; ENSDomain = _ENSDomain; // https://docs.ens.domains/contract-api-reference/reverseregistrar#claim-address IReverseResolver(0x084b1c3C81545d370f3634392De611CaaBFf8148) .claim(msg.sender); } /** * @dev Allow current `owner` to transfer ownership to another address */ function transferOwnership (address payable newOwner) public onlyOwner { owner = newOwner; } /** * @dev Update the "avatar" value that gets set by default. */ function setAvatarBaseUrl(string calldata url) public onlyOwner { avatarBaseURI = url; } /** * @dev Update the default TTL value. */ function setDefaultTTL(uint64 newTTL) public onlyOwner { defaultTTL = newTTL; } /** * @dev Pass ownership of a subnode of the contract's root hash to the owner. */ function giveControl(bytes32 nodeId) public onlyOwner { IRegistry(0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e).setSubnodeOwner(rootHash, nodeId, owner); } /** * @dev Rescue ERC20 assets sent directly to this contract. */ function withdrawForeignERC20(address tokenContract) public onlyOwner { IERC20 token = IERC20(tokenContract); token.transfer(owner, token.balanceOf(address(this))); } /** * @dev Rescue ERC721 assets sent directly to this contract. */ function withdrawForeignERC721(address tokenContract, uint256 tokenId) public onlyOwner { IERC721(tokenContract).safeTransferFrom(address(this), owner, tokenId); } /** * @dev ERC165 support for ENS resolver interface * https://docs.ens.domains/contract-developer-guide/writing-a-resolver */ function supportsInterface(bytes4 interfaceID) public pure returns (bool) { return interfaceID == 0x01ffc9a7 // supportsInterface call itself || interfaceID == 0x3b3b57de // EIP137: ENS resolver || interfaceID == 0xf1cb7e06 // EIP2304: Multichain addresses || interfaceID == 0x59d1d43c // EIP634: ENS text records || interfaceID == 0xbc1c58d1 // EIP1577: contenthash ; } /** * @dev For a given ENS Node ID, return the Ethereum address it points to. * EIP137 core functionality */ function addr(bytes32 nodeID) public view returns (address) { uint256 rescueOrder = getRescueOrderFromNodeId(nodeID); address actualOwner = MCA.ownerOf(rescueOrder); if ( MCR.catOwners(MCR.rescueOrder(rescueOrder)) != address(MCA) || actualOwner != lastAnnouncedAddress[rescueOrder] ) { return address(0); // Not Acclimated/Announced; return zero (per spec) } else { return lastAnnouncedAddress[rescueOrder]; } } /** * @dev For a given ENS Node ID, return an address on a different blockchain it points to. * EIP2304 functionality */ function addr(bytes32 nodeID, uint256 coinType) public view returns (bytes memory) { uint256 rescueOrder = getRescueOrderFromNodeId(nodeID); if (MCR.catOwners(MCR.rescueOrder(rescueOrder)) != address(MCA)) { return bytes(''); // Not Acclimated; return zero (per spec) } if (coinType == 60) { // Ethereum address return abi.encodePacked(addr(nodeID)); } else { return MultichainMapping[rescueOrder][coinType]; } } /** * @dev For a given ENS Node ID, set it to point to an address on a different blockchain. * EIP2304 functionality */ function setAddr(bytes32 nodeID, uint256 coinType, bytes calldata newAddr) public { uint256 rescueOrder = getRescueOrderFromNodeId(nodeID); setAddr(rescueOrder, coinType, newAddr); } /** * @dev For a given MoonCat rescue order, set the subdomains associated with it to point to an address on a different blockchain. */ function setAddr(uint256 rescueOrder, uint256 coinType, bytes calldata newAddr) public onlyMoonCatOwner(rescueOrder) { if (coinType == 60) { // Ethereum address announceMoonCat(rescueOrder); return; } emit AddressChanged(getSubdomainNameHash(uint2str(rescueOrder)), coinType, newAddr); emit AddressChanged(getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder))), coinType, newAddr); MultichainMapping[rescueOrder][coinType] = newAddr; } /** * @dev For a given ENS Node ID, return the value associated with a given text key. * If the key is "avatar", and the matching value is not explicitly set, a url pointing to the MoonCat's image is returned * EIP634 functionality */ function text(bytes32 nodeID, string calldata key) public view returns (string memory) { uint256 rescueOrder = getRescueOrderFromNodeId(nodeID); string memory value = TextKeyMapping[rescueOrder][key]; if (bytes(value).length > 0) { // This value has been set explicitly; return that return value; } // Check if there's a default value for this key bytes memory keyBytes = bytes(key); if (keyBytes.length == avatarKeyLength && keccak256(keyBytes) == avatarKeyHash){ // Avatar default return string(abi.encodePacked(avatarBaseURI, uint2str(rescueOrder))); } // No default; just return the empty string return value; } /** * @dev Update a text record for a specific subdomain. * EIP634 functionality */ function setText(bytes32 nodeID, string calldata key, string calldata value) public { uint256 rescueOrder = getRescueOrderFromNodeId(nodeID); setText(rescueOrder, key, value); } /** * @dev Update a text record for subdomains owned by a specific MoonCat rescue order. */ function setText(uint256 rescueOrder, string calldata key, string calldata value) public onlyMoonCatOwner(rescueOrder) { bytes memory keyBytes = bytes(key); bytes32 orderHash = getSubdomainNameHash(uint2str(rescueOrder)); bytes32 hexHash = getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder))); if (bytes(value).length == 0 && keyBytes.length == avatarKeyLength && keccak256(keyBytes) == avatarKeyHash){ // Avatar default string memory avatarRecordValue = string(abi.encodePacked(avatarBaseURI, uint2str(rescueOrder))); emit TextChanged(orderHash, key, avatarRecordValue); emit TextChanged(hexHash, key, avatarRecordValue); } else { emit TextChanged(orderHash, key, value); emit TextChanged(hexHash, key, value); } TextKeyMapping[rescueOrder][key] = value; } /** * @dev Get the "content hash" of a given subdomain. * EIP1577 functionality */ function contenthash(bytes32 nodeID) public view returns (bytes memory) { uint256 rescueOrder = getRescueOrderFromNodeId(nodeID); return ContentsMapping[rescueOrder]; } /** * @dev Update the "content hash" of a given subdomain. * EIP1577 functionality */ function setContenthash(bytes32 nodeID, bytes calldata hash) public { uint256 rescueOrder = getRescueOrderFromNodeId(nodeID); setContenthash(rescueOrder, hash); } /** * @dev Update the "content hash" of a given MoonCat's subdomains. */ function setContenthash(uint256 rescueOrder, bytes calldata hash) public onlyMoonCatOwner(rescueOrder) { emit ContenthashChanged(getSubdomainNameHash(uint2str(rescueOrder)), hash); emit ContenthashChanged(getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder))), hash); ContentsMapping[rescueOrder] = hash; } /** * @dev Set the TTL for a given MoonCat's subdomains. */ function setTTL(uint rescueOrder, uint64 newTTL) public onlyMoonCatOwner(rescueOrder) { IRegistry registry = IRegistry(0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e); registry.setTTL(getSubdomainNameHash(uint2str(rescueOrder)), newTTL); registry.setTTL(getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder))), newTTL); } /** * @dev Allow calling multiple functions on this contract in one transaction. */ function multicall(bytes[] calldata data) external returns(bytes[] memory results) { results = new bytes[](data.length); for (uint i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); require(success); results[i] = result; } return results; } /** * @dev Reverse lookup for ENS Node ID, to determine the MoonCat rescue order of the MoonCat associated with it. */ function getRescueOrderFromNodeId(bytes32 nodeID) public view returns (uint256) { uint256 rescueOrder = NamehashMapping[nodeID]; if (rescueOrder == 0) { // Are we actually dealing with MoonCat #0? require( nodeID == 0x8bde039a2a7841d31e0561fad9d5cfdfd4394902507c72856cf5950eaf9e7d5a // 0.ismymooncat.eth || nodeID == 0x1002474938c26fb23080c33c3db026c584b30ec6e7d3edf4717f3e01e627da26, // 0x00d658d50b.ismymooncat.eth "Unknown Node ID" ); } return rescueOrder; } /** * @dev Calculate the "namehash" of a specific domain, using the ENS standard algorithm. * The namehash of 'ismymooncat.eth' is 0x204665c32985055ed5daf374d6166861ba8892a3b0849d798c919fffe38a1a15 * The namehash of 'foo.ismymooncat.eth' is keccak256(0x204665c32985055ed5daf374d6166861ba8892a3b0849d798c919fffe38a1a15, keccak256('foo')) */ function getSubdomainNameHash(string memory subdomain) public view returns (bytes32) { return keccak256(abi.encodePacked(rootHash, keccak256(abi.encodePacked(subdomain)))); } /** * @dev Cache a single MoonCat's (identified by Rescue Order) subdomain hashes. */ function mapMoonCat(uint256 rescueOrder) public { string memory orderSubdomain = uint2str(rescueOrder); string memory hexSubdomain = bytes5ToHexString(MCR.rescueOrder(rescueOrder)); bytes32 orderHash = getSubdomainNameHash(orderSubdomain); bytes32 hexHash = getSubdomainNameHash(hexSubdomain); if (uint256(NamehashMapping[orderHash]) != 0) { // Already Mapped return; } NamehashMapping[orderHash] = rescueOrder; NamehashMapping[hexHash] = rescueOrder; if(MCR.catOwners(MCR.rescueOrder(rescueOrder)) != address(MCA)) { // MoonCat is not Acclimated return; } IRegistry registry = IRegistry(0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e); registry.setSubnodeRecord(rootHash, keccak256(bytes(orderSubdomain)), address(this), address(this), defaultTTL); registry.setSubnodeRecord(rootHash, keccak256(bytes(hexSubdomain)), address(this), address(this), defaultTTL); address moonCatOwner = MCA.ownerOf(rescueOrder); lastAnnouncedAddress[rescueOrder] = moonCatOwner; emit AddrChanged(orderHash, moonCatOwner); emit AddrChanged(hexHash, moonCatOwner); emit AddressChanged(orderHash, 60, abi.encodePacked(moonCatOwner)); emit AddressChanged(hexHash, 60, abi.encodePacked(moonCatOwner)); string memory avatarRecordValue = string(abi.encodePacked(avatarBaseURI, uint2str(rescueOrder))); emit TextChanged(orderHash, "avatar", avatarRecordValue); emit TextChanged(hexHash, "avatar", avatarRecordValue); } /** * @dev Announce a single MoonCat's (identified by Rescue Order) assigned address. */ function announceMoonCat(uint256 rescueOrder) public { require(MCR.catOwners(MCR.rescueOrder(rescueOrder)) == address(MCA), "Not Acclimated"); address moonCatOwner = MCA.ownerOf(rescueOrder); lastAnnouncedAddress[rescueOrder] = moonCatOwner; bytes32 orderHash = getSubdomainNameHash(uint2str(rescueOrder)); bytes32 hexHash = getSubdomainNameHash(bytes5ToHexString(MCR.rescueOrder(rescueOrder))); emit AddrChanged(orderHash, moonCatOwner); emit AddrChanged(hexHash, moonCatOwner); emit AddressChanged(orderHash, 60, abi.encodePacked(moonCatOwner)); emit AddressChanged(hexHash, 60, abi.encodePacked(moonCatOwner)); } /** * @dev Has an AddrChanged event been emitted for the current owner of a MoonCat (identified by Rescue Order)? */ function needsAnnouncing(uint256 rescueOrder) public view returns (bool) { require(MCR.catOwners(MCR.rescueOrder(rescueOrder)) == address(MCA), "Not Acclimated"); return lastAnnouncedAddress[rescueOrder] != MCA.ownerOf(rescueOrder); } /** * @dev Convenience function to iterate through all MoonCats owned by an address to check if they need announcing. */ function needsAnnouncing(address moonCatOwner) public view returns (uint256[] memory) { uint256 balance = MCA.balanceOf(moonCatOwner); uint256 announceCount = 0; uint256[] memory tempRescueOrders = new uint256[](balance); for (uint256 i = 0; i < balance; i++) { uint256 rescueOrder = MCA.tokenOfOwnerByIndex(moonCatOwner, i); if (lastAnnouncedAddress[rescueOrder] != moonCatOwner){ tempRescueOrders[announceCount] = rescueOrder; announceCount++; } } uint256[] memory rescueOrders = new uint256[](announceCount); for (uint256 i = 0; i < announceCount; i++){ rescueOrders[i] = tempRescueOrders[i]; } return rescueOrders; } /** * @dev Convenience function to iterate through all MoonCats owned by sender to check if they need announcing. */ function needsAnnouncing() public view returns (uint256[] memory) { return needsAnnouncing(msg.sender); } /** * @dev Set a manual list of MoonCats (identified by Rescue Order) to announce or cache their subdomain hashes. */ function mapMoonCats(uint256[] memory rescueOrders) public { for (uint256 i = 0; i < rescueOrders.length; i++) { address lastAnnounced = lastAnnouncedAddress[rescueOrders[i]]; if (lastAnnounced == address(0)){ mapMoonCat(rescueOrders[i]); } else if (lastAnnounced != MCA.ownerOf(rescueOrders[i])){ announceMoonCat(rescueOrders[i]); } } } /** * @dev Convenience function to iterate through all MoonCats owned by an address and announce or cache their subdomain hashes. */ function mapMoonCats(address moonCatOwner) public { for (uint256 i = 0; i < MCA.balanceOf(moonCatOwner); i++) { uint256 rescueOrder = MCA.tokenOfOwnerByIndex(moonCatOwner, i); address lastAnnounced = lastAnnouncedAddress[rescueOrder]; if (lastAnnounced == address(0)){ mapMoonCat(rescueOrder); } else if (lastAnnounced != moonCatOwner){ announceMoonCat(rescueOrder); } } } /** * @dev Convenience function to iterate through all MoonCats owned by the sender and announce or cache their subdomain hashes. */ function mapMoonCats() public { mapMoonCats(msg.sender); } /** * @dev Utility function to convert a bytes5 variable into a hexadecimal string. * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol */ bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; function bytes5ToHexString(bytes5 x) internal pure returns (string memory) { uint256 length = 5; uint256 value = uint256(uint40(x)); 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 Utility function to convert a uint256 variable into a decimal string. */ function uint2str(uint value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } }
Set a manual list of MoonCats (identified by Rescue Order) to announce or cache their subdomain hashes./
function mapMoonCats(uint256[] memory rescueOrders) public { for (uint256 i = 0; i < rescueOrders.length; i++) { address lastAnnounced = lastAnnouncedAddress[rescueOrders[i]]; if (lastAnnounced == address(0)){ mapMoonCat(rescueOrders[i]); announceMoonCat(rescueOrders[i]); } } }
15,333,113
./full_match/1/0xfff2c6b6e13B3fc9fEEeBC6920dA3224De566f77/sources/project_/contracts/PapaNFT.sol
sets default URI/
function setDefaultURI(string calldata __defaultURI) external onlyOwner { defaultURI = __defaultURI; }
16,530,224
./partial_match/42/0x631FFD1AA2A854736727b02379a147cBE0E98F9f/sources/UBXGStaking.sol
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
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; }
3,328,039
./partial_match/1/0x8f2eCCCc42ED88348AD39A1985188Dc57D75bdF0/sources/NamiCrowdSale.sol
Available only if presale is running. require ICO time or binary option add new token to buyer add new token to totalSupply
function buy(address _buyer) payable public { require(currentPhase == Phase.Running); require(now <= 1519862400 || msg.sender == binaryAddress); require(msg.value != 0); uint newTokens = msg.value * getPrice(); require (totalSupply + newTokens < TOKEN_SUPPLY_LIMIT); balanceOf[_buyer] = balanceOf[_buyer].add(newTokens); totalSupply = totalSupply.add(newTokens); LogBuy(_buyer, newTokens); }
16,019,437
./partial_match/1/0xa3cc9e4B9784c80a05B3Af215C32ff223C3ebE5c/sources/home/david/repc-v1.0.0/contracts/lib/pools/CompoundPoolController.sol
Deposits funds to the Compound pool. Assumes that you have already approved >= the amount to Compound. amount The amount of tokens to be deposited. return Boolean indicating success./ require(mintResult == 0, "Error calling mint on Compound cToken: error code not equal to 0");
function deposit(uint256 amount) external returns (bool) { require(amount > 0, "Amount must be greater than 0."); _cETHContract.mint.value(amount)(); return true; }
4,092,568
./full_match/43114/0x2FAd2cBdAAb8Ae320F015CaD0E072Fa0281Eb5e9/sources/avax1.sol
manual claim for the greedy humans
function ___claimRewards() public { distributor.claimDividend(); }
4,505,398
/** */ /** Trumpettttttttttttttttttttttttttttttttttttttttttttttttttt WELCOME TO Trumpet Inu (Trumpet) ! TOKENOMICS: Supply: 1,000,000 tokens 8% marketing 2% LP 2% max TRX, 2% max wallet at launch 5% max TRX, 5% max wallet after launch Telegram : @trumpetinu Twitter : twitter.com/trumpetinu Inuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu */ // 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; } } // File contracts/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File contracts/IERC20.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/IUniswapV2Router01.sol pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // File contracts/IUniswapV2Router02.sol pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // File contracts/IUniswapV2Factory.sol pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // File contracts/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File contracts pragma solidity ^0.8.0; contract trumpetinu is Context, IERC20, Ownable { using Address for address payable; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcluded; mapping(address => bool) private _isExcludedFromMaxWallet; mapping(address => bool) public isBot; address[] private _excluded; uint8 private constant _decimals = 9; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 1_000_000 * 10**_decimals; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 public maxTxAmountBuy = _tTotal / 50; // 2% of supply uint256 public maxTxAmountSell = _tTotal / 50; // 2% of supply uint256 public maxWalletAmount = _tTotal / 50; // 2% of supply uint256 public tokenstosell = 0; //antisnipers uint256 public liqAddedBlockNumber; uint256 public blocksToWait = 0; address payable public treasuryAddress; address payable public devAddress; mapping(address => bool) public isAutomatedMarketMakerPair; string private constant _name = "Trumpet Inu"; string private constant _symbol = "Trumpet"; bool private inSwapAndLiquify; IUniswapV2Router02 public UniswapV2Router; address public uniswapPair; bool public swapAndLiquifyEnabled = true; uint256 public numTokensSellToAddToLiquidity = _tTotal * 7 / 1000; //0.7% struct feeRatesStruct { uint8 rfi; uint8 treasury; uint8 dev; uint8 lp; uint8 toSwap; } // feeRatesStruct public buyRates = feeRatesStruct({ rfi: 0, // RFI rate, in % dev: 4, // dev team fee in % treasury: 4, // treasury fee in % lp: 2, // lp rate in % toSwap: 10 // treasury + dev + lp }); feeRatesStruct public sellRates = feeRatesStruct({ rfi: 0, // RFI rate, in % dev: 4, // dev team fee in % treasury: 4, // treasury fee in % lp: 2, // lp rate in % toSwap: 10 // treasury + dev + lp }); feeRatesStruct private appliedRates = buyRates; struct TotFeesPaidStruct { uint256 rfi; uint256 toSwap; } TotFeesPaidStruct public totFeesPaid; struct valuesFromGetValues { uint256 rAmount; uint256 rTransferAmount; uint256 rRfi; uint256 rToSwap; uint256 tTransferAmount; uint256 tRfi; uint256 tToSwap; } event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ETHReceived, uint256 tokensIntotoSwap ); event LiquidityAdded(uint256 tokenAmount, uint256 ETHAmount); event TreasuryAndDevFeesAdded(uint256 devFee, uint256 treasuryFee); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event BlacklistedUser(address botAddress, bool indexed value); event MaxWalletAmountUpdated(uint256 amount); event ExcludeFromMaxWallet(address account, bool indexed isExcluded); modifier lockTheSwap() { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() { IUniswapV2Router02 _UniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); uniswapPair = IUniswapV2Factory(_UniswapV2Router.factory()).createPair(address(this), _UniswapV2Router.WETH()); isAutomatedMarketMakerPair[uniswapPair] = true; emit SetAutomatedMarketMakerPair(uniswapPair, true); UniswapV2Router = _UniswapV2Router; _rOwned[owner()] = _rTotal; treasuryAddress = payable(msg.sender); devAddress = payable(msg.sender); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[treasuryAddress] = true; _isExcludedFromFee[devAddress] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromMaxWallet[owner()] = true; _isExcludedFromMaxWallet[treasuryAddress] = true; _isExcludedFromMaxWallet[devAddress] = true; _isExcludedFromMaxWallet[address(this)] = true; _isExcludedFromMaxWallet[uniswapPair] = true; emit Transfer(address(0), owner(), _tTotal); } //std ERC20: function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } //override ERC20: function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require( currentAllowance >= amount, "ERC20: transfer amount exceeds allowance" ); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender] + addedValue ); return true; } 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; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function reflectionFromToken(uint256 tAmount, bool deductTransferRfi) public view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferRfi) { valuesFromGetValues memory s = _getValues(tAmount, true); return s.rAmount; } else { valuesFromGetValues memory s = _getValues(tAmount, true); return s.rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount / currentRate; } //No current rfi - Tiered Rewarding Feature Applied at APP Launch function excludeFromReward(address account) external onlyOwner { require(!_isExcluded[account], "Account is already excluded"); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } function includeInReward(address account) external onlyOwner { require(_isExcluded[account], "Account is not excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } function excludeFromFee(address account) external onlyOwner { _isExcludedFromFee[account] = true; } function includeInFee(address account) external onlyOwner { _isExcludedFromFee[account] = false; } function isExcludedFromFee(address account) public view returns (bool) { return _isExcludedFromFee[account]; } function isExcludedFromMaxWallet(address account) public view returns (bool) { return _isExcludedFromMaxWallet[account]; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } // @dev receive ETH from UniswapV2Router when swapping receive() external payable {} function _reflectRfi(uint256 rRfi, uint256 tRfi) private { _rTotal -= rRfi; totFeesPaid.rfi += tRfi; } function _takeToSwap(uint256 rToSwap, uint256 tToSwap) private { _rOwned[address(this)] += rToSwap; if (_isExcluded[address(this)]) _tOwned[address(this)] += tToSwap; totFeesPaid.toSwap += tToSwap; } function _getValues(uint256 tAmount, bool takeFee) private view returns (valuesFromGetValues memory to_return) { to_return = _getTValues(tAmount, takeFee); ( to_return.rAmount, to_return.rTransferAmount, to_return.rRfi, to_return.rToSwap ) = _getRValues(to_return, tAmount, takeFee, _getRate()); return to_return; } function _getTValues(uint256 tAmount, bool takeFee) private view returns (valuesFromGetValues memory s) { if (!takeFee) { s.tTransferAmount = tAmount; return s; } s.tRfi = (tAmount * appliedRates.rfi) / 100; s.tToSwap = (tAmount * appliedRates.toSwap) / 100; s.tTransferAmount = tAmount - s.tRfi - s.tToSwap; return s; } function _getRValues( valuesFromGetValues memory s, uint256 tAmount, bool takeFee, uint256 currentRate ) private pure returns ( uint256 rAmount, uint256 rTransferAmount, uint256 rRfi, uint256 rToSwap ) { rAmount = tAmount * currentRate; if (!takeFee) { return (rAmount, rAmount, 0, 0); } rRfi = s.tRfi * currentRate; rToSwap = s.tToSwap * currentRate; rTransferAmount = rAmount - rRfi - rToSwap; return (rAmount, rTransferAmount, rRfi, rToSwap); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply / tSupply; } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply -= _rOwned[_excluded[i]]; tSupply -= _tOwned[_excluded[i]]; } if (rSupply < _rTotal / _tTotal) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { if (liqAddedBlockNumber == 0 && isAutomatedMarketMakerPair[to]) { liqAddedBlockNumber = block.number; } require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!isBot[from], "ERC20: address blacklisted (bot)"); require(amount > 0, "Transfer amount must be greater than zero"); require( amount <= balanceOf(from), "You are trying to transfer more than your balance" ); bool takeFee = !(_isExcludedFromFee[from] || _isExcludedFromFee[to]); if (takeFee) { if (isAutomatedMarketMakerPair[from]) { if (block.number < liqAddedBlockNumber + blocksToWait) { isBot[to] = true; emit BlacklistedUser(to, true); } appliedRates = buyRates; require( amount <= maxTxAmountBuy, "amount must be <= maxTxAmountBuy" ); } else { appliedRates = sellRates; require( amount <= maxTxAmountSell, "amount must be <= maxTxAmountSell" ); } } if ( balanceOf(address(this)) >= numTokensSellToAddToLiquidity && !inSwapAndLiquify && !isAutomatedMarketMakerPair[from] && swapAndLiquifyEnabled ) { //add liquidity swapAndLiquify(numTokensSellToAddToLiquidity); } _tokenTransfer(from, to, amount, takeFee); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer( address sender, address recipient, uint256 tAmount, bool takeFee ) private { valuesFromGetValues memory s = _getValues(tAmount, takeFee); if (_isExcluded[sender]) { _tOwned[sender] -= tAmount; } if (_isExcluded[recipient]) { _tOwned[recipient] += s.tTransferAmount; } _rOwned[sender] -= s.rAmount; _rOwned[recipient] += s.rTransferAmount; if (takeFee) { _reflectRfi(s.rRfi, s.tRfi); _takeToSwap(s.rToSwap, s.tToSwap); emit Transfer(sender, address(this), s.tToSwap); } require( _isExcludedFromMaxWallet[recipient] || balanceOf(recipient) <= maxWalletAmount, "Recipient cannot hold more than maxWalletAmount" ); emit Transfer(sender, recipient, s.tTransferAmount); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { uint256 denominator = appliedRates.toSwap * 2; uint256 tokensToAddLiquidityWith = (contractTokenBalance * appliedRates.lp) / denominator; uint256 toSwap = contractTokenBalance - tokensToAddLiquidityWith; uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForETH(toSwap); uint256 deltaBalance = address(this).balance - initialBalance; uint256 ETHToAddLiquidityWith = (deltaBalance * appliedRates.lp) / (denominator - appliedRates.lp); // add liquidity addLiquidity(tokensToAddLiquidityWith, ETHToAddLiquidityWith); // we give the remaining tax to dev & treasury wallets uint256 remainingBalance = address(this).balance; uint256 devFee = (remainingBalance * appliedRates.dev) / (denominator - appliedRates.dev); uint256 treasuryFee = (remainingBalance * appliedRates.treasury) / (denominator - appliedRates.treasury); devAddress.sendValue(devFee); treasuryAddress.sendValue(treasuryFee); } function swapTokensForETH(uint256 tokenAmount) private { // generate the pair path of token address[] memory path = new address[](2); path[0] = address(this); path[1] = UniswapV2Router.WETH(); if (allowance(address(this), address(UniswapV2Router)) < tokenAmount) { _approve(address(this), address(UniswapV2Router), ~uint256(0)); } // make the swap UniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ETHAmount) private { // add the liquidity UniswapV2Router.addLiquidityETH{value: ETHAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable devAddress, block.timestamp ); emit LiquidityAdded(tokenAmount, ETHAmount); } function setAutomatedMarketMakerPair(address _pair, bool value) external onlyOwner { require( isAutomatedMarketMakerPair[_pair] != value, "Automated market maker pair is already set to that value" ); isAutomatedMarketMakerPair[_pair] = value; if (value) { _isExcludedFromMaxWallet[_pair] = true; emit ExcludeFromMaxWallet(_pair, value); } emit SetAutomatedMarketMakerPair(_pair, value); } function setBuyFees( uint8 _rfi, uint8 _treasury, uint8 _dev, uint8 _lp ) external onlyOwner { buyRates.rfi = _rfi; buyRates.treasury = _treasury; buyRates.dev = _dev; buyRates.lp = _lp; buyRates.toSwap = _treasury + _dev + _lp; } function setSellFees( uint8 _rfi, uint8 _treasury, uint8 _dev, uint8 _lp ) external onlyOwner { sellRates.rfi = _rfi; sellRates.treasury = _treasury; sellRates.dev = _dev; sellRates.lp = _lp; sellRates.toSwap = _treasury + _dev + _lp; } function setMaxTransactionAmount( uint256 _maxTxAmountBuyPct, uint256 _maxTxAmountSellPct ) external onlyOwner { maxTxAmountBuy = _tTotal / _maxTxAmountBuyPct; // 100 = 1%, 50 = 2% etc. maxTxAmountSell = _tTotal / _maxTxAmountSellPct; // 100 = 1%, 50 = 2% etc. } function setNumTokensSellToAddToLiq(uint256 amountTokens) external onlyOwner { numTokensSellToAddToLiquidity = amountTokens * 10**_decimals; } function setTreasuryAddress(address payable _treasuryAddress) external onlyOwner { treasuryAddress = _treasuryAddress; } function setDevAddress(address payable _devAddress) external onlyOwner { devAddress = _devAddress; } function manualSwapAll() external onlyOwner { swapAndLiquify(balanceOf(address(this))); } //Manual swap percent of outstanding token function manualSwapPercentage(uint256 tokenpercentage) external onlyOwner { tokenstosell = (balanceOf(address(this))*tokenpercentage)/1000; swapTokensForETH(tokenstosell); payable(devAddress).sendValue(address(this).balance); } //Use this in case BNB are sent to the contract by mistake function rescueBNB() external { devAddress.sendValue(address(this).balance); } function rescueAnyBEP20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner { IERC20(_tokenAddr).transfer(_to, _amount); } // To exclude bots & snipers function isBots(address botAddress, bool isban) external onlyOwner { isBot[botAddress] = isban; } function setMaxWalletAmount(uint256 _maxWalletAmountPct) external onlyOwner { maxWalletAmount = _tTotal / _maxWalletAmountPct; // 100 = 1%, 50 = 2% etc. emit MaxWalletAmountUpdated(maxWalletAmount); } function excludeFromMaxWallet(address account, bool excluded) external onlyOwner { require( _isExcludedFromMaxWallet[account] != excluded, "_isExcludedFromMaxWallet already set to that value" ); _isExcludedFromMaxWallet[account] = excluded; emit ExcludeFromMaxWallet(account, excluded); } }
No current rfi - Tiered Rewarding Feature Applied at APP Launch
function excludeFromReward(address account) external onlyOwner { require(!_isExcluded[account], "Account is already excluded"); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); }
241,636
pragma solidity 0.4.24; import "./SafeMath.sol"; import "./Ownable.sol"; import "./PLGToken.sol"; import "./Whitelist.sol"; /// @title Pledgecamp Crowdsale /// @author Sam Pullman /// @notice Capped crowdsale with bonuses for the Pledgecamp platform contract PLGCrowdsale is Ownable { using SafeMath for uint256; /// @notice Indicates successful token purchase /// @param buyer Fund provider for the token purchase. Must either be `owner` or equal to `beneficiary` /// @param beneficiary Account that ultimately receives purchased tokens /// @param value Amount in wei of investment /// @param tokenAmount Number of tokens purchased (not including bonus) /// @param bonusAmount Number of bonus tokens received event TokenPurchase(address indexed buyer, address indexed beneficiary, uint256 value, uint256 tokenAmount, uint256 bonusAmount); /// @notice Emitted when the ETH to PLG exchange rate has been updated /// @param oldRate The previous exchange rate /// @param newRate The new exchange rate event ExchangeRateUpdated(uint256 oldRate, uint256 newRate); /// @notice Emitted when the crowdsale ends event Closed(); /// True if the sale is active bool public saleActive; /// ERC20 token the crowdsale is based on PLGToken plgToken; /// Timestamp for when the crowdsale may start uint256 public startTime; /// Timestamp set when crowdsale purchasing stops uint256 public endTime; /// Token to ether conversion rate uint256 public tokensPerEther; /// Amount raised so far in wei uint256 public amountRaised; /// The minimum purchase amount in wei uint256 public minimumPurchase; /// The address from which bonus tokens are distributed address public bonusPool; /// The strategy for assigning bonus tokens from bonusPool and assigning vesting contracts Whitelist whitelist; /// @notice Constructor for the Pledgecamp crowdsale contract /// @param _plgToken ERC20 token contract used in the crowdsale /// @param _startTime Timestamp for when the crowdsale may start /// @param _rate Token to ether conversion rate /// @param _minimumPurchase The minimum purchase amount in wei constructor(address _plgToken, uint256 _startTime, uint256 _rate, uint256 _minimumPurchase) public { require(_startTime >= now); require(_rate > 0); require(_plgToken != address(0)); startTime = _startTime; tokensPerEther = _rate; minimumPurchase = _minimumPurchase; plgToken = PLGToken(_plgToken); } /// @notice Set the address of the bonus pool, which provides tokens /// @notice during bonus periods if it contains sufficient PLG /// @param _bonusPool Address of PLG holder function setBonusPool(address _bonusPool) public onlyOwner { bonusPool = _bonusPool; } /// @notice Set the contract that whitelists and calculates how many bonus tokens to award each purchase. /// @param _whitelist The address of the whitelist, which must be a `Whitelist` function setWhitelist(address _whitelist) public onlyOwner { require(_whitelist != address(0)); whitelist = Whitelist(_whitelist); } /// @notice Starts the crowdsale under appropriate conditions function start() public onlyOwner { require(!saleActive); require(now > startTime); require(endTime == 0); require(plgToken.initialized()); require(plgToken.lockExceptions(address(this))); require(bonusPool != address(0)); require(whitelist != address(0)); saleActive = true; } /// @notice End the crowdsale if the sale is active /// @notice Transfer remaining tokens to reserve pool function end() public onlyOwner { require(saleActive); require(bonusPool != address(0)); saleActive = false; endTime = now; withdrawTokens(); owner.transfer(address(this).balance); } /// @notice Withdraw crowdsale ETH to owner wallet function withdrawEth() public onlyOwner { owner.transfer(address(this).balance); } /// @notice Send remaining crowdsale tokens to `bonusPool` after sale is over function withdrawTokens() public onlyOwner { require(!saleActive); uint256 remainingTokens = plgToken.balanceOf(this); plgToken.transfer(bonusPool, remainingTokens); } /// Default function tries to make a token purchase function () external payable { buyTokensInternal(msg.sender); } /// @notice Public crowdsale purchase method function buyTokens() external payable { buyTokensInternal(msg.sender); } /// @notice Owner only method for purchasing on behalf of another person /// @param beneficiary Address to receive the tokens function buyTokensFor(address beneficiary) external payable onlyOwner { require(beneficiary != address(0)); buyTokensInternal(beneficiary); } /// @notice Main crowdsale purchase method, which validates the purchase and assigns bonuses /// @param beneficiary Address to receive the tokens function buyTokensInternal(address beneficiary) private { require(whitelist != address(0)); require(bonusPool != address(0)); require(validPurchase(msg.value)); uint256 weiAmount = msg.value; // This is the whitelist/max purchase check require(whitelist.isValidPurchase(beneficiary, weiAmount)); // Calculate the amount of PLG that's been purchased uint256 tokens = weiAmount.mul(tokensPerEther); // update state amountRaised = amountRaised.add(weiAmount); // Record the purchase in the whitelist contract whitelist.recordPurchase(beneficiary, weiAmount); plgToken.transfer(beneficiary, tokens); uint256 bonusPercent = whitelist.getBonusPercent(beneficiary); uint256 bonusTokens = tokens.mul(bonusPercent) / 100; if(bonusTokens > 0) { plgToken.transferFrom(bonusPool, beneficiary, bonusTokens); } emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens, bonusTokens); } /// @notice Set a new ETH to PLG exchange rate /// @param _tokensPerEther Exchange rate function setExchangeRate(uint256 _tokensPerEther) external onlyOwner { emit ExchangeRateUpdated(tokensPerEther, _tokensPerEther); tokensPerEther = _tokensPerEther; } /// @notice Check various conditions to determine whether a purchase is currently valid /// @param amount The amount of tokens to be purchased function validPurchase(uint256 amount) public view returns (bool) { bool nonZeroPurchase = amount != 0; bool isMinPurchase = (amount >= minimumPurchase); return saleActive && nonZeroPurchase && isMinPurchase; } }
Main crowdsale purchase method, which validates the purchase and assigns bonuses beneficiary Address to receive the tokens This is the whitelist/max purchase check Calculate the amount of PLG that's been purchased update state Record the purchase in the whitelist contract
function buyTokensInternal(address beneficiary) private { require(whitelist != address(0)); require(bonusPool != address(0)); require(validPurchase(msg.value)); uint256 weiAmount = msg.value; require(whitelist.isValidPurchase(beneficiary, weiAmount)); uint256 tokens = weiAmount.mul(tokensPerEther); amountRaised = amountRaised.add(weiAmount); whitelist.recordPurchase(beneficiary, weiAmount); plgToken.transfer(beneficiary, tokens); uint256 bonusPercent = whitelist.getBonusPercent(beneficiary); uint256 bonusTokens = tokens.mul(bonusPercent) / 100; if(bonusTokens > 0) { plgToken.transferFrom(bonusPool, beneficiary, bonusTokens); } emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens, bonusTokens); }
6,427,164
// SPDX-License-Identifier: MIT pragma solidity ^0.8.12; // Get the latest ETH/USD price from chainlink price feed import "AggregatorV3Interface.sol"; import "LinkTokenInterface.sol"; import "VRFCoordinatorV2Interface.sol"; import "VRFConsumerBaseV2.sol"; import "Ownable.sol"; contract MyFundStorage is VRFConsumerBaseV2, Ownable { address payable[] private payers; uint256 private usdEntryFee; uint256 private MINIMUM_ENTRY_FEE = 50; AggregatorV3Interface internal ethUsdPriceFeed; enum FUNDING_STATE { OPEN, CLOSED, END } FUNDING_STATE private funding_state; VRFCoordinatorV2Interface immutable COORDINATOR; LinkTokenInterface immutable LINKTOKEN; // Your subscription ID. uint64 immutable s_subscriptionId; // The gas lane to use, which specifies the maximum gas price to bump to. // For a list of available gas lanes on each network, bytes32 immutable s_keyHash; // Depends on the number of requested values that you want sent to the // fulfillRandomWords() function. Storing each word costs about 20,000 gas, // so 100,000 is a safe default for this example contract. Test and adjust // this limit based on the network that you select, the size of the request, // and the processing of the callback request in the fulfillRandomWords() // function. uint32 immutable s_callbackGasLimit = 100000; // The default is 3, but you can set this higher. uint16 immutable s_requestConfirmations = 3; // For this example, retrieve 2 random values in one request. // Cannot exceed VRFCoordinatorV2.MAX_NUM_WORDS. uint32 immutable s_numWords = 2; uint256[] public s_randomWords; uint256 public s_requestId; address s_owner; event ReturnedRandomness1_endFunding(uint256 requestId); event ReturnedRandomness2_withdraw(uint256 requestId); event ReturnedRandomness3_fulfill(uint256 requestId); /** * @notice Constructor inherits VRFConsumerBaseV2 * * @param subscriptionId - the subscription ID that this contract uses for funding requests * @param vrfCoordinator - coordinator, check https://docs.chain.link/docs/vrf-contracts/#configurations * @param keyHash - the gas lane to use, which specifies the maximum gas price to bump to */ constructor( address _priceFeedAddress, uint64 subscriptionId, address vrfCoordinator, address link, bytes32 keyHash ) VRFConsumerBaseV2(vrfCoordinator) { COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator); LINKTOKEN = LinkTokenInterface(link); s_keyHash = keyHash; s_owner = msg.sender; s_subscriptionId = subscriptionId; usdEntryFee = MINIMUM_ENTRY_FEE * (10**18); ethUsdPriceFeed = AggregatorV3Interface(_priceFeedAddress); funding_state = FUNDING_STATE.CLOSED; } function startFunding() public onlyOwner { require( funding_state == FUNDING_STATE.CLOSED, "Can't start a new fund yet! Current funding is not closed yet!" ); funding_state = FUNDING_STATE.OPEN; } function fund() public payable { // $50 minimum require(funding_state == FUNDING_STATE.OPEN, "Can't fund yet."); require(msg.value >= getEntranceFee(), "Not enough ETH! Minimum $50 value of ETH require!"); payers.push(payable(msg.sender)); } function getETHprice() private view returns (uint256) { (, int256 price, , , ) = ethUsdPriceFeed.latestRoundData(); uint256 adjustedPrice = uint256(price) * 10**10; // 18 decimals return adjustedPrice; } // 1000000000 function getETHpriceUSD() private view returns (uint256) { uint256 ethPrice = getETHprice(); uint256 ethAmountInUsd = ethPrice / 1000000000000000000; // the actual ETH/USD conversation rate, after adjusting the extra 0s. return ethAmountInUsd; } function getEntranceFee() public view returns (uint256) { uint256 adjustedPrice = getETHprice(); // $50, $2,000 / ETH // 50/2,000 // 50 * 100000 / 2000 uint256 costToEnter = (usdEntryFee * 10**18) / adjustedPrice; return costToEnter; } function getCurrentFundingState() public view returns (FUNDING_STATE) { return funding_state; } function getUsersTotalAmount() public view returns (uint256) { return uint256(address(this).balance); } /* function getUserAmount(address user) public view returns (uint256) { return payable(payers[user]).balance; } */ function endFunding() public onlyOwner { require(funding_state == FUNDING_STATE.OPEN, "Funding is not opened yet."); funding_state = FUNDING_STATE.END; this.requestRandomWords(); //funding_state = FUNDING_STATE.CLOSED; emit ReturnedRandomness1_endFunding(s_requestId); } function withdraw() public onlyOwner { require( funding_state == FUNDING_STATE.END, "Funding must be ended before withdraw!" ); require(address(this).balance > 0, "balance: 0"); payable(msg.sender).transfer(address(this).balance); payers = new address payable[](0); funding_state = FUNDING_STATE.CLOSED; emit ReturnedRandomness2_withdraw(s_requestId); } function updateFundingState(FUNDING_STATE _funding_state) public onlyOwner { funding_state = _funding_state; } /** * @notice Requests randomness * Assumes the subscription is funded sufficiently; "Words" refers to unit of data in Computer Science */ function requestRandomWords() external onlyOwner { // Will revert if subscription is not set and funded. s_requestId = COORDINATOR.requestRandomWords( s_keyHash, s_subscriptionId, s_requestConfirmations, s_callbackGasLimit, s_numWords ); } /* * @notice Callback function used by VRF Coordinator * * @param requestId - id of the request * @param randomWords - array of random results from VRF Coordinator */ function fulfillRandomWords( uint256, /* requestId */ uint256[] memory randomWords ) internal override { s_randomWords = randomWords; if (address(this).balance > 0) payable(msg.sender).transfer(address(this).balance); payers = new address payable[](0); funding_state = FUNDING_STATE.CLOSED; emit ReturnedRandomness3_fulfill(s_requestId); } } // 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 ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface LinkTokenInterface { function allowance( address owner, address spender ) external view returns ( uint256 remaining ); function approve( address spender, uint256 value ) external returns ( bool success ); function balanceOf( address owner ) external view returns ( uint256 balance ); function decimals() external view returns ( uint8 decimalPlaces ); function decreaseApproval( address spender, uint256 addedValue ) external returns ( bool success ); function increaseApproval( address spender, uint256 subtractedValue ) external; function name() external view returns ( string memory tokenName ); function symbol() external view returns ( string memory tokenSymbol ); function totalSupply() external view returns ( uint256 totalTokensIssued ); function transfer( address to, uint256 value ) external returns ( bool success ); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns ( bool success ); function transferFrom( address from, address to, uint256 value ) external returns ( bool success ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface VRFCoordinatorV2Interface { /** * @notice Returns the global config that applies to all VRF requests. * @return minimumRequestBlockConfirmations - A minimum number of confirmation * blocks on VRF requests before oracles should respond. * @return fulfillmentFlatFeeLinkPPM - The charge per request on top of the gas fees. * Its flat fee specified in millionths of LINK. * @return maxGasLimit - The maximum gas limit supported for a fulfillRandomWords callback. * @return stalenessSeconds - How long we wait until we consider the ETH/LINK price * (used for converting gas costs to LINK) is stale and use `fallbackWeiPerUnitLink` * @return gasAfterPaymentCalculation - How much gas is used outside of the payment calculation, * i.e. the gas overhead of actually making the payment to oracles. * @return minimumSubscriptionBalance - The minimum subscription balance required to make a request. Its set to be about 300% * of the cost of a single request to handle in ETH/LINK price between request and fulfillment time. * @return fallbackWeiPerUnitLink - fallback ETH/LINK price in the case of a stale feed. */ function getConfig() external view returns ( uint16 minimumRequestBlockConfirmations, uint32 fulfillmentFlatFeeLinkPPM, uint32 maxGasLimit, uint32 stalenessSeconds, uint32 gasAfterPaymentCalculation, uint96 minimumSubscriptionBalance, int256 fallbackWeiPerUnitLink ); /** * @notice Request a set of random words. * @param keyHash - Corresponds to a particular oracle job which uses * that key for generating the VRF proof. Different keyHash's have different gas price * ceilings, so you can select a specific one to bound your maximum per request cost. * @param subId - The ID of the VRF subscription. Must be funded * with at least minimumSubscriptionBalance (see getConfig) LINK * before making a request. * @param minimumRequestConfirmations - How many blocks you'd like the * oracle to wait before responding to the request. See SECURITY CONSIDERATIONS * for why you may want to request more. The acceptable range is * [minimumRequestBlockConfirmations, 200]. * @param callbackGasLimit - How much gas you'd like to receive in your * fulfillRandomWords callback. Note that gasleft() inside fulfillRandomWords * may be slightly less than this amount because of gas used calling the function * (argument decoding etc.), so you may need to request slightly more than you expect * to have inside fulfillRandomWords. The acceptable range is * [5000, maxGasLimit]. * @param numWords - The number of uint256 random values you'd like to receive * in your fulfillRandomWords callback. Note these numbers are expanded in a * secure way by the VRFCoordinator from a single random value supplied by the oracle. * @return requestId - A unique identifier of the request. Can be used to match * a request to a response in fulfillRandomWords. */ function requestRandomWords( bytes32 keyHash, uint64 subId, uint16 minimumRequestConfirmations, uint32 callbackGasLimit, uint32 numWords ) external returns ( uint256 requestId ); /** * @notice Create a VRF subscription. * @return subId - A unique subscription id. * @dev You can manage the consumer set dynamically with addConsumer/removeConsumer. * @dev Note to fund the subscription, use transferAndCall. For example * @dev LINKTOKEN.transferAndCall( * @dev address(COORDINATOR), * @dev amount, * @dev abi.encode(subId)); */ function createSubscription() external returns ( uint64 subId ); /** * @notice Get a VRF subscription. * @param subId - ID of the subscription * @return balance - LINK balance of the subscription in juels. * @return owner - Owner of the subscription * @return consumers - List of consumer address which are able to use this subscription. */ function getSubscription( uint64 subId ) external view returns ( uint96 balance, address owner, address[] memory consumers ); /** * @notice Request subscription owner transfer. * @param subId - ID of the subscription * @param newOwner - proposed new owner of the subscription */ function requestSubscriptionOwnerTransfer( uint64 subId, address newOwner ) external; /** * @notice Request subscription owner transfer. * @param subId - ID of the subscription * @dev will revert if original owner of subId has * not requested that msg.sender become the new owner. */ function acceptSubscriptionOwnerTransfer( uint64 subId ) external; /** * @notice Add a consumer to a VRF subscription. * @param subId - ID of the subscription * @param consumer - New consumer which can use the subscription */ function addConsumer( uint64 subId, address consumer ) external; /** * @notice Remove a consumer from a VRF subscription. * @param subId - ID of the subscription * @param consumer - Consumer to remove from the subscription */ function removeConsumer( uint64 subId, address consumer ) external; /** * @notice Withdraw funds from a VRF subscription * @param subId - ID of the subscription * @param to - Where to send the withdrawn LINK to * @param amount - How much to withdraw in juels */ function defundSubscription( uint64 subId, address to, uint96 amount ) external; /** * @notice Cancel a subscription * @param subId - ID of the subscription * @param to - Where to send the remaining LINK to */ function cancelSubscription( uint64 subId, address to ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. It ensures 2 things: * @dev 1. The fulfillment came from the VRFCoordinator * @dev 2. The consumer contract implements fulfillRandomWords. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash). Create subscription, fund it * @dev and your consumer contract as a consumer of it (see VRFCoordinatorInterface * @dev subscription management functions). * @dev Call requestRandomWords(keyHash, subId, minimumRequestConfirmations, * @dev callbackGasLimit, numWords), * @dev see (VRFCoordinatorInterface for a description of the arguments). * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomWords method. * * @dev The randomness argument to fulfillRandomWords is a set of random words * @dev generated from your requestId and the blockHash of the request. * * @dev If your contract could have concurrent requests open, you can use the * @dev requestId returned from requestRandomWords to track which response is associated * @dev with which randomness request. * @dev See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously. * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. It is for this reason that * @dev that you can signal to an oracle you'd like them to wait longer before * @dev responding to the request (however this is not enforced in the contract * @dev and so remains effective only in the case of unmodified oracle software). */ abstract contract VRFConsumerBaseV2 { error OnlyCoordinatorCanFulfill(address have, address want); address immutable private vrfCoordinator; /** * @param _vrfCoordinator address of VRFCoordinator contract */ constructor( address _vrfCoordinator ) { vrfCoordinator = _vrfCoordinator; } /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBaseV2 expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomWords the VRF output expanded to the requested number of words */ function fulfillRandomWords( uint256 requestId, uint256[] memory randomWords ) internal virtual; // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomWords( uint256 requestId, uint256[] memory randomWords ) external { if (msg.sender != vrfCoordinator) { revert OnlyCoordinatorCanFulfill(msg.sender, vrfCoordinator); } fulfillRandomWords(requestId, randomWords); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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
interface VRFCoordinatorV2Interface { function getConfig() external view returns ( uint16 minimumRequestBlockConfirmations, uint32 fulfillmentFlatFeeLinkPPM, uint32 maxGasLimit, uint32 stalenessSeconds, uint32 gasAfterPaymentCalculation, uint96 minimumSubscriptionBalance, int256 fallbackWeiPerUnitLink ); function requestRandomWords( bytes32 keyHash, uint64 subId, uint16 minimumRequestConfirmations, uint32 callbackGasLimit, uint32 numWords ) external returns ( uint256 requestId ); function createSubscription() external returns ( uint64 subId ); function getSubscription( uint64 subId ) external view returns ( uint96 balance, address owner, address[] memory consumers ); function requestSubscriptionOwnerTransfer( uint64 subId, address newOwner ) external; function acceptSubscriptionOwnerTransfer( uint64 subId ) external; function addConsumer( uint64 subId, address consumer ) external; function removeConsumer( uint64 subId, address consumer ) external; function defundSubscription( uint64 subId, address to, uint96 amount ) external; function cancelSubscription( uint64 subId, address to ) external; }
10,125,601
./partial_match/1/0xE3C67a3be126b6f41D66EAbB89F1e346Cd099195/sources/MiltonUsdt.sol
Calculates interest fixed without division by Constants.D18 Constants.YEAR_IN_SECONDS
function calculateQuasiInterestFixed( uint256 notional, uint256 swapFixedInterestRate, uint256 swapPeriodInSeconds ) internal pure returns (uint256) { return notional * Constants.WAD_YEAR_IN_SECONDS + notional * swapFixedInterestRate * swapPeriodInSeconds; }
2,612,683
./full_match/1/0x327Fe52E44A1Fc68E8596dF8769A4B5DC538550e/sources/project:/contracts/lending/WasabiBNPL.sol
Returns the option data for the given option id
function getOptionData( uint256 _optionId ) external view returns (WasabiStructs.OptionData memory optionData) { LoanInfo memory loanInfo = optionToLoan[_optionId]; INFTLending.LoanDetails memory loanDetails = INFTLending( loanInfo.nftLending ).getLoanDetails(loanInfo.loanId); bool active = wasabiOption.ownerOf(_optionId) != address(0) && loanDetails.loanExpiration > block.timestamp; optionData = WasabiStructs.OptionData( active, WasabiStructs.OptionType.CALL, loanDetails.repayAmount, loanDetails.loanExpiration, loanDetails.tokenId ); }
8,325,897
./full_match/1/0x833f7bDa72AcDbE7acA33F28d00bBF2dF20682d6/sources/contracts/integrations/uniswap/IUniswapV3.sol
Router token swapping functionality Functions for swapping tokens via Uniswap V3
interface ISwapRouter { pragma solidity >=0.7.5; struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } 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; } function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } }
4,976,265
pragma solidity ^0.4.19; // Vicent Nos & Enrique Santos 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 Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() internal { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } ////////////////////////////////////////////////////////////// // // // Lescovex, Shareholder's ERC20 // // // ////////////////////////////////////////////////////////////// contract LescovexERC20 is Ownable { using SafeMath for uint256; mapping (address => uint256) holded; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; uint256 public constant blockEndICO = 1524182460; /* Public variables for the ERC20 token */ string public constant standard = "ERC20 Lescovex"; uint8 public constant decimals = 8; // hardcoded to be a constant uint256 public totalSupply; string public name; string public symbol; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function holdedOf(address _owner) public view returns (uint256 balance) { return holded[_owner]; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function transfer(address _to, uint256 _value) public returns (bool) { require(block.timestamp > blockEndICO || msg.sender == owner); require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); holded[_to] = block.number; balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); holded[_to] = block.number; balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public onlyOwner returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public onlyOwner 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 onlyOwner 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; } /* Approve and then communicate the approved contract in a single tx */ 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; } } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public ; } contract Lescovex is LescovexERC20 { // Contract variables and constants uint256 constant initialSupply = 0; string constant tokenName = "Lescovex Shareholder's"; string constant tokenSymbol = "LCX"; address public LescovexAddr = 0xD26286eb9E6E623dba88Ed504b628F648ADF7a0E; uint256 public constant minPrice = 7500000000000000; uint256 public buyPrice = minPrice; uint256 public tokenReward = 0; // constant to simplify conversion of token amounts into integer form uint256 public tokenUnit = uint256(10)**decimals; //Declare logging events event LogDeposit(address sender, uint amount); event LogWithdrawal(address receiver, uint amount); /* Initializes contract with initial supply tokens to the creator of the contract */ function Lescovex() public { totalSupply = initialSupply; // Update total supply name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } function () public payable { buy(); // Allow to buy tokens sending ether directly to contract } modifier status() { _; // modified function code should go before prices update if (block.timestamp < 1519862460){ //until 1 march 2018 if (totalSupply < 50000000000000){ buyPrice = 7500000000000000; } else { buyPrice = 8000000000000000; } } else if (block.timestamp < 1520640060){ // until 10 march 2018 buyPrice = 8000000000000000; } else if (block.timestamp<1521504060){ //until 20 march 2018 buyPrice = 8500000000000000; } else if (block.timestamp < 1522368060){ //until 30 march 2018 buyPrice = 9000000000000000; } else if (block.timestamp < 1523232060){ //until 9 april 2018 buyPrice = 9500000000000000; } else { buyPrice = 10000000000000000; } } function deposit() public payable onlyOwner returns(bool success) { // Check for overflows; assert (this.balance + msg.value >= this.balance); // Check for overflows tokenReward = this.balance / totalSupply; //executes event to reflect the changes LogDeposit(msg.sender, msg.value); return true; } function withdrawReward() public status { require (block.number - holded[msg.sender] > 172800); //1 month holded[msg.sender] = block.number; uint256 ethAmount = tokenReward * balances[msg.sender]; //send eth to owner address msg.sender.transfer(ethAmount); //executes event to register the changes LogWithdrawal(msg.sender, ethAmount); } function withdraw(uint value) public onlyOwner { //send eth to owner address msg.sender.transfer(value); //executes event to register the changes LogWithdrawal(msg.sender, value); } function buy() public payable status { require (totalSupply <= 1000000000000000); require(block.timestamp < blockEndICO); uint256 tokenAmount = (msg.value / buyPrice)*tokenUnit ; // calculates the amount transferBuy(msg.sender, tokenAmount); LescovexAddr.transfer(msg.value); } function transferBuy(address _to, uint256 _value) internal returns (bool) { require(_to != address(0)); // SafeMath.add will throw if there is not enough balance. totalSupply = totalSupply.add(_value*2); holded[_to] = block.number; balances[LescovexAddr] = balances[LescovexAddr].add(_value); balances[_to] = balances[_to].add(_value); Transfer(this, _to, _value); Transfer(this, LescovexAddr, _value); return true; } function burn(address addr) public onlyOwner{ totalSupply=totalSupply.sub(balances[addr]); balances[addr]=0; } }
Initializes contract with initial supply tokens to the creator of the contract /
function Lescovex() public { }
6,359,981
pragma solidity >=0.4.22 <0.5.0; import "./KeyValueStorage.sol"; import "./Managed.sol"; /** * owned = own an eternal shared storage. * * The owner is stored in the key value storage with a special key * */ contract owned is managed { /////////////////////////////////////// // the special key of owner in the _storage // using different hash algorithm to avoid conflict with other keys bytes32 internal constant __OWNER__ = sha256("__owner__"); // the external key-value storage for this module. KeyValueStorage internal _storage; /** * returns the external storage address */ function getStorage() view public returns (address) { return address(_storage); } /** * set the storage, just for test cases. * in normal scenario, only ModuleFactory, i.e. the manager of Module * can call this. however, ModuleFactory does not expose this function * to the external world. */ function setStorage(KeyValueStorage _newStorage) onlyManager public { // no need to check _newStorage or _newStorage manager. this func should be only used for testing. _storage = _newStorage; } // owner event OwnerChanged(address _from, address _to); modifier onlyOwner { // no need to check storage because getOwner will do it. require(msg.sender == getOwner(), "only owner"); _; } function getOwner() view public returns (address) { // no need to check _storage, 0x0.getAddress will fail anyway. return _storage.getAddress(__OWNER__); } /** * requires owner of manager to change the owner */ function changeOwner(address _newOwner) isRunning public { // allows only owner or manager to do this require(msg.sender == manager || msg.sender == getOwner(), "only manager or owner"); // no need to check _storage, 0x0.setAddress will fail anyway. address _oldOwner = getOwner(); _storage.setAddress(__OWNER__, _newOwner); emit OwnerChanged(_oldOwner, _newOwner); } }
no need to check _storage, 0x0.getAddress will fail anyway.
function getOwner() view public returns (address) { return _storage.getAddress(__OWNER__); }
12,778,017
// SPDX-License-Identifier: MIT pragma solidity ^0.5.17; interface IERC20 { function TOTALSUPPLY676() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF365(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER984(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE421(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE350(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM233(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER7(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL756(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD231(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB723(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB723(a, b, "SafeMath: subtraction overflow"); } function SUB723(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 MUL124(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV477(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV477(a, b, "SafeMath: division by zero"); } function DIV477(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD902(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD902(a, b, "SafeMath: modulo by zero"); } function MOD902(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT563(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } function TOPAYABLE474(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE638(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING 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"); } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER541(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN431(token, abi.encodeWithSelector(token.TRANSFER984.selector, to, value)); } function SAFETRANSFERFROM607(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN431(token, abi.encodeWithSelector(token.TRANSFERFROM233.selector, from, to, value)); } function SAFEAPPROVE839(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.ALLOWANCE421(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN431(token, abi.encodeWithSelector(token.APPROVE350.selector, spender, value)); } function SAFEINCREASEALLOWANCE550(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE421(address(this), spender).ADD231(value); CALLOPTIONALRETURN431(token, abi.encodeWithSelector(token.APPROVE350.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE384(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE421(address(this), spender).SUB723(value, "SafeERC20: decreased allowance below zero"); CALLOPTIONALRETURN431(token, abi.encodeWithSelector(token.APPROVE350.selector, spender, newAllowance)); } function CALLOPTIONALRETURN431(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // 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).ISCONTRACT563(), "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"); } } } // interface IController { function WITHDRAW26(address, uint256) external; //inject NONSTANDARD NAMING function BALANCEOF365(address) external view returns (uint256); //inject NONSTANDARD NAMING function EARN979(address, uint256) external; //inject NONSTANDARD NAMING function WANT15(address) external view returns (address); //inject NONSTANDARD NAMING function REWARDS956() external view returns (address); //inject NONSTANDARD NAMING function VAULTS197(address) external view returns (address); //inject NONSTANDARD NAMING function STRATEGIES736(address) external view returns (address); //inject NONSTANDARD NAMING } // interface Gauge { function DEPOSIT301(uint256) external; //inject NONSTANDARD NAMING function BALANCEOF365(address) external view returns (uint256); //inject NONSTANDARD NAMING function WITHDRAW26(uint256) external; //inject NONSTANDARD NAMING } // interface Mintr { function MINT474(address) external; //inject NONSTANDARD NAMING } // interface Uni { function SWAPEXACTTOKENSFORTOKENS884( //inject NONSTANDARD NAMING uint256, uint256, address[] calldata, address, uint256 ) external; } // interface ICurveFi { function GET_VIRTUAL_PRICE966() external view returns (uint256); //inject NONSTANDARD NAMING function ADD_LIQUIDITY5( //inject NONSTANDARD NAMING // sBTC pool uint256[3] calldata amounts, uint256 min_mint_amount ) external; function ADD_LIQUIDITY5( //inject NONSTANDARD NAMING // bUSD pool uint256[4] calldata amounts, uint256 min_mint_amount ) external; function REMOVE_LIQUIDITY_IMBALANCE212(uint256[4] calldata amounts, uint256 max_burn_amount) external; //inject NONSTANDARD NAMING function REMOVE_LIQUIDITY359(uint256 _amount, uint256[4] calldata amounts) external; //inject NONSTANDARD NAMING function EXCHANGE368( //inject NONSTANDARD NAMING int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; } interface Zap { function REMOVE_LIQUIDITY_ONE_COIN241( //inject NONSTANDARD NAMING uint256, int128, uint256 ) external; } // // NOTE: Basically an alias for Vaults interface yERC20 { function DEPOSIT301(uint256 _amount) external; //inject NONSTANDARD NAMING function WITHDRAW26(uint256 _amount) external; //inject NONSTANDARD NAMING function GETPRICEPERFULLSHARE41() external view returns (uint256); //inject NONSTANDARD NAMING } // interface VoterProxy { function WITHDRAW26( //inject NONSTANDARD NAMING address _gauge, address _token, uint256 _amount ) external returns (uint256); function BALANCEOF365(address _gauge) external view returns (uint256); //inject NONSTANDARD NAMING function WITHDRAWALL38(address _gauge, address _token) external returns (uint256); //inject NONSTANDARD NAMING function DEPOSIT301(address _gauge, address _token) external; //inject NONSTANDARD NAMING function HARVEST174(address _gauge) external; //inject NONSTANDARD NAMING function LOCK81() external; //inject NONSTANDARD NAMING } contract StrategyCurve3CrvVoterProxy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public constant want150 = address(0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490); //inject NONSTANDARD NAMING address public constant crv64 = address(0xD533a949740bb3306d119CC777fa900bA034cd52); //inject NONSTANDARD NAMING address public constant uni956 = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //inject NONSTANDARD NAMING address public constant weth657 = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // used for crv <> weth <> dai route //inject NONSTANDARD NAMING address public constant dai412 = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); //inject NONSTANDARD NAMING address public constant curve384 = address(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7); //inject NONSTANDARD NAMING address public constant gauge100 = address(0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A); //inject NONSTANDARD NAMING address public constant voter170 = address(0xF147b8125d2ef93FB6965Db97D6746952a133934); //inject NONSTANDARD NAMING uint256 public keepCRV = 1000; uint256 public performanceFee = 450; uint256 public strategistReward = 50; uint256 public withdrawalFee = 50; uint256 public constant fee_denominator706 = 10000; //inject NONSTANDARD NAMING address public proxy; address public governance; address public controller; address public strategist; uint256 public earned; // lifetime strategy earnings denominated in `want` token event HARVESTED63(uint wantEarned, uint lifetimeEarned); //inject NONSTANDARD NAMING constructor(address _controller) public { governance = msg.sender; strategist = msg.sender; controller = _controller; } function GETNAME974() external pure returns (string memory) { //inject NONSTANDARD NAMING return "StrategyCurve3CrvVoterProxy"; } function SETSTRATEGIST311(address _strategist) external { //inject NONSTANDARD NAMING require(msg.sender == governance || msg.sender == strategist, "!authorized"); strategist = _strategist; } function SETKEEPCRV999(uint256 _keepCRV) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); keepCRV = _keepCRV; } function SETWITHDRAWALFEE117(uint256 _withdrawalFee) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); withdrawalFee = _withdrawalFee; } function SETPERFORMANCEFEE881(uint256 _performanceFee) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); performanceFee = _performanceFee; } function SETSTRATEGISTREWARD913(uint _strategistReward) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); strategistReward = _strategistReward; } function SETPROXY556(address _proxy) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); proxy = _proxy; } function DEPOSIT301() public { //inject NONSTANDARD NAMING uint256 _want = IERC20(want150).BALANCEOF365(address(this)); if (_want > 0) { IERC20(want150).SAFETRANSFER541(proxy, _want); VoterProxy(proxy).DEPOSIT301(gauge100, want150); } } // Controller only function for creating additional rewards from dust function WITHDRAW26(IERC20 _asset) external returns (uint256 balance) { //inject NONSTANDARD NAMING require(msg.sender == controller, "!controller"); require(want150 != address(_asset), "want"); require(crv64 != address(_asset), "crv"); require(dai412 != address(_asset), "dai"); balance = _asset.BALANCEOF365(address(this)); _asset.SAFETRANSFER541(controller, balance); } // Withdraw partial funds, normally used with a vault withdrawal function WITHDRAW26(uint256 _amount) external { //inject NONSTANDARD NAMING require(msg.sender == controller, "!controller"); uint256 _balance = IERC20(want150).BALANCEOF365(address(this)); if (_balance < _amount) { _amount = _WITHDRAWSOME169(_amount.SUB723(_balance)); _amount = _amount.ADD231(_balance); } uint256 _fee = _amount.MUL124(withdrawalFee).DIV477(fee_denominator706); IERC20(want150).SAFETRANSFER541(IController(controller).REWARDS956(), _fee); address _vault = IController(controller).VAULTS197(address(want150)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want150).SAFETRANSFER541(_vault, _amount.SUB723(_fee)); } function _WITHDRAWSOME169(uint256 _amount) internal returns (uint256) { //inject NONSTANDARD NAMING return VoterProxy(proxy).WITHDRAW26(gauge100, want150, _amount); } // Withdraw all funds, normally used when migrating strategies function WITHDRAWALL38() external returns (uint256 balance) { //inject NONSTANDARD NAMING require(msg.sender == controller, "!controller"); _WITHDRAWALL587(); balance = IERC20(want150).BALANCEOF365(address(this)); address _vault = IController(controller).VAULTS197(address(want150)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want150).SAFETRANSFER541(_vault, balance); } function _WITHDRAWALL587() internal { //inject NONSTANDARD NAMING VoterProxy(proxy).WITHDRAWALL38(gauge100, want150); } function HARVEST174() public { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!authorized"); VoterProxy(proxy).HARVEST174(gauge100); uint256 _crv = IERC20(crv64).BALANCEOF365(address(this)); if (_crv > 0) { uint256 _keepCRV = _crv.MUL124(keepCRV).DIV477(fee_denominator706); IERC20(crv64).SAFETRANSFER541(voter170, _keepCRV); _crv = _crv.SUB723(_keepCRV); IERC20(crv64).SAFEAPPROVE839(uni956, 0); IERC20(crv64).SAFEAPPROVE839(uni956, _crv); address[] memory path = new address[](3); path[0] = crv64; path[1] = weth657; path[2] = dai412; Uni(uni956).SWAPEXACTTOKENSFORTOKENS884(_crv, uint256(0), path, address(this), now.ADD231(1800)); } uint256 _dai = IERC20(dai412).BALANCEOF365(address(this)); if (_dai > 0) { IERC20(dai412).SAFEAPPROVE839(curve384, 0); IERC20(dai412).SAFEAPPROVE839(curve384, _dai); ICurveFi(curve384).ADD_LIQUIDITY5([_dai, 0, 0], 0); } uint256 _want = IERC20(want150).BALANCEOF365(address(this)); if (_want > 0) { uint256 _fee = _want.MUL124(performanceFee).DIV477(fee_denominator706); uint256 _reward = _want.MUL124(strategistReward).DIV477(fee_denominator706); IERC20(want150).SAFETRANSFER541(IController(controller).REWARDS956(), _fee); IERC20(want150).SAFETRANSFER541(strategist, _reward); DEPOSIT301(); } VoterProxy(proxy).LOCK81(); earned = earned.ADD231(_want); emit HARVESTED63(_want, earned); } function BALANCEOFWANT698() public view returns (uint256) { //inject NONSTANDARD NAMING return IERC20(want150).BALANCEOF365(address(this)); } function BALANCEOFPOOL677() public view returns (uint256) { //inject NONSTANDARD NAMING return VoterProxy(proxy).BALANCEOF365(gauge100); } function BALANCEOF365() public view returns (uint256) { //inject NONSTANDARD NAMING return BALANCEOFWANT698().ADD231(BALANCEOFPOOL677()); } function SETGOVERNANCE126(address _governance) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function SETCONTROLLER597(address _controller) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); controller = _controller; } }
inject NONSTANDARD NAMING
function DEPOSIT301(uint256 _amount) external;
14,088,957
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./interfaces/IProposer.sol"; import "./libraries/Cast.sol"; import "./libraries/Checkpoint.sol"; import "./libraries/ERC721Permit.sol"; import "./libraries/Firewall.sol"; import "./libraries/Header.sol"; import "./libraries/Status.sol"; interface IAttest { function weightOf(address account) external view returns (uint256); function weightIn(address account, uint256 blockNumber) external view returns (uint256); function weightAt( address account, uint256 index ) external view returns (uint160, uint32, uint32); } /// @title Proposer /// @notice Tokenizes proposals as ERC721. contract Proposer is IProposer, ERC721Permit, Firewall { using Cast for uint256; using Header for Header.Data; error AttestOverflow(); error ContestationFailed(); error InvalidCheckpoint(uint256 index); error InvalidChoice(uint8 choice); error StatusError(Status status); error UndefinedId(uint256 tokenId); error UndefinedSelector(bytes4 selector); /// @inheritdoc IProposer address public immutable runtime; /// @inheritdoc IProposer address public immutable token; /// @inheritdoc IProposer uint128 public threshold; /// @inheritdoc IProposer uint128 public quorum; /// @inheritdoc IProposer uint32 public delay; /// @inheritdoc IProposer uint32 public period; /// @inheritdoc IProposer uint32 public window; /// @inheritdoc IProposer uint32 public extension; /// @inheritdoc IProposer uint32 public ttl; /// @inheritdoc IProposer uint32 public lifespan; /// @dev The next minted token id. uint256 private _nextId = 0; /// @inheritdoc IProposer mapping(uint256 => Proposal) public proposals; /// @inheritdoc IProposer mapping(uint256 => mapping(address => uint256)) public attests; constructor(address runtime_, address token_) ERC721Permit( "DAO Execution System Proposal NFT-V1", "DES-NFT-V1" ) { runtime = runtime_; token = token_; delay = 17280; // 3 days pending period = 40320; // 7 days to attest window = 17280; // 3 days to contest extension = 17280; // 3 days of contestation ttl = 17280; // 3 days queued lifespan = 80640; // 14 days until expiry (when accepted) } /// @inheritdoc IProposer function get(uint256 tokenId) external view returns (Proposal memory) { return proposals[tokenId]; } /// @inheritdoc IProposer function set(bytes4 selector, bytes memory data) external { if (selector == IProposer.threshold.selector) threshold = abi.decode(data, (uint128)); else if (selector == IProposer.threshold.selector) quorum = abi.decode(data, (uint128)); else if (selector == IProposer.delay.selector) delay = abi.decode(data, (uint32)); else if (selector == IProposer.period.selector) period = abi.decode(data, (uint32)); else if (selector == IProposer.window.selector) window = abi.decode(data, (uint32)); else if (selector == IProposer.extension.selector) extension = abi.decode(data, (uint32)); else if (selector == IProposer.ttl.selector) ttl = abi.decode(data, (uint32)); else if (selector == IProposer.lifespan.selector) lifespan = abi.decode(data, (uint32)); else revert UndefinedSelector(selector); } /// @inheritdoc IProposer function next() external view returns (uint256) { return _nextId; } /// @inheritdoc IProposer function hash(uint256 tokenId, uint256 index) external view returns (bytes32) { return proposals[tokenId].hash[index]; } /// @inheritdoc IProposer function hashes(uint256 tokenId) external view returns (bytes32[] memory) { return proposals[tokenId].hash; } /// @inheritdoc IProposer function maturity(uint256 tokenId) public view returns (uint32) { return proposals[tokenId].finality + ttl; } /// @inheritdoc IProposer function expiry(uint256 tokenId) public view returns (uint32) { return proposals[tokenId].finality + ttl + lifespan; } /// @inheritdoc IProposer function status(uint256 tokenId) public view returns (Status) { if (proposals[tokenId].merged) return Status.Merged; if (proposals[tokenId].closed) return Status.Closed; if (proposals[tokenId].start == 0) { if (proposals[tokenId].staged) { return Status.Staged; } else { return Status.Draft; } } if (_blockNumber() < proposals[tokenId].start) return Status.Pending; if (_blockNumber() < proposals[tokenId].end) return Status.Open; if (_blockNumber() < proposals[tokenId].trial) return Status.Contesting; if (_blockNumber() < proposals[tokenId].finality) return Status.Validation; if ( proposals[tokenId].ack > proposals[tokenId].nack && proposals[tokenId].ack > quorum ) { if (_blockNumber() < maturity(tokenId)) { return Status.Queued; } if (_blockNumber() < expiry(tokenId)) { return Status.Approved; } } return Status.Closed; } /// @inheritdoc IProposer function mint(address to, Header.Data calldata header) external auth returns (uint256 tokenId) { _mint(to, (tokenId = _nextId++)); _commit(tokenId, header); } /// @inheritdoc IProposer function stage(uint256 tokenId) external { require(_isApprovedOrOwner(msg.sender, tokenId), "Unauthorized"); require(status(tokenId) == Status.Draft, "NotDraft"); proposals[tokenId].staged = true; emit Stage(msg.sender, tokenId); } /// @inheritdoc IProposer function unstage(uint256 tokenId) external { require(_isApprovedOrOwner(msg.sender, tokenId), "Unauthorized"); require(status(tokenId) == Status.Staged, "NotStaged"); proposals[tokenId].staged = false; emit Unstage(msg.sender, tokenId); } /// @inheritdoc IProposer function open(uint256 tokenId) external { if (_isApprovedOrOwner(msg.sender, tokenId)) require(status(tokenId) == Status.Draft, "NotDraft"); else require(status(tokenId) == Status.Staged, "NotStaged"); require(IAttest(token).weightOf(msg.sender) >= threshold, "Insufficient"); proposals[tokenId].start = uint32(block.number) + delay; proposals[tokenId].end = proposals[tokenId].start + period; proposals[tokenId].trial = proposals[tokenId].end; proposals[tokenId].finality = proposals[tokenId].end + window; emit Open( msg.sender, tokenId, proposals[tokenId].start, proposals[tokenId].end, proposals[tokenId].finality ); } /// @inheritdoc IProposer function close(uint256 tokenId) external { require(_isApprovedOrOwner(msg.sender, tokenId), "Unauthorized"); require( status(tokenId) != Status.Closed || status(tokenId) != Status.Merged, "StatusMismatch" ); proposals[tokenId].closed = true; emit Close(msg.sender, tokenId); } /// @inheritdoc IProposer function done(uint256 tokenId) external auth { require(status(tokenId) == Status.Approved, "NotApproved"); proposals[tokenId].merged = true; emit Merge(tokenId); } /// @inheritdoc IProposer function attest(uint256 tokenId, uint8 support, uint96 amount, string memory comment) external { if (!_exists(tokenId)) revert UndefinedId(tokenId); Proposal storage proposal = proposals[tokenId]; Status status_ = status(tokenId); if (status_ == Status.Open) { if (support > 2) { revert InvalidChoice(support); } } else if (status_ == Status.Contesting) { if (proposal.side) { if (support != 1 && support != 2) { revert InvalidChoice(support); } } else { if (support != 0 && support != 2) { revert InvalidChoice(support); } } } else { revert StatusError(status_); } uint160 weight = IAttest(token).weightIn(msg.sender, proposal.start).u160(); if (amount > weight - attests[tokenId][msg.sender]) revert AttestOverflow(); if (support == 0) proposal.ack += amount; if (support == 1) proposal.nack += amount; attests[tokenId][msg.sender] += amount; emit Attest(msg.sender, tokenId, support, amount, comment); } /// @inheritdoc IProposer function contest(uint256 tokenId) external { if (status(tokenId) != Status.Validation) revert StatusError(status(tokenId)); Proposal storage proposal = proposals[tokenId]; if (proposal.ack < quorum) revert ContestationFailed(); if (proposal.side && proposal.ack > proposal.nack) revert ContestationFailed(); if (!proposal.side && proposal.nack > proposal.ack) revert ContestationFailed(); proposal.trial = _blockNumber() + extension; proposal.finality = proposal.trial + window; proposal.side = !proposal.side; emit Contest( msg.sender, tokenId, proposal.trial, proposal.finality, proposal.side ); } /// @inheritdoc IProposer function commit(uint256 tokenId, Header.Data calldata header) external { require(_isApprovedOrOwner(msg.sender, tokenId), "NotApprovedOrOwner"); _commit(tokenId, header); } /// @dev Internal commit function. function _commit(uint256 tokenId, Header.Data calldata header) internal { require(status(tokenId) == Status.Draft, "NotDraft"); proposals[tokenId].hash = header.hash(); emit Commit(msg.sender, tokenId, proposals[tokenId].hash, header); } /// @dev Increments a proposal nonce used for `ERC721Permit`. function _getAndIncrementNonce(uint256 tokenId) internal override returns (uint256) { return uint256(proposals[tokenId].nonce++); } /// @dev Returns a `uint32` casted `block.number`. function _blockNumber() internal view returns (uint32) { return uint32(block.number); } }
@inheritdoc IProposer
function maturity(uint256 tokenId) public view returns (uint32) { return proposals[tokenId].finality + ttl; }
5,475,946
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../ConvergentCurvePool.sol"; import "../balancer-core-v2/lib/math/FixedPoint.sol"; contract TestConvergentCurvePool is ConvergentCurvePool { using FixedPoint for uint256; constructor( IERC20 _underlying, IERC20 _bond, uint256 _expiration, uint256 _unitSeconds, IVault vault, uint256 _percentFee, address _governance, string memory name, string memory symbol ) ConvergentCurvePool( _underlying, _bond, _expiration, _unitSeconds, vault, _percentFee, _percentFee, _governance, name, symbol ) {} // solhint-disable-line no-empty-blocks event UIntReturn(uint256 data); // Allows tests to burn LP tokens directly function burnLP( uint256 outputUnderlying, uint256 outputBond, uint256[] memory currentBalances, address source ) public { uint256[] memory outputs = _burnLP( outputUnderlying, outputBond, currentBalances, source ); // We use this to return because returndata from state changing tx isn't easily accessible. emit UIntReturn(outputs[baseIndex]); emit UIntReturn(outputs[bondIndex]); } // Allows tests to mint LP tokens directly function mintLP( uint256 inputUnderlying, uint256 inputBond, uint256[] memory currentBalances, address recipient ) public { uint256[] memory amountsIn = _mintLP( inputUnderlying, inputBond, currentBalances, recipient ); // We use this to return because returndata from state changing tx isn't easily accessible. emit UIntReturn(amountsIn[baseIndex]); emit UIntReturn(amountsIn[bondIndex]); } // Allows tests to access mint gov LP function mintGovLP(uint256[] memory currentReserves) public { _mintGovernanceLP(currentReserves); } // Allows tests to access the trade fee calculator function assignTradeFee( uint256 amountIn, uint256 amountOut, IERC20 outputToken, bool isInputTrade ) public { IERC20 quoteToken; if (outputToken == underlying) { amountIn = _tokenToFixed(amountIn, bond); amountOut = _tokenToFixed(amountOut, underlying); quoteToken = isInputTrade ? bond : underlying; } else { amountIn = _tokenToFixed(amountIn, underlying); amountOut = _tokenToFixed(amountOut, bond); quoteToken = isInputTrade ? underlying : bond; } uint256 newQuote = _assignTradeFee( amountIn, amountOut, outputToken, isInputTrade ); emit UIntReturn(_fixedToToken(newQuote, quoteToken)); } // Allows tests to specify fees without making trades function setFees(uint128 amountUnderlying, uint128 amountBond) public { feesUnderlying = amountUnderlying; feesBond = amountBond; } function setLPBalance(address who, uint256 what) public { uint256 current = this.balanceOf(who); if (what > current) { _mintPoolTokens(who, what - current); } else if (what < current) { _burnPoolTokens(who, current - what); } } // Public interface to test '_getYieldExponent' function getYieldExponent() public view returns (uint256) { return _getYieldExponent(); } uint256 public time; function swapSimulation( IPoolSwapStructs.SwapRequest memory request, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut, uint256 _time, uint256 expectedPrice, uint256 totalSupply ) public returns (uint256) { time = _time; // We now set the total supply setLPBalance(request.from, totalSupply); uint256 quote = onSwap( request, currentBalanceTokenIn, currentBalanceTokenOut ); time = 0; if (expectedPrice != 0) { return (quote > expectedPrice) ? quote - expectedPrice : expectedPrice - quote; } else { return quote; } } // Allows the error measurement test to set the time function _getYieldExponent() internal override view returns (uint256) { // Load the stored time if it's set use that instead if (time > 0) { return uint256(FixedPoint.ONE).sub(time); } else { return super._getYieldExponent(); } } // Public interface to test '_tokenToFixed' function tokenToFixed(uint256 amount, IERC20 token) public view returns (uint256) { return _tokenToFixed(amount, token); } // Public interface to test '_fixedToToken' function fixedToToken(uint256 amount, IERC20 token) public view returns (uint256) { return _fixedToToken(amount, token); } // Public interface to test '_normalize' function normalize( uint256 amount, uint8 decimalsBefore, uint8 decimalsAfter ) public pure returns (uint256) { return _normalize(amount, decimalsBefore, decimalsAfter); } }
Allows tests to mint LP tokens directly We use this to return because returndata from state changing tx isn't easily accessible.
function mintLP( uint256 inputUnderlying, uint256 inputBond, uint256[] memory currentBalances, address recipient ) public { uint256[] memory amountsIn = _mintLP( inputUnderlying, inputBond, currentBalances, recipient ); emit UIntReturn(amountsIn[baseIndex]); emit UIntReturn(amountsIn[bondIndex]); }
898,144
// VERSION K pragma solidity ^0.4.8; // // FOR REFERENCE - INCLUDE iE4RowEscrow (interface) CONTRACT at the top ..... // contract iE4RowEscrow { function getNumGamesStarted() constant returns (int ngames); } // Abstract contract for the full ERC 20 Token standard // https://github.com/ethereum/EIPs/issues/20 // --------------------------------- // ABSTRACT standard token class // --------------------------------- 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); } // -------------------------- // E4RowRewards - abstract e4 dividend contract // -------------------------- contract E4RowRewards { function checkDividends(address _addr) constant returns(uint _amount); function withdrawDividends() public returns (uint namount); } // -------------------------- // Finney Chip - token contract // -------------------------- contract E4Token is Token, E4RowRewards { event StatEvent(string msg); event StatEventI(string msg, uint val); enum SettingStateValue {debug, release, lockedRelease} enum IcoStatusValue {anouncement, saleOpen, saleClosed, failed, succeeded} struct tokenAccount { bool alloced; // flag to ascert prior allocation uint tokens; // num tokens uint balance; // rewards balance } // ----------------------------- // data storage // ---------------------------------------- address developers; // developers token holding address address public owner; // deployer executor address founderOrg; // founder orginaization contract address auxPartner; // aux partner (pr/auditing) - 1 percent upon close address e4_partner; // e4row contract addresses mapping (address => tokenAccount) holderAccounts ; // who holds how many tokens (high two bytes contain curPayId) mapping (uint => address) holderIndexes ; // for iteration thru holder uint numAccounts; uint partnerCredits; // amount partner (e4row) has paid mapping (address => mapping (address => uint256)) allowed; // approvals uint maxMintableTokens; // ... uint minIcoTokenGoal;// token goal by sale end uint minUsageGoal; // num games goal by usage deadline uint public tokenPrice; // price per token uint public payoutThreshold; // threshold till payout uint totalTokenFundsReceived; // running total of token funds received uint public totalTokensMinted; // total number of tokens minted uint public holdoverBalance; // hold this amount until threshhold before reward payout int public payoutBalance; // hold this amount until threshhold before reward payout int prOrigPayoutBal; // original payout balance before run uint prOrigTokensMint; // tokens minted at start of pay run uint public curPayoutId; // current payout id uint public lastPayoutIndex; // payout idx between run segments uint public maxPaysPer; // num pays per segment uint public minPayInterval; // min interval between start pay run uint fundingStart; // funding start time immediately after anouncement uint fundingDeadline; // funding end time uint usageDeadline; // deadline where minimum usage needs to be met before considered success uint public lastPayoutTime; // timestamp of last payout time uint vestTime; // 1 year past sale vest developer tokens uint numDevTokens; // 10 per cent of tokens after close to developers bool developersGranted; // flag uint remunerationStage; // 0 for not yet, 1 for 10 percent, 2 for remaining upon succeeded. uint public remunerationBalance; // remuneration balance to release token funds uint auxPartnerBalance; // aux partner balance - 1 percent uint rmGas; // remuneration gas uint rwGas; // reward gas uint rfGas; // refund gas IcoStatusValue icoStatus; // current status of ico SettingStateValue public settingsState; // -------------------- // contract constructor // -------------------- function E4Token() { owner = msg.sender; developers = msg.sender; } // ----------------------------------- // use this to reset everything, will never be called after lockRelease // ----------------------------------- function applySettings(SettingStateValue qState, uint _saleStart, uint _saleEnd, uint _usageEnd, uint _minUsage, uint _tokGoal, uint _maxMintable, uint _threshold, uint _price, uint _mpp, uint _mpi ) { if (msg.sender != owner) return; // these settings are permanently tweakable for performance adjustments payoutThreshold = _threshold; maxPaysPer = _mpp; minPayInterval = _mpi; // this first test checks if already locked if (settingsState == SettingStateValue.lockedRelease) return; settingsState = qState; // this second test allows locking without changing other permanent settings // WARNING, MAKE SURE YOUR'RE HAPPY WITH ALL SETTINGS // BEFORE LOCKING if (qState == SettingStateValue.lockedRelease) { StatEvent("Locking!"); return; } icoStatus = IcoStatusValue.anouncement; rmGas = 100000; // remuneration gas rwGas = 10000; // reward gas rfGas = 10000; // refund gas // zero out all token holders. // leave alloced on, leave num accounts // cant delete them anyways if (totalTokensMinted > 0) { for (uint i = 0; i < numAccounts; i++ ) { address a = holderIndexes[i]; if (a != address(0)) { holderAccounts[a].tokens = 0; holderAccounts[a].balance = 0; } } } // do not reset numAccounts! totalTokensMinted = 0; // this will erase totalTokenFundsReceived = 0; // this will erase. partnerCredits = 0; // reset all partner credits fundingStart = _saleStart; fundingDeadline = _saleEnd; usageDeadline = _usageEnd; minUsageGoal = _minUsage; minIcoTokenGoal = _tokGoal; maxMintableTokens = _maxMintable; tokenPrice = _price; vestTime = fundingStart + (365 days); numDevTokens = 0; holdoverBalance = 0; payoutBalance = 0; curPayoutId = 1; lastPayoutIndex = 0; remunerationStage = 0; remunerationBalance = 0; auxPartnerBalance = 0; developersGranted = false; lastPayoutTime = 0; if (this.balance > 0) { if (!owner.call.gas(rfGas).value(this.balance)()) StatEvent("ERROR!"); } StatEvent("ok"); } // --------------------------------------------------- // tokens held reserve the top two bytes for the payid last paid. // this is so holders at the top of the list dont transfer tokens // to themselves on the bottom of the list thus scamming the // system. this function deconstructs the tokenheld value. // --------------------------------------------------- function getPayIdAndHeld(uint _tokHeld) internal returns (uint _payId, uint _held) { _payId = (_tokHeld / (2 ** 48)) & 0xffff; _held = _tokHeld & 0xffffffffffff; } function getHeld(uint _tokHeld) internal returns (uint _held) { _held = _tokHeld & 0xffffffffffff; } // --------------------------------------------------- // allocate a new account by setting alloc to true // set the top to bytes of tokens to cur pay id to leave out of current round // add holder index, bump the num accounts // --------------------------------------------------- function addAccount(address _addr) internal { holderAccounts[_addr].alloced = true; holderAccounts[_addr].tokens = (curPayoutId * (2 ** 48)); holderIndexes[numAccounts++] = _addr; } // -------------------------------------- // BEGIN ERC-20 from StandardToken // -------------------------------------- function totalSupply() constant returns (uint256 supply) { if (icoStatus == IcoStatusValue.saleOpen || icoStatus == IcoStatusValue.anouncement) supply = maxMintableTokens; else supply = totalTokensMinted; } function transfer(address _to, uint256 _value) returns (bool success) { if ((msg.sender == developers) && (now < vestTime)) { //statEvent("Tokens not yet vested."); return false; } //Default assumes totalSupply can't be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. //Replace the if with this one instead. //if (holderAccounts[msg.sender] >= _value && balances[_to] + _value > holderAccounts[_to]) { var (pidFrom, heldFrom) = getPayIdAndHeld(holderAccounts[msg.sender].tokens); if (heldFrom >= _value && _value > 0) { holderAccounts[msg.sender].tokens -= _value; if (!holderAccounts[_to].alloced) { addAccount(_to); } uint newHeld = _value + getHeld(holderAccounts[_to].tokens); holderAccounts[_to].tokens = newHeld | (pidFrom * (2 ** 48)); Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if ((_from == developers) && (now < vestTime)) { //statEvent("Tokens not yet vested."); return false; } //same as above. Replace this line with the following if you want to protect against wrapping uints. //if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { var (pidFrom, heldFrom) = getPayIdAndHeld(holderAccounts[_from].tokens); if (heldFrom >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { holderAccounts[_from].tokens -= _value; if (!holderAccounts[_to].alloced) addAccount(_to); uint newHeld = _value + getHeld(holderAccounts[_to].tokens); holderAccounts[_to].tokens = newHeld | (pidFrom * (2 ** 48)); allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { // vars default to 0 if (holderAccounts[_owner].alloced) { balance = getHeld(holderAccounts[_owner].tokens); } } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // ---------------------------------- // END ERC20 // ---------------------------------- // ------------------------------------------- // default payable function. // if sender is e4row partner, this is a rake fee payment // otherwise this is a token purchase. // tokens only purchaseable between tokenfundingstart and end // ------------------------------------------- function () payable { if (msg.sender == e4_partner) { feePayment(); // from e4row game escrow contract } else { purchaseToken(); } } // ----------------------------- // purchase token function - tokens only sold during sale period up until the max tokens // purchase price is tokenPrice. all units in wei. // purchaser will not be included in current pay run // ----------------------------- function purchaseToken() payable { uint nvalue = msg.value; // being careful to preserve msg.value address npurchaser = msg.sender; if (nvalue < tokenPrice) throw; uint qty = nvalue/tokenPrice; updateIcoStatus(); if (icoStatus != IcoStatusValue.saleOpen) // purchase is closed throw; if (totalTokensMinted + qty > maxMintableTokens) throw; if (!holderAccounts[npurchaser].alloced) addAccount(npurchaser); // purchaser waits for next payrun. otherwise can disrupt cur pay run uint newHeld = qty + getHeld(holderAccounts[npurchaser].tokens); holderAccounts[npurchaser].tokens = newHeld | (curPayoutId * (2 ** 48)); totalTokensMinted += qty; totalTokenFundsReceived += nvalue; if (totalTokensMinted == maxMintableTokens) { icoStatus = IcoStatusValue.saleClosed; //test unnecessary - if (getNumTokensPurchased() >= minIcoTokenGoal) doDeveloperGrant(); StatEventI("Purchased,Granted", qty); } else StatEventI("Purchased", qty); } // --------------------------- // accept payment from e4row contract // DO NOT CALL THIS FUNCTION LEST YOU LOSE YOUR MONEY // --------------------------- function feePayment() payable { if (msg.sender != e4_partner) { StatEvent("forbidden"); return; // thank you } uint nfvalue = msg.value; // preserve value in case changed in dev grant updateIcoStatus(); holdoverBalance += nfvalue; partnerCredits += nfvalue; StatEventI("Payment", nfvalue); if (holdoverBalance > payoutThreshold || payoutBalance > 0) doPayout(maxPaysPer); } // --------------------------- // set the e4row partner, this is only done once // --------------------------- function setE4RowPartner(address _addr) public { // ONLY owner can set and ONLY ONCE! (unless "unlocked" debug) // once its locked. ONLY ONCE! if (msg.sender == owner) { if ((e4_partner == address(0)) || (settingsState == SettingStateValue.debug)) { e4_partner = _addr; partnerCredits = 0; //StatEventI("E4-Set", 0); } else { StatEvent("Already Set"); } } } // ---------------------------- // return the total tokens purchased // ---------------------------- function getNumTokensPurchased() constant returns(uint _purchased) { _purchased = totalTokensMinted-numDevTokens; } // ---------------------------- // return the num games as reported from the e4row contract // ---------------------------- function getNumGames() constant returns(uint _games) { //_games = 0; if (e4_partner != address(0)) { iE4RowEscrow pe4 = iE4RowEscrow(e4_partner); _games = uint(pe4.getNumGamesStarted()); } //else //StatEvent("Empty E4"); } // ------------------------------------------------ // get the founders, auxPartner, developer // -------------------------------------------------- function getSpecialAddresses() constant returns (address _fndr, address _aux, address _dev, address _e4) { //if (_sender == owner) { // no msg.sender on constant functions at least in mew _fndr = founderOrg; _aux = auxPartner; _dev = developers; _e4 = e4_partner; //} } // ---------------------------- // update the ico status // ---------------------------- function updateIcoStatus() public { if (icoStatus == IcoStatusValue.succeeded || icoStatus == IcoStatusValue.failed) return; else if (icoStatus == IcoStatusValue.anouncement) { if (now > fundingStart && now <= fundingDeadline) { icoStatus = IcoStatusValue.saleOpen; } else if (now > fundingDeadline) { // should not be here - this will eventually fail icoStatus = IcoStatusValue.saleClosed; } } else { uint numP = getNumTokensPurchased(); uint numG = getNumGames(); if ((now > fundingDeadline && numP < minIcoTokenGoal) || (now > usageDeadline && numG < minUsageGoal)) { icoStatus = IcoStatusValue.failed; } else if ((now > fundingDeadline) // dont want to prevent more token sales && (numP >= minIcoTokenGoal) && (numG >= minUsageGoal)) { icoStatus = IcoStatusValue.succeeded; // hooray } if (icoStatus == IcoStatusValue.saleOpen && ((numP >= maxMintableTokens) || (now > fundingDeadline))) { icoStatus = IcoStatusValue.saleClosed; } } if (!developersGranted && icoStatus != IcoStatusValue.saleOpen && icoStatus != IcoStatusValue.anouncement && getNumTokensPurchased() >= minIcoTokenGoal) { doDeveloperGrant(); // grant whenever status goes from open to anything... } } // ---------------------------- // request refund. Caller must call to request and receive refund // WARNING - withdraw rewards/dividends before calling. // YOU HAVE BEEN WARNED // ---------------------------- function requestRefund() { address nrequester = msg.sender; updateIcoStatus(); uint ntokens = getHeld(holderAccounts[nrequester].tokens); if (icoStatus != IcoStatusValue.failed) StatEvent("No Refund"); else if (ntokens == 0) StatEvent("No Tokens"); else { uint nrefund = ntokens * tokenPrice; if (getNumTokensPurchased() >= minIcoTokenGoal) nrefund -= (nrefund /10); // only 90 percent b/c 10 percent payout holderAccounts[developers].tokens += ntokens; holderAccounts[nrequester].tokens = 0; if (holderAccounts[nrequester].balance > 0) { // see above warning!! if (!holderAccounts[developers].alloced) addAccount(developers); holderAccounts[developers].balance += holderAccounts[nrequester].balance; holderAccounts[nrequester].balance = 0; } if (!nrequester.call.gas(rfGas).value(nrefund)()) throw; //StatEventI("Refunded", nrefund); } } // --------------------------------------------------- // payout rewards to all token holders // use a second holding variable called PayoutBalance to do // the actual payout from b/c too much gas to iterate thru // each payee. Only start a new run at most once per "minpayinterval". // Its done in runs of "_numPays" // we use special coding for the holderAccounts to avoid a hack // of getting paid at the top of the list then transfering tokens // to another address at the bottom of the list. // because of that each holderAccounts entry gets the payoutid stamped upon it (top two bytes) // also a token transfer will transfer the payout id. // --------------------------------------------------- function doPayout(uint _numPays) internal { if (totalTokensMinted == 0) return; if ((holdoverBalance > 0) && (payoutBalance == 0) && (now > (lastPayoutTime+minPayInterval))) { // start a new run curPayoutId++; if (curPayoutId >= 32768) curPayoutId = 1; lastPayoutTime = now; payoutBalance = int(holdoverBalance); prOrigPayoutBal = payoutBalance; prOrigTokensMint = totalTokensMinted; holdoverBalance = 0; lastPayoutIndex = 0; StatEventI("StartRun", uint(curPayoutId)); } else if (payoutBalance > 0) { // work down the p.o.b uint nAmount; uint nPerTokDistrib = uint(prOrigPayoutBal)/prOrigTokensMint; uint paids = 0; uint i; // intentional for (i = lastPayoutIndex; (paids < _numPays) && (i < numAccounts) && (payoutBalance > 0); i++ ) { address a = holderIndexes[i]; if (a == address(0)) { continue; } var (pid, held) = getPayIdAndHeld(holderAccounts[a].tokens); if ((held > 0) && (pid != curPayoutId)) { nAmount = nPerTokDistrib * held; if (int(nAmount) <= payoutBalance){ holderAccounts[a].balance += nAmount; holderAccounts[a].tokens = (curPayoutId * (2 ** 48)) | held; payoutBalance -= int(nAmount); paids++; } } } lastPayoutIndex = i; if (lastPayoutIndex >= numAccounts || payoutBalance <= 0) { lastPayoutIndex = 0; if (payoutBalance > 0) holdoverBalance += uint(payoutBalance);// put back any leftovers payoutBalance = 0; StatEventI("RunComplete", uint(prOrigPayoutBal) ); } else { StatEventI("PayRun", paids ); } } } // ---------------------------- // sender withdraw entire rewards/dividends // ---------------------------- function withdrawDividends() public returns (uint _amount) { if (holderAccounts[msg.sender].balance == 0) { //_amount = 0; StatEvent("0 Balance"); return; } else { if ((msg.sender == developers) && (now < vestTime)) { //statEvent("Tokens not yet vested."); //_amount = 0; return; } _amount = holderAccounts[msg.sender].balance; holderAccounts[msg.sender].balance = 0; if (!msg.sender.call.gas(rwGas).value(_amount)()) throw; //StatEventI("Paid", _amount); } } // ---------------------------- // set gas for operations // ---------------------------- function setOpGas(uint _rm, uint _rf, uint _rw) { if (msg.sender != owner && msg.sender != developers) { //StatEvent("only owner calls"); return; } else { rmGas = _rm; rfGas = _rf; rwGas = _rw; } } // ---------------------------- // get gas for operations // ---------------------------- function getOpGas() constant returns (uint _rm, uint _rf, uint _rw) { _rm = rmGas; _rf = rfGas; _rw = rwGas; } // ---------------------------- // check rewards. pass in address of token holder // ---------------------------- function checkDividends(address _addr) constant returns(uint _amount) { if (holderAccounts[_addr].alloced) _amount = holderAccounts[_addr].balance; } // ------------------------------------------------ // icoCheckup - check up call for administrators // after sale is closed if min ico tokens sold, 10 percent will be distributed to // company to cover various operating expenses // after sale and usage dealines have been met, remaining 90 percent will be distributed to // company. // ------------------------------------------------ function icoCheckup() public { if (msg.sender != owner && msg.sender != developers) throw; uint nmsgmask; //nmsgmask = 0; if (icoStatus == IcoStatusValue.saleClosed) { if ((getNumTokensPurchased() >= minIcoTokenGoal) && (remunerationStage == 0 )) { remunerationStage = 1; remunerationBalance = (totalTokenFundsReceived/100)*9; // 9 percent auxPartnerBalance = (totalTokenFundsReceived/100); // 1 percent nmsgmask |= 1; } } if (icoStatus == IcoStatusValue.succeeded) { if (remunerationStage == 0 ) { remunerationStage = 1; remunerationBalance = (totalTokenFundsReceived/100)*9; auxPartnerBalance = (totalTokenFundsReceived/100); nmsgmask |= 4; } if (remunerationStage == 1) { // we have already suceeded remunerationStage = 2; remunerationBalance += totalTokenFundsReceived - (totalTokenFundsReceived/10); // 90 percent nmsgmask |= 8; } } uint ntmp; if (remunerationBalance > 0) { // only pay one entity per call, dont want to run out of gas ntmp = remunerationBalance; remunerationBalance = 0; if (!founderOrg.call.gas(rmGas).value(ntmp)()) { remunerationBalance = ntmp; nmsgmask |= 32; } else { nmsgmask |= 64; } } else if (auxPartnerBalance > 0) { // note the "else" only pay one entity per call, dont want to run out of gas ntmp = auxPartnerBalance; auxPartnerBalance = 0; if (!auxPartner.call.gas(rmGas).value(ntmp)()) { auxPartnerBalance = ntmp; nmsgmask |= 128; } else { nmsgmask |= 256; } } StatEventI("ico-checkup", nmsgmask); } // ---------------------------- // swap executor // ---------------------------- function changeOwner(address _addr) { if (msg.sender != owner || settingsState == SettingStateValue.lockedRelease) throw; owner = _addr; } // ---------------------------- // swap developers account // ---------------------------- function changeDevevoperAccont(address _addr) { if (msg.sender != owner || settingsState == SettingStateValue.lockedRelease) throw; developers = _addr; } // ---------------------------- // change founder // ---------------------------- function changeFounder(address _addr) { if (msg.sender != owner || settingsState == SettingStateValue.lockedRelease) throw; founderOrg = _addr; } // ---------------------------- // change auxPartner // ---------------------------- function changeAuxPartner(address _aux) { if (msg.sender != owner || settingsState == SettingStateValue.lockedRelease) throw; auxPartner = _aux; } // ---------------------------- // DEBUG ONLY - end this contract, suicide to developers // ---------------------------- function haraKiri() { if (settingsState != SettingStateValue.debug) throw; if (msg.sender != owner) throw; suicide(developers); } // ---------------------------- // get all ico status, funding and usage info // ---------------------------- function getIcoInfo() constant returns(IcoStatusValue _status, uint _saleStart, uint _saleEnd, uint _usageEnd, uint _saleGoal, uint _usageGoal, uint _sold, uint _used, uint _funds, uint _credits, uint _remuStage, uint _vest) { _status = icoStatus; _saleStart = fundingStart; _saleEnd = fundingDeadline; _usageEnd = usageDeadline; _vest = vestTime; _saleGoal = minIcoTokenGoal; _usageGoal = minUsageGoal; _sold = getNumTokensPurchased(); _used = getNumGames(); _funds = totalTokenFundsReceived; _credits = partnerCredits; _remuStage = remunerationStage; } // ---------------------------- // NOTE! CALL AT THE RISK OF RUNNING OUT OF GAS. // ANYONE CAN CALL THIS FUNCTION BUT YOU HAVE TO SUPPLY // THE CORRECT AMOUNT OF GAS WHICH MAY DEPEND ON // THE _NUMPAYS PARAMETER. WHICH MUST BE BETWEEN 1 AND 1000 // THE STANDARD VALUE IS STORED IN "maxPaysPer" // ---------------------------- function flushDividends(uint _numPays) { if ((_numPays == 0) || (_numPays > 1000)) { StatEvent("Invalid."); } else if (holdoverBalance > 0 || payoutBalance > 0) { doPayout(_numPays); } else { StatEvent("Nothing to do."); } } function doDeveloperGrant() internal { if (!developersGranted) { developersGranted = true; numDevTokens = (totalTokensMinted * 15)/100; totalTokensMinted += numDevTokens; if (!holderAccounts[developers].alloced) addAccount(developers); uint newHeld = getHeld(holderAccounts[developers].tokens) + numDevTokens; holderAccounts[developers].tokens = newHeld | (curPayoutId * (2 ** 48)); } } }
---------------------------- return the num games as reported from the e4row contract ----------------------------_games = 0;
function getNumGames() constant returns(uint _games) { if (e4_partner != address(0)) { iE4RowEscrow pe4 = iE4RowEscrow(e4_partner); _games = uint(pe4.getNumGamesStarted()); }
12,974,033