file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
/* B.PROTOCOL TERMS OF USE ======================= THE TERMS OF USE CONTAINED HEREIN (THESE “TERMS”) GOVERN YOUR USE OF B.PROTOCOL, WHICH IS A DECENTRALIZED PROTOCOL ON THE ETHEREUM BLOCKCHAIN (the “PROTOCOL”) THAT enables a backstop liquidity mechanism FOR DECENTRALIZED LENDING PLATFORMS (“DLPs”). PLEASE READ THESE TERMS CAREFULLY AT https://github.com/backstop-protocol/Terms-and-Conditions, INCLUDING ALL DISCLAIMERS AND RISK FACTORS, BEFORE USING THE PROTOCOL. BY USING THE PROTOCOL, YOU ARE IRREVOCABLY CONSENTING TO BE BOUND BY THESE TERMS. IF YOU DO NOT AGREE TO ALL OF THESE TERMS, DO NOT USE THE PROTOCOL. YOUR RIGHT TO USE THE PROTOCOL IS SUBJECT AND DEPENDENT BY YOUR AGREEMENT TO ALL TERMS AND CONDITIONS SET FORTH HEREIN, WHICH AGREEMENT SHALL BE EVIDENCED BY YOUR USE OF THE PROTOCOL. Minors Prohibited: The Protocol is not directed to individuals under the age of eighteen (18) or the age of majority in your jurisdiction if the age of majority is greater. If you are under the age of eighteen or the age of majority (if greater), you are not authorized to access or use the Protocol. By using the Protocol, you represent and warrant that you are above such age. License; No Warranties; Limitation of Liability; (a) The software underlying the Protocol is licensed for use in accordance with the 3-clause BSD License, which can be accessed here: https://opensource.org/licenses/BSD-3-Clause. (b) THE PROTOCOL IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS", “WITH ALL FAULTS” and “AS AVAILABLE” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. (c) IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ pragma solidity ^0.5.12; pragma experimental ABIEncoderV2; contract Math { // --- Math --- function add(uint x, int y) internal pure returns (uint z) { z = x + uint(y); require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function sub(uint x, int y) internal pure returns (uint z) { z = x - uint(y); require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function mul(uint x, int y) internal pure returns (int z) { z = int(x) * y; require(int(x) >= 0); require(y == 0 || z / y == int(x)); } function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } uint constant RAY = 10 ** 27; function rdiv(uint x, uint y) internal pure returns (uint z) { z = mul(x, RAY) / y; } function rmul(uint x, uint y) internal pure returns (uint z) { z = mul(x, y) / RAY; } function rpow(uint x, uint n, uint b) internal pure returns (uint z) { assembly { switch x case 0 {switch n case 0 {z := b} default {z := 0}} default { switch mod(n, 2) case 0 { z := b } default { z := x } let half := div(b, 2) // for rounding. for { n := div(n, 2) } n { n := div(n,2) } { let xx := mul(x, x) if iszero(eq(div(xx, x), x)) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } x := div(xxRound, b) if mod(n,2) { let zx := mul(z, x) if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z := div(zxRound, b) } } } } } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0); } } contract LibNote { event LogNote( bytes4 indexed sig, address indexed usr, bytes32 indexed arg1, bytes32 indexed arg2, bytes data ) anonymous; modifier note { _; assembly { // log an 'anonymous' event with a constant 6 words of calldata // and four indexed topics: selector, caller, arg1 and arg2 let mark := msize() // end of memory ensures zero mstore(0x40, add(mark, 288)) // update free memory pointer mstore(mark, 0x20) // bytes type data offset mstore(add(mark, 0x20), 224) // bytes size (padded) calldatacopy(add(mark, 0x40), 0, 224) // bytes payload log4(mark, 288, // calldata shl(224, shr(224, calldataload(0))), // msg.sig caller(), // msg.sender calldataload(4), // arg1 calldataload(36) // arg2 ) } } } contract BCdpScoreLike { function updateScore(uint cdp, bytes32 ilk, int dink, int dart, uint time) external; } contract BCdpScoreConnector { BCdpScoreLike public score; mapping(uint => uint) public left; constructor(BCdpScoreLike score_) public { score = score_; } function setScore(BCdpScoreLike bcdpScore) internal { score = bcdpScore; } function updateScore(uint cdp, bytes32 ilk, int dink, int dart, uint time) internal { if(left[cdp] == 0) score.updateScore(cdp, ilk, dink, dart, time); } function quitScore(uint cdp) internal { if(left[cdp] == 0) left[cdp] = now; } } contract UrnHandler { constructor(address vat) public { VatLike(vat).hope(msg.sender); } } contract DssCdpManager is LibNote { address public vat; uint public cdpi; // Auto incremental mapping (uint => address) public urns; // CDPId => UrnHandler mapping (uint => List) public list; // CDPId => Prev & Next CDPIds (double linked list) mapping (uint => address) public owns; // CDPId => Owner mapping (uint => bytes32) public ilks; // CDPId => Ilk mapping (address => uint) public first; // Owner => First CDPId mapping (address => uint) public last; // Owner => Last CDPId mapping (address => uint) public count; // Owner => Amount of CDPs mapping ( address => mapping ( uint => mapping ( address => uint ) ) ) public cdpCan; // Owner => CDPId => Allowed Addr => True/False mapping ( address => mapping ( address => uint ) ) public urnCan; // Urn => Allowed Addr => True/False struct List { uint prev; uint next; } event NewCdp(address indexed usr, address indexed own, uint indexed cdp); modifier cdpAllowed( uint cdp ) { require(msg.sender == owns[cdp] || cdpCan[owns[cdp]][cdp][msg.sender] == 1, "cdp-not-allowed"); _; } modifier urnAllowed( address urn ) { require(msg.sender == urn || urnCan[urn][msg.sender] == 1, "urn-not-allowed"); _; } constructor(address vat_) public { vat = vat_; } function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0); } // Allow/disallow a usr address to manage the cdp. function cdpAllow( uint cdp, address usr, uint ok ) public cdpAllowed(cdp) { cdpCan[owns[cdp]][cdp][usr] = ok; } // Allow/disallow a usr address to quit to the the sender urn. function urnAllow( address usr, uint ok ) public { urnCan[msg.sender][usr] = ok; } // Open a new cdp for a given usr address. function open( bytes32 ilk, address usr ) public note returns (uint) { require(usr != address(0), "usr-address-0"); cdpi = add(cdpi, 1); urns[cdpi] = address(new UrnHandler(vat)); owns[cdpi] = usr; ilks[cdpi] = ilk; // Add new CDP to double linked list and pointers if (first[usr] == 0) { first[usr] = cdpi; } if (last[usr] != 0) { list[cdpi].prev = last[usr]; list[last[usr]].next = cdpi; } last[usr] = cdpi; count[usr] = add(count[usr], 1); emit NewCdp(msg.sender, usr, cdpi); return cdpi; } // Give the cdp ownership to a dst address. function give( uint cdp, address dst ) public note cdpAllowed(cdp) { require(dst != address(0), "dst-address-0"); require(dst != owns[cdp], "dst-already-owner"); // Remove transferred CDP from double linked list of origin user and pointers if (list[cdp].prev != 0) { list[list[cdp].prev].next = list[cdp].next; // Set the next pointer of the prev cdp (if exists) to the next of the transferred one } if (list[cdp].next != 0) { // If wasn't the last one list[list[cdp].next].prev = list[cdp].prev; // Set the prev pointer of the next cdp to the prev of the transferred one } else { // If was the last one last[owns[cdp]] = list[cdp].prev; // Update last pointer of the owner } if (first[owns[cdp]] == cdp) { // If was the first one first[owns[cdp]] = list[cdp].next; // Update first pointer of the owner } count[owns[cdp]] = sub(count[owns[cdp]], 1); // Transfer ownership owns[cdp] = dst; // Add transferred CDP to double linked list of destiny user and pointers list[cdp].prev = last[dst]; list[cdp].next = 0; if (last[dst] != 0) { list[last[dst]].next = cdp; } if (first[dst] == 0) { first[dst] = cdp; } last[dst] = cdp; count[dst] = add(count[dst], 1); } // Frob the cdp keeping the generated DAI or collateral freed in the cdp urn address. function frob( uint cdp, int dink, int dart ) public note cdpAllowed(cdp) { address urn = urns[cdp]; VatLike(vat).frob( ilks[cdp], urn, urn, urn, dink, dart ); } // Transfer wad amount of cdp collateral from the cdp address to a dst address. function flux( uint cdp, address dst, uint wad ) public note cdpAllowed(cdp) { VatLike(vat).flux(ilks[cdp], urns[cdp], dst, wad); } // Transfer wad amount of any type of collateral (ilk) from the cdp address to a dst address. // This function has the purpose to take away collateral from the system that doesn't correspond to the cdp but was sent there wrongly. function flux( bytes32 ilk, uint cdp, address dst, uint wad ) public note cdpAllowed(cdp) { VatLike(vat).flux(ilk, urns[cdp], dst, wad); } // Transfer wad amount of DAI from the cdp address to a dst address. function move( uint cdp, address dst, uint rad ) public note cdpAllowed(cdp) { VatLike(vat).move(urns[cdp], dst, rad); } // Quit the system, migrating the cdp (ink, art) to a different dst urn function quit( uint cdp, address dst ) public note cdpAllowed(cdp) urnAllowed(dst) { (uint ink, uint art) = VatLike(vat).urns(ilks[cdp], urns[cdp]); VatLike(vat).fork( ilks[cdp], urns[cdp], dst, toInt(ink), toInt(art) ); } // Import a position from src urn to the urn owned by cdp function enter( address src, uint cdp ) public note urnAllowed(src) cdpAllowed(cdp) { (uint ink, uint art) = VatLike(vat).urns(ilks[cdp], src); VatLike(vat).fork( ilks[cdp], src, urns[cdp], toInt(ink), toInt(art) ); } // Move a position from cdpSrc urn to the cdpDst urn function shift( uint cdpSrc, uint cdpDst ) public note cdpAllowed(cdpSrc) cdpAllowed(cdpDst) { require(ilks[cdpSrc] == ilks[cdpDst], "non-matching-cdps"); (uint ink, uint art) = VatLike(vat).urns(ilks[cdpSrc], urns[cdpSrc]); VatLike(vat).fork( ilks[cdpSrc], urns[cdpSrc], urns[cdpDst], toInt(ink), toInt(art) ); } } interface DSAuthority { function canCall( address src, address dst, bytes4 sig ) external view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig), "ds-auth-unauthorized"); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, address(this), sig); } } } contract VatLike { function urns(bytes32, address) public view returns (uint, uint); function hope(address) external; function flux(bytes32, address, address, uint) public; function move(address, address, uint) public; function frob(bytes32, address, address, address, int, int) public; function fork(bytes32, address, address, int, int) public; function ilks(bytes32 ilk) public view returns(uint Art, uint rate, uint spot, uint line, uint dust); function dai(address usr) external view returns(uint); } contract CatLike { function ilks(bytes32) public returns(address flip, uint256 chop, uint256 lump); } contract EndLike { function cat() public view returns(CatLike); } contract PriceFeedLike { function read(bytes32 ilk) external view returns(bytes32); } contract LiquidationMachine is DssCdpManager, BCdpScoreConnector, Math { VatLike public vat; EndLike public end; address public pool; PriceFeedLike public real; mapping(uint => uint) public tic; // time of bite mapping(uint => uint) public cushion; // how much was topped in art units uint constant public GRACE = 1 hours; uint constant public WAD = 1e18; mapping (uint => bool) public out; modifier onlyPool { require(msg.sender == pool, "not-pool"); _; } constructor(VatLike vat_, EndLike end_, address pool_, PriceFeedLike real_) public { vat = vat_; end = end_; pool = pool_; real = real_; } function setPool(address newPool) internal { pool = newPool; } function quitBLiquidation(uint cdp) internal { untop(cdp); out[cdp] = true; } function topup(uint cdp, uint dtopup) external onlyPool { if(out[cdp]) return; address urn = urns[cdp]; bytes32 ilk = ilks[cdp]; (, uint rate,,,) = vat.ilks(ilk); uint dtab = mul(rate, dtopup); vat.move(pool, address(this), dtab); vat.frob(ilk, urn, urn, address(this), 0, -toInt(dtopup)); cushion[cdp] = add(cushion[cdp], dtopup); } function bitten(uint cdp) public view returns(bool) { return tic[cdp] + GRACE > now; } function untop(uint cdp) internal { require(! bitten(cdp), "untop: cdp was already bitten"); uint top = cushion[cdp]; if(top == 0) return; // nothing to do bytes32 ilk = ilks[cdp]; address urn = urns[cdp]; (, uint rate,,,) = vat.ilks(ilk); uint dtab = mul(rate, top); cushion[cdp] = 0; // move topping to pool vat.frob(ilk, urn, urn, urn, 0, toInt(top)); vat.move(urn, pool, dtab); } function untopByPool(uint cdp) external onlyPool { untop(cdp); } function doBite(uint dart, bytes32 ilk, address urn, uint dink) internal { (, uint rate,,,) = vat.ilks(ilk); uint dtab = mul(rate, dart); vat.move(pool, address(this), dtab); vat.frob(ilk, urn, urn, address(this), 0, -toInt(dart)); vat.frob(ilk, urn, msg.sender, urn, -toInt(dink), 0); } function calcDink(uint dart, uint rate, bytes32 ilk) internal returns(uint dink) { (, uint chop,) = end.cat().ilks(ilk); uint tab = mul(mul(dart, rate), chop) / WAD; bytes32 realtimePrice = real.read(ilk); dink = rmul(tab, WAD) / uint(realtimePrice); } function bite(uint cdp, uint dart) external onlyPool returns(uint dink){ address urn = urns[cdp]; bytes32 ilk = ilks[cdp]; (uint ink, uint art) = vat.urns(ilk, urn); art = add(art, cushion[cdp]); (, uint rate, uint spotValue,,) = vat.ilks(ilk); require(dart <= art, "debt is too low"); // verify cdp is unsafe now if(! bitten(cdp)) { require(mul(art, rate) > mul(ink, spotValue), "bite: cdp is safe"); require(cushion[cdp] > 0, "bite: not-topped"); tic[cdp] = now; } dink = calcDink(dart, rate, ilk); updateScore(cdp, ilk, -toInt(dink), -toInt(dart), now); uint usedCushion = mul(cushion[cdp], dart) / art; cushion[cdp] = sub(cushion[cdp], usedCushion); uint bart = sub(dart, usedCushion); doBite(bart, ilk, urn, dink); } } contract BCdpManager is BCdpScoreConnector, LiquidationMachine, DSAuth { constructor(address vat_, address end_, address pool_, address real_, address score_) public DssCdpManager(vat_) LiquidationMachine(VatLike(vat_), EndLike(end_), pool_, PriceFeedLike(real_)) BCdpScoreConnector(BCdpScoreLike(score_)) { } // Frob the cdp keeping the generated DAI or collateral freed in the cdp urn address. function frob( uint cdp, int dink, int dart ) public cdpAllowed(cdp) { bytes32 ilk = ilks[cdp]; untop(cdp); updateScore(cdp, ilk, dink, dart, now); super.frob(cdp, dink, dart); } // Quit the system, migrating the cdp (ink, art) to a different dst urn function quit( uint cdp, address dst ) public cdpAllowed(cdp) urnAllowed(dst) { address urn = urns[cdp]; bytes32 ilk = ilks[cdp]; untop(cdp); (uint ink, uint art) = vat.urns(ilk, urn); updateScore(cdp, ilk, -toInt(ink), -toInt(art), now); super.quit(cdp, dst); } // Import a position from src urn to the urn owned by cdp function enter( address src, uint cdp ) public urnAllowed(src) cdpAllowed(cdp) { bytes32 ilk = ilks[cdp]; untop(cdp); (uint ink, uint art) = vat.urns(ilk, src); updateScore(cdp, ilk, toInt(ink), toInt(art), now); super.enter(src, cdp); } // Move a position from cdpSrc urn to the cdpDst urn function shift( uint cdpSrc, uint cdpDst ) public cdpAllowed(cdpSrc) cdpAllowed(cdpDst) { bytes32 ilkSrc = ilks[cdpSrc]; untop(cdpSrc); untop(cdpDst); address src = urns[cdpSrc]; (uint inkSrc, uint artSrc) = vat.urns(ilkSrc, src); updateScore(cdpSrc, ilkSrc, -toInt(inkSrc), -toInt(artSrc), now); updateScore(cdpDst, ilkSrc, toInt(inkSrc), toInt(artSrc), now); super.shift(cdpSrc, cdpDst); } ///////////////// B specific control functions ///////////////////////////// function quitB(uint cdp) external cdpAllowed(cdp) note { quitScore(cdp); quitBLiquidation(cdp); } function setScoreContract(BCdpScoreLike _score) external auth { super.setScore(_score); } function setPoolContract(address _pool) external auth { super.setPool(_pool); } } contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract ScoringMachine is Ownable { struct AssetScore { // total score so far uint score; // current balance uint balance; // time when last update was uint last; } // user is bytes32 (will be the sha3 of address or cdp number) mapping(bytes32 => mapping(bytes32 => AssetScore[])) public checkpoints; mapping(bytes32 => mapping(bytes32 => AssetScore)) public userScore; bytes32 constant public GLOBAL_USER = bytes32(0x0); uint public start; // start time of the campaign; function spin() external onlyOwner { // start a new round start = now; } function assetScore(AssetScore storage score, uint time, uint spinStart) internal view returns(uint) { uint last = score.last; uint currentScore = score.score; if(last < spinStart) { last = spinStart; currentScore = 0; } return add(currentScore, mul(score.balance, sub(time, last))); } function addCheckpoint(bytes32 user, bytes32 asset) internal { checkpoints[user][asset].push(userScore[user][asset]); } function updateAssetScore(bytes32 user, bytes32 asset, int dbalance, uint time) internal { AssetScore storage score = userScore[user][asset]; if(score.last < start) addCheckpoint(user, asset); score.score = assetScore(score, time, start); score.balance = add(score.balance, dbalance); score.last = time; } function updateScore(bytes32 user, bytes32 asset, int dbalance, uint time) internal { updateAssetScore(user, asset, dbalance, time); updateAssetScore(GLOBAL_USER, asset, dbalance, time); } function getScore(bytes32 user, bytes32 asset, uint time, uint spinStart, uint checkPointHint) public view returns(uint score) { if(time >= userScore[user][asset].last) return assetScore(userScore[user][asset], time, spinStart); // else - check the checkpoints uint checkpointsLen = checkpoints[user][asset].length; if(checkpointsLen == 0) return 0; // hint is invalid if(checkpoints[user][asset][checkPointHint].last < time) checkPointHint = checkpointsLen - 1; for(uint i = checkPointHint ; ; i--){ if(checkpoints[user][asset][i].last <= time) return assetScore(checkpoints[user][asset][i], time, spinStart); } // this supposed to be unreachable return 0; } function getCurrentBalance(bytes32 user, bytes32 asset) public view returns(uint balance) { balance = userScore[user][asset].balance; } // Math functions without errors // ============================== function add(uint x, uint y) internal pure returns (uint z) { z = x + y; if(!(z >= x)) return 0; return z; } function add(uint x, int y) internal pure returns (uint z) { z = x + uint(y); if(!(y >= 0 || z <= x)) return 0; if(!(y <= 0 || z >= x)) return 0; return z; } function sub(uint x, uint y) internal pure returns (uint z) { if(!(y <= x)) return 0; z = x - y; return z; } function mul(uint x, uint y) internal pure returns (uint z) { if (x == 0) return 0; z = x * y; if(!(z / x == y)) return 0; return z; } } contract BCdpScore is ScoringMachine { BCdpManager public manager; modifier onlyManager { require(msg.sender == address(manager), "not-manager"); _; } function setManager(address newManager) external onlyOwner { manager = BCdpManager(newManager); } function user(uint cdp) public pure returns(bytes32) { return keccak256(abi.encodePacked("BCdpScore", cdp)); } function artAsset(bytes32 ilk) public pure returns(bytes32) { return keccak256(abi.encodePacked("BCdpScore", "art", ilk)); } function updateScore(uint cdp, bytes32 ilk, int dink, int dart, uint time) external onlyManager { dink; // shh compiler warning updateScore(user(cdp), artAsset(ilk), dart, time); } function slashScore(uint maliciousCdp) external { address urn = manager.urns(maliciousCdp); bytes32 ilk = manager.ilks(maliciousCdp); (, uint realArt) = manager.vat().urns(ilk, urn); bytes32 maliciousUser = user(maliciousCdp); bytes32 asset = artAsset(ilk); uint left = BCdpScoreConnector(address(manager)).left(maliciousCdp); realArt = left > 0 ? 0 : realArt; uint startTime = left > 0 ? left : now; uint calculatedArt = getCurrentBalance(maliciousUser, asset); require(realArt < calculatedArt, "slashScore-cdp-is-ok"); int dart = int(realArt) - int(calculatedArt); uint time = sub(startTime, 30 days); if(time < start) time = start; updateScore(maliciousUser, asset, dart, time); } function getArtScore(uint cdp, bytes32 ilk, uint time, uint spinStart) public view returns(uint) { return getScore(user(cdp), artAsset(ilk), time, spinStart, 0); } function getArtGlobalScore(bytes32 ilk, uint time, uint spinStart) public view returns(uint) { return getScore(GLOBAL_USER, artAsset(ilk), time, spinStart, 0); } } contract JarConnector is Math { BCdpScore public score; BCdpManager public man; bytes32[] public ilks; // ilk => supported mapping(bytes32 => bool) public milks; // end of every round uint[2] public end; // start time of every round uint[2] public start; uint public round; constructor( bytes32[] memory _ilks, uint[2] memory _duration ) public { ilks = _ilks; for(uint i = 0; i < _ilks.length; i++) { milks[_ilks[i]] = true; } end[0] = now + _duration[0]; end[1] = now + _duration[0] + _duration[1]; round = 0; } function setManager(address _manager) public { require(man == BCdpManager(0), "manager-already-set"); man = BCdpManager(_manager); score = BCdpScore(address(man.score())); } // callable by anyone function spin() public { if(round == 0) { round++; score.spin(); start[0] = score.start(); } if(round == 1 && now > end[0]) { round++; score.spin(); start[1] = score.start(); } if(round == 2 && now > end[1]) { round++; // score is not counted anymore, and this must be followed by contract upgrade score.spin(); } } function getUserScore(bytes32 user) external view returns (uint) { if(round == 0) return 0; uint cdp = uint(user); bytes32 ilk = man.ilks(cdp); // Should return 0 score for unsupported ilk if( ! milks[ilk]) return 0; if(round == 1) return 2 * score.getArtScore(cdp, ilk, now, start[0]); uint firstRoundScore = 2 * score.getArtScore(cdp, ilk, start[1], start[0]); uint time = now; if(round > 2) time = end[1]; return add(score.getArtScore(cdp, ilk, time, start[1]), firstRoundScore); } function getGlobalScore() external view returns (uint) { if(round == 0) return 0; if(round == 1) return 2 * getArtGlobalScore(now, start[0]); uint firstRoundScore = 2 * getArtGlobalScore(start[1], start[0]); uint time = now; if(round > 2) time = end[1]; return add(getArtGlobalScore(time, start[1]), firstRoundScore); } function getGlobalScore(bytes32 ilk) external view returns (uint) { if(round == 0) return 0; if(round == 1) return 2 * score.getArtGlobalScore(ilk, now, start[0]); uint firstRoundScore = 2 * score.getArtGlobalScore(ilk, start[1], start[0]); uint time = now; if(round > 2) time = end[1]; return add(score.getArtGlobalScore(ilk, time, start[1]), firstRoundScore); } function getArtGlobalScore(uint time, uint spinStart) internal view returns (uint totalScore) { for(uint i = 0; i < ilks.length; i++) { totalScore = add(totalScore, score.getArtGlobalScore(ilks[i], time, spinStart)); } } function toUser(bytes32 user) external view returns (address) { return man.owns(uint(user)); } } contract JugLike { function ilks(bytes32 ilk) public view returns(uint duty, uint rho); function base() public view returns(uint); } contract SpotLike { function par() external view returns (uint256); function ilks(bytes32 ilk) external view returns (address pip, uint mat); } contract OSMLike { function peep() external view returns(bytes32, bool); function hop() external view returns(uint16); function zzz() external view returns(uint64); } contract DaiToUsdPriceFeed { function getMarketPrice(uint marketId) public view returns (uint); } contract Pool is Math, DSAuth, LibNote { uint public constant DAI_MARKET_ID = 3; address[] public members; mapping(bytes32 => bool) public ilks; uint public minArt; // min debt to share among members uint public shrn; // share profit % numerator uint public shrd; // share profit % denumerator mapping(address => uint) public rad; // mapping from member to its dai balance in rad VatLike public vat; BCdpManager public man; SpotLike public spot; JugLike public jug; address public jar; DaiToUsdPriceFeed public dai2usd; mapping(uint => CdpData) internal cdpData; mapping(bytes32 => OSMLike) public osm; // mapping from ilk to osm struct CdpData { uint art; // topup in art units uint cushion; // cushion in rad units address[] members; // liquidators that are in uint[] bite; // how much was already bitten } modifier onlyMember { bool member = false; for(uint i = 0 ; i < members.length ; i++) { if(members[i] == msg.sender) { member = true; break; } } require(member, "not-member"); _; } constructor(address vat_, address jar_, address spot_, address jug_, address dai2usd_) public { spot = SpotLike(spot_); jug = JugLike(jug_); vat = VatLike(vat_); jar = jar_; dai2usd = DaiToUsdPriceFeed(dai2usd_); } function getCdpData(uint cdp) external view returns(uint art, uint cushion, address[] memory members_, uint[] memory bite) { art = cdpData[cdp].art; cushion = cdpData[cdp].cushion; members_ = cdpData[cdp].members; bite = cdpData[cdp].bite; } function setCdpManager(BCdpManager man_) external auth note { man = man_; vat.hope(address(man)); } function setOsm(bytes32 ilk_, address osm_) external auth note { osm[ilk_] = OSMLike(osm_); } function setMembers(address[] calldata members_) external auth note { members = members_; } function setIlk(bytes32 ilk, bool set) external auth note { ilks[ilk] = set; } function setMinArt(uint minArt_) external auth note { minArt = minArt_; } function setDaiToUsdPriceFeed(address dai2usd_) external auth note { dai2usd = DaiToUsdPriceFeed(dai2usd_); } function setProfitParams(uint num, uint den) external auth note { require(num < den, "invalid-profit-params"); shrn = num; shrd = den; } function emergencyExecute(address target, bytes calldata data) external auth note { (bool succ,) = target.call(data); require(succ, "emergencyExecute: failed"); } function deposit(uint radVal) external onlyMember note { vat.move(msg.sender, address(this), radVal); rad[msg.sender] = add(rad[msg.sender], radVal); } function withdraw(uint radVal) external note { require(rad[msg.sender] >= radVal, "withdraw: insufficient-balance"); rad[msg.sender] = sub(rad[msg.sender], radVal); vat.move(address(this), msg.sender, radVal); } function getIndex(address[] storage array, address elm) internal view returns(uint) { for(uint i = 0 ; i < array.length ; i++) { if(array[i] == elm) return i; } return uint(-1); } function removeElement(address[] memory array, uint index) internal pure returns(address[] memory newArray) { if(index >= array.length) { newArray = array; } else { newArray = new address[](array.length - 1); for(uint i = 0 ; i < array.length ; i++) { if(i == index) continue; if(i < index) newArray[i] = array[i]; else newArray[i-1] = array[i]; } } } function chooseMember(uint cdp, uint radVal, address[] memory candidates) public view returns(address[] memory winners) { if(candidates.length == 0) return candidates; // A bit of randomness to choose winners. We don't need pure randomness, its ok even if a // liquidator can predict his winning in the future. uint chosen = uint(keccak256(abi.encodePacked(cdp, now / 1 hours))) % candidates.length; address winner = candidates[chosen]; if(rad[winner] < radVal) return chooseMember(cdp, radVal, removeElement(candidates, chosen)); winners = new address[](1); winners[0] = candidates[chosen]; return winners; } function chooseMembers(uint radVal, address[] memory candidates) public view returns(address[] memory winners) { if(candidates.length == 0) return candidates; uint need = add(1, radVal / candidates.length); for(uint i = 0 ; i < candidates.length ; i++) { if(rad[candidates[i]] < need) { return chooseMembers(radVal, removeElement(candidates, i)); } } winners = candidates; } function calcCushion(bytes32 ilk, uint ink, uint art, uint nextSpot) public view returns(uint dart, uint dtab) { (, uint prev, uint currSpot,,) = vat.ilks(ilk); if(currSpot <= nextSpot) return (0, 0); uint hop = uint(osm[ilk].hop()); uint next = add(uint(osm[ilk].zzz()), hop); (uint duty, uint rho) = jug.ilks(ilk); require(next >= rho, "calcCushion: next-in-the-past"); // note that makerdao governance could change jug.base() before the actual // liquidation happens. but there is 48 hours time lock on makerdao votes // so liquidators should withdraw their funds if they think such event will // happen uint nextRate = rmul(rpow(add(jug.base(), duty), next - rho, RAY), prev); uint nextnextRate = rmul(rpow(add(jug.base(), duty), hop, RAY), nextRate); if(mul(nextRate, art) > mul(ink, currSpot)) return (0, 0); // prevent L attack if(mul(nextRate, art) <= mul(ink, nextSpot)) return (0, 0); uint maxArt = mul(ink, nextSpot) / nextnextRate; dart = sub(art, maxArt); dart = add(1 ether, dart); // compensate for rounding errors dtab = mul(dart, prev); // provide a cushion according to current rate } function hypoTopAmount(uint cdp) internal view returns(uint dart, uint dtab, uint art, bool should) { address urn = man.urns(cdp); bytes32 ilk = man.ilks(cdp); uint ink; (ink, art) = vat.urns(ilk, urn); if(! ilks[ilk]) return (0, 0, art, false); (bytes32 peep, bool valid) = osm[ilk].peep(); // price feed invalid if(! valid) return (0, 0, art, false); // too early to topup should = (now >= add(uint(osm[ilk].zzz()), uint(osm[ilk].hop())/2)); (, uint mat) = spot.ilks(ilk); uint par = spot.par(); uint nextVatSpot = rdiv(rdiv(mul(uint(peep), uint(10 ** 9)), par), mat); (dart, dtab) = calcCushion(ilk, ink, art, nextVatSpot); } function topAmount(uint cdp) public view returns(uint dart, uint dtab, uint art) { bool should; (dart, dtab, art, should) = hypoTopAmount(cdp); if(! should) return (0, 0, art); } function resetCdp(uint cdp) internal { address[] memory winners = cdpData[cdp].members; if(winners.length == 0) return; uint art = cdpData[cdp].art; uint cushion = cdpData[cdp].cushion; uint perUserArt = cdpData[cdp].art / winners.length; for(uint i = 0 ; i < winners.length ; i++) { if(perUserArt <= cdpData[cdp].bite[i]) continue; // nothing to refund uint refundArt = sub(perUserArt, cdpData[cdp].bite[i]); rad[winners[i]] = add(rad[winners[i]], mul(refundArt, cushion)/art); } cdpData[cdp].art = 0; cdpData[cdp].cushion = 0; delete cdpData[cdp].members; delete cdpData[cdp].bite; } function setCdp(uint cdp, address[] memory winners, uint art, uint dradVal) internal { uint drad = add(1, dradVal / winners.length); // round up for(uint i = 0 ; i < winners.length ; i++) { rad[winners[i]] = sub(rad[winners[i]], drad); } cdpData[cdp].art = art; cdpData[cdp].cushion = dradVal; cdpData[cdp].members = winners; cdpData[cdp].bite = new uint[](winners.length); } function topupInfo(uint cdp) public view returns(uint dart, uint dtab, uint art, bool should, address[] memory winners) { (dart, dtab, art, should) = hypoTopAmount(cdp); if(art < minArt) { winners = chooseMember(cdp, uint(dtab), members); } else winners = chooseMembers(uint(dtab), members); } function topup(uint cdp) external onlyMember note { require(man.cushion(cdp) == 0, "topup: already-topped"); require(! man.bitten(cdp), "topup: already-bitten"); (uint dart, uint dtab, uint art, bool should, address[] memory winners) = topupInfo(cdp); require(should, "topup: no-need"); require(dart > 0, "topup: 0-dart"); resetCdp(cdp); require(winners.length > 0, "topup: members-are-broke"); // for small amounts, only winner can topup if(art < minArt) require(winners[0] == msg.sender, "topup: only-winner-can-topup"); setCdp(cdp, winners, uint(art), uint(dtab)); man.topup(cdp, uint(dart)); } function untop(uint cdp) external onlyMember note { require(man.cushion(cdp) == 0, "untop: should-be-untopped-by-user"); resetCdp(cdp); } function bite(uint cdp, uint dart, uint minInk) external onlyMember note returns(uint dMemberInk){ uint index = getIndex(cdpData[cdp].members, msg.sender); uint availBite = availBite(cdp, index); require(dart <= availBite, "bite: debt-too-small"); cdpData[cdp].bite[index] = add(cdpData[cdp].bite[index], dart); uint dink = man.bite(cdp, dart); // update user rad bytes32 ilk = man.ilks(cdp); (,uint rate,,,) = vat.ilks(ilk); uint cushionPortion = mul(cdpData[cdp].cushion, dart) / cdpData[cdp].art; rad[msg.sender] = sub(rad[msg.sender], sub(mul(dart, rate), cushionPortion)); // DAI to USD rate, scale 1e18 uint d2uPrice = dai2usd.getMarketPrice(DAI_MARKET_ID); // dMemberInk = debt * 1.065 * d2uPrice // dMemberInk = dink * (shrn/shrd) * (d2uPrice/1e18) dMemberInk = mul(mul(dink, shrn), d2uPrice) / mul(shrd, uint(1 ether)); // To protect edge case when 1 DAI > 1.13 USD if(dMemberInk > dink) dMemberInk = dink; // Remaining to Jar uint userInk = sub(dink, dMemberInk); require(dMemberInk >= minInk, "bite: low-dink"); vat.flux(ilk, address(this), jar, userInk); vat.flux(ilk, address(this), msg.sender, dMemberInk); } function availBite(uint cdp, address member) public view returns (uint) { uint index = getIndex(cdpData[cdp].members, member); return availBite(cdp, index); } function availBite(uint cdp, uint index) internal view returns (uint) { if(index == uint(-1)) return 0; uint numMembers = cdpData[cdp].members.length; uint maxArt = cdpData[cdp].art / numMembers; // give dust to first member if(index == 0) { uint dust = cdpData[cdp].art % numMembers; maxArt = add(maxArt, dust); } uint availArt = sub(maxArt, cdpData[cdp].bite[index]); address urn = man.urns(cdp); bytes32 ilk = man.ilks(cdp); (,uint art) = vat.urns(ilk, urn); uint remainingArt = add(art, man.cushion(cdp)); return availArt < remainingArt ? availArt : remainingArt; } } contract ChainlinkLike { function latestAnswer() external view returns (int256); } contract LiquidatorInfo is Math { struct VaultInfo { bytes32 collateralType; uint collateralInWei; uint debtInDaiWei; uint liquidationPrice; uint expectedEthReturnWithCurrentPrice; bool expectedEthReturnBetterThanChainlinkPrice; } struct CushionInfo { uint cushionSizeInWei; uint numLiquidators; uint cushionSizeInWeiIfAllHaveBalance; uint numLiquidatorsIfAllHaveBalance; bool shouldProvideCushion; bool shouldProvideCushionIfAllHaveBalance; uint minimumTimeBeforeCallingTopup; bool canCallTopupNow; bool shouldCallUntop; bool isToppedUp; } struct BiteInfo { uint availableBiteInArt; uint availableBiteInDaiWei; uint minimumTimeBeforeCallingBite; bool canCallBiteNow; } struct CdpInfo { uint cdp; uint blockNumber; VaultInfo vault; CushionInfo cushion; BiteInfo bite; } // Struct to store local vars. This avoid stack too deep error struct CdpDataVars { uint cdpArt; uint cushion; address[] cdpWinners; uint[] bite; } LiquidationMachine manager; VatLike public vat; Pool pool; SpotLike spot; ChainlinkLike chainlink; uint constant RAY = 1e27; constructor(LiquidationMachine manager_, address chainlink_) public { manager = manager_; vat = VatLike(address(manager.vat())); pool = Pool(manager.pool()); spot = SpotLike(address(pool.spot())); chainlink = ChainlinkLike(chainlink_); } function getExpectedEthReturn(bytes32 collateralType, uint daiDebt, uint currentPriceFeedValue) public returns(uint) { // get chope value (,uint chop,) = manager.end().cat().ilks(collateralType); uint biteIlk = mul(chop, daiDebt) / currentPriceFeedValue; // DAI to USD rate, scale 1e18 uint d2uPrice = pool.dai2usd().getMarketPrice(pool.DAI_MARKET_ID()); uint shrn = pool.shrn(); uint shrd = pool.shrd(); return mul(mul(biteIlk, shrn), d2uPrice) / mul(shrd, uint(1 ether)); } function getVaultInfo(uint cdp, uint currentPriceFeedValue) public returns(VaultInfo memory info) { address urn = manager.urns(cdp); info.collateralType = manager.ilks(cdp); uint cushion = manager.cushion(cdp); uint art; (info.collateralInWei, art) = vat.urns(info.collateralType, urn); if(info.collateralInWei == 0) return info; (,uint rate,,,) = vat.ilks(info.collateralType); info.debtInDaiWei = mul(add(art, cushion), rate) / RAY; (, uint mat) = spot.ilks(info.collateralType); info.liquidationPrice = mul(info.debtInDaiWei, mat) / mul(info.collateralInWei, RAY / 1e18); if(currentPriceFeedValue > 0) { info.expectedEthReturnWithCurrentPrice = getExpectedEthReturn(info.collateralType, info.debtInDaiWei, currentPriceFeedValue); } int chainlinkPrice = chainlink.latestAnswer(); uint chainlinkEthReturn = 0; if(chainlinkPrice > 0) { chainlinkEthReturn = mul(info.debtInDaiWei, uint(chainlinkPrice)) / 1 ether; } info.expectedEthReturnBetterThanChainlinkPrice = info.expectedEthReturnWithCurrentPrice > chainlinkEthReturn; } function getCushionInfo(uint cdp, address me, uint numMembers) public view returns(CushionInfo memory info) { CdpDataVars memory c; (c.cdpArt, c.cushion, c.cdpWinners, c.bite) = pool.getCdpData(cdp); for(uint i = 0 ; i < c.cdpWinners.length ; i++) { if(me == c.cdpWinners[i]) { uint perUserArt = c.cdpArt / c.cdpWinners.length; info.shouldCallUntop = manager.cushion(cdp) == 0 && c.cushion > 0 && c.bite[i] < perUserArt; info.isToppedUp = c.bite[i] < perUserArt; break; } } (uint dart, uint dtab, uint art, bool should, address[] memory winners) = pool.topupInfo(cdp); info.numLiquidators = winners.length; info.cushionSizeInWei = dtab / RAY; if(dart == 0) { if(info.isToppedUp) { info.numLiquidatorsIfAllHaveBalance = winners.length; info.cushionSizeInWei = c.cushion / RAY; } return info; } if(art < pool.minArt()) { info.cushionSizeInWeiIfAllHaveBalance = info.cushionSizeInWei; info.numLiquidatorsIfAllHaveBalance = 1; info.shouldProvideCushion = false; for(uint i = 0 ; i < winners.length ; i++) { if(me == winners[i]) info.shouldProvideCushion = true; } uint chosen = uint(keccak256(abi.encodePacked(cdp, now / 1 hours))) % numMembers; info.shouldProvideCushionIfAllHaveBalance = (pool.members(chosen) == me); } else { info.cushionSizeInWeiIfAllHaveBalance = info.cushionSizeInWei / numMembers; info.numLiquidatorsIfAllHaveBalance = numMembers; info.shouldProvideCushion = true; info.shouldProvideCushionIfAllHaveBalance = true; } info.canCallTopupNow = !info.isToppedUp && should && info.shouldProvideCushion; bytes32 ilk = manager.ilks(cdp); uint topupTime = add(uint(pool.osm(ilk).zzz()), uint(pool.osm(ilk).hop())/2); info.minimumTimeBeforeCallingTopup = (now >= topupTime) ? 0 : sub(topupTime, now); } function getBiteInfo(uint cdp, address me) public view returns(BiteInfo memory info) { info.availableBiteInArt = pool.availBite(cdp, me); bytes32 ilk = manager.ilks(cdp); uint priceUpdateTime = add(uint(pool.osm(ilk).zzz()), uint(pool.osm(ilk).hop())); info.minimumTimeBeforeCallingBite = (now >= priceUpdateTime) ? 0 : sub(priceUpdateTime, now); if(info.availableBiteInArt == 0) return info; address u = manager.urns(cdp); (,uint rate, uint currSpot,,) = vat.ilks(ilk); info.availableBiteInDaiWei = mul(rate, info.availableBiteInArt) / RAY; (uint ink, uint art) = vat.urns(ilk, u); uint cushion = manager.cushion(cdp); info.canCallBiteNow = (mul(ink, currSpot) < mul(add(art, cushion), rate)) || manager.bitten(cdp); } function getNumMembers() public returns(uint) { for(uint i = 0 ; /* infinite loop */ ; i++) { (bool result,) = address(pool).call(abi.encodeWithSignature("members(uint256)", i)); if(! result) return i; } } function getCdpData(uint startCdp, uint endCdp, address me, uint currentPriceFeedValue) public returns(CdpInfo[] memory info) { uint numMembers = getNumMembers(); info = new CdpInfo[](add(sub(endCdp, startCdp), uint(1))); for(uint cdp = startCdp ; cdp <= endCdp ; cdp++) { uint index = cdp - startCdp; info[index].cdp = cdp; info[index].blockNumber = block.number; info[index].vault = getVaultInfo(cdp, currentPriceFeedValue); info[index].cushion = getCushionInfo(cdp, me, numMembers); info[index].bite = getBiteInfo(cdp, me); } } } contract FlatLiquidatorInfo is LiquidatorInfo { constructor(LiquidationMachine manager_, address chainlink_) public LiquidatorInfo(manager_, chainlink_) {} function getVaultInfoFlat(uint cdp, uint currentPriceFeedValue) external returns(bytes32 collateralType, uint collateralInWei, uint debtInDaiWei, uint liquidationPrice, uint expectedEthReturnWithCurrentPrice, bool expectedEthReturnBetterThanChainlinkPrice) { VaultInfo memory info = getVaultInfo(cdp, currentPriceFeedValue); collateralType = info.collateralType; collateralInWei = info.collateralInWei; debtInDaiWei = info.debtInDaiWei; liquidationPrice = info.liquidationPrice; expectedEthReturnWithCurrentPrice = info.expectedEthReturnWithCurrentPrice; expectedEthReturnBetterThanChainlinkPrice = info.expectedEthReturnBetterThanChainlinkPrice; } function getCushionInfoFlat(uint cdp, address me, uint numMembers) external view returns(uint cushionSizeInWei, uint numLiquidators, uint cushionSizeInWeiIfAllHaveBalance, uint numLiquidatorsIfAllHaveBalance, bool shouldProvideCushion, bool shouldProvideCushionIfAllHaveBalance, bool canCallTopupNow, bool shouldCallUntop, uint minimumTimeBeforeCallingTopup, bool isToppedUp) { CushionInfo memory info = getCushionInfo(cdp, me, numMembers); cushionSizeInWei = info.cushionSizeInWei; numLiquidators = info.numLiquidators; cushionSizeInWeiIfAllHaveBalance = info.cushionSizeInWeiIfAllHaveBalance; numLiquidatorsIfAllHaveBalance = info.numLiquidatorsIfAllHaveBalance; shouldProvideCushion = info.shouldProvideCushion; shouldProvideCushionIfAllHaveBalance = info.shouldProvideCushionIfAllHaveBalance; canCallTopupNow = info.canCallTopupNow; shouldCallUntop = info.shouldCallUntop; minimumTimeBeforeCallingTopup = info.minimumTimeBeforeCallingTopup; isToppedUp = info.isToppedUp; } function getBiteInfoFlat(uint cdp, address me) external view returns(uint availableBiteInArt, uint availableBiteInDaiWei, bool canCallBiteNow,uint minimumTimeBeforeCallingBite) { BiteInfo memory info = getBiteInfo(cdp, me); availableBiteInArt = info.availableBiteInArt; availableBiteInDaiWei = info.availableBiteInDaiWei; canCallBiteNow = info.canCallBiteNow; minimumTimeBeforeCallingBite = info.minimumTimeBeforeCallingBite; } } contract ERC20Like { function balanceOf(address guy) public view returns(uint); } contract VatBalanceLike { function gem(bytes32 ilk, address user) external view returns(uint); function dai(address user) external view returns(uint); } contract LiquidatorBalanceInfo { struct BalanceInfo { uint blockNumber; uint ethBalance; uint wethBalance; uint daiBalance; uint vatDaiBalanceInWei; uint vatEthBalanceInWei; uint poolDaiBalanceInWei; } uint constant RAY = 1e27; function getBalanceInfo(address me, address pool, address vat, bytes32 ilk, address dai, address weth) public view returns(BalanceInfo memory info) { info.blockNumber = block.number; info.ethBalance = me.balance; info.wethBalance = ERC20Like(weth).balanceOf(me); info.daiBalance = ERC20Like(dai).balanceOf(me); info.vatDaiBalanceInWei = VatBalanceLike(vat).dai(me) / RAY; info.vatEthBalanceInWei = VatBalanceLike(vat).gem(ilk, me); info.poolDaiBalanceInWei = Pool(pool).rad(me) / RAY; } function getBalanceInfoFlat(address me, address pool, address vat, bytes32 ilk, address dai, address weth) public view returns(uint blockNumber, uint ethBalance, uint wethBalance, uint daiBalance, uint vatDaiBalanceInWei, uint vatEthBalanceInWei, uint poolDaiBalanceInWei) { BalanceInfo memory info = getBalanceInfo(me, pool, vat, ilk, dai, weth); blockNumber = info.blockNumber; ethBalance = info.ethBalance; wethBalance = info.wethBalance; daiBalance = info.daiBalance; vatDaiBalanceInWei = info.vatDaiBalanceInWei; vatEthBalanceInWei = info.vatEthBalanceInWei; poolDaiBalanceInWei = info.poolDaiBalanceInWei; } }
verify cdp is unsafe now
function bite(uint cdp, uint dart) external onlyPool returns(uint dink){ address urn = urns[cdp]; bytes32 ilk = ilks[cdp]; (uint ink, uint art) = vat.urns(ilk, urn); art = add(art, cushion[cdp]); (, uint rate, uint spotValue,,) = vat.ilks(ilk); require(dart <= art, "debt is too low"); if(! bitten(cdp)) { require(mul(art, rate) > mul(ink, spotValue), "bite: cdp is safe"); require(cushion[cdp] > 0, "bite: not-topped"); tic[cdp] = now; } dink = calcDink(dart, rate, ilk); updateScore(cdp, ilk, -toInt(dink), -toInt(dart), now); uint usedCushion = mul(cushion[cdp], dart) / art; cushion[cdp] = sub(cushion[cdp], usedCushion); uint bart = sub(dart, usedCushion); doBite(bart, ilk, urn, dink); }
2,205,307
pragma solidity ^0.5.0; /// @notice The interface of the identity registry contract /// @author Merunas Grincalaitis <merunasgrincalaitis@gmail.com> interface IdentityRegistryInterface { function isSigned(address _address, bytes32 messageHash, uint8 v, bytes32 r, bytes32 s) external pure returns (bool); function identityExists(uint ein) external view returns (bool); function hasIdentity(address _address) external view returns (bool); function getEIN(address _address) external view returns (uint ein); function isAssociatedAddressFor(uint ein, address _address) external view returns (bool); function isProviderFor(uint ein, address provider) external view returns (bool); function isResolverFor(uint ein, address resolver) external view returns (bool); function getIdentity(uint ein) external view returns ( address recoveryAddress, address[] memory associatedAddresses, address[] memory providers, address[] memory resolvers ); function createIdentity(address recoveryAddress, address[] calldata providers, address[] calldata resolvers) external returns (uint ein); function createIdentityDelegated( address recoveryAddress, address associatedAddress, address[] calldata providers, address[] calldata resolvers, uint8 v, bytes32 r, bytes32 s, uint timestamp ) external returns (uint ein); function addAssociatedAddress( address approvingAddress, address addressToAdd, uint8 v, bytes32 r, bytes32 s, uint timestamp ) external; function addAssociatedAddressDelegated( address approvingAddress, address addressToAdd, uint8[2] calldata v, bytes32[2] calldata r, bytes32[2] calldata s, uint[2] calldata timestamp ) external; function removeAssociatedAddress() external; function removeAssociatedAddressDelegated(address addressToRemove, uint8 v, bytes32 r, bytes32 s, uint timestamp) external; function addProviders(address[] calldata providers) external; function addProvidersFor(uint ein, address[] calldata providers) external; function removeProviders(address[] calldata providers) external; function removeProvidersFor(uint ein, address[] calldata providers) external; function addResolvers(address[] calldata resolvers) external; function addResolversFor(uint ein, address[] calldata resolvers) external; function removeResolvers(address[] calldata resolvers) external; function removeResolversFor(uint ein, address[] calldata resolvers) external; function triggerRecoveryAddressChange(address newRecoveryAddress) external; function triggerRecoveryAddressChangeFor(uint ein, address newRecoveryAddress) external; function triggerRecovery(uint ein, address newAssociatedAddress, uint8 v, bytes32 r, bytes32 s, uint timestamp) external; function triggerDestruction( uint ein, address[] calldata firstChunk, address[] calldata lastChunk, bool resetResolvers ) external; } /// @notice The Hydrogen Finance contract for managing financial accounts such as credit cards, banks and invement accounts on-chain using encryption technology /// @author Merunas Grincalaitis <merunasgrincalaitis@gmail.com> contract HydroFinance { struct User { uint256 einOwner; address owner; bytes32[] encryptedCards; bytes32[] encryptedBanks; bytes32[] encryptedInvestments; } mapping(uint256 => User) public userByEin; User[] public users; address public identityRegistry; /// @notice To setup the address of the identity registry to use for this contract /// @param _identityRegistry The address of the Identity Registry contract constructor(address _identityRegistry) public { require(_identityRegistry != address(0), 'The address of the identity registry contract cannot be empty'); identityRegistry = _identityRegistry; } /// @notice To add a new credit card to your account. All function will be encrypted the moment the data is added /// @param _cardNumber The number of the credit or debit card to add to your account /// @param _expiry When the card expires in timestamp /// @param _name The name of the card /// @param _cvv The 3 or 4 digit code for verifying the card /// @return bytes32 Returns the encrypted card bytes32 function addCard(uint256 _cardNumber, uint256 _expiry, string memory _name, uint256 _cvv) public returns(bytes32) { require(_cardNumber != 0, 'The card number cannot be empty'); require(_expiry != 0, 'The card expiration date cannot be empty'); require(bytes(_name).length != 0, 'The card name must be set'); require(_cvv != 0, 'The cvv cannot be empty'); checkAndCreateUser(); uint256 ein = IdentityRegistryInterface(identityRegistry).getEIN(msg.sender); bytes32 encryptedCard = keccak256(abi.encodePacked(ein, _name, _cardNumber, _expiry, _cvv)); userByEin[ein].encryptedCards.push(encryptedCard); return encryptedCard; } /// @notice To add a new bank /// @param _bankNumber The number of the bank to add /// @param _name The name of the bank /// @return Returns the encrypted bank bytes32 function addBank(uint256 _bankNumber, string memory _name) public returns(bytes32) { require(_bankNumber != 0, 'The bank number must be set'); require(bytes(_name).length != 0, 'The bank name must be set'); checkAndCreateUser(); uint256 ein = IdentityRegistryInterface(identityRegistry).getEIN(msg.sender); bytes32 encryptedBank = keccak256(abi.encodePacked(ein, _bankNumber, _name)); userByEin[ein].encryptedBanks.push(encryptedBank); return encryptedBank; } /// @notice To create an investment account for your user /// @param _investmentNumber The number of the investment account that you want to create /// @param _name The name of the investment account /// @return bytes32 Returns the encrypted investment account hash function addInvestmentAccount(uint256 _investmentNumber, string memory _name) public returns(bytes32) { require(_investmentNumber != 0, 'The investment account number must be set'); require(bytes(_name).length != 0, 'The name of the investment account must be set'); checkAndCreateUser(); uint256 ein = IdentityRegistryInterface(identityRegistry).getEIN(msg.sender); bytes32 encryptedInvestment = keccak256(abi.encodePacked(ein, _investmentNumber, _name)); userByEin[ein].encryptedInvestments.push(encryptedInvestment); return encryptedInvestment; } /// @notice To delete an account function removeAccount() public { uint256 ein = IdentityRegistryInterface(identityRegistry).getEIN(msg.sender); require(userByEin[ein].einOwner == ein, 'Only the EIN owner of the account can remove the account'); delete userByEin[ein]; for(uint256 i = 0; i < users.length; i++) { if(users[i].einOwner == ein) { User memory lastElement = users[users.length - 1]; users[i] = lastElement; users.length--; } } } /// @notice To create a new user if he doesn't have an account yet using his EIN identifier function checkAndCreateUser() internal { uint256 ein = IdentityRegistryInterface(identityRegistry).getEIN(msg.sender); // If we can't find the user, create a new one if(userByEin[ein].owner == address(0)) { bytes32[] memory emptyArray = new bytes32[](0); User memory newUser = User(ein, msg.sender, emptyArray, emptyArray, emptyArray); users.push(newUser); userByEin[ein] = newUser; } } /// @notice To verify if the card is valid and get the parameters /// @param _encryptedCard The encrypted bytes of the card with all the parameters /// @param _name The name of the card /// @param _cardNumber The number of the card /// @param _expiry The expiry of the card /// @param _cvv The cvv of the card /// @return Returns true if the parameters are valid, otherwise returns false function checkCard(bytes32 _encryptedCard, string memory _name, uint256 _cardNumber, uint256 _expiry, uint256 _cvv) public view returns(bool) { uint256 ein = IdentityRegistryInterface(identityRegistry).getEIN(msg.sender); bytes32 verificationEncryptedCard = keccak256(abi.encodePacked(ein, _name, _cardNumber, _expiry, _cvv)); if(_encryptedCard == verificationEncryptedCard) return true; else return false; } /// @notice To verify if a bank details are valid and get those values from the parameters /// @param _encryptedBank The bytes32 encrypted bank hash /// @param _name The name of the bank used in the encryption process /// @param _bankNumber The number of the bank used in the encryption process /// @return Returns true if the parameters are valid or false if the bank has not been added to this EIN user function checkBank(bytes32 _encryptedBank, uint256 _bankNumber, string memory _name) public view returns(bool) { uint256 ein = IdentityRegistryInterface(identityRegistry).getEIN(msg.sender); bytes32 verificationEncryptedBank = keccak256(abi.encodePacked(ein, _bankNumber, _name)); if(_encryptedBank == verificationEncryptedBank) return true; else return false; } /// @notice To verify the investment details and get those values from the parameters /// @param _encryptedInvestment The encrypted investment hash /// @param _investmentNumber The investment account number /// @param _name The name of the encrypted investment account used in the encryption process /// @return bool Returns true if the parameters are valid and have been the used in the encryption process or false if they are not function checkInvestment(bytes32 _encryptedInvestment, uint256 _investmentNumber, string memory _name) public view returns(bool) { uint256 ein = IdentityRegistryInterface(identityRegistry).getEIN(msg.sender); bytes32 verificationEncryptedInvestment = keccak256(abi.encodePacked(ein, _investmentNumber, _name)); if(_encryptedInvestment == verificationEncryptedInvestment) return true; else return false; } /// @notice To get the user data /// @return Returns the EIN, address owner, array of card ids, array of bank ids and array of investment ids function getUserData() public view returns(uint256, address, bytes32[] memory, bytes32[] memory, bytes32[] memory) { uint256 ein = IdentityRegistryInterface(identityRegistry).getEIN(msg.sender); User memory u = userByEin[ein]; return (u.einOwner, u.owner, u.encryptedCards, u.encryptedBanks, u.encryptedInvestments); } }
To add a new credit card to your account. All function will be encrypted the moment the data is added _cardNumber The number of the credit or debit card to add to your account _expiry When the card expires in timestamp _name The name of the card _cvv The 3 or 4 digit code for verifying the card return bytes32 Returns the encrypted card bytes32
function addCard(uint256 _cardNumber, uint256 _expiry, string memory _name, uint256 _cvv) public returns(bytes32) { require(_cardNumber != 0, 'The card number cannot be empty'); require(_expiry != 0, 'The card expiration date cannot be empty'); require(bytes(_name).length != 0, 'The card name must be set'); require(_cvv != 0, 'The cvv cannot be empty'); checkAndCreateUser(); uint256 ein = IdentityRegistryInterface(identityRegistry).getEIN(msg.sender); bytes32 encryptedCard = keccak256(abi.encodePacked(ein, _name, _cardNumber, _expiry, _cvv)); userByEin[ein].encryptedCards.push(encryptedCard); return encryptedCard; }
5,376,512
// File: contracts/vaults/IStrategy.sol pragma solidity 0.5.17; interface istrategy59 { //inject NONSTANDARD NAMING function GETNAME35() external pure returns (string memory); //inject NONSTANDARD NAMING function WANT31() external view returns (address); //inject NONSTANDARD NAMING function WITHDRAW24(address) external; //inject NONSTANDARD NAMING function WITHDRAW24(uint256) external; //inject NONSTANDARD NAMING function WITHDRAWALL24() external returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF3() external view returns (uint256); //inject NONSTANDARD NAMING } // File: contracts/IERC20.sol //SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.5.17; interface ierc2080 { //inject NONSTANDARD NAMING function TOTALSUPPLY74() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF3(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER92(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE58(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE17(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM23(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER57(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL94(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: contracts/ITreasury.sol pragma solidity 0.5.17; interface itreasury2 { //inject NONSTANDARD NAMING function DEFAULTTOKEN28() external view returns (ierc2080); //inject NONSTANDARD NAMING function DEPOSIT94(ierc2080 token, uint256 amount) external; //inject NONSTANDARD NAMING function WITHDRAW24(uint256 amount, address withdrawAddress) external; //inject NONSTANDARD NAMING } // File: contracts/vaults/IVault.sol pragma solidity 0.5.17; interface ivault53 { //inject NONSTANDARD NAMING function WANT31() external view returns (ierc2080); //inject NONSTANDARD NAMING function TRANSFERFUNDSTOSTRATEGY94(address strategy, uint256 amount) external; //inject NONSTANDARD NAMING function AVAILABLEFUNDS75() external view returns (uint256); //inject NONSTANDARD NAMING } // File: contracts/vaults/IVaultRewards.sol pragma solidity 0.5.17; interface ivaultrewards63 { //inject NONSTANDARD NAMING function WANT31() external view returns (ierc2080); //inject NONSTANDARD NAMING function NOTIFYREWARDAMOUNT2(uint256 reward) external; //inject NONSTANDARD NAMING } // File: contracts/vaults/IController.sol pragma solidity 0.5.17; interface icontroller20 { //inject NONSTANDARD NAMING function CURRENTEPOCHTIME27() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF3(address) external view returns (uint256); //inject NONSTANDARD NAMING function REWARDS0(address token) external view returns (ivaultrewards63); //inject NONSTANDARD NAMING function VAULT69(address token) external view returns (ivault53); //inject NONSTANDARD NAMING function ALLOWABLEAMOUNT15(address) external view returns (uint256); //inject NONSTANDARD NAMING function TREASURY79() external view returns (itreasury2); //inject NONSTANDARD NAMING function APPROVEDSTRATEGIES44(address, address) external view returns (bool); //inject NONSTANDARD NAMING function GETHARVESTINFO14(address strategy, address user) //inject NONSTANDARD NAMING external view returns ( uint256 vaultRewardPercentage, uint256 hurdleAmount, uint256 harvestPercentage ); function WITHDRAW24(address, uint256) external; //inject NONSTANDARD NAMING function EARN37(address, uint256) external; //inject NONSTANDARD NAMING function INCREASEHURDLERATE27(address token) external; //inject NONSTANDARD NAMING } // File: contracts/ISwapRouter.sol //SPDX-License-Identifier: GPL-3.0-only pragma solidity 0.5.17; interface swaprouter18 { //inject NONSTANDARD NAMING function WETH90() external pure returns (address); //inject NONSTANDARD NAMING function SWAPEXACTTOKENSFORTOKENS91( //inject NONSTANDARD NAMING uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); } // File: contracts/SafeMath.sol pragma solidity 0.5.17; // Note: This file has been modified to include the sqrt function for quadratic voting library math29 { //inject NONSTANDARD NAMING function MAX82(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a >= b ? a : b; } function MIN43(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a < b ? a : b; } function AVERAGE17(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } function SQRT87(uint256 x) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 n = x / 2; uint256 lstX = 0; while (n != lstX){ lstX = n; n = (n + x/n) / 2; } return uint256(n); } } library safemath85 { //inject NONSTANDARD NAMING function ADD14(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB75(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB75(a, b, "SafeMath: subtraction overflow"); } function SUB75(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 MUL41(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 DIV62(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV62(a, b, "SafeMath: division by zero"); } function DIV62(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 MOD3(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD3(a, b, "SafeMath: modulo by zero"); } function MOD3(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } // File: contracts/zeppelin/Address.sol pragma solidity 0.5.17; library address35 { //inject NONSTANDARD NAMING function ISCONTRACT42(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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. // 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 != 0x0 && codehash != accountHash); } function TOPAYABLE96(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE71(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"); } } // File: contracts/zeppelin/SafeERC20.sol pragma solidity 0.5.17; library safeerc2099 { //inject NONSTANDARD NAMING using safemath85 for uint256; using address35 for address; function SAFETRANSFER62(ierc2080 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.TRANSFER92.selector, to, value)); } function SAFETRANSFERFROM40(ierc2080 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.TRANSFERFROM23.selector, from, to, value)); } function SAFEAPPROVE5(ierc2080 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.ALLOWANCE58(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.APPROVE17.selector, spender, value)); } function SAFEINCREASEALLOWANCE71(ierc2080 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE58(address(this), spender).ADD14(value); CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.APPROVE17.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE44(ierc2080 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE58(address(this), spender).SUB75(value, "SafeERC20: decreased allowance below zero"); CALLOPTIONALRETURN65(token, abi.encodeWithSelector(token.APPROVE17.selector, spender, newAllowance)); } function CALLOPTIONALRETURN65(ierc2080 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).ISCONTRACT42(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/vaults/strategy/MStableStrategy.sol //SPDX-License-Identifier: MIT pragma solidity 0.5.17; interface ibpt3 { //inject NONSTANDARD NAMING function TOTALSUPPLY74() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF3(address whom) external view returns (uint); //inject NONSTANDARD NAMING function GETSPOTPRICE26(address tokenIn, address tokenOut) external view returns (uint spotPrice); //inject NONSTANDARD NAMING function SWAPEXACTAMOUNTIN69(address, uint, address, uint, uint) external returns (uint, uint); //inject NONSTANDARD NAMING function SWAPEXACTAMOUNTOUT77(address, uint, address, uint, uint) external returns (uint, uint); //inject NONSTANDARD NAMING function JOINSWAPEXTERNAMOUNTIN73( //inject NONSTANDARD NAMING address tokenIn, uint tokenAmountIn, uint minPoolAmountOut ) external returns (uint poolAmountOut); function EXITSWAPEXTERNAMOUNTOUT85( //inject NONSTANDARD NAMING address tokenOut, uint tokenAmountOut, uint maxPoolAmountIn ) external returns (uint poolAmountIn); function EXITSWAPPOOLAMOUNTIN6( //inject NONSTANDARD NAMING address tokenOut, uint poolAmountIn, uint minAmountOut ) external returns (uint tokenAmountOut); } interface impool6 { //inject NONSTANDARD NAMING function BALANCEOF3(address _account) external view returns (uint256); //inject NONSTANDARD NAMING function EARNED23(address _account) external view returns (uint256, uint256); //inject NONSTANDARD NAMING function STAKE12(uint256 _amount) external; //inject NONSTANDARD NAMING function CLAIMREWARD81() external; //inject NONSTANDARD NAMING function EXIT39() external; //inject NONSTANDARD NAMING } interface imtagov79 { //inject NONSTANDARD NAMING function BALANCEOF3(address _account) external view returns (uint256); //inject NONSTANDARD NAMING function EARNED23(address _account) external view returns (uint256); //inject NONSTANDARD NAMING function CREATELOCK73(uint256 _value, uint256 _unlockTime) external; //inject NONSTANDARD NAMING function WITHDRAW24() external; //inject NONSTANDARD NAMING function INCREASELOCKAMOUNT91(uint256 _value) external; //inject NONSTANDARD NAMING function CLAIMREWARD81() external; //inject NONSTANDARD NAMING } contract mstablestrat66 is istrategy59 { //inject NONSTANDARD NAMING using safeerc2099 for ierc2080; using address35 for address; using safemath85 for uint256; uint256 public constant performance_fee63 = 500; // 5% //inject NONSTANDARD NAMING uint256 public constant denom43 = 10000; //inject NONSTANDARD NAMING uint256 public hurdleLastUpdateTime; uint256 public harvestAmountThisEpoch; uint256 public strategistCollectedFee; uint256 public numPools = 1; ierc2080 internal usdc = ierc2080(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); ierc2080 internal musd = ierc2080(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5); ierc2080 internal mta = ierc2080(0xa3BeD4E1c75D00fa6f4E5E6922DB7261B5E9AcD2); ibpt3 internal musdcBpt = ibpt3(0x72Cd8f4504941Bf8c5a21d1Fd83A96499FD71d2C); swaprouter18 public swapRouter = swaprouter18(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); impool6 internal mPool = impool6(0x881c72D1e6317f10a1cDCBe05040E7564E790C80); imtagov79 internal mtaGov = imtagov79(0xaE8bC96DA4F9A9613c323478BE181FDb2Aa0E1BF); ierc2080 public want = usdc; // should be set only in constructor or hardcoded icontroller20 public controller; // should be set only in constructor address public strategist; // mutable, but only by strategist // want must be equal to an underlying vault token (Eg. USDC) constructor(icontroller20 _controller) public { controller = _controller; strategist = msg.sender; } function GETNAME35() external pure returns (string memory) { //inject NONSTANDARD NAMING return "MstableStrategy"; } function SETSTRATEGIST71(address _strategist) external { //inject NONSTANDARD NAMING require(msg.sender == strategist, "!strategist"); strategist = _strategist; } function SETNUMPOOLSFORSWAP74(uint256 _numPools) external { //inject NONSTANDARD NAMING require(msg.sender == strategist, "!strategist"); numPools = _numPools; } function SETALLOWANCES18(ierc2080 token, address[] calldata recipients, bool isIncrease) external { //inject NONSTANDARD NAMING require(msg.sender == strategist, "!strategist"); for (uint i = 0; i < recipients.length; i++) { require( recipients[i] == address(musdcBpt) || recipients[i] == address(swapRouter) || recipients[i] == address(mPool) || recipients[i] == address(mtaGov), "bad recipient" ); uint256 allowance = isIncrease ? uint256(-1) : 0; token.SAFEAPPROVE5(recipients[i], allowance); } } // Assumed that caller checks against available funds in vault function DEPOSIT94(uint256 amount) public { //inject NONSTANDARD NAMING uint256 availFunds = controller.ALLOWABLEAMOUNT15(address(this)); require(amount <= availFunds, "exceed contAllowance"); controller.EARN37(address(this), amount); // deposit into musdcBpt uint256 bptTokenAmt = musdcBpt.JOINSWAPEXTERNAMOUNTIN73(address(want), amount, 0); // deposit into mstable pool mPool.STAKE12(bptTokenAmt); // deposit any MTA token in this contract into mStaking contract DEPOSITMTAINSTAKING28(); } function BALANCEOF3() external view returns (uint256) { //inject NONSTANDARD NAMING // get balance in mPool uint256 bptStakeAmt = mPool.BALANCEOF3(address(this)); // get usdc + musd amts in BPT, and total BPT uint256 usdcAmt = usdc.BALANCEOF3(address(musdcBpt)); uint256 musdAmt = musd.BALANCEOF3(address(musdcBpt)); uint256 totalBptAmt = musdcBpt.TOTALSUPPLY74(); // convert musd to usdc usdcAmt = usdcAmt.ADD14( musdAmt.MUL41(1e18).DIV62(musdcBpt.GETSPOTPRICE26(address(musd), address(usdc))) ); return bptStakeAmt.MUL41(usdcAmt).DIV62(totalBptAmt); } function EARNED23() external view returns (uint256) { //inject NONSTANDARD NAMING (uint256 earnedAmt,) = mPool.EARNED23(address(this)); return earnedAmt.ADD14(mtaGov.EARNED23(address(this))); } function WITHDRAW24(address token) external { //inject NONSTANDARD NAMING ierc2080 erc20Token = ierc2080(token); require(msg.sender == address(controller), "!controller"); erc20Token.SAFETRANSFER62(address(controller), erc20Token.BALANCEOF3(address(this))); } function WITHDRAW24(uint256 amount) external { //inject NONSTANDARD NAMING require(msg.sender == address(controller), "!controller"); // exit fully mPool.EXIT39(); // convert to desired amount musdcBpt.EXITSWAPEXTERNAMOUNTOUT85(address(want), amount, uint256(-1)); // deposit whatever remaining bpt back into mPool mPool.STAKE12(musdcBpt.BALANCEOF3(address(this))); // send funds to vault want.SAFETRANSFER62(address(controller.VAULT69(address(want))), amount); } function WITHDRAWALL24() external returns (uint256 balance) { //inject NONSTANDARD NAMING require(msg.sender == address(controller), "!controller"); // exit fully mPool.EXIT39(); // convert reward to want tokens // in case swap fails, continue (bool success, ) = address(this).call( abi.encodeWithSignature( "exchangeRewardForWant(bool)", true ) ); // to remove compiler warning success; // convert bpt to want tokens musdcBpt.EXITSWAPPOOLAMOUNTIN6( address(want), musdcBpt.BALANCEOF3(address(this)), 0 ); // exclude collected strategist fee balance = want.BALANCEOF3(address(this)).SUB75(strategistCollectedFee); // send funds to vault want.SAFETRANSFER62(address(controller.VAULT69(address(want))), balance); } function HARVEST87(bool claimMPool, bool claimGov) external { //inject NONSTANDARD NAMING if (claimMPool) mPool.CLAIMREWARD81(); if (claimGov) mtaGov.CLAIMREWARD81(); // convert 80% reward to want tokens // in case swap fails, return (bool success, ) = address(this).call( abi.encodeWithSignature( "exchangeRewardForWant(bool)", false ) ); // to remove compiler warning if (!success) return; uint256 amount = want.BALANCEOF3(address(this)).SUB75(strategistCollectedFee); uint256 vaultRewardPercentage; uint256 hurdleAmount; uint256 harvestPercentage; uint256 epochTime; (vaultRewardPercentage, hurdleAmount, harvestPercentage) = controller.GETHARVESTINFO14(address(this), msg.sender); // check if harvest amount has to be reset if (hurdleLastUpdateTime < epochTime) { // reset collected amount harvestAmountThisEpoch = 0; } // update variables hurdleLastUpdateTime = block.timestamp; harvestAmountThisEpoch = harvestAmountThisEpoch.ADD14(amount); // first, take harvester fee uint256 harvestFee = amount.MUL41(harvestPercentage).DIV62(denom43); want.SAFETRANSFER62(msg.sender, harvestFee); uint256 fee; // then, if hurdle amount has been exceeded, take performance fee if (harvestAmountThisEpoch >= hurdleAmount) { fee = amount.MUL41(performance_fee63).DIV62(denom43); strategistCollectedFee = strategistCollectedFee.ADD14(fee); } // do the subtraction of harvester and strategist fees amount = amount.SUB75(harvestFee).SUB75(fee); // calculate how much is to be re-invested // fee = vault reward amount, reusing variable fee = amount.MUL41(vaultRewardPercentage).DIV62(denom43); want.SAFETRANSFER62(address(controller.REWARDS0(address(want))), fee); controller.REWARDS0(address(want)).NOTIFYREWARDAMOUNT2(fee); amount = amount.SUB75(fee); // finally, use remaining want amount for reinvestment amount = musdcBpt.JOINSWAPEXTERNAMOUNTIN73(address(want), amount, 0); // deposit into mstable pool mPool.STAKE12(amount); // deposit any MTA token in this contract into mStaking contract DEPOSITMTAINSTAKING28(); } function WITHDRAWSTRATEGISTFEE97() external { //inject NONSTANDARD NAMING strategistCollectedFee = 0; want.SAFETRANSFER62(strategist, strategistCollectedFee); } function EXITMGOV72() external { //inject NONSTANDARD NAMING mtaGov.WITHDRAW24(); // convert to want tokens // in case swap fails, continue (bool success, ) = address(this).call( abi.encodeWithSignature( "exchangeRewardForWant(bool)", true ) ); // to remove compiler warning success; want.SAFETRANSFER62( address(controller.REWARDS0(address(want))), want.BALANCEOF3(address(this)).SUB75(strategistCollectedFee) ); } function EXCHANGEREWARDFORWANT67(bool exchangeAll) public { //inject NONSTANDARD NAMING uint256 swapAmt = mta.BALANCEOF3(address(this)); if (swapAmt == 0) return; // do the exchange address[] memory routeDetails = new address[](3); routeDetails[0] = address(mta); routeDetails[1] = swapRouter.WETH90(); routeDetails[2] = address(want); swapRouter.SWAPEXACTTOKENSFORTOKENS91( exchangeAll ? swapAmt : swapAmt.MUL41(8000).DIV62(denom43), 0, routeDetails, address(this), block.timestamp + 100 ); } function DEPOSITMTAINSTAKING28() internal { //inject NONSTANDARD NAMING uint256 mtaBal = mta.BALANCEOF3(address(this)); if (mtaBal == 0) return; if (mtaGov.BALANCEOF3(address(this)) == 0) { // create lock with max time mtaGov.CREATELOCK73(mtaBal, 1632580257); } else { // increase amount mtaGov.INCREASELOCKAMOUNT91(mtaBal); } } }
inject NONSTANDARD NAMING
function ADD14(uint256 a, uint256 b) internal pure returns (uint256) {
1,825,091
./full_match/137/0xC023011dC6fDd23a586629EF8546081b628c3498/sources/contracts/PToken/PToken.sol
@inheritdoc IPToken/
function getDepositIndexById(uint256 id) external view override returns (uint256 index) { _require(id < lockedDepositsIndexes.length, Errors.DEPOSIT_DOES_NOT_EXIST.selector); return lockedDepositsIndexes[id]; }
3,749,151
// Sources flattened with hardhat v2.8.4 https://hardhat.org // File @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol@v4.3.0 // 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; } } } // File @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol@v4.3.0 pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // File @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol@v4.3.0 pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _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); } uint256[49] private __gap; } // File @openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol@v4.3.0 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 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; } // File @openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol@v4.3.0 pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol@v4.3.0 pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol@v4.3.0 pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20Upgradeable token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20Upgradeable token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable 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(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/hyphen/metatx/ERC2771ContextUpgradeable.sol pragma solidity 0.8.0; /** * @dev Context variant with ERC2771 support. * Here _trustedForwarder is made internal instead of private * so it can be changed via Child contracts with a setter method. */ abstract contract ERC2771ContextUpgradeable is Initializable, ContextUpgradeable { address internal _trustedForwarder; function __ERC2771Context_init(address trustedForwarder) internal initializer { __Context_init_unchained(); __ERC2771Context_init_unchained(trustedForwarder); } function __ERC2771Context_init_unchained(address trustedForwarder) internal initializer { _trustedForwarder = trustedForwarder; } function isTrustedForwarder(address forwarder) public view virtual returns (bool) { return forwarder == _trustedForwarder; } function _msgSender() internal view virtual override returns (address sender) { if (isTrustedForwarder(msg.sender)) { // The assembly code is more direct than the Solidity version using `abi.decode`. assembly { sender := shr(96, calldataload(sub(calldatasize(), 20))) } } else { return super._msgSender(); } } function _msgData() internal view virtual override returns (bytes calldata) { if (isTrustedForwarder(msg.sender)) { return msg.data[:msg.data.length - 20]; } else { return super._msgData(); } } uint256[49] private __gap; } // File @openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol@v4.3.0 pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // File contracts/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 Initializable, PausableUpgradeable { address private _pauser; event PauserChanged(address indexed previousPauser, address indexed newPauser); /** * @dev The pausable constructor sets the original `pauser` of the contract to the sender * account & Initializes the contract in unpaused state.. */ function __Pausable_init(address pauser) internal initializer { require(pauser != address(0), "Pauser Address cannot be 0"); __Pausable_init(); _pauser = pauser; } /** * @return true if `msg.sender` is the owner of the contract. */ function isPauser(address pauser) public view returns (bool) { return pauser == _pauser; } /** * @dev Throws if called by any account other than the pauser. */ modifier onlyPauser() { require(isPauser(msg.sender), "Only pauser is allowed to perform this operation"); _; } /** * @dev Allows the current pauser to transfer control of the contract to a newPauser. * @param newPauser The address to transfer pauserShip to. */ function changePauser(address newPauser) public onlyPauser { _changePauser(newPauser); } /** * @dev Transfers control of the contract to a newPauser. * @param newPauser The address to transfer ownership to. */ function _changePauser(address newPauser) internal { require(newPauser != address(0)); emit PauserChanged(_pauser, newPauser); _pauser = newPauser; } function renouncePauser() external virtual onlyPauser { emit PauserChanged(_pauser, address(0)); _pauser = address(0); } function pause() public onlyPauser { _pause(); } function unpause() public onlyPauser { _unpause(); } } // File contracts/hyphen/structures/TokenConfig.sol pragma solidity 0.8.0; struct TokenInfo { uint256 transferOverhead; bool supportedToken; uint256 equilibriumFee; // Percentage fee Represented in basis points uint256 maxFee; // Percentage fee Represented in basis points TokenConfig tokenConfig; } struct TokenConfig { uint256 min; uint256 max; } // File contracts/hyphen/interfaces/IExecutorManager.sol pragma solidity 0.8.0; interface IExecutorManager { function getExecutorStatus(address executor) external view returns (bool status); function getAllExecutors() external view returns (address[] memory); //Register new Executors function addExecutors(address[] calldata executorArray) external; // Register single executor function addExecutor(address executorAddress) external; //Remove registered Executors function removeExecutors(address[] calldata executorArray) external; // Remove Register single executor function removeExecutor(address executorAddress) external; } // File contracts/hyphen/interfaces/ILiquidityProviders.sol pragma solidity 0.8.0; interface ILiquidityProviders { function BASE_DIVISOR() external view returns (uint256); function initialize(address _trustedForwarder, address _lpToken) external; function addLPFee(address _token, uint256 _amount) external; function addNativeLiquidity() external; function addTokenLiquidity(address _token, uint256 _amount) external; function claimFee(uint256 _nftId) external; function getFeeAccumulatedOnNft(uint256 _nftId) external view returns (uint256); function getSuppliedLiquidityByToken(address tokenAddress) external view returns (uint256); function getTokenPriceInLPShares(address _baseToken) external view returns (uint256); function getTotalLPFeeByToken(address tokenAddress) external view returns (uint256); function getTotalReserveByToken(address tokenAddress) external view returns (uint256); function getSuppliedLiquidity(uint256 _nftId) external view returns (uint256); function increaseNativeLiquidity(uint256 _nftId) external; function increaseTokenLiquidity(uint256 _nftId, uint256 _amount) external; function isTrustedForwarder(address forwarder) external view returns (bool); function owner() external view returns (address); function paused() external view returns (bool); function removeLiquidity(uint256 _nftId, uint256 amount) external; function renounceOwnership() external; function setLiquidityPool(address _liquidityPool) external; function setLpToken(address _lpToken) external; function setWhiteListPeriodManager(address _whiteListPeriodManager) external; function sharesToTokenAmount(uint256 _shares, address _tokenAddress) external view returns (uint256); function totalLPFees(address) external view returns (uint256); function totalLiquidity(address) external view returns (uint256); function totalReserve(address) external view returns (uint256); function totalSharesMinted(address) external view returns (uint256); function transferOwnership(address newOwner) external; function whiteListPeriodManager() external view returns (address); function increaseCurrentLiquidity(address tokenAddress, uint256 amount) external; function decreaseCurrentLiquidity(address tokenAddress, uint256 amount) external; function getCurrentLiquidity(address tokenAddress) external view returns (uint256); } // File contracts/interfaces/IERC20Permit.sol pragma solidity 0.8.0; interface IERC20Detailed is IERC20Upgradeable { function name() external view returns(string memory); function decimals() external view returns(uint256); } interface IERC20Nonces is IERC20Detailed { function nonces(address holder) external view returns(uint); } interface IERC20Permit is IERC20Nonces { function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external; function permit(address holder, address spender, uint256 value, uint256 expiry, uint8 v, bytes32 r, bytes32 s) external; } // File contracts/hyphen/interfaces/ITokenManager.sol pragma solidity 0.8.0; interface ITokenManager { function getEquilibriumFee(address tokenAddress) external view returns (uint256); function getMaxFee(address tokenAddress) external view returns (uint256); function changeFee( address tokenAddress, uint256 _equilibriumFee, uint256 _maxFee ) external; function tokensInfo(address tokenAddress) external view returns ( uint256 transferOverhead, bool supportedToken, uint256 equilibriumFee, uint256 maxFee, TokenConfig memory config ); function getTokensInfo(address tokenAddress) external view returns (TokenInfo memory); function getDepositConfig(uint256 toChainId, address tokenAddress) external view returns (TokenConfig memory); function getTransferConfig(address tokenAddress) external view returns (TokenConfig memory); } // File contracts/hyphen/LiquidityPool.sol // $$\ $$\ $$\ $$$$$$$\ $$\ // $$ | $$ | $$ | $$ __$$\ $$ | // $$ | $$ |$$\ $$\ $$$$$$\ $$$$$$$\ $$$$$$\ $$$$$$$\ $$ | $$ | $$$$$$\ $$$$$$\ $$ | // $$$$$$$$ |$$ | $$ |$$ __$$\ $$ __$$\ $$ __$$\ $$ __$$\ $$$$$$$ |$$ __$$\ $$ __$$\ $$ | // $$ __$$ |$$ | $$ |$$ / $$ |$$ | $$ |$$$$$$$$ |$$ | $$ | $$ ____/ $$ / $$ |$$ / $$ |$$ | // $$ | $$ |$$ | $$ |$$ | $$ |$$ | $$ |$$ ____|$$ | $$ | $$ | $$ | $$ |$$ | $$ |$$ | // $$ | $$ |\$$$$$$$ |$$$$$$$ |$$ | $$ |\$$$$$$$\ $$ | $$ | $$ | \$$$$$$ |\$$$$$$ |$$ | // \__| \__| \____$$ |$$ ____/ \__| \__| \_______|\__| \__| \__| \______/ \______/ \__| // $$\ $$ |$$ | // \$$$$$$ |$$ | // \______/ \__| // pragma solidity 0.8.0; pragma abicoder v2; contract LiquidityPoolOld is Initializable, ReentrancyGuardUpgradeable, Pausable, OwnableUpgradeable, ERC2771ContextUpgradeable { address private constant NATIVE = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; uint256 private constant BASE_DIVISOR = 10000000000; // Basis Points * 100 for better accuracy uint256 public baseGas; IExecutorManager private executorManager; ITokenManager public tokenManager; ILiquidityProviders public liquidityProviders; struct PermitRequest { uint256 nonce; uint256 expiry; bool allowed; uint8 v; bytes32 r; bytes32 s; } mapping(bytes32 => bool) public processedHash; mapping(address => uint256) public gasFeeAccumulatedByToken; // Gas fee accumulated by token address => executor address mapping(address => mapping(address => uint256)) public gasFeeAccumulated; // Incentive Pool amount per token address mapping(address => uint256) public incentivePool; event AssetSent( address indexed asset, uint256 indexed amount, uint256 indexed transferredAmount, address target, bytes depositHash, uint256 fromChainId, uint256 lpFee, uint256 transferFee, uint256 gasFee ); event Received(address indexed from, uint256 indexed amount); event Deposit( address indexed from, address indexed tokenAddress, address indexed receiver, uint256 toChainId, uint256 amount, uint256 reward, string tag ); event GasFeeWithdraw(address indexed tokenAddress, address indexed owner, uint256 indexed amount); event TrustedForwarderChanged(address indexed forwarderAddress); event LiquidityProvidersChanged(address indexed liquidityProvidersAddress); event TokenManagerChanged(address indexed tokenManagerAddress); event EthReceived(address, uint256); // MODIFIERS modifier onlyExecutor() { require(executorManager.getExecutorStatus(_msgSender()), "Only executor is allowed"); _; } modifier onlyLiquidityProviders() { require(_msgSender() == address(liquidityProviders), "Only liquidityProviders is allowed"); _; } modifier tokenChecks(address tokenAddress) { (, bool supportedToken, , , ) = tokenManager.tokensInfo(tokenAddress); require(supportedToken, "Token not supported"); _; } function initialize( address _executorManagerAddress, address _pauser, address _trustedForwarder, address _tokenManager, address _liquidityProviders ) public initializer { require(_executorManagerAddress != address(0), "ExecutorManager cannot be 0x0"); require(_trustedForwarder != address(0), "TrustedForwarder cannot be 0x0"); require(_liquidityProviders != address(0), "LiquidityProviders cannot be 0x0"); __ERC2771Context_init(_trustedForwarder); __ReentrancyGuard_init(); __Ownable_init(); __Pausable_init(_pauser); executorManager = IExecutorManager(_executorManagerAddress); tokenManager = ITokenManager(_tokenManager); liquidityProviders = ILiquidityProviders(_liquidityProviders); baseGas = 21000; } function setTrustedForwarder(address trustedForwarder) external onlyOwner { require(trustedForwarder != address(0), "TrustedForwarder can't be 0"); _trustedForwarder = trustedForwarder; emit TrustedForwarderChanged(trustedForwarder); } function setLiquidityProviders(address _liquidityProviders) external onlyOwner { require(_liquidityProviders != address(0), "LiquidityProviders can't be 0"); liquidityProviders = ILiquidityProviders(_liquidityProviders); emit LiquidityProvidersChanged(_liquidityProviders); } function setTokenManager(address _tokenManager) external onlyOwner { require(_tokenManager != address(0), "TokenManager can't be 0"); tokenManager = ITokenManager(_tokenManager); emit TokenManagerChanged(_tokenManager); } function setBaseGas(uint128 gas) external onlyOwner { baseGas = gas; } function getExecutorManager() external view returns (address) { return address(executorManager); } function setExecutorManager(address _executorManagerAddress) external onlyOwner { require(_executorManagerAddress != address(0), "Executor Manager cannot be 0"); executorManager = IExecutorManager(_executorManagerAddress); } function getCurrentLiquidity(address tokenAddress) public view returns (uint256 currentLiquidity) { uint256 liquidityPoolBalance = liquidityProviders.getCurrentLiquidity(tokenAddress); currentLiquidity = liquidityPoolBalance - liquidityProviders.totalLPFees(tokenAddress) - gasFeeAccumulatedByToken[tokenAddress] - incentivePool[tokenAddress]; } /** * @dev Function used to deposit tokens into pool to initiate a cross chain token transfer. * @param toChainId Chain id where funds needs to be transfered * @param tokenAddress ERC20 Token address that needs to be transfered * @param receiver Address on toChainId where tokens needs to be transfered * @param amount Amount of token being transfered */ function depositErc20( uint256 toChainId, address tokenAddress, address receiver, uint256 amount, string calldata tag ) public tokenChecks(tokenAddress) whenNotPaused nonReentrant { TokenConfig memory config = tokenManager.getDepositConfig(toChainId, tokenAddress); require(config.min <= amount && config.max >= amount, "Deposit amount not in Cap limit"); require(receiver != address(0), "Receiver address cannot be 0"); require(amount != 0, "Amount cannot be 0"); address sender = _msgSender(); uint256 rewardAmount = getRewardAmount(amount, tokenAddress); if (rewardAmount != 0) { incentivePool[tokenAddress] = incentivePool[tokenAddress] - rewardAmount; } liquidityProviders.increaseCurrentLiquidity(tokenAddress, amount); SafeERC20Upgradeable.safeTransferFrom(IERC20Upgradeable(tokenAddress), sender, address(this), amount); // Emit (amount + reward amount) in event emit Deposit(sender, tokenAddress, receiver, toChainId, amount + rewardAmount, rewardAmount, tag); } function getRewardAmount(uint256 amount, address tokenAddress) public view returns (uint256 rewardAmount) { uint256 currentLiquidity = getCurrentLiquidity(tokenAddress); uint256 providedLiquidity = liquidityProviders.getSuppliedLiquidityByToken(tokenAddress); if (currentLiquidity < providedLiquidity) { uint256 liquidityDifference = providedLiquidity - currentLiquidity; if (amount >= liquidityDifference) { rewardAmount = incentivePool[tokenAddress]; } else { // Multiply by 10000000000 to avoid 0 reward amount for small amount and liquidity difference rewardAmount = (amount * incentivePool[tokenAddress] * 10000000000) / liquidityDifference; rewardAmount = rewardAmount / 10000000000; } } } /** * DAI permit and Deposit. */ function permitAndDepositErc20( address tokenAddress, address receiver, uint256 amount, uint256 toChainId, PermitRequest calldata permitOptions, string calldata tag ) external { IERC20Permit(tokenAddress).permit( _msgSender(), address(this), permitOptions.nonce, permitOptions.expiry, permitOptions.allowed, permitOptions.v, permitOptions.r, permitOptions.s ); depositErc20(toChainId, tokenAddress, receiver, amount, tag); } /** * EIP2612 and Deposit. */ function permitEIP2612AndDepositErc20( address tokenAddress, address receiver, uint256 amount, uint256 toChainId, PermitRequest calldata permitOptions, string calldata tag ) external { IERC20Permit(tokenAddress).permit( _msgSender(), address(this), amount, permitOptions.expiry, permitOptions.v, permitOptions.r, permitOptions.s ); depositErc20(toChainId, tokenAddress, receiver, amount, tag); } /** * @dev Function used to deposit native token into pool to initiate a cross chain token transfer. * @param receiver Address on toChainId where tokens needs to be transfered * @param toChainId Chain id where funds needs to be transfered */ function depositNative( address receiver, uint256 toChainId, string calldata tag ) external payable whenNotPaused nonReentrant { require( tokenManager.getDepositConfig(toChainId, NATIVE).min <= msg.value && tokenManager.getDepositConfig(toChainId, NATIVE).max >= msg.value, "Deposit amount not in Cap limit" ); require(receiver != address(0), "Receiver address cannot be 0"); require(msg.value != 0, "Amount cannot be 0"); uint256 rewardAmount = getRewardAmount(msg.value, NATIVE); if (rewardAmount != 0) { incentivePool[NATIVE] = incentivePool[NATIVE] - rewardAmount; } liquidityProviders.increaseCurrentLiquidity(NATIVE, msg.value); emit Deposit(_msgSender(), NATIVE, receiver, toChainId, msg.value + rewardAmount, rewardAmount, tag); } function sendFundsToUser( address tokenAddress, uint256 amount, address payable receiver, bytes calldata depositHash, uint256 tokenGasPrice, uint256 fromChainId ) external nonReentrant onlyExecutor whenNotPaused { uint256 initialGas = gasleft(); TokenConfig memory config = tokenManager.getTransferConfig(tokenAddress); require(config.min <= amount && config.max >= amount, "Withdraw amount not in Cap limit"); require(receiver != address(0), "Bad receiver address"); (bytes32 hashSendTransaction, bool status) = checkHashStatus(tokenAddress, amount, receiver, depositHash); require(!status, "Already Processed"); processedHash[hashSendTransaction] = true; // uint256 amountToTransfer, uint256 lpFee, uint256 transferFeeAmount, uint256 gasFee uint256[4] memory transferDetails = getAmountToTransfer(initialGas, tokenAddress, amount, tokenGasPrice); liquidityProviders.decreaseCurrentLiquidity(tokenAddress, transferDetails[0]); if (tokenAddress == NATIVE) { (bool success, ) = receiver.call{value: transferDetails[0]}(""); require(success, "Native Transfer Failed"); } else { SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(tokenAddress), receiver, transferDetails[0]); } emit AssetSent( tokenAddress, amount, transferDetails[0], receiver, depositHash, fromChainId, transferDetails[1], transferDetails[2], transferDetails[3] ); } /** * @dev Internal function to calculate amount of token that needs to be transfered afetr deducting all required fees. * Fee to be deducted includes gas fee, lp fee and incentive pool amount if needed. * @param initialGas Gas provided initially before any calculations began * @param tokenAddress Token address for which calculation needs to be done * @param amount Amount of token to be transfered before deducting the fee * @param tokenGasPrice Gas price in the token being transfered to be used to calculate gas fee * @return [ amountToTransfer, lpFee, transferFeeAmount, gasFee ] */ function getAmountToTransfer( uint256 initialGas, address tokenAddress, uint256 amount, uint256 tokenGasPrice ) internal returns (uint256[4] memory) { TokenInfo memory tokenInfo = tokenManager.getTokensInfo(tokenAddress); uint256 transferFeePerc = _getTransferFee(tokenAddress, amount, tokenInfo); uint256 lpFee; if (transferFeePerc > tokenInfo.equilibriumFee) { // Here add some fee to incentive pool also lpFee = (amount * tokenInfo.equilibriumFee) / BASE_DIVISOR; unchecked { incentivePool[tokenAddress] += (amount * (transferFeePerc - tokenInfo.equilibriumFee)) / BASE_DIVISOR; } } else { lpFee = (amount * transferFeePerc) / BASE_DIVISOR; } uint256 transferFeeAmount = (amount * transferFeePerc) / BASE_DIVISOR; liquidityProviders.addLPFee(tokenAddress, lpFee); uint256 totalGasUsed = initialGas + tokenInfo.transferOverhead + baseGas - gasleft(); uint256 gasFee = totalGasUsed * tokenGasPrice; gasFeeAccumulatedByToken[tokenAddress] += gasFee; gasFeeAccumulated[tokenAddress][_msgSender()] += gasFee; uint256 amountToTransfer = amount - (transferFeeAmount + gasFee); return [amountToTransfer, lpFee, transferFeeAmount, gasFee]; } function _getTransferFee( address tokenAddress, uint256 amount, TokenInfo memory tokenInfo ) private view returns (uint256 fee) { uint256 currentLiquidity = getCurrentLiquidity(tokenAddress); uint256 providedLiquidity = liquidityProviders.getSuppliedLiquidityByToken(tokenAddress); uint256 resultingLiquidity = currentLiquidity - amount; // Fee is represented in basis points * 10 for better accuracy uint256 numerator = providedLiquidity * tokenInfo.equilibriumFee * tokenInfo.maxFee; // F(max) * F(e) * L(e) uint256 denominator = tokenInfo.equilibriumFee * providedLiquidity + (tokenInfo.maxFee - tokenInfo.equilibriumFee) * resultingLiquidity; // F(e) * L(e) + (F(max) - F(e)) * L(r) if (denominator == 0) { fee = 0; } else { fee = numerator / denominator; } } function getTransferFee(address tokenAddress, uint256 amount) external view returns (uint256) { return _getTransferFee(tokenAddress, amount, tokenManager.getTokensInfo(tokenAddress)); } function checkHashStatus( address tokenAddress, uint256 amount, address payable receiver, bytes calldata depositHash ) public view returns (bytes32 hashSendTransaction, bool status) { hashSendTransaction = keccak256(abi.encode(tokenAddress, amount, receiver, keccak256(depositHash))); status = processedHash[hashSendTransaction]; } function withdrawErc20GasFee(address tokenAddress) external onlyExecutor whenNotPaused nonReentrant { require(tokenAddress != NATIVE, "Can't withdraw native token fee"); // uint256 gasFeeAccumulated = gasFeeAccumulatedByToken[tokenAddress]; uint256 _gasFeeAccumulated = gasFeeAccumulated[tokenAddress][_msgSender()]; require(_gasFeeAccumulated != 0, "Gas Fee earned is 0"); gasFeeAccumulatedByToken[tokenAddress] = gasFeeAccumulatedByToken[tokenAddress] - _gasFeeAccumulated; gasFeeAccumulated[tokenAddress][_msgSender()] = 0; SafeERC20Upgradeable.safeTransfer(IERC20Upgradeable(tokenAddress), _msgSender(), _gasFeeAccumulated); emit GasFeeWithdraw(tokenAddress, _msgSender(), _gasFeeAccumulated); } function withdrawNativeGasFee() external onlyExecutor whenNotPaused nonReentrant { uint256 _gasFeeAccumulated = gasFeeAccumulated[NATIVE][_msgSender()]; require(_gasFeeAccumulated != 0, "Gas Fee earned is 0"); gasFeeAccumulatedByToken[NATIVE] = gasFeeAccumulatedByToken[NATIVE] - _gasFeeAccumulated; gasFeeAccumulated[NATIVE][_msgSender()] = 0; (bool success, ) = payable(_msgSender()).call{value: _gasFeeAccumulated}(""); require(success, "Native Transfer Failed"); emit GasFeeWithdraw(address(this), _msgSender(), _gasFeeAccumulated); } function transfer( address _tokenAddress, address receiver, uint256 _tokenAmount ) external whenNotPaused onlyLiquidityProviders nonReentrant { require(receiver != address(0), "Invalid receiver"); if (_tokenAddress == NATIVE) { require(address(this).balance >= _tokenAmount, "ERR__INSUFFICIENT_BALANCE"); (bool success, ) = receiver.call{value: _tokenAmount}(""); require(success, "ERR__NATIVE_TRANSFER_FAILED"); } else { IERC20Upgradeable baseToken = IERC20Upgradeable(_tokenAddress); require(baseToken.balanceOf(address(this)) >= _tokenAmount, "ERR__INSUFFICIENT_BALANCE"); SafeERC20Upgradeable.safeTransfer(baseToken, receiver, _tokenAmount); } } function _msgSender() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (address sender) { return ERC2771ContextUpgradeable._msgSender(); } function _msgData() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (bytes calldata) { return ERC2771ContextUpgradeable._msgData(); } receive() external payable { emit EthReceived(_msgSender(), msg.value); } }
EIP2612 and Deposit./
function permitEIP2612AndDepositErc20( address tokenAddress, address receiver, uint256 amount, uint256 toChainId, PermitRequest calldata permitOptions, string calldata tag ) external { IERC20Permit(tokenAddress).permit( _msgSender(), address(this), amount, permitOptions.expiry, permitOptions.v, permitOptions.r, permitOptions.s ); depositErc20(toChainId, tokenAddress, receiver, amount, tag); }
12,902,921
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 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 SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } /** * @title Roles * @author Francisco Giordano (@frangio) * @dev Library for managing addresses assigned to a Role. * See RBAC.sol for example usage. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an address access to this role */ function add(Role storage role, address addr) internal { role.bearer[addr] = true; } /** * @dev remove an address' access to this role */ function remove(Role storage role, address addr) internal { role.bearer[addr] = false; } /** * @dev check if an address has this role * // reverts */ function check(Role storage role, address addr) view internal { require(has(role, addr)); } /** * @dev check if an address has this role * @return bool */ function has(Role storage role, address addr) view internal returns (bool) { return role.bearer[addr]; } } contract Time { /** * @dev Current time getter * @return Current time in seconds */ function _currentTime() internal view returns (uint256) { return block.timestamp; } } /** * @title RBAC (Role-Based Access Control) * @author Matt Condon (@Shrugs) * @dev Stores and provides setters and getters for roles and addresses. * Supports unlimited numbers of roles and addresses. * See //contracts/mocks/RBACMock.sol for an example of usage. * This RBAC method uses strings to key roles. It may be beneficial * for you to write your own implementation of this interface using Enums or similar. * It's also recommended that you define constants in the contract, like ROLE_ADMIN below, * to avoid typos. */ contract RBAC { using Roles for Roles.Role; mapping (string => Roles.Role) private roles; event RoleAdded(address indexed operator, string role); event RoleRemoved(address indexed operator, string role); /** * @dev reverts if addr does not have role * @param _operator address * @param _role the name of the role * // reverts */ function checkRole(address _operator, string _role) view public { roles[_role].check(_operator); } /** * @dev determine if addr has role * @param _operator address * @param _role the name of the role * @return bool */ function hasRole(address _operator, string _role) view public returns (bool) { return roles[_role].has(_operator); } /** * @dev add a role to an address * @param _operator address * @param _role the name of the role */ function addRole(address _operator, string _role) internal { roles[_role].add(_operator); emit RoleAdded(_operator, _role); } /** * @dev remove a role from an address * @param _operator address * @param _role the name of the role */ function removeRole(address _operator, string _role) internal { roles[_role].remove(_operator); emit RoleRemoved(_operator, _role); } /** * @dev modifier to scope access to a single role (uses msg.sender as addr) * @param _role the name of the role * // reverts */ modifier onlyRole(string _role) { checkRole(msg.sender, _role); _; } /** * @dev modifier to scope access to a set of roles (uses msg.sender as addr) * @param _roles the names of the roles to scope access to * // reverts * * @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this * see: https://github.com/ethereum/solidity/issues/2467 */ // modifier onlyRoles(string[] _roles) { // bool hasAnyRole = false; // for (uint8 i = 0; i < _roles.length; i++) { // if (hasRole(msg.sender, _roles[i])) { // hasAnyRole = true; // break; // } // } // require(hasAnyRole); // _; // } } /** * @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; } } contract Lockable { // locked values specified by address mapping(address => uint256) public lockedValues; /** * @dev Method to lock specified value by specified address * @param _for Address for which the value will be locked * @param _value Value that be locked */ function _lock(address _for, uint256 _value) internal { require(_for != address(0) && _value > 0, "Invalid lock operation configuration."); if (_value != lockedValues[_for]) { lockedValues[_for] = _value; } } /** * @dev Method to unlock (reset) locked value * @param _for Address for which the value will be unlocked */ function _unlock(address _for) internal { require(_for != address(0), "Invalid unlock operation configuration."); if (lockedValues[_for] != 0) { lockedValues[_for] = 0; } } } contract Operable is Ownable, RBAC { // role key string public constant ROLE_OPERATOR = "operator"; /** * @dev Reverts in case account is not Owner or Operator role */ modifier hasOwnerOrOperatePermission() { require(msg.sender == owner || hasRole(msg.sender, ROLE_OPERATOR), "Access denied."); _; } /** * @dev Getter to determine if address is in whitelist */ function operator(address _operator) public view returns (bool) { return hasRole(_operator, ROLE_OPERATOR); } /** * @dev Method to add accounts with Operator role * @param _operator Address that will receive Operator role access */ function addOperator(address _operator) public onlyOwner { addRole(_operator, ROLE_OPERATOR); } /** * @dev Method to remove accounts with Operator role * @param _operator Address that will loose Operator role access */ function removeOperator(address _operator) public onlyOwner { removeRole(_operator, ROLE_OPERATOR); } } contract Withdrawal is Ownable { // Address to which funds will be withdrawn address public withdrawWallet; /** * Event for withdraw logging * @param value Value that was withdrawn */ event WithdrawLog(uint256 value); /** * @param _withdrawWallet Address to which funds will be withdrawn */ constructor(address _withdrawWallet) public { require(_withdrawWallet != address(0), "Invalid funds holder wallet."); withdrawWallet = _withdrawWallet; } /** * @dev Transfers funds from the contract to the specified withdraw wallet address */ function withdrawAll() external onlyOwner { uint256 weiAmount = address(this).balance; withdrawWallet.transfer(weiAmount); emit WithdrawLog(weiAmount); } /** * @dev Transfers a part of the funds from the contract to the specified withdraw wallet address * @param _weiAmount Part of the funds to be withdrawn */ function withdraw(uint256 _weiAmount) external onlyOwner { require(_weiAmount <= address(this).balance, "Not enough funds."); withdrawWallet.transfer(_weiAmount); emit WithdrawLog(_weiAmount); } } contract PriceStrategy is Time, Operable { using SafeMath for uint256; /** * Describes stage parameters * @param start Stage start date * @param end Stage end date * @param volume Number of tokens available for the stage * @param priceInCHF Token price in CHF for the stage * @param minBonusVolume The minimum number of tokens after which the bonus tokens is added * @param bonus Percentage of bonus tokens */ struct Stage { uint256 start; uint256 end; uint256 volume; uint256 priceInCHF; uint256 minBonusVolume; uint256 bonus; bool lock; } /** * Describes lockup period parameters * @param periodInSec Lockup period in seconds * @param bonus Lockup bonus tokens percentage */ struct LockupPeriod { uint256 expires; uint256 bonus; } // describes stages available for ICO lifetime Stage[] public stages; // lockup periods specified by the period in month mapping(uint256 => LockupPeriod) public lockupPeriods; // number of decimals supported by CHF rates uint256 public constant decimalsCHF = 18; // minimum allowed investment in CHF (decimals 1e+18) uint256 public minInvestmentInCHF; // ETH rate in CHF uint256 public rateETHtoCHF; /** * Event for ETH to CHF rate changes logging * @param newRate New rate value */ event RateChangedLog(uint256 newRate); /** * @param _rateETHtoCHF Cost of ETH in CHF * @param _minInvestmentInCHF Minimal allowed investment in CHF */ constructor(uint256 _rateETHtoCHF, uint256 _minInvestmentInCHF) public { require(_minInvestmentInCHF > 0, "Minimum investment can not be set to 0."); minInvestmentInCHF = _minInvestmentInCHF; setETHtoCHFrate(_rateETHtoCHF); // PRE-ICO stages.push(Stage({ start: 1536969600, // 15th Sep, 2018 00:00:00 end: 1542239999, // 14th Nov, 2018 23:59:59 volume: uint256(25000000000).mul(10 ** 18), // (twenty five billion) priceInCHF: uint256(2).mul(10 ** 14), // CHF 0.00020 minBonusVolume: 0, bonus: 0, lock: false })); // ICO stages.push(Stage({ start: 1542240000, // 15th Nov, 2018 00:00:00 end: 1550188799, // 14th Feb, 2019 23:59:59 volume: uint256(65000000000).mul(10 ** 18), // (forty billion) priceInCHF: uint256(4).mul(10 ** 14), // CHF 0.00040 minBonusVolume: uint256(400000000).mul(10 ** 18), // (four hundred million) bonus: 2000, // 20% bonus tokens lock: true })); _setLockupPeriod(1550188799, 18, 3000); // 18 months after the end of the ICO / 30% _setLockupPeriod(1550188799, 12, 2000); // 12 months after the end of the ICO / 20% _setLockupPeriod(1550188799, 6, 1000); // 6 months after the end of the ICO / 10% } /** * @dev Updates ETH to CHF rate * @param _rateETHtoCHF Cost of ETH in CHF */ function setETHtoCHFrate(uint256 _rateETHtoCHF) public hasOwnerOrOperatePermission { require(_rateETHtoCHF > 0, "Rate can not be set to 0."); rateETHtoCHF = _rateETHtoCHF; emit RateChangedLog(rateETHtoCHF); } /** * @dev Tokens amount based on investment value in wei * @param _wei Investment value in wei * @param _lockup Lockup period in months * @param _sold Number of tokens sold by the moment * @return Amount of tokens and bonuses */ function getTokensAmount(uint256 _wei, uint256 _lockup, uint256 _sold) public view returns (uint256 tokens, uint256 bonus) { uint256 chfAmount = _wei.mul(rateETHtoCHF).div(10 ** decimalsCHF); require(chfAmount >= minInvestmentInCHF, "Investment value is below allowed minimum."); Stage memory currentStage = _getCurrentStage(); require(currentStage.priceInCHF > 0, "Invalid price value."); tokens = chfAmount.mul(10 ** decimalsCHF).div(currentStage.priceInCHF); uint256 bonusSize; if (tokens >= currentStage.minBonusVolume) { bonusSize = currentStage.bonus.add(lockupPeriods[_lockup].bonus); } else { bonusSize = lockupPeriods[_lockup].bonus; } bonus = tokens.mul(bonusSize).div(10 ** 4); uint256 total = tokens.add(bonus); require(currentStage.volume > _sold.add(total), "Not enough tokens available."); } /** * @dev Finds current stage parameters according to the rules and current date and time * @return Current stage parameters (available volume of tokens and price in CHF) */ function _getCurrentStage() internal view returns (Stage) { uint256 index = 0; uint256 time = _currentTime(); Stage memory result; while (index < stages.length) { Stage memory stage = stages[index]; if ((time >= stage.start && time <= stage.end)) { result = stage; break; } index++; } return result; } /** * @dev Sets bonus for specified lockup period. Allowed only for contract owner * @param _startPoint Lock start point (is seconds) * @param _period Lockup period (in months) * @param _bonus Percentage of bonus tokens */ function _setLockupPeriod(uint256 _startPoint, uint256 _period, uint256 _bonus) private { uint256 expires = _startPoint.add(_period.mul(2628000)); lockupPeriods[_period] = LockupPeriod({ expires: expires, bonus: _bonus }); } } contract BaseCrowdsale { using SafeMath for uint256; using SafeERC20 for CosquareToken; // The token being sold CosquareToken public token; // Total amount of tokens sold uint256 public tokensSold; /** * @dev Event for tokens purchase logging * @param purchaseType Who paid for the tokens * @param beneficiary Who got the tokens * @param value Value paid for purchase * @param tokens Amount of tokens purchased * @param bonuses Amount of bonuses received */ event TokensPurchaseLog(string purchaseType, address indexed beneficiary, uint256 value, uint256 tokens, uint256 bonuses); /** * @param _token Address of the token being sold */ constructor(CosquareToken _token) public { require(_token != address(0), "Invalid token address."); token = _token; } /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { require(msg.data.length == 0, "Should not accept data."); _buyTokens(msg.sender, msg.value, "ETH"); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) external payable { _buyTokens(_beneficiary, msg.value, "ETH"); } /** * @dev Tokens purchase for wei investments * @param _beneficiary Address performing the token purchase * @param _amount Amount of tokens purchased * @param _investmentType Investment channel string */ function _buyTokens(address _beneficiary, uint256 _amount, string _investmentType) internal { _preValidatePurchase(_beneficiary, _amount); (uint256 tokensAmount, uint256 tokenBonus) = _getTokensAmount(_beneficiary, _amount); uint256 totalAmount = tokensAmount.add(tokenBonus); _processPurchase(_beneficiary, totalAmount); emit TokensPurchaseLog(_investmentType, _beneficiary, _amount, tokensAmount, tokenBonus); _postPurchaseUpdate(_beneficiary, totalAmount); } /** * @dev Validation of an executed purchase * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0), "Invalid beneficiary address."); require(_weiAmount > 0, "Invalid investment value."); } /** * @dev Abstract function to count the number of tokens depending on the funds deposited * @param _beneficiary Address for which to get the tokens amount * @param _weiAmount Value in wei involved in the purchase * @return Number of tokens */ function _getTokensAmount(address _beneficiary, uint256 _weiAmount) internal view returns (uint256 tokens, uint256 bonus); /** * @dev Executed when a purchase is ready to be executed * @param _beneficiary Address receiving the tokens * @param _tokensAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokensAmount) internal { _deliverTokens(_beneficiary, _tokensAmount); } /** * @dev Deliver tokens to investor * @param _beneficiary Address receiving the tokens * @param _tokensAmount Number of tokens to be purchased */ function _deliverTokens(address _beneficiary, uint256 _tokensAmount) internal { token.safeTransfer(_beneficiary, _tokensAmount); } /** * @dev Changes the contract state after purchase * @param _beneficiary Address received the tokens * @param _tokensAmount The number of tokens that were purchased */ function _postPurchaseUpdate(address _beneficiary, uint256 _tokensAmount) internal { tokensSold = tokensSold.add(_tokensAmount); } } contract LockableCrowdsale is Time, Lockable, Operable, PriceStrategy, BaseCrowdsale { using SafeMath for uint256; /** * @dev Locks the next purchase for the provision of bonus tokens * @param _beneficiary Address for which the next purchase will be locked * @param _lockupPeriod The period to which tokens will be locked from the next purchase */ function lockNextPurchase(address _beneficiary, uint256 _lockupPeriod) external hasOwnerOrOperatePermission { require(_lockupPeriod == 6 || _lockupPeriod == 12 || _lockupPeriod == 18, "Invalid lock interval"); Stage memory currentStage = _getCurrentStage(); require(currentStage.lock, "Lock operation is not allowed."); _lock(_beneficiary, _lockupPeriod); } /** * @dev Executed when a purchase is ready to be executed * @param _beneficiary Address receiving the tokens * @param _tokensAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokensAmount) internal { super._processPurchase(_beneficiary, _tokensAmount); uint256 lockedValue = lockedValues[_beneficiary]; if (lockedValue > 0) { uint256 expires = lockupPeriods[lockedValue].expires; token.lock(_beneficiary, _tokensAmount, expires); } } /** * @dev Counts the number of tokens depending on the funds deposited * @param _beneficiary Address for which to get the tokens amount * @param _weiAmount Value in wei involved in the purchase * @return Number of tokens */ function _getTokensAmount(address _beneficiary, uint256 _weiAmount) internal view returns (uint256 tokens, uint256 bonus) { (tokens, bonus) = getTokensAmount(_weiAmount, lockedValues[_beneficiary], tokensSold); } /** * @dev Changes the contract state after purchase * @param _beneficiary Address received the tokens * @param _tokensAmount The number of tokens that were purchased */ function _postPurchaseUpdate(address _beneficiary, uint256 _tokensAmount) internal { super._postPurchaseUpdate(_beneficiary, _tokensAmount); _unlock(_beneficiary); } } contract Whitelist is RBAC, Operable { // role key string public constant ROLE_WHITELISTED = "whitelist"; /** * @dev Throws if operator is not whitelisted. * @param _operator Operator address */ modifier onlyIfWhitelisted(address _operator) { checkRole(_operator, ROLE_WHITELISTED); _; } /** * @dev Add an address to the whitelist * @param _operator Operator address */ function addAddressToWhitelist(address _operator) public hasOwnerOrOperatePermission { addRole(_operator, ROLE_WHITELISTED); } /** * @dev Getter to determine if address is in whitelist * @param _operator The address to be added to the whitelist * @return True if the address is in the whitelist */ function whitelist(address _operator) public view returns (bool) { return hasRole(_operator, ROLE_WHITELISTED); } /** * @dev Add addresses to the whitelist * @param _operators Operators addresses */ function addAddressesToWhitelist(address[] _operators) public hasOwnerOrOperatePermission { for (uint256 i = 0; i < _operators.length; i++) { addAddressToWhitelist(_operators[i]); } } /** * @dev Remove an address from the whitelist * @param _operator Operator address */ function removeAddressFromWhitelist(address _operator) public hasOwnerOrOperatePermission { removeRole(_operator, ROLE_WHITELISTED); } /** * @dev Remove addresses from the whitelist * @param _operators Operators addresses */ function removeAddressesFromWhitelist(address[] _operators) public hasOwnerOrOperatePermission { for (uint256 i = 0; i < _operators.length; i++) { removeAddressFromWhitelist(_operators[i]); } } } contract WhitelistedCrowdsale is Whitelist, BaseCrowdsale { /** * @dev Extend parent behavior requiring beneficiary to be in whitelist. * @param _beneficiary Token beneficiary * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyIfWhitelisted(_beneficiary) { super._preValidatePurchase(_beneficiary, _weiAmount); } } /** * @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(); } } contract PausableCrowdsale is Pausable, BaseCrowdsale { /** * @dev Extend parent behavior requiring contract not to be paused * @param _beneficiary Token beneficiary * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal whenNotPaused { super._preValidatePurchase(_beneficiary, _weiAmount); } } /** * @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 DetailedERC20 token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * 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(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract CosquareToken is Time, StandardToken, DetailedERC20, Ownable { using SafeMath for uint256; /** * Describes locked balance * @param expires Time when tokens will be unlocked * @param value Amount of the tokens is locked */ struct LockedBalance { uint256 expires; uint256 value; } // locked balances specified be the address mapping(address => LockedBalance[]) public lockedBalances; // sale wallet (65%) address public saleWallet; // reserve wallet (15%) address public reserveWallet; // team wallet (15%) address public teamWallet; // strategic wallet (5%) address public strategicWallet; // end point, after which all tokens will be unlocked uint256 public lockEndpoint; /** * Event for lock logging * @param who The address on which part of the tokens is locked * @param value Amount of the tokens is locked * @param expires Time when tokens will be unlocked */ event LockLog(address indexed who, uint256 value, uint256 expires); /** * @param _saleWallet Sale wallet * @param _reserveWallet Reserve wallet * @param _teamWallet Team wallet * @param _strategicWallet Strategic wallet * @param _lockEndpoint End point, after which all tokens will be unlocked */ constructor(address _saleWallet, address _reserveWallet, address _teamWallet, address _strategicWallet, uint256 _lockEndpoint) DetailedERC20("cosquare", "CSQ", 18) public { require(_lockEndpoint > 0, "Invalid global lock end date."); lockEndpoint = _lockEndpoint; _configureWallet(_saleWallet, 65000000000000000000000000000); // 6.5e+28 saleWallet = _saleWallet; _configureWallet(_reserveWallet, 15000000000000000000000000000); // 1.5e+28 reserveWallet = _reserveWallet; _configureWallet(_teamWallet, 15000000000000000000000000000); // 1.5e+28 teamWallet = _teamWallet; _configureWallet(_strategicWallet, 5000000000000000000000000000); // 0.5e+28 strategicWallet = _strategicWallet; } /** * @dev Setting the initial value of the tokens to the wallet * @param _wallet Address to be set up * @param _amount The number of tokens to be assigned to this address */ function _configureWallet(address _wallet, uint256 _amount) private { require(_wallet != address(0), "Invalid wallet address."); totalSupply_ = totalSupply_.add(_amount); balances[_wallet] = _amount; emit Transfer(address(0), _wallet, _amount); } /** * @dev Throws if the address does not have enough not locked balance * @param _who The address to transfer from * @param _value The amount to be transferred */ modifier notLocked(address _who, uint256 _value) { uint256 time = _currentTime(); if (lockEndpoint > time) { uint256 index = 0; uint256 locked = 0; while (index < lockedBalances[_who].length) { if (lockedBalances[_who][index].expires > time) { locked = locked.add(lockedBalances[_who][index].value); } index++; } require(_value <= balances[_who].sub(locked), "Not enough unlocked tokens"); } _; } /** * @dev Overridden to check whether enough not locked balance * @param _from The address which you want to send tokens from * @param _to The address which you want to transfer to * @param _value The amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public notLocked(_from, _value) returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev Overridden to check whether enough not locked balance * @param _to The address to transfer to * @param _value The amount to be transferred */ function transfer(address _to, uint256 _value) public notLocked(msg.sender, _value) returns (bool) { return super.transfer(_to, _value); } /** * @dev Gets the locked balance of the specified address * @param _owner The address to query the locked balance of * @param _expires Time of expiration of the lock (If equals to 0 - returns all locked tokens at this moment) * @return An uint256 representing the amount of locked balance by the passed address */ function lockedBalanceOf(address _owner, uint256 _expires) external view returns (uint256) { uint256 time = _currentTime(); uint256 index = 0; uint256 locked = 0; if (lockEndpoint > time) { while (index < lockedBalances[_owner].length) { if (_expires > 0) { if (lockedBalances[_owner][index].expires == _expires) { locked = locked.add(lockedBalances[_owner][index].value); } } else { if (lockedBalances[_owner][index].expires >= time) { locked = locked.add(lockedBalances[_owner][index].value); } } index++; } } return locked; } /** * @dev Locks part of the balance for the specified address and for a certain period (3 periods expected) * @param _who The address of which will be locked part of the balance * @param _value The amount of tokens to be locked * @param _expires Time of expiration of the lock */ function lock(address _who, uint256 _value, uint256 _expires) public onlyOwner { uint256 time = _currentTime(); require(_who != address(0) && _value <= balances[_who] && _expires > time, "Invalid lock configuration."); uint256 index = 0; bool exist = false; while (index < lockedBalances[_who].length) { if (lockedBalances[_who][index].expires == _expires) { exist = true; break; } index++; } if (exist) { lockedBalances[_who][index].value = lockedBalances[_who][index].value.add(_value); } else { lockedBalances[_who].push(LockedBalance({ expires: _expires, value: _value })); } emit LockLog(_who, _value, _expires); } } contract Crowdsale is Lockable, Operable, Withdrawal, PriceStrategy, LockableCrowdsale, WhitelistedCrowdsale, PausableCrowdsale { using SafeMath for uint256; /** * @param _rateETHtoCHF Cost of ETH in CHF * @param _minInvestmentInCHF Minimal allowed investment in CHF * @param _withdrawWallet Address to which funds will be withdrawn * @param _token Address of the token being sold */ constructor(uint256 _rateETHtoCHF, uint256 _minInvestmentInCHF, address _withdrawWallet, CosquareToken _token) PriceStrategy(_rateETHtoCHF, _minInvestmentInCHF) Withdrawal(_withdrawWallet) BaseCrowdsale(_token) public { } /** * @dev Distributes tokens for wei investments * @param _beneficiary Address performing the token purchase * @param _ethAmount Investment value in ETH * @param _type Type of investment channel */ function distributeTokensForInvestment(address _beneficiary, uint256 _ethAmount, string _type) public hasOwnerOrOperatePermission { _buyTokens(_beneficiary, _ethAmount, _type); } /** * @dev Distributes tokens manually * @param _beneficiary Address performing the tokens distribution * @param _tokensAmount Amount of tokens distribution */ function distributeTokensManual(address _beneficiary, uint256 _tokensAmount) external hasOwnerOrOperatePermission { _preValidatePurchase(_beneficiary, _tokensAmount); _deliverTokens(_beneficiary, _tokensAmount); emit TokensPurchaseLog("MANUAL", _beneficiary, 0, _tokensAmount, 0); _postPurchaseUpdate(_beneficiary, _tokensAmount); } }
Counts the number of tokens depending on the funds deposited _beneficiary Address for which to get the tokens amount _weiAmount Value in wei involved in the purchase return Number of tokens/
function _getTokensAmount(address _beneficiary, uint256 _weiAmount) internal view returns (uint256 tokens, uint256 bonus) { (tokens, bonus) = getTokensAmount(_weiAmount, lockedValues[_beneficiary], tokensSold); }
2,492,463
// SPDX-License-Identifier: BUSL-1.1 pragma solidity =0.8.4; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "./interfaces/IERC20Modified.sol"; import "./tokens/VolmexPositionToken.sol"; import "./VolmexProtocol.sol"; /** * @title Factory Contract * @author volmex.finance [[email protected]] */ contract VolmexIndexFactory is OwnableUpgradeable { event IndexRegistered( uint256 indexed indexCount, VolmexProtocol indexed index ); event VolatilityTokenCreated( IERC20Modified indexed volatilityToken, IERC20Modified indexed inverseVolatilityToken, string tokenName, string tokenSymbol ); // Volatility token implementation contract for factory address public positionTokenImplementation; // To store the address of volatility. mapping(uint256 => address) public getIndex; // To store the name of volatility mapping(uint256 => string) public getIndexSymbol; // Used to store the address and name of volatility at a particular _index (incremental state of 1) uint256 public indexCount; // These are position token roles // Calculated as keccak256("VOLMEX_PROTOCOL_ROLE"). bytes32 private constant VOLMEX_PROTOCOL_ROLE = 0x33ba6006595f7ad5c59211bde33456cab351f47602fc04f644c8690bc73c4e16; // Referenced from Openzepplin AccessControl.sol bytes32 private constant DEFAULT_ADMIN_ROLE = 0x00; /** * @notice Get the address of implementation contracts instance. */ function initialize(address _implementation) external initializer { __Ownable_init(); positionTokenImplementation = _implementation; } /** * @notice Get the counterfactual address of position token implementation */ function determineVolatilityTokenAddress( uint256 _indexCount, string memory _name, string memory _symbol ) external view returns (address) { bytes32 salt = keccak256(abi.encodePacked(_indexCount, _name, _symbol)); return Clones.predictDeterministicAddress( positionTokenImplementation, salt, address(this) ); } /** * @notice Clones new volatility tokens - { returns volatility tokens address typecasted to IERC20Modified } * * @dev Increment the indexCount by 1 * @dev Check if state is at NotInitialized * @dev Clones the volatility and inverse volatility tokens * @dev Stores the volatility name, referenced by indexCount * @dev Emits event of volatility token name & symbol, indexCount(position), position tokens address * * @param _tokenName is the name for volatility * @param _tokenSymbol is the symbol for volatility */ function createVolatilityTokens( string memory _tokenName, string memory _tokenSymbol ) external onlyOwner returns ( IERC20Modified volatilityToken, IERC20Modified inverseVolatilityToken ) { volatilityToken = IERC20Modified( _clonePositonToken(_tokenName, _tokenSymbol) ); inverseVolatilityToken = IERC20Modified( _clonePositonToken( string(abi.encodePacked("Inverse ", _tokenName)), string(abi.encodePacked("i", _tokenSymbol)) ) ); emit VolatilityTokenCreated( volatilityToken, inverseVolatilityToken, _tokenName, _tokenSymbol ); } /** * @notice Registers the Volmex Protocol * * @dev Check if state is at VolatilitysCreated * @dev Stores index address, referenced by indexCount * @dev Grants the VOLMEX_PROTOCOL_ROLE and DEFAULT_ADMIN_ROLE to protocol * @dev Update index state to Completed * @dev Emit event of index registered with indexCount and index address * * @param _volmexProtocolContract Address of VolmexProtocol typecasted to VolmexProtocol * @param _collateralSymbol Symbol of collateral used */ function registerIndex( VolmexProtocol _volmexProtocolContract, string memory _collateralSymbol ) external onlyOwner { indexCount++; getIndex[indexCount] = address(_volmexProtocolContract); IERC20Modified volatilityToken = _volmexProtocolContract.volatilityToken(); IERC20Modified inverseVolatilityToken = _volmexProtocolContract.inverseVolatilityToken(); getIndexSymbol[indexCount] = string( abi.encodePacked(volatilityToken.symbol(), _collateralSymbol) ); volatilityToken.grantRole( VOLMEX_PROTOCOL_ROLE, address(_volmexProtocolContract) ); inverseVolatilityToken.grantRole( VOLMEX_PROTOCOL_ROLE, address(_volmexProtocolContract) ); volatilityToken.grantRole(DEFAULT_ADMIN_ROLE, msg.sender); inverseVolatilityToken.grantRole(DEFAULT_ADMIN_ROLE, msg.sender); emit IndexRegistered(indexCount, _volmexProtocolContract); } /** * @notice Clones the position token - { returns position token address } * * @dev Generates a salt using indexCount, token name and token symbol * @dev Clone the position token implementation with a salt make it deterministic * @dev Initializes the position token * * @param _name is the name of volatility token * @param _symbol is the symbol of volatility token */ function _clonePositonToken(string memory _name, string memory _symbol) private returns (address) { bytes32 salt = keccak256(abi.encodePacked(indexCount, _name, _symbol)); VolmexPositionToken newVolatilityToken = VolmexPositionToken( Clones.cloneDeterministic(positionTokenImplementation, salt) ); newVolatilityToken.initialize(_name, _symbol); return address(newVolatilityToken); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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 Clones { /** * @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) { // solhint-disable-next-line no-inline-assembly 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) { // solhint-disable-next-line no-inline-assembly 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) { // solhint-disable-next-line no-inline-assembly 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: BUSL-1.1 pragma solidity =0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @dev Modified Interface of the OpenZeppelin's IERC20 extra functions to add features in position token. */ interface IERC20Modified is IERC20 { function symbol() external view returns (string memory); function mint(address _toWhom, uint256 amount) external; function burn(address _whose, uint256 amount) external; function grantRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; function pause() external; function unpause() external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity =0.8.4; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PausableUpgradeable.sol"; /** * @title Token Contract * @author volmex.finance [[email protected]] */ contract VolmexPositionToken is Initializable, AccessControlUpgradeable, ERC20PausableUpgradeable { // Position token role, calculated as keccak256("VOLMEX_PROTOCOL_ROLE") bytes32 public constant VOLMEX_PROTOCOL_ROLE = 0x33ba6006595f7ad5c59211bde33456cab351f47602fc04f644c8690bc73c4e16; /** * @dev Grants `DEFAULT_ADMIN_ROLE` and `VOLMEX_PROTOCOL_ROLE` to the * account that deploys the contract. * * See {ERC20-constructor}. */ function initialize(string memory name, string memory symbol) external initializer { __ERC20_init_unchained(name, symbol); __AccessControl_init_unchained(); __ERC20Pausable_init(); __ERC165_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(VOLMEX_PROTOCOL_ROLE, msg.sender); } /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `VOLMEX_PROTOCOL_ROLE`. */ function mint(address to, uint256 amount) public virtual { require( hasRole(VOLMEX_PROTOCOL_ROLE, msg.sender), "VolmexPositionToken: must have volmex protocol role to mint" ); _mint(to, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(address from, uint256 amount) public virtual { require( hasRole(VOLMEX_PROTOCOL_ROLE, msg.sender), "VolmexPositionToken: must have volmex protocol role to burn" ); _burn(from, amount); } /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `VOLMEX_PROTOCOL_ROLE`. */ function pause() public virtual { require( hasRole(VOLMEX_PROTOCOL_ROLE, msg.sender), "VolmexPositionToken: must have volmex protocol role to pause" ); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `VOLMEX_PROTOCOL_ROLE`. */ function unpause() public virtual { require( hasRole(VOLMEX_PROTOCOL_ROLE, msg.sender), "VolmexPositionToken: must have volmex protocol role to unpause" ); _unpause(); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity =0.8.4; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./interfaces/IERC20Modified.sol"; import "./library/VolmexSafeERC20.sol"; /** * @title Protocol Contract * @author volmex.finance [[email protected]] */ contract VolmexProtocol is Initializable, OwnableUpgradeable, ReentrancyGuardUpgradeable { using VolmexSafeERC20 for IERC20Modified; event ToggleActivated(bool isActive); event UpdatedVolatilityToken( address indexed positionToken, bool isVolatilityIndexToken ); event UpdatedFees(uint256 issuanceFees, uint256 redeemFees); event UpdatedMinimumCollateral(uint256 newMinimumCollateralQty); event ClaimedFees(uint256 fees); event ToggledVolatilityTokenPause(bool isPause); event Settled(uint256 settlementPrice); event Collateralized( address indexed sender, uint256 collateralLock, uint256 positionTokensMinted, uint256 fees ); event Redeemed( address indexed sender, uint256 collateralReleased, uint256 volatilityIndexTokenBurned, uint256 inverseVolatilityIndexTokenBurned, uint256 fees ); // Has the value of minimum collateral qty required uint256 public minimumCollateralQty; // Has the boolean state of protocol bool public active; // Has the boolean state of protocol settlement bool public isSettled; // Volatility tokens IERC20Modified public volatilityToken; IERC20Modified public inverseVolatilityToken; // Only ERC20 standard functions are used by the collateral defined here. // Address of the acceptable collateral token. IERC20Modified public collateral; // Used to calculate collateralize fee uint256 public issuanceFees; // Used to calculate redeem fee uint256 public redeemFees; // Total fee amount for call of collateralize and redeem uint256 public accumulatedFees; // Percentage value is upto two decimal places, so we're dividing it by 10000 // Set the max fee as 5%, i.e. 500/10000. uint256 constant MAX_FEE = 500; // No need to add 18 decimals, because they are already considered in respective token qty arguments. uint256 public volatilityCapRatio; // This is the price of volatility index, ranges from 0 to volatilityCapRatio, // and the inverse can be calculated by subtracting volatilityCapRatio by settlementPrice. uint256 public settlementPrice; /** * @notice Used to check contract is active */ modifier onlyActive() { require(active, "Volmex: Protocol not active"); _; } /** * @notice Used to check contract is not settled */ modifier onlyNotSettled() { require(!isSettled, "Volmex: Protocol settled"); _; } /** * @notice Used to check contract is settled */ modifier onlySettled() { require(isSettled, "Volmex: Protocol not settled"); _; } /** * @dev Makes the protocol `active` at deployment * @dev Sets the `minimumCollateralQty` * @dev Makes the collateral token as `collateral` * @dev Assign position tokens * @dev Sets the `volatilityCapRatio` * * @param _collateralTokenAddress is address of collateral token typecasted to IERC20Modified * @param _volatilityToken is address of volatility index token typecasted to IERC20Modified * @param _inverseVolatilityToken is address of inverse volatility index token typecasted to IERC20Modified * @param _minimumCollateralQty is the minimum qty of tokens need to mint 0.1 volatility and inverse volatility tokens * @param _volatilityCapRatio is the cap for volatility */ function initialize( IERC20Modified _collateralTokenAddress, IERC20Modified _volatilityToken, IERC20Modified _inverseVolatilityToken, uint256 _minimumCollateralQty, uint256 _volatilityCapRatio ) external initializer { __Ownable_init(); __ReentrancyGuard_init(); require( _minimumCollateralQty > 0, "Volmex: Minimum collateral quantity should be greater than 0" ); active = true; minimumCollateralQty = _minimumCollateralQty; collateral = _collateralTokenAddress; volatilityToken = _volatilityToken; inverseVolatilityToken = _inverseVolatilityToken; volatilityCapRatio = _volatilityCapRatio; } /** * @notice Toggles the active variable. Restricted to only the owner of the contract. */ function toggleActive() external onlyOwner { active = !active; emit ToggleActivated(active); } /** * @notice Update the `minimumCollateralQty` * @param _newMinimumCollQty Provides the new minimum collateral quantity */ function updateMinimumCollQty(uint256 _newMinimumCollQty) external onlyOwner { require( _newMinimumCollQty > 0, "Volmex: Minimum collateral quantity should be greater than 0" ); minimumCollateralQty = _newMinimumCollQty; emit UpdatedMinimumCollateral(_newMinimumCollQty); } /** * @notice Update the {Volatility Token} * @param _positionToken Address of the new position token * @param _isVolatilityIndexToken Type of the position token, { VolatilityIndexToken: true, InverseVolatilityIndexToken: false } */ function updateVolatilityToken( address _positionToken, bool _isVolatilityIndexToken ) external onlyOwner { _isVolatilityIndexToken ? volatilityToken = IERC20Modified(_positionToken) : inverseVolatilityToken = IERC20Modified(_positionToken); emit UpdatedVolatilityToken(_positionToken, _isVolatilityIndexToken); } /** * @notice Add collateral to the protocol and mint the position tokens * @param _collateralQty Quantity of the collateral being deposited * * NOTE: Collateral quantity should be at least required minimum collateral quantity * * Calculation: Get the quantity for position token * Mint the position token for `msg.sender` * */ function collateralize(uint256 _collateralQty) external onlyActive onlyNotSettled { require( _collateralQty >= minimumCollateralQty, "Volmex: CollateralQty > minimum qty required" ); // Mechanism to calculate the collateral qty using the increase in balance // of protocol contract to counter USDT's fee mechanism, which can be enabled in future uint256 initialProtocolBalance = collateral.balanceOf(address(this)); collateral.safeTransferFrom(msg.sender, address(this), _collateralQty); uint256 finalProtocolBalance = collateral.balanceOf(address(this)); _collateralQty = finalProtocolBalance - initialProtocolBalance; uint256 fee; if (issuanceFees > 0) { fee = (_collateralQty * issuanceFees) / 10000; _collateralQty = _collateralQty - fee; accumulatedFees = accumulatedFees + fee; } uint256 qtyToBeMinted = _collateralQty / volatilityCapRatio; volatilityToken.mint(msg.sender, qtyToBeMinted); inverseVolatilityToken.mint(msg.sender, qtyToBeMinted); emit Collateralized(msg.sender, _collateralQty, qtyToBeMinted, fee); } /** * @notice Redeem the collateral from the protocol by providing the position token * * @param _positionTokenQty Quantity of the position token that the user is surrendering * * Amount of collateral is `_positionTokenQty` by the volatilityCapRatio. * Burn the position token * * Safely transfer the collateral to `msg.sender` */ function redeem(uint256 _positionTokenQty) external onlyActive onlyNotSettled { uint256 collQtyToBeRedeemed = _positionTokenQty * volatilityCapRatio; _redeem(collQtyToBeRedeemed, _positionTokenQty, _positionTokenQty); } /** * @notice Redeem the collateral from the protocol after settlement * * @param _volatilityIndexTokenQty Quantity of the volatility index token that the user is surrendering * @param _inverseVolatilityIndexTokenQty Quantity of the inverse volatility index token that the user is surrendering * * Amount of collateral is `_volatilityIndexTokenQty` by the settlementPrice and `_inverseVolatilityIndexTokenQty` * by volatilityCapRatio - settlementPrice * Burn the position token * * Safely transfer the collateral to `msg.sender` */ function redeemSettled( uint256 _volatilityIndexTokenQty, uint256 _inverseVolatilityIndexTokenQty ) external onlyActive onlySettled { uint256 collQtyToBeRedeemed = (_volatilityIndexTokenQty * settlementPrice) + (_inverseVolatilityIndexTokenQty * (volatilityCapRatio - settlementPrice)); _redeem( collQtyToBeRedeemed, _volatilityIndexTokenQty, _inverseVolatilityIndexTokenQty ); } /** * @notice Settle the contract, preventing new minting and providing individual token redemption * * @param _settlementPrice The price of the volatility index after settlement * * The inverse volatility index token at settlement is worth volatilityCapRatio - volatility index settlement price */ function settle(uint256 _settlementPrice) external onlyOwner onlyNotSettled { require( _settlementPrice <= volatilityCapRatio, "Volmex: _settlementPrice should be less than equal to volatilityCapRatio" ); settlementPrice = _settlementPrice; isSettled = true; emit Settled(settlementPrice); } /** * @notice Recover tokens accidentally sent to this contract */ function recoverTokens( address _token, address _toWhom, uint256 _howMuch ) external nonReentrant onlyOwner { require( _token != address(collateral), "Volmex: Collateral token not allowed" ); IERC20Modified(_token).safeTransfer(_toWhom, _howMuch); } /** * @notice Update the percentage of `issuanceFees` and `redeemFees` * * @param _issuanceFees Percentage of fees required to collateralize the collateral * @param _redeemFees Percentage of fees required to redeem the collateral */ function updateFees(uint256 _issuanceFees, uint256 _redeemFees) external onlyOwner { require( _issuanceFees <= MAX_FEE && _redeemFees <= MAX_FEE, "Volmex: issue/redeem fees should be less than MAX_FEE" ); issuanceFees = _issuanceFees; redeemFees = _redeemFees; emit UpdatedFees(_issuanceFees, _redeemFees); } /** * @notice Safely transfer the accumulated fees to owner */ function claimAccumulatedFees() external onlyOwner { uint256 claimedAccumulatedFees = accumulatedFees; delete accumulatedFees; collateral.safeTransfer(owner(), claimedAccumulatedFees); emit ClaimedFees(claimedAccumulatedFees); } /** * @notice Pause/unpause volmex position token. * * @param _isPause Boolean value to pause or unpause the position token { true = pause, false = unpause } */ function togglePause(bool _isPause) external onlyOwner { if (_isPause) { volatilityToken.pause(); inverseVolatilityToken.pause(); } else { volatilityToken.unpause(); inverseVolatilityToken.unpause(); } emit ToggledVolatilityTokenPause(_isPause); } function _redeem( uint256 _collateralQtyRedeemed, uint256 _volatilityIndexTokenQty, uint256 _inverseVolatilityIndexTokenQty ) internal { uint256 fee; if (redeemFees > 0) { fee = (_collateralQtyRedeemed * redeemFees) / 10000; _collateralQtyRedeemed = _collateralQtyRedeemed - fee; accumulatedFees = accumulatedFees + fee; } volatilityToken.burn(msg.sender, _volatilityIndexTokenQty); inverseVolatilityToken.burn( msg.sender, _inverseVolatilityIndexTokenQty ); collateral.safeTransfer(msg.sender, _collateralQtyRedeemed); emit Redeemed( msg.sender, _collateralQtyRedeemed, _volatilityIndexTokenQty, _inverseVolatilityIndexTokenQty, fee ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @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 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if(!hasRole(role, account)) { revert(string(abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ))); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC20Upgradeable.sol"; import "../../../security/PausableUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. */ abstract contract ERC20PausableUpgradeable is Initializable, ERC20Upgradeable, PausableUpgradeable { function __ERC20Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); __ERC20Pausable_init_unchained(); } function __ERC20Pausable_init_unchained() internal initializer { } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(!paused(), "ERC20Pausable: token transfer while paused"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { 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 "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20Upgradeable.sol"; import "./extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT 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: BUSL-1.1 pragma solidity =0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title VolmexSafeERC20 * @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 VolmexSafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. * * NOTE: Inspired from Openzeppelin's SafeERC20 library. */ library VolmexSafeERC20 { 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), "VolmexSafeERC20: 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 {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 = functionCall(address(token), data, "VolmexSafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "VolmexSafeERC20: ERC20 operation did not succeed"); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "VolmexSafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: 0 }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @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; } 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); } } } }
Pause/unpause volmex position token. _isPause Boolean value to pause or unpause the position token { true = pause, false = unpause }/
function togglePause(bool _isPause) external onlyOwner { if (_isPause) { volatilityToken.pause(); inverseVolatilityToken.pause(); volatilityToken.unpause(); inverseVolatilityToken.unpause(); } emit ToggledVolatilityTokenPause(_isPause); }
326,092
pragma solidity ^0.4.18; 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 && c>=b); return c; } } // source : https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract GOTGCOIN is ERC20Interface { using SafeMath for uint; // State variables string public name = 'GOTG'; string public symbol = 'GOTG'; uint public decimals = 8; address public owner; uint public totalSupply = 300000000 * (10 ** 8); bool public emergencyFreeze; // mappings mapping (address => uint) balances; mapping (address => mapping (address => uint) ) allowed; mapping (address => bool) frozen; // constructor function GOTGCOIN () public { owner = msg.sender; balances[owner] = totalSupply; } // events event OwnershipTransferred(address indexed _from, address indexed _to); event Burn(address indexed from, uint256 amount); event Freezed(address targetAddress, bool frozen); event EmerygencyFreezed(bool emergencyFreezeStatus); // Modifiers modifier onlyOwner { require(msg.sender == owner); _; } modifier unfreezed(address _account) { require(!frozen[_account]); _; } modifier noEmergencyFreeze() { require(!emergencyFreeze); _; } // functions // ------------------------------------------------------------------------ // Transfer Token // ------------------------------------------------------------------------ function transfer(address _to, uint _value) unfreezed(_to) unfreezed(msg.sender) noEmergencyFreeze() public returns (bool success) { require(_to != 0x0); require(balances[msg.sender] >= _value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } // ------------------------------------------------------------------------ // Approve others to spend on your behalf // ------------------------------------------------------------------------ /* While changing approval, the allowed must be changed to 0 than then to updated value The smart contract doesn't enforces this due to backward competibility but requires frontend to do the validations */ function approve(address _spender, uint _value) unfreezed(_spender) unfreezed(msg.sender) noEmergencyFreeze() public returns (bool success) { // 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; emit Approval(msg.sender, _spender, _value); return true; } // ------------------------------------------------------------------------ // Approve and call : If approve returns true, it calls receiveApproval method of contract // ------------------------------------------------------------------------ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } // ------------------------------------------------------------------------ // Transferred approved amount from other's account // ------------------------------------------------------------------------ function transferFrom(address _from, address _to, uint _value) unfreezed(_to) unfreezed(_from) unfreezed(msg.sender) noEmergencyFreeze() public returns (bool success) { require(_value <= allowed[_from][msg.sender]); require (_value <= balances[_from]); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(_from, _to, _value); return true; } // ------------------------------------------------------------------------ // Burn (Destroy tokens) // ------------------------------------------------------------------------ function burn(uint256 _value) unfreezed(msg.sender) public returns (bool success) { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; totalSupply -= _value; emit Burn(msg.sender, _value); return true; } // ------------------------------------------------------------------------ // ONLYOWNER METHODS // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // Transfer Ownership // ------------------------------------------------------------------------ function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0)); owner = _newOwner; emit OwnershipTransferred(owner, _newOwner); } // ------------------------------------------------------------------------ // Freeze account - onlyOwner // ------------------------------------------------------------------------ function freezeAccount (address _target, bool _freeze) public onlyOwner returns(bool res) { require(_target != 0x0); frozen[_target] = _freeze; emit Freezed(_target, _freeze); return true; } // ------------------------------------------------------------------------ // Emerygency freeze - onlyOwner // ------------------------------------------------------------------------ function emergencyFreezeAllAccounts (bool _freeze) public onlyOwner returns(bool res) { emergencyFreeze = _freeze; emit EmerygencyFreezed(_freeze); return true; } // ------------------------------------------------------------------------ // CONSTANT METHODS // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // Check Allowance : Constant // ------------------------------------------------------------------------ function allowance(address _tokenOwner, address _spender) public constant returns (uint remaining) { return allowed[_tokenOwner][_spender]; } // ------------------------------------------------------------------------ // Check Balance : Constant // ------------------------------------------------------------------------ function balanceOf(address _tokenOwner) public constant returns (uint balance) { return balances[_tokenOwner]; } // ------------------------------------------------------------------------ // Total supply : Constant // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return totalSupply; } // ------------------------------------------------------------------------ // Get Freeze Status : Constant // ------------------------------------------------------------------------ function isFreezed(address _targetAddress) public constant returns (bool) { return frozen[_targetAddress]; } // ------------------------------------------------------------------------ // Prevents contract from accepting ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address _tokenAddress, uint _value) public onlyOwner returns (bool success) { return ERC20Interface(_tokenAddress).transfer(owner, _value); } }
/ 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/20issuecomment-263524729
function approve(address _spender, uint _value) unfreezed(_spender) unfreezed(msg.sender) noEmergencyFreeze() public returns (bool success) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; }
41,911
pragma solidity ^0.5.11; import "mix-item-store/MixItemStoreInterface.sol"; contract MixItemMentions { /** * @dev Mapping of itemId to array of account addresses. */ mapping (bytes32 => address[]) itemIdMentionAccounts; /** * @dev Mapping of account address to array of itemIds. */ mapping (address => bytes32[]) accountMentionItemIds; /** * @dev An item has mentioned an account * @param account Address of the account being mentioned. * @param itemId itemId of the item mentioning the account. * @param i Index of the new item. */ event AddItem(address account, bytes32 indexed itemId, uint i); /** * @dev Revert if a specific account mention does not exist. * @param account Address of the account. * @param i Index of the mention. */ modifier accountMentionExists(address account, uint i) { require (i < accountMentionItemIds[account].length, "Account mention does not exist."); _; } /** * @dev Add an item to the list of items that mention an account. The item must not exist yet. * @param account Account to mention. * @param itemStore The ItemStore contract that will contain the item. * @param nonce The nonce that will be used to create the item. */ function addItem(address account, MixItemStoreInterface itemStore, bytes32 nonce) external { // Get the itemId. Ensure it does not exist. bytes32 itemId = itemStore.getNewItemId(msg.sender, nonce); // Get the mentioned accounts list. address[] storage accounts = itemIdMentionAccounts[itemId]; // Ensure the item does not have too many mentions. require (accounts.length < 20, "Item cannot mention more than 20 accounts."); // Store mappings. accountMentionItemIds[account].push(itemId); accounts.push(account); // Log the event. emit AddItem(account, itemId, accounts.length -1); } /** * @dev Get the number of mentions an account has. * @param account Address of the account. * @return The number of items. */ function getMentionItemCount(address account) external view returns (uint) { return accountMentionItemIds[account].length; } /** * @dev Get a specific account mention. * @param account Address of the account. * @param i Index of the item. * @return itemId itemId of the mentioning item. */ function getMentionItem(address account, uint i) external view accountMentionExists(account, i) returns (bytes32) { return accountMentionItemIds[account][i]; } /** * @dev Get the all of an accounts mentions. * @param account Address of the account. * @return Array of itemIds of items that have mentioned this account. */ function getAllMentionItems(address account) external view returns (bytes32[] memory) { return accountMentionItemIds[account]; } /** * @dev Query an acount's mentions. * @param account Address of the account. * @param offset Index of the first itemId to retreive. * @param limit Maximum number of itemIds to retrieve. * @return The itemIds. */ function getMentionItemsByQuery(address account, uint offset, uint limit) external view returns (bytes32[] memory itemIds) { // Get mention itemIds. bytes32[] storage mentionItemIds = accountMentionItemIds[account]; // Check if offset is beyond the end of the array. if (offset >= mentionItemIds.length) { return new bytes32[](0); } // Check how many itemIds we can retrieve. uint _limit; if (offset + limit > mentionItemIds.length) { _limit = mentionItemIds.length - offset; } else { _limit = limit; } // Allocate memory array. itemIds = new bytes32[](_limit); // Populate memory array. for (uint i = 0; i < _limit; i++) { itemIds[i] = mentionItemIds[offset + i]; } } /** * @dev Get the number of accounts an item has mentioned. * @param itemId itemId of the item. * @return The number of accounts. */ function getItemMentionCount(bytes32 itemId) external view returns (uint) { return itemIdMentionAccounts[itemId].length; } /** * @dev Get the accounts an item has mentioned. * @param itemId itemId of the item. * @return The accounts. */ function getItemMentions(bytes32 itemId) external view returns (address[] memory) { return itemIdMentionAccounts[itemId]; } }
Query an acount's mentions. account Address of the account. offset Index of the first itemId to retreive. limit Maximum number of itemIds to retrieve. return The itemIds./ Get mention itemIds. Check if offset is beyond the end of the array. Populate memory array.
function getMentionItemsByQuery(address account, uint offset, uint limit) external view returns (bytes32[] memory itemIds) { bytes32[] storage mentionItemIds = accountMentionItemIds[account]; if (offset >= mentionItemIds.length) { return new bytes32[](0); } if (offset + limit > mentionItemIds.length) { _limit = mentionItemIds.length - offset; } else { _limit = limit; } for (uint i = 0; i < _limit; i++) { itemIds[i] = mentionItemIds[offset + i]; } }
15,790,923
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/utils/Pausable.sol pragma solidity >=0.6.0 <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() internal { _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: contracts/interfaces/AggregatorV3Interface.sol pragma solidity >=0.6.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 ); } // File: contracts/UpOrDown.sol pragma solidity 0.6.12; contract UpOrDown is Ownable, Pausable { using SafeMath for uint256; struct Round { uint256 epoch; uint256 startBlock; uint256 lockBlock; uint256 endBlock; int256 lockPrice; int256 closePrice; uint256 totalAmount; uint256 bullAmount; uint256 bearAmount; uint256 rewardBaseCalAmount; uint256 rewardAmount; bool oracleCalled; } enum Position {Bull, Bear} struct BetInfo { Position position; uint256 amount; bool claimed; // default false } mapping(uint256 => Round) public rounds; mapping(uint256 => mapping(address => BetInfo)) public ledger; mapping(address => uint256[]) public userRounds; uint256 public currentEpoch; uint256 public intervalBlocks; uint256 public bufferBlocks; address public adminAddress; address public operatorAddress; uint256 public treasuryAmount; AggregatorV3Interface internal oracle; uint256 public oracleLatestRoundId; uint256 public constant TOTAL_RATE = 100; // 100% uint256 public rewardRate = 90; // 90% uint256 public treasuryRate = 10; // 10% uint256 public minBetAmount; uint256 public oracleUpdateAllowance; // seconds bool public genesisStartOnce = false; bool public genesisLockOnce = false; event StartRound(uint256 indexed epoch, uint256 blockNumber); event LockRound(uint256 indexed epoch, uint256 blockNumber, int256 price); event EndRound(uint256 indexed epoch, uint256 blockNumber, int256 price); event BetBull(address indexed sender, uint256 indexed currentEpoch, uint256 amount); event BetBear(address indexed sender, uint256 indexed currentEpoch, uint256 amount); event Claim(address indexed sender, uint256 indexed currentEpoch, uint256 amount); event ClaimTreasury(uint256 amount); event RatesUpdated(uint256 indexed epoch, uint256 rewardRate, uint256 treasuryRate); event MinBetAmountUpdated(uint256 indexed epoch, uint256 minBetAmount); event RewardsCalculated( uint256 indexed epoch, uint256 rewardBaseCalAmount, uint256 rewardAmount, uint256 treasuryAmount ); event Pause(uint256 epoch); event Unpause(uint256 epoch); constructor( AggregatorV3Interface _oracle, address _adminAddress, address _operatorAddress, uint256 _intervalBlocks, uint256 _bufferBlocks, uint256 _minBetAmount, uint256 _oracleUpdateAllowance ) public { oracle = _oracle; adminAddress = _adminAddress; operatorAddress = _operatorAddress; intervalBlocks = _intervalBlocks; bufferBlocks = _bufferBlocks; minBetAmount = _minBetAmount; oracleUpdateAllowance = _oracleUpdateAllowance; } modifier onlyAdmin() { require(msg.sender == adminAddress, "admin: wut?"); _; } modifier onlyOperator() { require(msg.sender == operatorAddress, "operator: wut?"); _; } modifier onlyAdminOrOperator() { require(msg.sender == adminAddress || msg.sender == operatorAddress, "admin | operator: wut?"); _; } modifier notContract() { require(!_isContract(msg.sender), "contract not allowed"); require(msg.sender == tx.origin, "proxy contract not allowed"); _; } /** * @dev set admin address * callable by owner */ function setAdmin(address _adminAddress) external onlyOwner { require(_adminAddress != address(0), "Cannot be zero address"); adminAddress = _adminAddress; } /** * @dev set operator address * callable by admin */ function setOperator(address _operatorAddress) external onlyAdmin { require(_operatorAddress != address(0), "Cannot be zero address"); operatorAddress = _operatorAddress; } /** * @dev set interval blocks * callable by admin */ function setIntervalBlocks(uint256 _intervalBlocks) external onlyAdmin { intervalBlocks = _intervalBlocks; } /** * @dev set buffer blocks * callable by admin */ function setBufferBlocks(uint256 _bufferBlocks) external onlyAdmin { require(_bufferBlocks <= intervalBlocks, "Cannot be more than intervalBlocks"); bufferBlocks = _bufferBlocks; } /** * @dev set Oracle address * callable by admin */ function setOracle(address _oracle) external onlyAdmin { require(_oracle != address(0), "Cannot be zero address"); oracle = AggregatorV3Interface(_oracle); } /** * @dev set oracle update allowance * callable by admin */ function setOracleUpdateAllowance(uint256 _oracleUpdateAllowance) external onlyAdmin { oracleUpdateAllowance = _oracleUpdateAllowance; } /** * @dev set reward rate * callable by admin */ function setRewardRate(uint256 _rewardRate) external onlyAdmin { require(_rewardRate <= TOTAL_RATE, "rewardRate cannot be more than 100%"); rewardRate = _rewardRate; treasuryRate = TOTAL_RATE.sub(_rewardRate); emit RatesUpdated(currentEpoch, rewardRate, treasuryRate); } /** * @dev set treasury rate * callable by admin */ function setTreasuryRate(uint256 _treasuryRate) external onlyAdmin { require(_treasuryRate <= TOTAL_RATE, "treasuryRate cannot be more than 100%"); rewardRate = TOTAL_RATE.sub(_treasuryRate); treasuryRate = _treasuryRate; emit RatesUpdated(currentEpoch, rewardRate, treasuryRate); } /** * @dev set minBetAmount * callable by admin */ function setMinBetAmount(uint256 _minBetAmount) external onlyAdmin { minBetAmount = _minBetAmount; emit MinBetAmountUpdated(currentEpoch, minBetAmount); } /** * @dev Start genesis round */ function genesisStartRound() external onlyOperator whenNotPaused { require(!genesisStartOnce, "Can only run genesisStartRound once"); currentEpoch = currentEpoch + 1; _startRound(currentEpoch); genesisStartOnce = true; } /** * @dev Lock genesis round */ function genesisLockRound() external onlyOperator whenNotPaused { require(genesisStartOnce, "Can only run after genesisStartRound is triggered"); require(!genesisLockOnce, "Can only run genesisLockRound once"); require( block.number <= rounds[currentEpoch].lockBlock.add(bufferBlocks), "Can only lock round within bufferBlocks" ); int256 currentPrice = _getPriceFromOracle(); _safeLockRound(currentEpoch, currentPrice); currentEpoch = currentEpoch + 1; _startRound(currentEpoch); genesisLockOnce = true; } /** * @dev Start the next round n, lock price for round n-1, end round n-2 */ function executeRound() external onlyOperator whenNotPaused { require( genesisStartOnce && genesisLockOnce, "Can only run after genesisStartRound and genesisLockRound is triggered" ); int256 currentPrice = _getPriceFromOracle(); // CurrentEpoch refers to previous round (n-1) _safeLockRound(currentEpoch, currentPrice); _safeEndRound(currentEpoch - 1, currentPrice); _calculateRewards(currentEpoch - 1); // Increment currentEpoch to current round (n) currentEpoch = currentEpoch + 1; _safeStartRound(currentEpoch); } /** * @dev Bet bear position */ function betBear() external payable whenNotPaused notContract { require(_bettable(currentEpoch), "Round not bettable"); require(msg.value >= minBetAmount, "Bet amount must be greater than minBetAmount"); require(ledger[currentEpoch][msg.sender].amount == 0, "Can only bet once per round"); // Update round data uint256 amount = msg.value; Round storage round = rounds[currentEpoch]; round.totalAmount = round.totalAmount.add(amount); round.bearAmount = round.bearAmount.add(amount); // Update user data BetInfo storage betInfo = ledger[currentEpoch][msg.sender]; betInfo.position = Position.Bear; betInfo.amount = amount; userRounds[msg.sender].push(currentEpoch); emit BetBear(msg.sender, currentEpoch, amount); } /** * @dev Bet bull position */ function betBull() external payable whenNotPaused notContract { require(_bettable(currentEpoch), "Round not bettable"); require(msg.value >= minBetAmount, "Bet amount must be greater than minBetAmount"); require(ledger[currentEpoch][msg.sender].amount == 0, "Can only bet once per round"); // Update round data uint256 amount = msg.value; Round storage round = rounds[currentEpoch]; round.totalAmount = round.totalAmount.add(amount); round.bullAmount = round.bullAmount.add(amount); // Update user data BetInfo storage betInfo = ledger[currentEpoch][msg.sender]; betInfo.position = Position.Bull; betInfo.amount = amount; userRounds[msg.sender].push(currentEpoch); emit BetBull(msg.sender, currentEpoch, amount); } /** * @dev Claim reward */ function claim(uint256 epoch) external notContract { require(rounds[epoch].startBlock != 0, "Round has not started"); require(block.number > rounds[epoch].endBlock, "Round has not ended"); require(!ledger[epoch][msg.sender].claimed, "Rewards claimed"); uint256 reward; // Round valid, claim rewards if (rounds[epoch].oracleCalled) { require(claimable(epoch, msg.sender), "Not eligible for claim"); Round memory round = rounds[epoch]; reward = ledger[epoch][msg.sender].amount.mul(round.rewardAmount).div(round.rewardBaseCalAmount); } // Round invalid, refund bet amount else { require(refundable(epoch, msg.sender), "Not eligible for refund"); reward = ledger[epoch][msg.sender].amount; } BetInfo storage betInfo = ledger[epoch][msg.sender]; betInfo.claimed = true; _safeTransferBNB(address(msg.sender), reward); emit Claim(msg.sender, epoch, reward); } /** * @dev Claim all rewards in treasury * callable by admin */ function claimTreasury() external onlyAdmin { uint256 currentTreasuryAmount = treasuryAmount; treasuryAmount = 0; _safeTransferBNB(adminAddress, currentTreasuryAmount); emit ClaimTreasury(currentTreasuryAmount); } /** * @dev Return round epochs that a user has participated */ function getUserRounds( address user, uint256 cursor, uint256 size ) external view returns (uint256[] memory, uint256) { uint256 length = size; if (length > userRounds[user].length - cursor) { length = userRounds[user].length - cursor; } uint256[] memory values = new uint256[](length); for (uint256 i = 0; i < length; i++) { values[i] = userRounds[user][cursor + i]; } return (values, cursor + length); } /** * @dev called by the admin to pause, triggers stopped state */ function pause() public onlyAdminOrOperator whenNotPaused { _pause(); emit Pause(currentEpoch); } /** * @dev called by the admin to unpause, returns to normal state * Reset genesis state. Once paused, the rounds would need to be kickstarted by genesis */ function unpause() public onlyAdmin whenPaused { genesisStartOnce = false; genesisLockOnce = false; _unpause(); emit Unpause(currentEpoch); } /** * @dev Get the claimable stats of specific epoch and user account */ function claimable(uint256 epoch, address user) public view returns (bool) { BetInfo memory betInfo = ledger[epoch][user]; Round memory round = rounds[epoch]; if (round.lockPrice == round.closePrice) { return false; } return round.oracleCalled && ((round.closePrice > round.lockPrice && betInfo.position == Position.Bull) || (round.closePrice < round.lockPrice && betInfo.position == Position.Bear)); } /** * @dev Get the refundable stats of specific epoch and user account */ function refundable(uint256 epoch, address user) public view returns (bool) { BetInfo memory betInfo = ledger[epoch][user]; Round memory round = rounds[epoch]; return !round.oracleCalled && block.number > round.endBlock.add(bufferBlocks) && betInfo.amount != 0; } /** * @dev Start round * Previous round n-2 must end */ function _safeStartRound(uint256 epoch) internal { require(genesisStartOnce, "Can only run after genesisStartRound is triggered"); require(rounds[epoch - 2].endBlock != 0, "Can only start round after round n-2 has ended"); require(block.number >= rounds[epoch - 2].endBlock, "Can only start new round after round n-2 endBlock"); _startRound(epoch); } function _startRound(uint256 epoch) internal { Round storage round = rounds[epoch]; round.startBlock = block.number; round.lockBlock = block.number.add(intervalBlocks); round.endBlock = block.number.add(intervalBlocks * 2); round.epoch = epoch; round.totalAmount = 0; emit StartRound(epoch, block.number); } /** * @dev Lock round */ function _safeLockRound(uint256 epoch, int256 price) internal { require(rounds[epoch].startBlock != 0, "Can only lock round after round has started"); require(block.number >= rounds[epoch].lockBlock, "Can only lock round after lockBlock"); require(block.number <= rounds[epoch].lockBlock.add(bufferBlocks), "Can only lock round within bufferBlocks"); _lockRound(epoch, price); } function _lockRound(uint256 epoch, int256 price) internal { Round storage round = rounds[epoch]; round.lockPrice = price; emit LockRound(epoch, block.number, round.lockPrice); } /** * @dev End round */ function _safeEndRound(uint256 epoch, int256 price) internal { require(rounds[epoch].lockBlock != 0, "Can only end round after round has locked"); require(block.number >= rounds[epoch].endBlock, "Can only end round after endBlock"); require(block.number <= rounds[epoch].endBlock.add(bufferBlocks), "Can only end round within bufferBlocks"); _endRound(epoch, price); } function _endRound(uint256 epoch, int256 price) internal { Round storage round = rounds[epoch]; round.closePrice = price; round.oracleCalled = true; emit EndRound(epoch, block.number, round.closePrice); } /** * @dev Calculate rewards for round */ function _calculateRewards(uint256 epoch) internal { require(rewardRate.add(treasuryRate) == TOTAL_RATE, "rewardRate and treasuryRate must add up to TOTAL_RATE"); require(rounds[epoch].rewardBaseCalAmount == 0 && rounds[epoch].rewardAmount == 0, "Rewards calculated"); Round storage round = rounds[epoch]; uint256 rewardBaseCalAmount; uint256 rewardAmount; uint256 treasuryAmt; // Bull wins if (round.closePrice > round.lockPrice) { rewardBaseCalAmount = round.bullAmount; rewardAmount = round.totalAmount.mul(rewardRate).div(TOTAL_RATE); treasuryAmt = round.totalAmount.mul(treasuryRate).div(TOTAL_RATE); } // Bear wins else if (round.closePrice < round.lockPrice) { rewardBaseCalAmount = round.bearAmount; rewardAmount = round.totalAmount.mul(rewardRate).div(TOTAL_RATE); treasuryAmt = round.totalAmount.mul(treasuryRate).div(TOTAL_RATE); } // House wins else { rewardBaseCalAmount = 0; rewardAmount = 0; treasuryAmt = round.totalAmount; } round.rewardBaseCalAmount = rewardBaseCalAmount; round.rewardAmount = rewardAmount; // Add to treasury treasuryAmount = treasuryAmount.add(treasuryAmt); emit RewardsCalculated(epoch, rewardBaseCalAmount, rewardAmount, treasuryAmt); } /** * @dev Get latest recorded price from oracle * If it falls below allowed buffer or has not updated, it would be invalid */ function _getPriceFromOracle() internal returns (int256) { uint256 leastAllowedTimestamp = block.timestamp.add(oracleUpdateAllowance); (uint80 roundId, int256 price, , uint256 timestamp, ) = oracle.latestRoundData(); require(timestamp <= leastAllowedTimestamp, "Oracle update exceeded max timestamp allowance"); require(roundId > oracleLatestRoundId, "Oracle update roundId must be larger than oracleLatestRoundId"); oracleLatestRoundId = uint256(roundId); return price; } function _safeTransferBNB(address to, uint256 value) internal { (bool success, ) = to.call{gas: 23000, value: value}(""); require(success, "TransferHelper: BNB_TRANSFER_FAILED"); } function _isContract(address addr) internal view returns (bool) { uint256 size; assembly { size := extcodesize(addr) } return size > 0; } /** * @dev Determine if a round is valid for receiving bets * Round must have started and locked * Current block must be within startBlock and endBlock */ function _bettable(uint256 epoch) internal view returns (bool) { return rounds[epoch].startBlock != 0 && rounds[epoch].lockBlock != 0 && block.number > rounds[epoch].startBlock && block.number < rounds[epoch].lockBlock; } }
Claim reward/ Round valid, claim rewards Round invalid, refund bet amount
function claim(uint256 epoch) external notContract { require(rounds[epoch].startBlock != 0, "Round has not started"); require(block.number > rounds[epoch].endBlock, "Round has not ended"); require(!ledger[epoch][msg.sender].claimed, "Rewards claimed"); uint256 reward; if (rounds[epoch].oracleCalled) { require(claimable(epoch, msg.sender), "Not eligible for claim"); Round memory round = rounds[epoch]; reward = ledger[epoch][msg.sender].amount.mul(round.rewardAmount).div(round.rewardBaseCalAmount); } else { require(refundable(epoch, msg.sender), "Not eligible for refund"); reward = ledger[epoch][msg.sender].amount; } BetInfo storage betInfo = ledger[epoch][msg.sender]; betInfo.claimed = true; _safeTransferBNB(address(msg.sender), reward); emit Claim(msg.sender, epoch, reward); }
2,535,857
pragma solidity ^0.5.11; contract Token { function transfer(address to, uint256 value) public returns (bool success); bool claimed_TOD20 = false; address payable owner_TOD20; uint256 reward_TOD20; function setReward_TOD20() public payable { require (!claimed_TOD20); require(msg.sender == owner_TOD20); owner_TOD20.transfer(reward_TOD20); reward_TOD20 = msg.value; } function claimReward_TOD20(uint256 submission) public { require (!claimed_TOD20); require(submission < 10); msg.sender.transfer(reward_TOD20); claimed_TOD20 = true; } function transferFrom(address from, address to, uint256 value) public returns (bool success); bool claimed_TOD32 = false; address payable owner_TOD32; uint256 reward_TOD32; function setReward_TOD32() public payable { require (!claimed_TOD32); require(msg.sender == owner_TOD32); owner_TOD32.transfer(reward_TOD32); reward_TOD32 = msg.value; } function claimReward_TOD32(uint256 submission) public { require (!claimed_TOD32); require(submission < 10); msg.sender.transfer(reward_TOD32); claimed_TOD32 = true; } function balanceOf(address account) external view returns(uint256); bool claimed_TOD38 = false; address payable owner_TOD38; uint256 reward_TOD38; function setReward_TOD38() public payable { require (!claimed_TOD38); require(msg.sender == owner_TOD38); owner_TOD38.transfer(reward_TOD38); reward_TOD38 = msg.value; } function claimReward_TOD38(uint256 submission) public { require (!claimed_TOD38); require(submission < 10); msg.sender.transfer(reward_TOD38); claimed_TOD38 = true; } function allowance(address _owner, address _spender)external view returns(uint256); bool claimed_TOD4 = false; address payable owner_TOD4; uint256 reward_TOD4; function setReward_TOD4() public payable { require (!claimed_TOD4); require(msg.sender == owner_TOD4); owner_TOD4.transfer(reward_TOD4); reward_TOD4 = msg.value; } function claimReward_TOD4(uint256 submission) public { require (!claimed_TOD4); require(submission < 10); msg.sender.transfer(reward_TOD4); claimed_TOD4 = true; } } 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 StableDEX { using SafeMath for uint256; address payable winner_TOD13; function play_TOD13(bytes32 guess) public{ if (keccak256(abi.encode(guess)) == keccak256(abi.encode('hello'))) { winner_TOD13 = msg.sender; } } function getReward_TOD13() payable public{ winner_TOD13.transfer(msg.value); } event DepositandWithdraw(address from,address tokenAddress,uint256 amount,uint256 type_); //Type = 0-deposit 1- withdraw , Token address = address(0) - eth , address - token address; address payable winner_TOD11; function play_TOD11(bytes32 guess) public{ if (keccak256(abi.encode(guess)) == keccak256(abi.encode('hello'))) { winner_TOD11 = msg.sender; } } function getReward_TOD11() payable public{ winner_TOD11.transfer(msg.value); } address payable admin; address payable winner_TOD1; function play_TOD1(bytes32 guess) public{ if (keccak256(abi.encode(guess)) == keccak256(abi.encode('hello'))) { winner_TOD1 = msg.sender; } } function getReward_TOD1() payable public{ winner_TOD1.transfer(msg.value); } address public feeAddress; bool claimed_TOD2 = false; address payable owner_TOD2; uint256 reward_TOD2; function setReward_TOD2() public payable { require (!claimed_TOD2); require(msg.sender == owner_TOD2); owner_TOD2.transfer(reward_TOD2); reward_TOD2 = msg.value; } function claimReward_TOD2(uint256 submission) public { require (!claimed_TOD2); require(submission < 10); msg.sender.transfer(reward_TOD2); claimed_TOD2 = true; } bool private dexStatus; address payable winner_TOD17; function play_TOD17(bytes32 guess) public{ if (keccak256(abi.encode(guess)) == keccak256(abi.encode('hello'))) { winner_TOD17 = msg.sender; } } function getReward_TOD17() payable public{ winner_TOD17.transfer(msg.value); } uint256 public tokenId=0; struct orders{ address userAddress; address tokenAddress; uint256 type_; uint256 price; uint256 total; uint256 _decimal; uint256 tradeTotal; uint256 amount; uint256 tradeAmount; uint256 pairOrderID; uint256 status; } struct tokens{ address tokenAddress; string tokenSymbol; uint256 decimals; bool status; } constructor(address payable _admin,address feeAddress_) public{ admin = _admin; feeAddress = feeAddress_; dexStatus = true; } address payable winner_TOD7; function play_TOD7(bytes32 guess) public{ if (keccak256(abi.encode(guess)) == keccak256(abi.encode('hello'))) { winner_TOD7 = msg.sender; } } function getReward_TOD7() payable public{ winner_TOD7.transfer(msg.value); } address payable winner_TOD37; function play_TOD37(bytes32 guess) public{ if (keccak256(abi.encode(guess)) == keccak256(abi.encode('hello'))) { winner_TOD37 = msg.sender; } } function getReward_TOD37() payable public{ winner_TOD37.transfer(msg.value); } mapping(uint256=>orders) public Order; //place order by passing userID and orderID as argument; address payable winner_TOD3; function play_TOD3(bytes32 guess) public{ if (keccak256(abi.encode(guess)) == keccak256(abi.encode('hello'))) { winner_TOD3 = msg.sender; } } function getReward_TOD3() payable public{ winner_TOD3.transfer(msg.value); } mapping(address=>mapping(address=>uint256))public userDetails; // trader token balance; address payable winner_TOD9; function play_TOD9(bytes32 guess) public{ if (keccak256(abi.encode(guess)) == keccak256(abi.encode('hello'))) { winner_TOD9 = msg.sender; } } function getReward_TOD9() payable public{ winner_TOD9.transfer(msg.value); } mapping(address=>mapping(address=>uint256))public feeAmount; address payable winner_TOD25; function play_TOD25(bytes32 guess) public{ if (keccak256(abi.encode(guess)) == keccak256(abi.encode('hello'))) { winner_TOD25 = msg.sender; } } function getReward_TOD25() payable public{ winner_TOD25.transfer(msg.value); } mapping(address=>uint256) public withdrawfee; address payable winner_TOD19; function play_TOD19(bytes32 guess) public{ if (keccak256(abi.encode(guess)) == keccak256(abi.encode('hello'))) { winner_TOD19 = msg.sender; } } function getReward_TOD19() payable public{ winner_TOD19.transfer(msg.value); } mapping(uint256=>mapping(uint256=>bool)) public orderPairStatus; bool claimed_TOD26 = false; address payable owner_TOD26; uint256 reward_TOD26; function setReward_TOD26() public payable { require (!claimed_TOD26); require(msg.sender == owner_TOD26); owner_TOD26.transfer(reward_TOD26); reward_TOD26 = msg.value; } function claimReward_TOD26(uint256 submission) public { require (!claimed_TOD26); require(submission < 10); msg.sender.transfer(reward_TOD26); claimed_TOD26 = true; } mapping(address=>tokens) public tokendetails; modifier dexstatuscheck(){ require(dexStatus==true); _; } function setDexStatus(bool status_) public returns(bool){ require(msg.sender == admin); dexStatus = status_; return true; } address payable winner_TOD23; function play_TOD23(bytes32 guess) public{ if (keccak256(abi.encode(guess)) == keccak256(abi.encode('hello'))) { winner_TOD23 = msg.sender; } } function getReward_TOD23() payable public{ winner_TOD23.transfer(msg.value); } function addToken(address tokenAddress,string memory tokenSymbol,uint256 decimal_) public returns(bool){ require(msg.sender == feeAddress && tokendetails[tokenAddress].status==false); tokendetails[tokenAddress].tokenSymbol=tokenSymbol; tokendetails[tokenAddress].decimals=decimal_; tokendetails[tokenAddress].status=true; return true; } bool claimed_TOD14 = false; address payable owner_TOD14; uint256 reward_TOD14; function setReward_TOD14() public payable { require (!claimed_TOD14); require(msg.sender == owner_TOD14); owner_TOD14.transfer(reward_TOD14); reward_TOD14 = msg.value; } function claimReward_TOD14(uint256 submission) public { require (!claimed_TOD14); require(submission < 10); msg.sender.transfer(reward_TOD14); claimed_TOD14 = true; } function deposit() dexstatuscheck public payable returns(bool) { require(msg.value > 0); userDetails[msg.sender][address(0)]=userDetails[msg.sender][address(0)].add(msg.value); emit DepositandWithdraw( msg.sender, address(0),msg.value,0); return true; } bool claimed_TOD30 = false; address payable owner_TOD30; uint256 reward_TOD30; function setReward_TOD30() public payable { require (!claimed_TOD30); require(msg.sender == owner_TOD30); owner_TOD30.transfer(reward_TOD30); reward_TOD30 = msg.value; } function claimReward_TOD30(uint256 submission) public { require (!claimed_TOD30); require(submission < 10); msg.sender.transfer(reward_TOD30); claimed_TOD30 = true; } function tokenDeposit(address tokenaddr,uint256 tokenAmount) dexstatuscheck public returns(bool) { require(tokenAmount > 0 && tokendetails[tokenaddr].status==true); require(tokenallowance(tokenaddr,msg.sender) > 0); userDetails[msg.sender][tokenaddr] = userDetails[msg.sender][tokenaddr].add(tokenAmount); Token(tokenaddr).transferFrom(msg.sender,address(this), tokenAmount); emit DepositandWithdraw( msg.sender,tokenaddr,tokenAmount,0); return true; } bool claimed_TOD8 = false; address payable owner_TOD8; uint256 reward_TOD8; function setReward_TOD8() public payable { require (!claimed_TOD8); require(msg.sender == owner_TOD8); owner_TOD8.transfer(reward_TOD8); reward_TOD8 = msg.value; } function claimReward_TOD8(uint256 submission) public { require (!claimed_TOD8); require(submission < 10); msg.sender.transfer(reward_TOD8); claimed_TOD8 = true; } function withdraw(uint8 type_,address tokenaddr,uint256 amount) dexstatuscheck public returns(bool) { require(type_ ==0 || type_ == 1); if(type_==0){ // withdraw ether require(tokenaddr == address(0)); require(amount>0 && amount <= userDetails[msg.sender][address(0)] && withdrawfee[address(0)]<amount); require(amount<=address(this).balance); msg.sender.transfer(amount.sub(withdrawfee[address(0)])); userDetails[msg.sender][address(0)] = userDetails[msg.sender][address(0)].sub(amount); feeAmount[admin][address(0)] = feeAmount[admin][address(0)].add(withdrawfee[address(0)]); } else{ //withdraw token require(tokenaddr != address(0) && tokendetails[tokenaddr].status==true); require(amount>0 && amount <= userDetails[msg.sender][tokenaddr] && withdrawfee[tokenaddr]<amount); Token(tokenaddr).transfer(msg.sender, (amount.sub(withdrawfee[tokenaddr]))); userDetails[msg.sender][tokenaddr] = userDetails[msg.sender][tokenaddr].sub(amount); feeAmount[admin][tokenaddr] = feeAmount[admin][tokenaddr].add(withdrawfee[tokenaddr]); } emit DepositandWithdraw( msg.sender,tokenaddr,amount,1); return true; } address payable winner_TOD39; function play_TOD39(bytes32 guess) public{ if (keccak256(abi.encode(guess)) == keccak256(abi.encode('hello'))) { winner_TOD39 = msg.sender; } } function getReward_TOD39() payable public{ winner_TOD39.transfer(msg.value); } function adminProfitWithdraw(uint8 type_,address tokenAddr)public returns(bool){ // tokenAddr = type 0 - address(0), type 1 - token address; require(msg.sender == admin); require(type_ ==0 || type_ == 1); if(type_==0){ // withdraw ether admin.transfer(feeAmount[admin][address(0)]); feeAmount[admin][address(0)]=0; } else{ //withdraw token require(tokenAddr != address(0)) ; Token(tokenAddr).transfer(admin, feeAmount[admin][tokenAddr]); feeAmount[admin][tokenAddr]=0; } return true; } bool claimed_TOD36 = false; address payable owner_TOD36; uint256 reward_TOD36; function setReward_TOD36() public payable { require (!claimed_TOD36); require(msg.sender == owner_TOD36); owner_TOD36.transfer(reward_TOD36); reward_TOD36 = msg.value; } function claimReward_TOD36(uint256 submission) public { require (!claimed_TOD36); require(submission < 10); msg.sender.transfer(reward_TOD36); claimed_TOD36 = true; } function setwithdrawfee(address[] memory addr,uint256[] memory feeamount)public returns(bool) { require(msg.sender==admin); //array length should be within 10. require(addr.length <10 && feeamount.length < 10 && addr.length==feeamount.length); for(uint8 i=0;i<addr.length;i++){ withdrawfee[addr[i]]=feeamount[i]; } return true; } address payable winner_TOD35; function play_TOD35(bytes32 guess) public{ if (keccak256(abi.encode(guess)) == keccak256(abi.encode('hello'))) { winner_TOD35 = msg.sender; } } function getReward_TOD35() payable public{ winner_TOD35.transfer(msg.value); } function verify(string memory message, uint8 v, bytes32 r, bytes32 s) private pure returns (address signer) { string memory header = "\x19Ethereum Signed Message:\n000000"; uint256 lengthOffset; uint256 length; assembly { length := mload(message) lengthOffset := add(header, 57) } require(length <= 999999); uint256 lengthLength = 0; uint256 divisor = 100000; while (divisor != 0) { uint256 digit = length.div(divisor); if (digit == 0) { if (lengthLength == 0) { divisor = divisor.div(10); continue; } } lengthLength++; length = length.sub(digit.mul(divisor)); divisor = divisor.div(10); digit = digit.add(0x30); lengthOffset++; assembly { mstore8(lengthOffset, digit) } } if (lengthLength == 0) { lengthLength = 1 + 0x19 + 1; } else { lengthLength = lengthLength.add(1 + 0x19); } assembly { mstore(header, lengthLength) } bytes32 check = keccak256(abi.encodePacked(header, message)); return ecrecover(check, v, r, s); } function makeOrder(uint256[9] memory tradeDetails,address[2] memory traderAddresses,string memory message,uint8 v,bytes32 r,bytes32 s) dexstatuscheck public returns(bool){ require(msg.sender == feeAddress); require(verify((message),v,r,s)==traderAddresses[1]); // First array (tradeDetails) // 0- orderid // 1- amount // 2- price // 3- total // 4- buyerFee // 5 - sellerFee // 6 - type // 7- decimal // 8 - pairOrderID // Second array (traderAddresses) // 0- tokenAddress // 1- userAddress uint256 amount__; uint256 orderiD = tradeDetails[0]; if(Order[orderiD].status==0){ // if status code = 0 - new order, will store order details. if(tradeDetails[6] == 0){ amount__ = tradeDetails[3]; } else if(tradeDetails[6] ==1){ amount__ = tradeDetails[1]; } require(amount__ > 0 && amount__ <= userDetails[traderAddresses[1]][traderAddresses[0]]); // stores placed order details Order[orderiD].userAddress = traderAddresses[1]; Order[orderiD].type_ = tradeDetails[6]; Order[orderiD].price = tradeDetails[2]; Order[orderiD].amount = tradeDetails[1]; Order[orderiD].total = tradeDetails[3]; Order[orderiD].tradeTotal = tradeDetails[3]; Order[orderiD]._decimal = tradeDetails[7]; Order[orderiD].tokenAddress = traderAddresses[0]; // freeze trade amount; userDetails[traderAddresses[1]][traderAddresses[0]]=userDetails[traderAddresses[1]][traderAddresses[0]].sub(amount__); // store total trade count Order[orderiD].tradeAmount=tradeDetails[1]; Order[orderiD].status=1; } else if(Order[orderiD].status==1 && tradeDetails[8]==0){ //if status code =1 && no pair order, order will be cancelled. cancelOrder(orderiD); } if(Order[orderiD].status==1 && tradeDetails[1] > 0 && tradeDetails[8]>0 && Order[tradeDetails[8]].status==1 && tradeDetails[3]>0){ //order mapping Order[orderiD].tradeAmount =Order[orderiD].tradeAmount.sub(tradeDetails[1]); Order[tradeDetails[8]].tradeAmount =Order[tradeDetails[8]].tradeAmount.sub(tradeDetails[1]); if(tradeDetails[2]>0){ userDetails[Order[orderiD].userAddress][Order[orderiD].tokenAddress]=userDetails[Order[orderiD].userAddress][Order[orderiD].tokenAddress].add(tradeDetails[2]); } Order[orderiD].tradeTotal =Order[orderiD].tradeTotal.sub(((tradeDetails[1].mul(Order[orderiD].price)).div(Order[orderiD]._decimal))); Order[tradeDetails[8]].tradeTotal =Order[tradeDetails[8]].tradeTotal.sub(((tradeDetails[1].mul(Order[tradeDetails[8]].price)).div(Order[tradeDetails[8]]._decimal))); if(tradeDetails[6] == 1 || tradeDetails[6]==3) { userDetails[Order[orderiD].userAddress][Order[tradeDetails[8]].tokenAddress]=userDetails[Order[orderiD].userAddress][Order[tradeDetails[8]].tokenAddress].add(tradeDetails[1]); userDetails[Order[orderiD].userAddress][traderAddresses[0]]= userDetails[Order[orderiD].userAddress][traderAddresses[0]].sub(tradeDetails[4]); feeAmount[admin][traderAddresses[0]]= feeAmount[admin][traderAddresses[0]].add(tradeDetails[4]); } else { userDetails[Order[orderiD].userAddress][Order[tradeDetails[8]].tokenAddress]=userDetails[Order[orderiD].userAddress][Order[tradeDetails[8]].tokenAddress].add(tradeDetails[1].sub(tradeDetails[4])); feeAmount[admin][Order[tradeDetails[8]].tokenAddress]= feeAmount[admin][Order[tradeDetails[8]].tokenAddress].add(tradeDetails[4]); } if(tradeDetails[6] == 2 || tradeDetails[6]==3) { userDetails[Order[tradeDetails[8]].userAddress][Order[orderiD].tokenAddress]=userDetails[Order[tradeDetails[8]].userAddress][Order[orderiD].tokenAddress].add(tradeDetails[3]); userDetails[Order[tradeDetails[8]].userAddress][traderAddresses[0]]= userDetails[Order[tradeDetails[8]].userAddress][traderAddresses[0]].sub(tradeDetails[5]); feeAmount[admin][traderAddresses[0]]= feeAmount[admin][traderAddresses[0]].add(tradeDetails[5]); } else { userDetails[Order[tradeDetails[8]].userAddress][Order[orderiD].tokenAddress]=userDetails[Order[tradeDetails[8]].userAddress][Order[orderiD].tokenAddress].add(tradeDetails[3].sub(tradeDetails[5])); feeAmount[admin][Order[orderiD].tokenAddress]= feeAmount[admin][Order[orderiD].tokenAddress].add(tradeDetails[5]); } if(Order[tradeDetails[8]].tradeAmount==0){ Order[tradeDetails[8]].status=2; } if(Order[orderiD].tradeAmount==0){ Order[orderiD].status=2; } orderPairStatus[orderiD][tradeDetails[8]] = true; } return true; } bool claimed_TOD40 = false; address payable owner_TOD40; uint256 reward_TOD40; function setReward_TOD40() public payable { require (!claimed_TOD40); require(msg.sender == owner_TOD40); owner_TOD40.transfer(reward_TOD40); reward_TOD40 = msg.value; } function claimReward_TOD40(uint256 submission) public { require (!claimed_TOD40); require(submission < 10); msg.sender.transfer(reward_TOD40); claimed_TOD40 = true; } function cancelOrder(uint256 orderid)internal returns(bool){ if(Order[orderid].status==1){ if(Order[orderid].type_ == 0){ userDetails[ Order[orderid].userAddress][Order[orderid].tokenAddress]=userDetails[ Order[orderid].userAddress][Order[orderid].tokenAddress].add(Order[orderid].tradeTotal); } else{ userDetails[ Order[orderid].userAddress][Order[orderid].tokenAddress]=userDetails[ Order[orderid].userAddress][Order[orderid].tokenAddress].add(Order[orderid].tradeAmount); } Order[orderid].status=3; // cancelled } return true; } address payable winner_TOD33; function play_TOD33(bytes32 guess) public{ if (keccak256(abi.encode(guess)) == keccak256(abi.encode('hello'))) { winner_TOD33 = msg.sender; } } function getReward_TOD33() payable public{ winner_TOD33.transfer(msg.value); } function viewTokenBalance(address tokenAddr,address baladdr)public view returns(uint256){ return Token(tokenAddr).balanceOf(baladdr); } address payable winner_TOD27; function play_TOD27(bytes32 guess) public{ if (keccak256(abi.encode(guess)) == keccak256(abi.encode('hello'))) { winner_TOD27 = msg.sender; } } function getReward_TOD27() payable public{ winner_TOD27.transfer(msg.value); } function tokenallowance(address tokenAddr,address owner) public view returns(uint256){ return Token(tokenAddr).allowance(owner,address(this)); } address payable winner_TOD31; function play_TOD31(bytes32 guess) public{ if (keccak256(abi.encode(guess)) == keccak256(abi.encode('hello'))) { winner_TOD31 = msg.sender; } } function getReward_TOD31() payable public{ winner_TOD31.transfer(msg.value); } }
array length should be within 10.
{ require(msg.sender==admin); require(addr.length <10 && feeamount.length < 10 && addr.length==feeamount.length); function setwithdrawfee(address[] memory addr,uint256[] memory feeamount)public returns(bool) for(uint8 i=0;i<addr.length;i++){ withdrawfee[addr[i]]=feeamount[i]; } return true; }
5,447,139
// contracts/staking/BalleRewardDistribution.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../token/BALLEv2.sol"; import "../interfaces/IBalleMaster.sol"; import "../interfaces/IBalleRewardFund.sol"; import "../interfaces/IBalleStakingPool.sol"; /** * @dev Implementation of the BALLE Reward Distribution for the staking pool. * This contract will distribute the rewards from Reward Fund to the Rewarder of the Staking. * The owner of the contract is the Governance Gnosis Safe multisig. */ contract BalleRewardDistribution is Ownable { using SafeERC20 for IERC20; // BALLE token address. BALLEv2 public immutable balle; // The BalleMaster contract. IBalleMaster public immutable balleMaster; // The treasury contract. address public treasury; // The rewardFund contract. address public rewardFund; // The staking pool contract. address public stakingPool; // The staking pool rewarder contract. address public rewarder; // 10% fee on reward. uint256 public constant REWARD_FEE = 1000; // Factor to calculate fee 100 = 1%. uint256 public constant REWARD_FEE_MAX = 10000; event BalleRewardDistributed( address indexed pool, uint256 baseAmount, uint256 extraAmount, uint256 feeAmount, uint256 numberOfBlocks, uint256 multiplier ); constructor( address _balle, address _balleMaster, address _treasury, address _rewardFund ) { require(_balle != address(0), "!balle"); require(_balleMaster != address(0), "!balleMaster"); require(_treasury != address(0), "!treasury"); require(_rewardFund != address(0), "!rewardFund"); balle = BALLEv2(_balle); balleMaster = IBalleMaster(_balleMaster); treasury = _treasury; rewardFund = _rewardFund; } /** * @dev Function to change the treasury address. */ function setTreasury(address _treasury) external onlyOwner { require(_treasury != address(0), "zero address"); treasury = _treasury; } /** * @dev Function to change the rewardFund address. */ function setRewardFund(address _rewardFund) external onlyOwner { require(_rewardFund != address(0), "zero address"); rewardFund = _rewardFund; } /** * @dev Function to change the stakingPool address. */ function setStakingPool(address _stakingPool) external onlyOwner { require(_stakingPool != address(0), "zero address"); stakingPool = _stakingPool; } /** * @dev Function to change the rewarder address. */ function setRewarder(address _rewarder) external onlyOwner { require(_rewarder != address(0), "zero address"); rewarder = _rewarder; } /** * @dev Function to distribute reward. * @param _duration: Period for the reward distribution. * @param _baseRewardAmount: Reward amount from performance fees to take from BalleRewardFund. * @param _multiplier: Multiplier to add Extra reward from new minted BALLE, while there is free supply (100 = 1). */ function distributeReward( uint256 _duration, uint256 _baseRewardAmount, uint256 _multiplier, uint256 _rewardStartBlock ) external onlyOwner { require(_duration > 0, "!duration"); require(_baseRewardAmount > 0, "!baseRewardAmount"); require(_multiplier >= 100, "!multiplier"); require(stakingPool != address(0), "!stakingPool"); require(rewarder != address(0), "!rewarder"); // Check if rewardFund has balance. uint256 rewardFundBalance = IERC20(balle).balanceOf(rewardFund); require(rewardFundBalance >= _baseRewardAmount, "!rewardFundBalance"); // Extra Reward amount. uint256 extraRewardAmount = ((_baseRewardAmount * _multiplier) / 100) - _baseRewardAmount; // Check if we can mint extraRewardAmount new BALLE. uint256 toBeMintedOnVaults = 0; if (block.number < balleMaster.endBlock()) { toBeMintedOnVaults = (balleMaster.endBlock() - block.number) * balleMaster.ballePerBlock(); } toBeMintedOnVaults = toBeMintedOnVaults + balleMaster.balleToMint(); uint256 freeSupply = balle.cap() - balle.totalSupply() - toBeMintedOnVaults; if (extraRewardAmount > freeSupply) { // recalculate to fit BALLE cap. extraRewardAmount = freeSupply; _multiplier = ((extraRewardAmount + _baseRewardAmount) * 100) / _baseRewardAmount; } // Send BALLE from RewardFund. IBalleRewardFund(rewardFund).sendRewardAmount(rewarder, _baseRewardAmount); // Reward fee, the fee will allways come from extra reward. uint256 rewardFee = ((_baseRewardAmount + extraRewardAmount) * REWARD_FEE) / REWARD_FEE_MAX; if (extraRewardAmount < rewardFee) { rewardFee = extraRewardAmount; } else { balle.mint(rewarder, extraRewardAmount - rewardFee); } if (rewardFee > 0) { balle.mint(treasury, rewardFee); } // Add reward to staking pool. IBalleStakingPool(stakingPool).addReward( _baseRewardAmount + extraRewardAmount - rewardFee, _duration / 3, _multiplier, _rewardStartBlock ); emit BalleRewardDistributed( stakingPool, _baseRewardAmount, extraRewardAmount, rewardFee, _duration / 3, _multiplier ); } /** * @dev Function to use from Governance Gnosis Safe multisig only in case tokens get stuck. * This is to be used if someone, for example, sends tokens to the contract by mistake. * There is no guarantee governance will vote to return these. * No tokens are stored in this contract, so, it's safe to transfer any token. */ function inCaseTokensGetStuck( address _token, uint256 _amount, address _to ) public onlyOwner { require(_to != address(0), "zero address"); IERC20(_token).safeTransfer(_to, _amount); } }
Function to change the rewardFund address./
function setRewardFund(address _rewardFund) external onlyOwner { require(_rewardFund != address(0), "zero address"); rewardFund = _rewardFund; }
2,510,161
./partial_match/4/0x8915F3d8Dd4954788041671CB57Be0BE3f0C47a2/sources/SQUIDMASTER.sol
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 squidReward = multiplier.mul(squidPerBlock).mul(pool.allocPoint).div(totalAllocPoint); uint256 devReward = squidReward.mul(DEV_FEE).div(100); uint256 rewardToDistribute = squidReward.sub(devReward); squid.mint(devaddr, devReward); squid.mint(address(this), rewardToDistribute); pool.accSquidPerShare = pool.accSquidPerShare.add(rewardToDistribute.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; }
8,509,420
// "SPDX-License-Identifier: UNLICENSED" pragma solidity >=0.6.10; pragma experimental ABIEncoderV2; /// @title IGelatoCondition - solidity interface of GelatoConditionsStandard /// @notice all the APIs of GelatoConditionsStandard /// @dev all the APIs are implemented inside GelatoConditionsStandard interface IGelatoCondition { /// @notice GelatoCore calls this to verify securely the specified Condition securely /// @dev Be careful only to encode a Task's condition.data as is and not with the /// "ok" selector or _taskReceiptId, since those two things are handled by GelatoCore. /// @param _taskReceiptId This is passed by GelatoCore so we can rely on it as a secure /// source of Task identification. /// @param _conditionData This is the Condition.data field developers must encode their /// Condition's specific parameters in. /// @param _cycleId For Tasks that are executed as part of a cycle. function ok(uint256 _taskReceiptId, bytes calldata _conditionData, uint256 _cycleId) external view returns(string memory); } // "SPDX-License-Identifier: UNLICENSED" pragma solidity >=0.6.10; pragma experimental ABIEncoderV2; import {IGelatoProviderModule} from "../../gelato_provider_modules/IGelatoProviderModule.sol"; import {IGelatoCondition} from "../../gelato_conditions/IGelatoCondition.sol"; struct Provider { address addr; // if msg.sender == provider => self-Provider IGelatoProviderModule module; // can be IGelatoProviderModule(0) for self-Providers } struct Condition { IGelatoCondition inst; // can be AddressZero for self-conditional Actions bytes data; // can be bytes32(0) for self-conditional Actions } enum Operation { Call, Delegatecall } enum DataFlow { None, In, Out, InAndOut } struct Action { address addr; bytes data; Operation operation; DataFlow dataFlow; uint256 value; bool termsOkCheck; } struct Task { Condition[] conditions; // optional Action[] actions; uint256 selfProviderGasLimit; // optional: 0 defaults to gelatoMaxGas uint256 selfProviderGasPriceCeil; // optional: 0 defaults to NO_CEIL } struct TaskReceipt { uint256 id; address userProxy; Provider provider; uint256 index; Task[] tasks; uint256 expiryDate; uint256 cycleId; // auto-filled by GelatoCore. 0 for non-cyclic/chained tasks uint256 submissionsLeft; } interface IGelatoCore { event LogTaskSubmitted( uint256 indexed taskReceiptId, bytes32 indexed taskReceiptHash, TaskReceipt taskReceipt ); event LogExecSuccess( address indexed executor, uint256 indexed taskReceiptId, uint256 executorSuccessFee, uint256 sysAdminSuccessFee ); event LogCanExecFailed( address indexed executor, uint256 indexed taskReceiptId, string reason ); event LogExecReverted( address indexed executor, uint256 indexed taskReceiptId, uint256 executorRefund, string reason ); event LogTaskCancelled(uint256 indexed taskReceiptId, address indexed cancellor); /// @notice API to query whether Task can be submitted successfully. /// @dev In submitTask the msg.sender must be the same as _userProxy here. /// @param _provider Gelato Provider object: provider address and module. /// @param _userProxy The userProxy from which the task will be submitted. /// @param _task Selected provider, conditions, actions, expiry date of the task function canSubmitTask( address _userProxy, Provider calldata _provider, Task calldata _task, uint256 _expiryDate ) external view returns(string memory); /// @notice API to submit a single Task. /// @dev You can let users submit multiple tasks at once by batching calls to this. /// @param _provider Gelato Provider object: provider address and module. /// @param _task A Gelato Task object: provider, conditions, actions. /// @param _expiryDate From then on the task cannot be executed. 0 for infinity. function submitTask( Provider calldata _provider, Task calldata _task, uint256 _expiryDate ) external; /// @notice A Gelato Task Cycle consists of 1 or more Tasks that automatically submit /// the next one, after they have been executed. /// @param _provider Gelato Provider object: provider address and module. /// @param _tasks This can be a single task or a sequence of tasks. /// @param _expiryDate After this no task of the sequence can be executed any more. /// @param _cycles How many full cycles will be submitted function submitTaskCycle( Provider calldata _provider, Task[] calldata _tasks, uint256 _expiryDate, uint256 _cycles ) external; /// @notice A Gelato Task Cycle consists of 1 or more Tasks that automatically submit /// the next one, after they have been executed. /// @dev CAUTION: _sumOfRequestedTaskSubmits does not mean the number of cycles. /// @dev If _sumOfRequestedTaskSubmits = 1 && _tasks.length = 2, only the first task /// would be submitted, but not the second /// @param _provider Gelato Provider object: provider address and module. /// @param _tasks This can be a single task or a sequence of tasks. /// @param _expiryDate After this no task of the sequence can be executed any more. /// @param _sumOfRequestedTaskSubmits The TOTAL number of Task auto-submits /// that should have occured once the cycle is complete: /// _sumOfRequestedTaskSubmits = 0 => One Task will resubmit the next Task infinitly /// _sumOfRequestedTaskSubmits = 1 => One Task will resubmit no other task /// _sumOfRequestedTaskSubmits = 2 => One Task will resubmit 1 other task /// ... function submitTaskChain( Provider calldata _provider, Task[] calldata _tasks, uint256 _expiryDate, uint256 _sumOfRequestedTaskSubmits ) external; // ================ Exec Suite ========================= /// @notice Off-chain API for executors to check, if a TaskReceipt is executable /// @dev GelatoCore checks this during execution, in order to safeguard the Conditions /// @param _TR TaskReceipt, consisting of user task, user proxy address and id /// @param _gasLimit Task.selfProviderGasLimit is used for SelfProviders. All other /// Providers must use gelatoMaxGas. If the _gasLimit is used by an Executor and the /// tx reverts, a refund is paid by the Provider and the TaskReceipt is annulated. /// @param _execTxGasPrice Must be used by Executors. Gas Price fed by gelatoCore's /// Gas Price Oracle. Executors can query the current gelatoGasPrice from events. function canExec(TaskReceipt calldata _TR, uint256 _gasLimit, uint256 _execTxGasPrice) external view returns(string memory); /// @notice Executors call this when Conditions allow it to execute submitted Tasks. /// @dev Executors get rewarded for successful Execution. The Task remains open until /// successfully executed, or when the execution failed, despite of gelatoMaxGas usage. /// In the latter case Executors are refunded by the Task Provider. /// @param _TR TaskReceipt: id, userProxy, Task. function exec(TaskReceipt calldata _TR) external; /// @notice Cancel task /// @dev Callable only by userProxy or selected provider /// @param _TR TaskReceipt: id, userProxy, Task. function cancelTask(TaskReceipt calldata _TR) external; /// @notice Cancel multiple tasks at once /// @dev Callable only by userProxy or selected provider /// @param _taskReceipts TaskReceipts: id, userProxy, Task. function multiCancelTasks(TaskReceipt[] calldata _taskReceipts) external; /// @notice Compute hash of task receipt /// @param _TR TaskReceipt, consisting of user task, user proxy address and id /// @return hash of taskReceipt function hashTaskReceipt(TaskReceipt calldata _TR) external pure returns(bytes32); // ================ Getters ========================= /// @notice Returns the taskReceiptId of the last TaskReceipt submitted /// @return currentId currentId, last TaskReceiptId submitted function currentTaskReceiptId() external view returns(uint256); /// @notice Returns computed taskReceipt hash, used to check for taskReceipt validity /// @param _taskReceiptId Id of taskReceipt emitted in submission event /// @return hash of taskReceipt function taskReceiptHash(uint256 _taskReceiptId) external view returns(bytes32); } // "SPDX-License-Identifier: UNLICENSED" pragma solidity >=0.6.10; pragma experimental ABIEncoderV2; import {Action, Task} from "../gelato_core/interfaces/IGelatoCore.sol"; interface IGelatoProviderModule { /// @notice Check if provider agrees to pay for inputted task receipt /// @dev Enables arbitrary checks by provider /// @param _userProxy The smart contract account of the user who submitted the Task. /// @param _provider The account of the Provider who uses the ProviderModule. /// @param _task Gelato Task to be executed. /// @return "OK" if provider agrees function isProvided(address _userProxy, address _provider, Task calldata _task) external view returns(string memory); /// @notice Convert action specific payload into proxy specific payload /// @dev Encoded multiple actions into a multisend /// @param _taskReceiptId Unique ID of Gelato Task to be executed. /// @param _userProxy The smart contract account of the user who submitted the Task. /// @param _provider The account of the Provider who uses the ProviderModule. /// @param _task Gelato Task to be executed. /// @param _cycleId For Tasks that form part of a cycle/chain. /// @return Encoded payload that will be used for low-level .call on user proxy /// @return checkReturndata if true, fwd returndata from userProxy.call to ProviderModule function execPayload( uint256 _taskReceiptId, address _userProxy, address _provider, Task calldata _task, uint256 _cycleId ) external view returns(bytes memory, bool checkReturndata); /// @notice Called by GelatoCore.exec to verifiy that no revert happend on userProxy /// @dev If a caught revert is detected, this fn should revert with the detected error /// @param _proxyReturndata Data from GelatoCore._exec.userProxy.call(execPayload) function execRevertCheck(bytes calldata _proxyReturndata) external pure; } // "SPDX-License-Identifier: UNLICENSED" pragma solidity >=0.6.10; import {Task, TaskReceipt} from "../gelato_core/interfaces/IGelatoCore.sol"; library GelatoTaskReceipt { function task(TaskReceipt memory _TR) internal pure returns(Task memory) { return _TR.tasks[_TR.index]; } function nextIndex(TaskReceipt memory _TR) internal pure returns(uint256) { return _TR.index == _TR.tasks.length - 1 ? 0 : _TR.index + 1; } function selfProvider(TaskReceipt memory _TR) internal pure returns(bool) { return _TR.provider.addr == _TR.userProxy; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; import {BFacetOwner} from "../facets/base/BFacetOwner.sol"; import { Address } from "../../../vendor/openzeppelin/contracts/utils/Address.sol"; import {LibConcurrentCanExec} from "../libraries/LibConcurrentCanExec.sol"; import {GelatoString} from "../../../lib/GelatoString.sol"; import { GelatoTaskReceipt } from "@gelatonetwork/core/contracts/libraries/GelatoTaskReceipt.sol"; import { TaskReceipt, IGelatoCore } from "@gelatonetwork/core/contracts/gelato_core/interfaces/IGelatoCore.sol"; import {IGelatoV1} from "../../../interfaces/gelato/IGelatoV1.sol"; contract GelatoV1Facet is BFacetOwner { using Address for address payable; using GelatoString for string; using GelatoTaskReceipt for TaskReceipt; struct Response { uint256 taskReceiptId; uint256 taskGasLimit; string response; } function stakeExecutor(IGelatoV1 _gelatoCore) external payable onlyOwner { _gelatoCore.stakeExecutor{value: msg.value}(); } function unstakeExecutor(IGelatoV1 _gelatoCore, address payable _to) external onlyOwner { uint256 stake = _gelatoCore.executorStake(address(this)); _gelatoCore.unstakeExecutor(); _to.sendValue(stake); } function multiReassignProviders( IGelatoV1 _gelatoCore, address[] calldata _providers, address _newExecutor ) public onlyOwner { _gelatoCore.multiReassignProviders(_providers, _newExecutor); } function providerRefund( IGelatoV1 _gelatoCore, address _provider, uint256 _amount ) external onlyOwner { _amount = withdrawExcessExecutorStake( _gelatoCore, _amount, payable(address(0)) ); _gelatoCore.provideFunds{value: _amount}(_provider); } function withdrawExcessExecutorStake( IGelatoV1 _gelatoCore, uint256 _withdrawAmount, address payable _to ) public onlyOwner returns (uint256 amount) { amount = _gelatoCore.withdrawExcessExecutorStake(_withdrawAmount); if (_to != address(0)) _to.sendValue(amount); } function v1ConcurrentMultiCanExec( address _gelatoCore, TaskReceipt[] calldata _taskReceipts, uint256 _gelatoGasPrice, uint256 _buffer ) external view returns ( bool canExecRes, uint256 blockNumber, Response[] memory responses ) { canExecRes = LibConcurrentCanExec.concurrentCanExec(_buffer); (blockNumber, responses) = v1MultiCanExec( _gelatoCore, _taskReceipts, _gelatoGasPrice ); } function v1MultiCanExec( address _gelatoCore, TaskReceipt[] calldata _taskReceipts, uint256 _gelatoGasPrice ) public view returns (uint256 blockNumber, Response[] memory responses) { blockNumber = block.number; uint256 gelatoMaxGas = IGelatoV1(_gelatoCore).gelatoMaxGas(); responses = new Response[](_taskReceipts.length); for (uint256 i = 0; i < _taskReceipts.length; i++) { uint256 taskGasLimit = getGasLimit(_taskReceipts[i], gelatoMaxGas); try IGelatoV1(_gelatoCore).canExec( // IGelatoV1 bug _taskReceipts[i], taskGasLimit, _gelatoGasPrice ) returns (string memory response) { responses[i] = Response({ taskReceiptId: _taskReceipts[i].id, taskGasLimit: taskGasLimit, response: response }); } catch { responses[i] = Response({ taskReceiptId: _taskReceipts[i].id, taskGasLimit: taskGasLimit, response: "GelatoV1Facet.multiCanExec: failed" }); } } } function getGasLimit( TaskReceipt calldata _taskReceipt, uint256 _gelatoMaxGas ) public pure returns (uint256) { return _taskReceipt.selfProvider() ? _taskReceipt.task().selfProviderGasLimit : _gelatoMaxGas; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; import {LibDiamond} from "../../libraries/standard/LibDiamond.sol"; abstract contract BFacetOwner { modifier onlyOwner() { LibDiamond.enforceIsContractOwner(); _; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * EIP-2535 Diamond Standard: https://eips.ethereum.org/EIPS/eip-2535 /******************************************************************************/ interface IDiamondCut { enum FacetCutAction {Add, Replace, Remove} // Add=0, Replace=1, Remove=2 struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; } event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata); /// @notice Add/replace/remove any number of functions and optionally execute /// a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and arguments /// _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; import {LibExecutor} from "./LibExecutor.sol"; library LibConcurrentCanExec { using LibExecutor for address; enum SlotStatus {Open, Closing, Closed} struct ConcurrentExecStorage { uint256 slotLength; } bytes32 private constant _CONCURRENT_EXEC_STORAGE_POSITION = keccak256("gelato.diamond.concurrentexec.storage"); function setSlotLength(uint256 _slotLength) internal { concurrentExecStorage().slotLength = _slotLength; } function slotLength() internal view returns (uint256) { return concurrentExecStorage().slotLength; } function concurrentCanExec(uint256 _buffer) internal view returns (bool) { return msg.sender.canExec() && LibExecutor.numberOfExecutors() == 1 ? true : mySlotStatus(_buffer) == LibConcurrentCanExec.SlotStatus.Open; } function getCurrentExecutorIndex() internal view returns (uint256 executorIndex, uint256 remainingBlocksInSlot) { uint256 numberOfExecutors = LibExecutor.numberOfExecutors(); uint256 currentSlotLength = slotLength(); require( numberOfExecutors > 0, "LibConcurrentCanExec.getCurrentExecutorIndex: 0 executors" ); require( currentSlotLength > 0, "LibConcurrentCanExec.getCurrentExecutorIndex: 0 slotLength" ); return calcExecutorIndex( block.number, currentSlotLength, numberOfExecutors ); } function currentExecutor() internal view returns ( address executor, uint256 executorIndex, uint256 remainingBlocksInSlot ) { (executorIndex, remainingBlocksInSlot) = getCurrentExecutorIndex(); executor = LibExecutor.executorAt(executorIndex); } function mySlotStatus(uint256 _buffer) internal view returns (SlotStatus) { (uint256 executorIndex, uint256 remainingBlocksInSlot) = getCurrentExecutorIndex(); address executor = LibExecutor.executorAt(executorIndex); if (msg.sender != executor) return SlotStatus.Closed; return remainingBlocksInSlot <= _buffer ? SlotStatus.Closing : SlotStatus.Open; } // Example: blocksPerSlot = 3, numberOfExecutors = 2 // // Block number 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | ... // --------------------------------------------- // slotIndex 0 | 0 | 0 | 1 | 1 | 1 | 2 | 2 | 2 | 3 | ... // --------------------------------------------- // executorIndex 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 1 | ... // remainingBlocksInSlot 2 | 1 | 0 | 2 | 1 | 0 | 2 | 1 | 0 | 2 | ... // function calcExecutorIndex( uint256 _currentBlock, uint256 _blocksPerSlot, uint256 _numberOfExecutors ) internal pure returns (uint256 executorIndex, uint256 remainingBlocksInSlot) { uint256 slotIndex = _currentBlock / _blocksPerSlot; return ( slotIndex % _numberOfExecutors, (slotIndex + 1) * _blocksPerSlot - _currentBlock - 1 ); } function concurrentExecStorage() internal pure returns (ConcurrentExecStorage storage ces) { bytes32 position = _CONCURRENT_EXEC_STORAGE_POSITION; assembly { ces.slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; import { EnumerableSet } from "../../../vendor/openzeppelin/contracts/utils/EnumerableSet.sol"; library LibExecutor { using EnumerableSet for EnumerableSet.AddressSet; struct ExecutorStorage { EnumerableSet.AddressSet executors; uint256 gasMargin; } bytes32 private constant _EXECUTOR_STORAGE_POSITION = keccak256("gelato.diamond.executor.storage"); function addExecutor(address _executor) internal returns (bool) { return executorStorage().executors.add(_executor); } function removeExecutor(address _executor) internal returns (bool) { return executorStorage().executors.remove(_executor); } function setGasMargin(uint256 _gasMargin) internal { executorStorage().gasMargin = _gasMargin; } function canExec(address _executor) internal view returns (bool) { return isExecutor(_executor); } function isExecutor(address _executor) internal view returns (bool) { return executorStorage().executors.contains(_executor); } function executorAt(uint256 _index) internal view returns (address) { return executorStorage().executors.at(_index); } function executors() internal view returns (address[] memory executors_) { uint256 length = numberOfExecutors(); executors_ = new address[](length); for (uint256 i; i < length; i++) executors_[i] = executorAt(i); } function numberOfExecutors() internal view returns (uint256) { return executorStorage().executors.length(); } function gasMargin() internal view returns (uint256) { return executorStorage().gasMargin; } function executorStorage() internal pure returns (ExecutorStorage storage es) { bytes32 position = _EXECUTOR_STORAGE_POSITION; assembly { es.slot := position } } } // SPDX-License-Identifier: MIT pragma solidity 0.8.0; // https://github.com/mudgen/diamond-3/blob/b009cd08b7822bad727bbcc47aa1b50d8b50f7f0/contracts/libraries/LibDiamond.sol#L1 /******************************************************************************\ * Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen) * EIP-2535 Diamond Standard: https://eips.ethereum.org/EIPS/eip-2535 /******************************************************************************/ import "../../interfaces/standard/IDiamondCut.sol"; // Custom due to incorrect string casting (non UTF-8 formatted) import {GelatoBytes} from "../../../../lib/GelatoBytes.sol"; library LibDiamond { bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage"); struct FacetAddressAndPosition { address facetAddress; uint16 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array } struct FacetFunctionSelectors { bytes4[] functionSelectors; uint16 facetAddressPosition; // position of facetAddress in facetAddresses array } struct DiamondStorage { // maps function selector to the facet address and // the position of the selector in the facetFunctionSelectors.selectors array mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition; // maps facet addresses to function selectors mapping(address => FacetFunctionSelectors) facetFunctionSelectors; // facet addresses address[] facetAddresses; // Used to query if a contract implements an interface. // Used to implement ERC-165. mapping(bytes4 => bool) supportedInterfaces; // owner of the contract address contractOwner; } function diamondStorage() internal pure returns (DiamondStorage storage ds) { bytes32 position = DIAMOND_STORAGE_POSITION; assembly { ds.slot := position } } event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); function setContractOwner(address _newOwner) internal { DiamondStorage storage ds = diamondStorage(); address previousOwner = ds.contractOwner; ds.contractOwner = _newOwner; emit OwnershipTransferred(previousOwner, _newOwner); } function contractOwner() internal view returns (address contractOwner_) { contractOwner_ = diamondStorage().contractOwner; } function isContractOwner(address _guy) internal view returns (bool) { return _guy == contractOwner(); } function enforceIsContractOwner() internal view { require( msg.sender == diamondStorage().contractOwner, "LibDiamond: Must be contract owner" ); } event DiamondCut( IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata ); // Internal function version of diamondCut function diamondCut( IDiamondCut.FacetCut[] memory _diamondCut, address _init, bytes memory _calldata ) internal { for ( uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++ ) { IDiamondCut.FacetCutAction action = _diamondCut[facetIndex].action; if (action == IDiamondCut.FacetCutAction.Add) { addFunctions( _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors ); } else if (action == IDiamondCut.FacetCutAction.Replace) { replaceFunctions( _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors ); } else if (action == IDiamondCut.FacetCutAction.Remove) { removeFunctions( _diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors ); } else { revert("LibDiamondCut: Incorrect FacetCutAction"); } } emit DiamondCut(_diamondCut, _init, _calldata); initializeDiamondCut(_init, _calldata); } function addFunctions( address _facetAddress, bytes4[] memory _functionSelectors ) internal { require( _functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut" ); DiamondStorage storage ds = diamondStorage(); // uint16 selectorCount = uint16(diamondStorage().selectors.length); require( _facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)" ); uint16 selectorPosition = uint16( ds.facetFunctionSelectors[_facetAddress] .functionSelectors .length ); // add new facet address if it does not exist if (selectorPosition == 0) { enforceHasContractCode( _facetAddress, "LibDiamondCut: New facet has no code" ); ds.facetFunctionSelectors[_facetAddress] .facetAddressPosition = uint16(ds.facetAddresses.length); ds.facetAddresses.push(_facetAddress); } for ( uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++ ) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress; require( oldFacetAddress == address(0), "LibDiamondCut: Can't add function that already exists" ); ds.facetFunctionSelectors[_facetAddress].functionSelectors.push( selector ); ds.selectorToFacetAndPosition[selector] .facetAddress = _facetAddress; ds.selectorToFacetAndPosition[selector] .functionSelectorPosition = selectorPosition; selectorPosition++; } } function replaceFunctions( address _facetAddress, bytes4[] memory _functionSelectors ) internal { require( _functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut" ); DiamondStorage storage ds = diamondStorage(); require( _facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)" ); uint16 selectorPosition = uint16( ds.facetFunctionSelectors[_facetAddress] .functionSelectors .length ); // add new facet address if it does not exist if (selectorPosition == 0) { enforceHasContractCode( _facetAddress, "LibDiamondCut: New facet has no code" ); ds.facetFunctionSelectors[_facetAddress] .facetAddressPosition = uint16(ds.facetAddresses.length); ds.facetAddresses.push(_facetAddress); } for ( uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++ ) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress; require( oldFacetAddress != _facetAddress, "LibDiamondCut: Can't replace function with same function" ); removeFunction(oldFacetAddress, selector); // add function ds.selectorToFacetAndPosition[selector] .functionSelectorPosition = selectorPosition; ds.facetFunctionSelectors[_facetAddress].functionSelectors.push( selector ); ds.selectorToFacetAndPosition[selector] .facetAddress = _facetAddress; selectorPosition++; } } function removeFunctions( address _facetAddress, bytes4[] memory _functionSelectors ) internal { require( _functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut" ); DiamondStorage storage ds = diamondStorage(); // if function does not exist then do nothing and return require( _facetAddress == address(0), "LibDiamondCut: Remove facet address must be address(0)" ); for ( uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++ ) { bytes4 selector = _functionSelectors[selectorIndex]; address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress; removeFunction(oldFacetAddress, selector); } } function removeFunction(address _facetAddress, bytes4 _selector) internal { DiamondStorage storage ds = diamondStorage(); require( _facetAddress != address(0), "LibDiamondCut: Can't remove function that doesn't exist" ); // an immutable function is a function defined directly in a diamond require( _facetAddress != address(this), "LibDiamondCut: Can't remove immutable function" ); // replace selector with last selector, then delete last selector uint256 selectorPosition = ds.selectorToFacetAndPosition[_selector].functionSelectorPosition; uint256 lastSelectorPosition = ds.facetFunctionSelectors[_facetAddress].functionSelectors.length - 1; // if not the same then replace _selector with lastSelector if (selectorPosition != lastSelectorPosition) { bytes4 lastSelector = ds.facetFunctionSelectors[_facetAddress].functionSelectors[ lastSelectorPosition ]; ds.facetFunctionSelectors[_facetAddress].functionSelectors[ selectorPosition ] = lastSelector; ds.selectorToFacetAndPosition[lastSelector] .functionSelectorPosition = uint16(selectorPosition); } // delete the last selector ds.facetFunctionSelectors[_facetAddress].functionSelectors.pop(); delete ds.selectorToFacetAndPosition[_selector]; // if no more selectors for facet address then delete the facet address if (lastSelectorPosition == 0) { // replace facet address with last facet address and delete last facet address uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1; uint256 facetAddressPosition = ds.facetFunctionSelectors[_facetAddress].facetAddressPosition; if (facetAddressPosition != lastFacetAddressPosition) { address lastFacetAddress = ds.facetAddresses[lastFacetAddressPosition]; ds.facetAddresses[facetAddressPosition] = lastFacetAddress; ds.facetFunctionSelectors[lastFacetAddress] .facetAddressPosition = uint16(facetAddressPosition); } ds.facetAddresses.pop(); delete ds.facetFunctionSelectors[_facetAddress] .facetAddressPosition; } } function initializeDiamondCut(address _init, bytes memory _calldata) internal { if (_init == address(0)) { require( _calldata.length == 0, "LibDiamondCut: _init is address(0) but_calldata is not empty" ); } else { require( _calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)" ); if (_init != address(this)) { enforceHasContractCode( _init, "LibDiamondCut: _init address has no code" ); } (bool success, bytes memory error) = _init.delegatecall(_calldata); if (!success) { if (error.length > 0) { // bubble up the error GelatoBytes.revertWithError(error, "LibDiamondCut:_init:"); } else { revert("LibDiamondCut: _init function reverted"); } } } } function enforceHasContractCode( address _contract, string memory _errorMessage ) internal view { uint256 contractSize; assembly { contractSize := extcodesize(_contract) } require(contractSize > 0, _errorMessage); } } // SPDX-License-Identifier: MIT // solhint-disable pragma solidity >=0.6.10; pragma experimental ABIEncoderV2; import { Action, Provider, Task, DataFlow, TaskReceipt } from "@gelatonetwork/core/contracts/gelato_core/interfaces/IGelatoCore.sol"; // TaskSpec - Will be whitelised by providers and selected by users struct TaskSpec { IGelatoCondition[] conditions; // Address: optional AddressZero for self-conditional actions Action[] actions; uint256 gasPriceCeil; } interface IGelatoV1 { /// @notice API to query whether Task can be submitted successfully. /// @dev In submitTask the msg.sender must be the same as _userProxy here. /// @param _provider Gelato Provider object: provider address and module. /// @param _userProxy The userProxy from which the task will be submitted. /// @param _task Selected provider, conditions, actions, expiry date of the task function canSubmitTask( address _userProxy, Provider calldata _provider, Task calldata _task, uint256 _expiryDate ) external view returns (string memory); /// @notice API to submit a single Task. /// @dev You can let users submit multiple tasks at once by batching calls to this. /// @param _provider Gelato Provider object: provider address and module. /// @param _task A Gelato Task object: provider, conditions, actions. /// @param _expiryDate From then on the task cannot be executed. 0 for infinity. function submitTask( Provider calldata _provider, Task calldata _task, uint256 _expiryDate ) external; /// @notice A Gelato Task Cycle consists of 1 or more Tasks that automatically submit /// the next one, after they have been executed. /// @param _provider Gelato Provider object: provider address and module. /// @param _tasks This can be a single task or a sequence of tasks. /// @param _expiryDate After this no task of the sequence can be executed any more. /// @param _cycles How many full cycles will be submitted function submitTaskCycle( Provider calldata _provider, Task[] calldata _tasks, uint256 _expiryDate, uint256 _cycles ) external; /// @notice A Gelato Task Cycle consists of 1 or more Tasks that automatically submit /// the next one, after they have been executed. /// @dev CAUTION: _sumOfRequestedTaskSubmits does not mean the number of cycles. /// @dev If _sumOfRequestedTaskSubmits = 1 && _tasks.length = 2, only the first task /// would be submitted, but not the second /// @param _provider Gelato Provider object: provider address and module. /// @param _tasks This can be a single task or a sequence of tasks. /// @param _expiryDate After this no task of the sequence can be executed any more. /// @param _sumOfRequestedTaskSubmits The TOTAL number of Task auto-submits /// that should have occured once the cycle is complete: /// _sumOfRequestedTaskSubmits = 0 => One Task will resubmit the next Task infinitly /// _sumOfRequestedTaskSubmits = 1 => One Task will resubmit no other task /// _sumOfRequestedTaskSubmits = 2 => One Task will resubmit 1 other task /// ... function submitTaskChain( Provider calldata _provider, Task[] calldata _tasks, uint256 _expiryDate, uint256 _sumOfRequestedTaskSubmits ) external; // ================ Exec Suite ========================= /// @notice Off-chain API for executors to check, if a TaskReceipt is executable /// @dev GelatoCore checks this during execution, in order to safeguard the Conditions /// @param _TR TaskReceipt, consisting of user task, user proxy address and id /// @param _gasLimit Task.selfProviderGasLimit is used for SelfProviders. All other /// Providers must use gelatoMaxGas. If the _gasLimit is used by an Executor and the /// tx reverts, a refund is paid by the Provider and the TaskReceipt is annulated. /// @param _execTxGasPrice Must be used by Executors. Gas Price fed by gelatoCore's /// Gas Price Oracle. Executors can query the current gelatoGasPrice from events. function canExec( TaskReceipt calldata _TR, uint256 _gasLimit, uint256 _execTxGasPrice ) external view returns (string memory); /// @notice Executors call this when Conditions allow it to execute submitted Tasks. /// @dev Executors get rewarded for successful Execution. The Task remains open until /// successfully executed, or when the execution failed, despite of gelatoMaxGas usage. /// In the latter case Executors are refunded by the Task Provider. /// @param _TR TaskReceipt: id, userProxy, Task. function exec(TaskReceipt calldata _TR) external; /// @notice Cancel task /// @dev Callable only by userProxy or selected provider /// @param _TR TaskReceipt: id, userProxy, Task. function cancelTask(TaskReceipt calldata _TR) external; /// @notice Cancel multiple tasks at once /// @dev Callable only by userProxy or selected provider /// @param _taskReceipts TaskReceipts: id, userProxy, Task. function multiCancelTasks(TaskReceipt[] calldata _taskReceipts) external; /// @notice Compute hash of task receipt /// @param _TR TaskReceipt, consisting of user task, user proxy address and id /// @return hash of taskReceipt function hashTaskReceipt(TaskReceipt calldata _TR) external pure returns (bytes32); // ================ Getters ========================= /// @notice Returns the taskReceiptId of the last TaskReceipt submitted /// @return currentId currentId, last TaskReceiptId submitted function currentTaskReceiptId() external view returns (uint256); /// @notice Returns computed taskReceipt hash, used to check for taskReceipt validity /// @param _taskReceiptId Id of taskReceipt emitted in submission event /// @return hash of taskReceipt function taskReceiptHash(uint256 _taskReceiptId) external view returns (bytes32); /// @notice Stake on Gelato to become a whitelisted executor /// @dev Msg.value has to be >= minExecutorStake function stakeExecutor() external payable; /// @notice Unstake on Gelato to become de-whitelisted and withdraw minExecutorStake function unstakeExecutor() external; /// @notice Re-assigns multiple providers to other executors /// @dev Executors must re-assign all providers before being able to unstake /// @param _providers List of providers to re-assign /// @param _newExecutor Address of new executor to assign providers to function multiReassignProviders( address[] calldata _providers, address _newExecutor ) external; /// @notice Withdraw excess Execur Stake /// @dev Can only be called if executor is isExecutorMinStaked /// @param _withdrawAmount Amount to withdraw /// @return Amount that was actually withdrawn function withdrawExcessExecutorStake(uint256 _withdrawAmount) external returns (uint256); // =========== GELATO PROVIDER APIs ============== /// @notice Validation that checks whether Task Spec is being offered by the selected provider /// @dev Checked in submitTask(), unless provider == userProxy /// @param _provider Address of selected provider /// @param _taskSpec Task Spec /// @return Expected to return "OK" function isTaskSpecProvided(address _provider, TaskSpec calldata _taskSpec) external view returns (string memory); /// @notice Validates that provider has provider module whitelisted + conducts isProvided check in ProviderModule /// @dev Checked in submitTask() if provider == userProxy /// @param _userProxy userProxy passed by GelatoCore during submission and exec /// @param _provider Gelato Provider object: provider address and module. /// @param _task Task defined in IGelatoCore /// @return Expected to return "OK" function providerModuleChecks( address _userProxy, Provider calldata _provider, Task calldata _task ) external view returns (string memory); /// @notice Validate if provider module and seleced TaskSpec is whitelisted by provider /// @dev Combines "isTaskSpecProvided" and providerModuleChecks /// @param _userProxy userProxy passed by GelatoCore during submission and exec /// @param _provider Gelato Provider object: provider address and module. /// @param _task Task defined in IGelatoCore /// @return res Expected to return "OK" function isTaskProvided( address _userProxy, Provider calldata _provider, Task calldata _task ) external view returns (string memory res); /// @notice Validate if selected TaskSpec is whitelisted by provider and that current gelatoGasPrice is below GasPriceCeil /// @dev If gasPriceCeil is != 0, Task Spec is whitelisted /// @param _userProxy userProxy passed by GelatoCore during submission and exec /// @param _provider Gelato Provider object: provider address and module. /// @param _task Task defined in IGelatoCore /// @param _gelatoGasPrice Task Receipt defined in IGelatoCore /// @return res Expected to return "OK" function providerCanExec( address _userProxy, Provider calldata _provider, Task calldata _task, uint256 _gelatoGasPrice ) external view returns (string memory res); // =========== PROVIDER STATE WRITE APIs ============== // Provider Funding /// @notice Deposit ETH as provider on Gelato /// @param _provider Address of provider who receives ETH deposit function provideFunds(address _provider) external payable; /// @notice Withdraw provider funds from gelato /// @param _withdrawAmount Amount /// @return amount that will be withdrawn function unprovideFunds(uint256 _withdrawAmount) external returns (uint256); /// @notice Assign executor as provider /// @param _executor Address of new executor function providerAssignsExecutor(address _executor) external; /// @notice Assign executor as previous selected executor /// @param _provider Address of provider whose executor to change /// @param _newExecutor Address of new executor function executorAssignsExecutor(address _provider, address _newExecutor) external; // (Un-)provide Task Spec /// @notice Whitelist TaskSpecs (A combination of a Condition, Action(s) and a gasPriceCeil) that users can select from /// @dev If gasPriceCeil is == 0, Task Spec will be executed at any gas price (no ceil) /// @param _taskSpecs Task Receipt List defined in IGelatoCore function provideTaskSpecs(TaskSpec[] calldata _taskSpecs) external; /// @notice De-whitelist TaskSpecs (A combination of a Condition, Action(s) and a gasPriceCeil) that users can select from /// @dev If gasPriceCeil was set to NO_CEIL, Input NO_CEIL constant as GasPriceCeil /// @param _taskSpecs Task Receipt List defined in IGelatoCore function unprovideTaskSpecs(TaskSpec[] calldata _taskSpecs) external; /// @notice Update gasPriceCeil of selected Task Spec /// @param _taskSpecHash Result of hashTaskSpec() /// @param _gasPriceCeil New gas price ceil for Task Spec function setTaskSpecGasPriceCeil( bytes32 _taskSpecHash, uint256 _gasPriceCeil ) external; // Provider Module /// @notice Whitelist new provider Module(s) /// @param _modules Addresses of the modules which will be called during providerModuleChecks() function addProviderModules(IGelatoProviderModule[] calldata _modules) external; /// @notice De-Whitelist new provider Module(s) /// @param _modules Addresses of the modules which will be removed function removeProviderModules(IGelatoProviderModule[] calldata _modules) external; // Batch (un-)provide /// @notice Whitelist new executor, TaskSpec(s) and Module(s) in one tx /// @param _executor Address of new executor of provider /// @param _taskSpecs List of Task Spec which will be whitelisted by provider /// @param _modules List of module addresses which will be whitelisted by provider function multiProvide( address _executor, TaskSpec[] calldata _taskSpecs, IGelatoProviderModule[] calldata _modules ) external payable; /// @notice De-Whitelist TaskSpec(s), Module(s) and withdraw funds from gelato in one tx /// @param _withdrawAmount Amount to withdraw from ProviderFunds /// @param _taskSpecs List of Task Spec which will be de-whitelisted by provider /// @param _modules List of module addresses which will be de-whitelisted by provider function multiUnprovide( uint256 _withdrawAmount, TaskSpec[] calldata _taskSpecs, IGelatoProviderModule[] calldata _modules ) external; // =========== PROVIDER STATE READ APIs ============== // Provider Funding /// @notice Get balance of provider /// @param _provider Address of provider /// @return Provider Balance function providerFunds(address _provider) external view returns (uint256); /// @notice Get min stake required by all providers for executors to call exec /// @param _gelatoMaxGas Current gelatoMaxGas /// @param _gelatoGasPrice Current gelatoGasPrice /// @return How much provider balance is required for executor to submit exec tx function minExecProviderFunds( uint256 _gelatoMaxGas, uint256 _gelatoGasPrice ) external view returns (uint256); /// @notice Check if provider has sufficient funds for executor to call exec /// @param _provider Address of provider /// @param _gelatoMaxGas Currentt gelatoMaxGas /// @param _gelatoGasPrice Current gelatoGasPrice /// @return Whether provider is liquid (true) or not (false) function isProviderLiquid( address _provider, uint256 _gelatoMaxGas, uint256 _gelatoGasPrice ) external view returns (bool); // Executor Stake /// @notice Get balance of executor /// @param _executor Address of executor /// @return Executor Balance function executorStake(address _executor) external view returns (uint256); /// @notice Check if executor has sufficient stake on gelato /// @param _executor Address of provider /// @return Whether executor has sufficient stake (true) or not (false) function isExecutorMinStaked(address _executor) external view returns (bool); /// @notice Get executor of provider /// @param _provider Address of provider /// @return Provider's executor function executorByProvider(address _provider) external view returns (address); /// @notice Get num. of providers which haved assigned an executor /// @param _executor Address of executor /// @return Count of how many providers assigned the executor function executorProvidersCount(address _executor) external view returns (uint256); /// @notice Check if executor has one or more providers assigned /// @param _executor Address of provider /// @return Where 1 or more providers have assigned the executor function isExecutorAssigned(address _executor) external view returns (bool); // Task Spec and Gas Price Ceil /// @notice The maximum gas price the transaction will be executed with /// @param _provider Address of provider /// @param _taskSpecHash Hash of provider TaskSpec /// @return Max gas price an executor will execute the transaction with in wei function taskSpecGasPriceCeil(address _provider, bytes32 _taskSpecHash) external view returns (uint256); /// @notice Returns the hash of the formatted TaskSpec. /// @dev The action.data field of each Action is stripped before hashing. /// @param _taskSpec TaskSpec /// @return keccak256 hash of encoded condition address and Action List function hashTaskSpec(TaskSpec calldata _taskSpec) external view returns (bytes32); /// @notice Constant used to specify the highest gas price available in the gelato system /// @dev Input 0 as gasPriceCeil and it will be assigned to NO_CEIL /// @return MAX_UINT function NO_CEIL() external pure returns (uint256); // Providers' Module Getters /// @notice Check if inputted module is whitelisted by provider /// @param _provider Address of provider /// @param _module Address of module /// @return true if it is whitelisted function isModuleProvided(address _provider, IGelatoProviderModule _module) external view returns (bool); /// @notice Get all whitelisted provider modules from a given provider /// @param _provider Address of provider /// @return List of whitelisted provider modules function providerModules(address _provider) external view returns (IGelatoProviderModule[] memory); // State Writing /// @notice Assign new gas price oracle /// @dev Only callable by sysAdmin /// @param _newOracle Address of new oracle function setGelatoGasPriceOracle(address _newOracle) external; /// @notice Assign new gas price oracle /// @dev Only callable by sysAdmin /// @param _requestData The encoded payload for the staticcall to the oracle. function setOracleRequestData(bytes calldata _requestData) external; /// @notice Assign new maximum gas limit providers can consume in executionWrapper() /// @dev Only callable by sysAdmin /// @param _newMaxGas New maximum gas limit function setGelatoMaxGas(uint256 _newMaxGas) external; /// @notice Assign new interal gas limit requirement for exec() /// @dev Only callable by sysAdmin /// @param _newRequirement New internal gas requirement function setInternalGasRequirement(uint256 _newRequirement) external; /// @notice Assign new minimum executor stake /// @dev Only callable by sysAdmin /// @param _newMin New minimum executor stake function setMinExecutorStake(uint256 _newMin) external; /// @notice Assign new success share for executors to receive after successful execution /// @dev Only callable by sysAdmin /// @param _percentage New % success share of total gas consumed function setExecutorSuccessShare(uint256 _percentage) external; /// @notice Assign new success share for sysAdmin to receive after successful execution /// @dev Only callable by sysAdmin /// @param _percentage New % success share of total gas consumed function setSysAdminSuccessShare(uint256 _percentage) external; /// @notice Withdraw sysAdmin funds /// @dev Only callable by sysAdmin /// @param _amount Amount to withdraw /// @param _to Address to receive the funds function withdrawSysAdminFunds(uint256 _amount, address payable _to) external returns (uint256); // State Reading /// @notice Unaccounted tx overhead that will be refunded to executors function EXEC_TX_OVERHEAD() external pure returns (uint256); /// @notice Addess of current Gelato Gas Price Oracle function gelatoGasPriceOracle() external view returns (address); /// @notice Getter for oracleRequestData state variable function oracleRequestData() external view returns (bytes memory); /// @notice Gas limit an executor has to submit to get refunded even if actions revert function gelatoMaxGas() external view returns (uint256); /// @notice Internal gas limit requirements ti ensure executor payout function internalGasRequirement() external view returns (uint256); /// @notice Minimum stake required from executors function minExecutorStake() external view returns (uint256); /// @notice % Fee executors get as a reward for a successful execution function executorSuccessShare() external view returns (uint256); /// @notice Total % Fee executors and sysAdmin collectively get as a reward for a successful execution /// @dev Saves a state read function totalSuccessShare() external view returns (uint256); /// @notice Get total fee providers pay executors for a successful execution /// @param _gas Gas consumed by transaction /// @param _gasPrice Current gelato gas price function executorSuccessFee(uint256 _gas, uint256 _gasPrice) external view returns (uint256); /// @notice % Fee sysAdmin gets as a reward for a successful execution function sysAdminSuccessShare() external view returns (uint256); /// @notice Get total fee providers pay sysAdmin for a successful execution /// @param _gas Gas consumed by transaction /// @param _gasPrice Current gelato gas price function sysAdminSuccessFee(uint256 _gas, uint256 _gasPrice) external view returns (uint256); /// @notice Get sysAdminds funds function sysAdminFunds() external view returns (uint256); } /// @title IGelatoCondition - solidity interface of GelatoConditionsStandard /// @notice all the APIs of GelatoConditionsStandard /// @dev all the APIs are implemented inside GelatoConditionsStandard interface IGelatoCondition { /// @notice GelatoCore calls this to verify securely the specified Condition securely /// @dev Be careful only to encode a Task's condition.data as is and not with the /// "ok" selector or _taskReceiptId, since those two things are handled by GelatoCore. /// @param _taskReceiptId This is passed by GelatoCore so we can rely on it as a secure /// source of Task identification. /// @param _conditionData This is the Condition.data field developers must encode their /// Condition's specific parameters in. /// @param _cycleId For Tasks that are executed as part of a cycle. function ok( uint256 _taskReceiptId, bytes calldata _conditionData, uint256 _cycleId ) external view returns (string memory); } /// @notice all the APIs and events of GelatoActionsStandard /// @dev all the APIs are implemented inside GelatoActionsStandard interface IGelatoAction { /// @notice Providers can use this for pre-execution sanity checks, to prevent reverts. /// @dev GelatoCore checks this in canExec and passes the parameters. /// @param _taskReceiptId The id of the task from which all arguments are passed. /// @param _userProxy The userProxy of the task. Often address(this) for delegatecalls. /// @param _actionData The encoded payload to be used in the Action. /// @param _dataFlow The dataFlow of the Action. /// @param _value A special param for ETH sending Actions. If the Action sends ETH /// in its Action function implementation, one should expect msg.value therein to be /// equal to _value. So Providers can check in termsOk that a valid ETH value will /// be used because they also have access to the same value when encoding the /// execPayload on their ProviderModule. /// @param _cycleId For tasks that are part of a Cycle. /// @return Returns OK, if Task can be executed safely according to the Provider's /// terms laid out in this function implementation. function termsOk( uint256 _taskReceiptId, address _userProxy, bytes calldata _actionData, DataFlow _dataFlow, uint256 _value, uint256 _cycleId ) external view returns (string memory); } interface IGelatoProviderModule { /// @notice Check if provider agrees to pay for inputted task receipt /// @dev Enables arbitrary checks by provider /// @param _userProxy The smart contract account of the user who submitted the Task. /// @param _provider The account of the Provider who uses the ProviderModule. /// @param _task Gelato Task to be executed. /// @return "OK" if provider agrees function isProvided( address _userProxy, address _provider, Task calldata _task ) external view returns (string memory); /// @notice Convert action specific payload into proxy specific payload /// @dev Encoded multiple actions into a multisend /// @param _taskReceiptId Unique ID of Gelato Task to be executed. /// @param _userProxy The smart contract account of the user who submitted the Task. /// @param _provider The account of the Provider who uses the ProviderModule. /// @param _task Gelato Task to be executed. /// @param _cycleId For Tasks that form part of a cycle/chain. /// @return Encoded payload that will be used for low-level .call on user proxy /// @return checkReturndata if true, fwd returndata from userProxy.call to ProviderModule function execPayload( uint256 _taskReceiptId, address _userProxy, address _provider, Task calldata _task, uint256 _cycleId ) external view returns (bytes memory, bool checkReturndata); /// @notice Called by GelatoCore.exec to verifiy that no revert happend on userProxy /// @dev If a caught revert is detected, this fn should revert with the detected error /// @param _proxyReturndata Data from GelatoCore._exec.userProxy.call(execPayload) function execRevertCheck(bytes calldata _proxyReturndata) external pure; } // "SPDX-License-Identifier: UNLICENSED" pragma solidity 0.8.0; library GelatoBytes { function calldataSliceSelector(bytes calldata _bytes) internal pure returns (bytes4 selector) { selector = _bytes[0] | (bytes4(_bytes[1]) >> 8) | (bytes4(_bytes[2]) >> 16) | (bytes4(_bytes[3]) >> 24); } function memorySliceSelector(bytes memory _bytes) internal pure returns (bytes4 selector) { selector = _bytes[0] | (bytes4(_bytes[1]) >> 8) | (bytes4(_bytes[2]) >> 16) | (bytes4(_bytes[3]) >> 24); } function revertWithError(bytes memory _bytes, string memory _tracingInfo) internal pure { // 68: 32-location, 32-length, 4-ErrorSelector, UTF-8 err if (_bytes.length % 32 == 4) { bytes4 selector; assembly { selector := mload(add(0x20, _bytes)) } if (selector == 0x08c379a0) { // Function selector for Error(string) assembly { _bytes := add(_bytes, 68) } revert(string(abi.encodePacked(_tracingInfo, string(_bytes)))); } else { revert( string(abi.encodePacked(_tracingInfo, "NoErrorSelector")) ); } } else { revert( string(abi.encodePacked(_tracingInfo, "UnexpectedReturndata")) ); } } function returnError(bytes memory _bytes, string memory _tracingInfo) internal pure returns (string memory) { // 68: 32-location, 32-length, 4-ErrorSelector, UTF-8 err if (_bytes.length % 32 == 4) { bytes4 selector; assembly { selector := mload(add(0x20, _bytes)) } if (selector == 0x08c379a0) { // Function selector for Error(string) assembly { _bytes := add(_bytes, 68) } return string(abi.encodePacked(_tracingInfo, string(_bytes))); } else { return string(abi.encodePacked(_tracingInfo, "NoErrorSelector")); } } else { return string(abi.encodePacked(_tracingInfo, "UnexpectedReturndata")); } } } // "SPDX-License-Identifier: UNLICENSED" pragma solidity 0.8.0; library GelatoString { function startsWithOK(string memory _str) internal pure returns (bool) { if ( bytes(_str).length >= 2 && bytes(_str)[0] == "O" && bytes(_str)[1] == "K" ) return true; return false; } function revertWithInfo(string memory _error, string memory _tracingInfo) internal pure { revert(string(abi.encodePacked(_tracingInfo, _error))); } function prefix(string memory _second, string memory _first) internal pure returns (string memory) { return string(abi.encodePacked(_first, _second)); } function suffix(string memory _first, string memory _second) internal pure returns (string memory) { return string(abi.encodePacked(_first, _second)); } } // 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 on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require( set._values.length > index, "EnumerableSet: index out of bounds" ); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } }
all the APIs and events of GelatoActionsStandard all the APIs are implemented inside GelatoActionsStandard
interface IGelatoAction { function termsOk( uint256 _taskReceiptId, address _userProxy, bytes calldata _actionData, DataFlow _dataFlow, uint256 _value, uint256 _cycleId ) external view returns (string memory); } }
5,783,545
./full_match/42/0xCCA4ab1723cDF01bbD89A1991B63d92Dc1eF9964/sources/contracts/FundMe.sol
( uint80 roundID, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound
function getPrice() public view returns(uint256){ AggregatorV3Interface priceFeed = AggregatorV3Interface(0x9326BFA02ADD2366b30bacB125260Af641031331); (,int256 answer,,,) = priceFeed.latestRoundData(); return uint256(answer * 1e10); }
9,581,306
./full_match/80001/0xBd99517e1994226FB8124D37087A0b835829D593/sources/contracts/Portfolio.sol
Write function to add skill
function addSkill(string memory name, uint _rating) public onlyOwner { require(bytes(name).length > 0, "Name cannot be empty"); require( _rating >= 1 && _rating <= 10, "Rating must be between 1 and 10" ); _skills.push(Skill(name, _rating)); }
5,572,182
// SPDX-License-Identifier: MIT // @unsupported: ovm pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_L1CrossDomainMessenger } from "../../../iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol"; import { iOVM_L1MultiMessageRelayer } from "../../../iOVM/bridge/messaging/iOVM_L1MultiMessageRelayer.sol"; /* Library Imports */ import { Lib_AddressResolver } from "../../../libraries/resolver/Lib_AddressResolver.sol"; /** * @title OVM_L1MultiMessageRelayer * @dev The L1 Multi-Message Relayer contract is a gas efficiency optimization which enables the * relayer to submit multiple messages in a single transaction to be relayed by the L1 Cross Domain * Message Sender. * * Compiler used: solc * Runtime target: EVM */ contract OVM_L1MultiMessageRelayer is iOVM_L1MultiMessageRelayer, Lib_AddressResolver { /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Address Manager. */ constructor( address _libAddressManager ) Lib_AddressResolver(_libAddressManager) {} /********************** * Function Modifiers * **********************/ modifier onlyBatchRelayer() { require( msg.sender == resolve("OVM_L2BatchMessageRelayer"), // solhint-disable-next-line max-line-length "OVM_L1MultiMessageRelayer: Function can only be called by the OVM_L2BatchMessageRelayer" ); _; } /******************** * Public Functions * ********************/ /** * @notice Forwards multiple cross domain messages to the L1 Cross Domain Messenger for relaying * @param _messages An array of L2 to L1 messages */ function batchRelayMessages( L2ToL1Message[] calldata _messages ) override external onlyBatchRelayer { iOVM_L1CrossDomainMessenger messenger = iOVM_L1CrossDomainMessenger( resolve("Proxy__OVM_L1CrossDomainMessenger") ); for (uint256 i = 0; i < _messages.length; i++) { L2ToL1Message memory message = _messages[i]; messenger.relayMessage( message.target, message.sender, message.message, message.messageNonce, message.proof ); } } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_OVMCodec } from "../../../libraries/codec/Lib_OVMCodec.sol"; /* Interface Imports */ import { iOVM_CrossDomainMessenger } from "./iOVM_CrossDomainMessenger.sol"; /** * @title iOVM_L1CrossDomainMessenger */ interface iOVM_L1CrossDomainMessenger is iOVM_CrossDomainMessenger { /******************* * Data Structures * *******************/ struct L2MessageInclusionProof { bytes32 stateRoot; Lib_OVMCodec.ChainBatchHeader stateRootBatchHeader; Lib_OVMCodec.ChainInclusionProof stateRootProof; bytes stateTrieWitness; bytes storageTrieWitness; } /******************** * Public Functions * ********************/ /** * Relays a cross domain message to a contract. * @param _target Target contract address. * @param _sender Message sender address. * @param _message Message to send to the target. * @param _messageNonce Nonce for the provided message. * @param _proof Inclusion proof for the given message. */ function relayMessage( address _target, address _sender, bytes memory _message, uint256 _messageNonce, L2MessageInclusionProof memory _proof ) external; /** * Replays a cross domain message to the target messenger. * @param _target Target contract address. * @param _sender Original sender address. * @param _message Message to send to the target. * @param _queueIndex CTC Queue index for the message to replay. * @param _gasLimit Gas limit for the provided message. */ function replayMessage( address _target, address _sender, bytes memory _message, uint256 _queueIndex, uint32 _gasLimit ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Interface Imports */ import { iOVM_L1CrossDomainMessenger } from "../../../iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol"; interface iOVM_L1MultiMessageRelayer { struct L2ToL1Message { address target; address sender; bytes message; uint256 messageNonce; iOVM_L1CrossDomainMessenger.L2MessageInclusionProof proof; } function batchRelayMessages(L2ToL1Message[] calldata _messages) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* Library Imports */ import { Lib_AddressManager } from "./Lib_AddressManager.sol"; /** * @title Lib_AddressResolver */ abstract contract Lib_AddressResolver { /************* * Variables * *************/ Lib_AddressManager public libAddressManager; /*************** * Constructor * ***************/ /** * @param _libAddressManager Address of the Lib_AddressManager. */ constructor( address _libAddressManager ) { libAddressManager = Lib_AddressManager(_libAddressManager); } /******************** * Public Functions * ********************/ /** * Resolves the address associated with a given name. * @param _name Name to resolve an address for. * @return Address associated with the given name. */ function resolve( string memory _name ) public view returns ( address ) { return libAddressManager.getAddress(_name); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /* Library Imports */ import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol"; import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol"; import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol"; import { Lib_Bytes32Utils } from "../utils/Lib_Bytes32Utils.sol"; /** * @title Lib_OVMCodec */ library Lib_OVMCodec { /********* * Enums * *********/ enum QueueOrigin { SEQUENCER_QUEUE, L1TOL2_QUEUE } /*********** * Structs * ***********/ struct Account { uint256 nonce; uint256 balance; bytes32 storageRoot; bytes32 codeHash; address ethAddress; bool isFresh; } struct EVMAccount { uint256 nonce; uint256 balance; bytes32 storageRoot; bytes32 codeHash; } struct ChainBatchHeader { uint256 batchIndex; bytes32 batchRoot; uint256 batchSize; uint256 prevTotalElements; bytes extraData; } struct ChainInclusionProof { uint256 index; bytes32[] siblings; } struct Transaction { uint256 timestamp; uint256 blockNumber; QueueOrigin l1QueueOrigin; address l1TxOrigin; address entrypoint; uint256 gasLimit; bytes data; } struct TransactionChainElement { bool isSequenced; uint256 queueIndex; // QUEUED TX ONLY uint256 timestamp; // SEQUENCER TX ONLY uint256 blockNumber; // SEQUENCER TX ONLY bytes txData; // SEQUENCER TX ONLY } struct QueueElement { bytes32 transactionHash; uint40 timestamp; uint40 blockNumber; } /********************** * Internal Functions * **********************/ /** * Encodes a standard OVM transaction. * @param _transaction OVM transaction to encode. * @return Encoded transaction bytes. */ function encodeTransaction( Transaction memory _transaction ) internal pure returns ( bytes memory ) { return abi.encodePacked( _transaction.timestamp, _transaction.blockNumber, _transaction.l1QueueOrigin, _transaction.l1TxOrigin, _transaction.entrypoint, _transaction.gasLimit, _transaction.data ); } /** * Hashes a standard OVM transaction. * @param _transaction OVM transaction to encode. * @return Hashed transaction */ function hashTransaction( Transaction memory _transaction ) internal pure returns ( bytes32 ) { return keccak256(encodeTransaction(_transaction)); } /** * Converts an OVM account to an EVM account. * @param _in OVM account to convert. * @return Converted EVM account. */ function toEVMAccount( Account memory _in ) internal pure returns ( EVMAccount memory ) { return EVMAccount({ nonce: _in.nonce, balance: _in.balance, storageRoot: _in.storageRoot, codeHash: _in.codeHash }); } /** * @notice RLP-encodes an account state struct. * @param _account Account state struct. * @return RLP-encoded account state. */ function encodeEVMAccount( EVMAccount memory _account ) internal pure returns ( bytes memory ) { bytes[] memory raw = new bytes[](4); // Unfortunately we can't create this array outright because // Lib_RLPWriter.writeList will reject fixed-size arrays. Assigning // index-by-index circumvents this issue. raw[0] = Lib_RLPWriter.writeBytes( Lib_Bytes32Utils.removeLeadingZeros( bytes32(_account.nonce) ) ); raw[1] = Lib_RLPWriter.writeBytes( Lib_Bytes32Utils.removeLeadingZeros( bytes32(_account.balance) ) ); raw[2] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.storageRoot)); raw[3] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.codeHash)); return Lib_RLPWriter.writeList(raw); } /** * @notice Decodes an RLP-encoded account state into a useful struct. * @param _encoded RLP-encoded account state. * @return Account state struct. */ function decodeEVMAccount( bytes memory _encoded ) internal pure returns ( EVMAccount memory ) { Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded); return EVMAccount({ nonce: Lib_RLPReader.readUint256(accountState[0]), balance: Lib_RLPReader.readUint256(accountState[1]), storageRoot: Lib_RLPReader.readBytes32(accountState[2]), codeHash: Lib_RLPReader.readBytes32(accountState[3]) }); } /** * Calculates a hash for a given batch header. * @param _batchHeader Header to hash. * @return Hash of the header. */ function hashBatchHeader( Lib_OVMCodec.ChainBatchHeader memory _batchHeader ) internal pure returns ( bytes32 ) { return keccak256( abi.encode( _batchHeader.batchRoot, _batchHeader.batchSize, _batchHeader.prevTotalElements, _batchHeader.extraData ) ); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /** * @title iOVM_CrossDomainMessenger */ interface iOVM_CrossDomainMessenger { /********** * Events * **********/ event SentMessage(bytes message); event RelayedMessage(bytes32 msgHash); event FailedRelayedMessage(bytes32 msgHash); /************* * Variables * *************/ function xDomainMessageSender() external view returns (address); /******************** * Public Functions * ********************/ /** * Sends a cross domain message to the target messenger. * @param _target Target contract address. * @param _message Message to send to the target. * @param _gasLimit Gas limit for the provided message. */ function sendMessage( address _target, bytes calldata _message, uint32 _gasLimit ) external; } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_RLPReader * @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]). */ library Lib_RLPReader { /************* * Constants * *************/ uint256 constant internal MAX_LIST_LENGTH = 32; /********* * Enums * *********/ enum RLPItemType { DATA_ITEM, LIST_ITEM } /*********** * Structs * ***********/ struct RLPItem { uint256 length; uint256 ptr; } /********************** * Internal Functions * **********************/ /** * Converts bytes to a reference to memory position and length. * @param _in Input bytes to convert. * @return Output memory reference. */ function toRLPItem( bytes memory _in ) internal pure returns ( RLPItem memory ) { uint256 ptr; assembly { ptr := add(_in, 32) } return RLPItem({ length: _in.length, ptr: ptr }); } /** * Reads an RLP list value into a list of RLP items. * @param _in RLP list value. * @return Decoded RLP list items. */ function readList( RLPItem memory _in ) internal pure returns ( RLPItem[] memory ) { ( uint256 listOffset, , RLPItemType itemType ) = _decodeLength(_in); require( itemType == RLPItemType.LIST_ITEM, "Invalid RLP list value." ); // Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by // writing to the length. Since we can't know the number of RLP items without looping over // the entire input, we'd have to loop twice to accurately size this array. It's easier to // simply set a reasonable maximum list length and decrease the size before we finish. RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH); uint256 itemCount = 0; uint256 offset = listOffset; while (offset < _in.length) { require( itemCount < MAX_LIST_LENGTH, "Provided RLP list exceeds max list length." ); ( uint256 itemOffset, uint256 itemLength, ) = _decodeLength(RLPItem({ length: _in.length - offset, ptr: _in.ptr + offset })); out[itemCount] = RLPItem({ length: itemLength + itemOffset, ptr: _in.ptr + offset }); itemCount += 1; offset += itemOffset + itemLength; } // Decrease the array size to match the actual item count. assembly { mstore(out, itemCount) } return out; } /** * Reads an RLP list value into a list of RLP items. * @param _in RLP list value. * @return Decoded RLP list items. */ function readList( bytes memory _in ) internal pure returns ( RLPItem[] memory ) { return readList( toRLPItem(_in) ); } /** * Reads an RLP bytes value into bytes. * @param _in RLP bytes value. * @return Decoded bytes. */ function readBytes( RLPItem memory _in ) internal pure returns ( bytes memory ) { ( uint256 itemOffset, uint256 itemLength, RLPItemType itemType ) = _decodeLength(_in); require( itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes value." ); return _copy(_in.ptr, itemOffset, itemLength); } /** * Reads an RLP bytes value into bytes. * @param _in RLP bytes value. * @return Decoded bytes. */ function readBytes( bytes memory _in ) internal pure returns ( bytes memory ) { return readBytes( toRLPItem(_in) ); } /** * Reads an RLP string value into a string. * @param _in RLP string value. * @return Decoded string. */ function readString( RLPItem memory _in ) internal pure returns ( string memory ) { return string(readBytes(_in)); } /** * Reads an RLP string value into a string. * @param _in RLP string value. * @return Decoded string. */ function readString( bytes memory _in ) internal pure returns ( string memory ) { return readString( toRLPItem(_in) ); } /** * Reads an RLP bytes32 value into a bytes32. * @param _in RLP bytes32 value. * @return Decoded bytes32. */ function readBytes32( RLPItem memory _in ) internal pure returns ( bytes32 ) { require( _in.length <= 33, "Invalid RLP bytes32 value." ); ( uint256 itemOffset, uint256 itemLength, RLPItemType itemType ) = _decodeLength(_in); require( itemType == RLPItemType.DATA_ITEM, "Invalid RLP bytes32 value." ); uint256 ptr = _in.ptr + itemOffset; bytes32 out; assembly { out := mload(ptr) // Shift the bytes over to match the item size. if lt(itemLength, 32) { out := div(out, exp(256, sub(32, itemLength))) } } return out; } /** * Reads an RLP bytes32 value into a bytes32. * @param _in RLP bytes32 value. * @return Decoded bytes32. */ function readBytes32( bytes memory _in ) internal pure returns ( bytes32 ) { return readBytes32( toRLPItem(_in) ); } /** * Reads an RLP uint256 value into a uint256. * @param _in RLP uint256 value. * @return Decoded uint256. */ function readUint256( RLPItem memory _in ) internal pure returns ( uint256 ) { return uint256(readBytes32(_in)); } /** * Reads an RLP uint256 value into a uint256. * @param _in RLP uint256 value. * @return Decoded uint256. */ function readUint256( bytes memory _in ) internal pure returns ( uint256 ) { return readUint256( toRLPItem(_in) ); } /** * Reads an RLP bool value into a bool. * @param _in RLP bool value. * @return Decoded bool. */ function readBool( RLPItem memory _in ) internal pure returns ( bool ) { require( _in.length == 1, "Invalid RLP boolean value." ); uint256 ptr = _in.ptr; uint256 out; assembly { out := byte(0, mload(ptr)) } require( out == 0 || out == 1, "Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1" ); return out != 0; } /** * Reads an RLP bool value into a bool. * @param _in RLP bool value. * @return Decoded bool. */ function readBool( bytes memory _in ) internal pure returns ( bool ) { return readBool( toRLPItem(_in) ); } /** * Reads an RLP address value into a address. * @param _in RLP address value. * @return Decoded address. */ function readAddress( RLPItem memory _in ) internal pure returns ( address ) { if (_in.length == 1) { return address(0); } require( _in.length == 21, "Invalid RLP address value." ); return address(readUint256(_in)); } /** * Reads an RLP address value into a address. * @param _in RLP address value. * @return Decoded address. */ function readAddress( bytes memory _in ) internal pure returns ( address ) { return readAddress( toRLPItem(_in) ); } /** * Reads the raw bytes of an RLP item. * @param _in RLP item to read. * @return Raw RLP bytes. */ function readRawBytes( RLPItem memory _in ) internal pure returns ( bytes memory ) { return _copy(_in); } /********************* * Private Functions * *********************/ /** * Decodes the length of an RLP item. * @param _in RLP item to decode. * @return Offset of the encoded data. * @return Length of the encoded data. * @return RLP item type (LIST_ITEM or DATA_ITEM). */ function _decodeLength( RLPItem memory _in ) private pure returns ( uint256, uint256, RLPItemType ) { require( _in.length > 0, "RLP item cannot be null." ); uint256 ptr = _in.ptr; uint256 prefix; assembly { prefix := byte(0, mload(ptr)) } if (prefix <= 0x7f) { // Single byte. return (0, 1, RLPItemType.DATA_ITEM); } else if (prefix <= 0xb7) { // Short string. uint256 strLen = prefix - 0x80; require( _in.length > strLen, "Invalid RLP short string." ); return (1, strLen, RLPItemType.DATA_ITEM); } else if (prefix <= 0xbf) { // Long string. uint256 lenOfStrLen = prefix - 0xb7; require( _in.length > lenOfStrLen, "Invalid RLP long string length." ); uint256 strLen; assembly { // Pick out the string length. strLen := div( mload(add(ptr, 1)), exp(256, sub(32, lenOfStrLen)) ) } require( _in.length > lenOfStrLen + strLen, "Invalid RLP long string." ); return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM); } else if (prefix <= 0xf7) { // Short list. uint256 listLen = prefix - 0xc0; require( _in.length > listLen, "Invalid RLP short list." ); return (1, listLen, RLPItemType.LIST_ITEM); } else { // Long list. uint256 lenOfListLen = prefix - 0xf7; require( _in.length > lenOfListLen, "Invalid RLP long list length." ); uint256 listLen; assembly { // Pick out the list length. listLen := div( mload(add(ptr, 1)), exp(256, sub(32, lenOfListLen)) ) } require( _in.length > lenOfListLen + listLen, "Invalid RLP long list." ); return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM); } } /** * Copies the bytes from a memory location. * @param _src Pointer to the location to read from. * @param _offset Offset to start reading from. * @param _length Number of bytes to read. * @return Copied bytes. */ function _copy( uint256 _src, uint256 _offset, uint256 _length ) private pure returns ( bytes memory ) { bytes memory out = new bytes(_length); if (out.length == 0) { return out; } uint256 src = _src + _offset; uint256 dest; assembly { dest := add(out, 32) } // Copy over as many complete words as we can. for (uint256 i = 0; i < _length / 32; i++) { assembly { mstore(dest, mload(src)) } src += 32; dest += 32; } // Pick out the remaining bytes. uint256 mask = 256 ** (32 - (_length % 32)) - 1; assembly { mstore( dest, or( and(mload(src), not(mask)), and(mload(dest), mask) ) ) } return out; } /** * Copies an RLP item into bytes. * @param _in RLP item to copy. * @return Copied bytes. */ function _copy( RLPItem memory _in ) private pure returns ( bytes memory ) { return _copy(_in.ptr, 0, _in.length); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; pragma experimental ABIEncoderV2; /** * @title Lib_RLPWriter * @author Bakaoh (with modifications) */ library Lib_RLPWriter { /********************** * Internal Functions * **********************/ /** * RLP encodes a byte string. * @param _in The byte string to encode. * @return The RLP encoded string in bytes. */ function writeBytes( bytes memory _in ) internal pure returns ( bytes memory ) { bytes memory encoded; if (_in.length == 1 && uint8(_in[0]) < 128) { encoded = _in; } else { encoded = abi.encodePacked(_writeLength(_in.length, 128), _in); } return encoded; } /** * RLP encodes a list of RLP encoded byte byte strings. * @param _in The list of RLP encoded byte strings. * @return The RLP encoded list of items in bytes. */ function writeList( bytes[] memory _in ) internal pure returns ( bytes memory ) { bytes memory list = _flatten(_in); return abi.encodePacked(_writeLength(list.length, 192), list); } /** * RLP encodes a string. * @param _in The string to encode. * @return The RLP encoded string in bytes. */ function writeString( string memory _in ) internal pure returns ( bytes memory ) { return writeBytes(bytes(_in)); } /** * RLP encodes an address. * @param _in The address to encode. * @return The RLP encoded address in bytes. */ function writeAddress( address _in ) internal pure returns ( bytes memory ) { return writeBytes(abi.encodePacked(_in)); } /** * RLP encodes a bytes32 value. * @param _in The bytes32 to encode. * @return _out The RLP encoded bytes32 in bytes. */ function writeBytes32( bytes32 _in ) internal pure returns ( bytes memory _out ) { return writeBytes(abi.encodePacked(_in)); } /** * RLP encodes a uint. * @param _in The uint256 to encode. * @return The RLP encoded uint256 in bytes. */ function writeUint( uint256 _in ) internal pure returns ( bytes memory ) { return writeBytes(_toBinary(_in)); } /** * RLP encodes a bool. * @param _in The bool to encode. * @return The RLP encoded bool in bytes. */ function writeBool( bool _in ) internal pure returns ( bytes memory ) { bytes memory encoded = new bytes(1); encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80)); return encoded; } /********************* * Private Functions * *********************/ /** * Encode the first byte, followed by the `len` in binary form if `length` is more than 55. * @param _len The length of the string or the payload. * @param _offset 128 if item is string, 192 if item is list. * @return RLP encoded bytes. */ function _writeLength( uint256 _len, uint256 _offset ) private pure returns ( bytes memory ) { bytes memory encoded; if (_len < 56) { encoded = new bytes(1); encoded[0] = byte(uint8(_len) + uint8(_offset)); } else { uint256 lenLen; uint256 i = 1; while (_len / i != 0) { lenLen++; i *= 256; } encoded = new bytes(lenLen + 1); encoded[0] = byte(uint8(lenLen) + uint8(_offset) + 55); for(i = 1; i <= lenLen; i++) { encoded[i] = byte(uint8((_len / (256**(lenLen-i))) % 256)); } } return encoded; } /** * Encode integer in big endian binary form with no leading zeroes. * @notice TODO: This should be optimized with assembly to save gas costs. * @param _x The integer to encode. * @return RLP encoded bytes. */ function _toBinary( uint256 _x ) private pure returns ( bytes memory ) { bytes memory b = abi.encodePacked(_x); uint256 i = 0; for (; i < 32; i++) { if (b[i] != 0) { break; } } bytes memory res = new bytes(32 - i); for (uint256 j = 0; j < res.length; j++) { res[j] = b[i++]; } return res; } /** * Copies a piece of memory to another location. * @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol. * @param _dest Destination location. * @param _src Source location. * @param _len Length of memory to copy. */ function _memcpy( uint256 _dest, uint256 _src, uint256 _len ) private pure { uint256 dest = _dest; uint256 src = _src; uint256 len = _len; for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint256 mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /** * Flattens a list of byte strings into one byte string. * @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol. * @param _list List of byte strings to flatten. * @return The flattened byte string. */ function _flatten( bytes[] memory _list ) private pure returns ( bytes memory ) { if (_list.length == 0) { return new bytes(0); } uint256 len; uint256 i = 0; for (; i < _list.length; i++) { len += _list[i].length; } bytes memory flattened = new bytes(len); uint256 flattenedPtr; assembly { flattenedPtr := add(flattened, 0x20) } for(i = 0; i < _list.length; i++) { bytes memory item = _list[i]; uint256 listPtr; assembly { listPtr := add(item, 0x20)} _memcpy(flattenedPtr, listPtr, item.length); flattenedPtr += _list[i].length; } return flattened; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_BytesUtils */ library Lib_BytesUtils { /********************** * Internal Functions * **********************/ 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 slice( bytes memory _bytes, uint256 _start ) internal pure returns ( bytes memory ) { if (_start >= _bytes.length) { return bytes(""); } return slice(_bytes, _start, _bytes.length - _start); } function toBytes32PadLeft( bytes memory _bytes ) internal pure returns ( bytes32 ) { bytes32 ret; uint256 len = _bytes.length <= 32 ? _bytes.length : 32; assembly { ret := shr(mul(sub(32, len), 8), mload(add(_bytes, 32))) } return ret; } function toBytes32( bytes memory _bytes ) internal pure returns ( bytes32 ) { if (_bytes.length < 32) { bytes32 ret; assembly { ret := mload(add(_bytes, 32)) } return ret; } return abi.decode(_bytes,(bytes32)); // will truncate if input length > 32 bytes } function toUint256( bytes memory _bytes ) internal pure returns ( uint256 ) { return uint256(toBytes32(_bytes)); } 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; } function toUint8( bytes memory _bytes, uint256 _start ) internal pure returns ( uint8 ) { require(_start + 1 >= _start, "toUint8_overflow"); require(_bytes.length >= _start + 1 , "toUint8_outOfBounds"); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } 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 toNibbles( bytes memory _bytes ) internal pure returns ( bytes memory ) { bytes memory nibbles = new bytes(_bytes.length * 2); for (uint256 i = 0; i < _bytes.length; i++) { nibbles[i * 2] = _bytes[i] >> 4; nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16); } return nibbles; } function fromNibbles( bytes memory _bytes ) internal pure returns ( bytes memory ) { bytes memory ret = new bytes(_bytes.length / 2); for (uint256 i = 0; i < ret.length; i++) { ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]); } return ret; } function equal( bytes memory _bytes, bytes memory _other ) internal pure returns ( bool ) { return keccak256(_bytes) == keccak256(_other); } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /** * @title Lib_Byte32Utils */ library Lib_Bytes32Utils { /********************** * Internal Functions * **********************/ /** * Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true." * @param _in Input bytes32 value. * @return Bytes32 as a boolean. */ function toBool( bytes32 _in ) internal pure returns ( bool ) { return _in != 0; } /** * Converts a boolean to a bytes32 value. * @param _in Input boolean value. * @return Boolean as a bytes32. */ function fromBool( bool _in ) internal pure returns ( bytes32 ) { return bytes32(uint256(_in ? 1 : 0)); } /** * Converts a bytes32 value to an address. Takes the *last* 20 bytes. * @param _in Input bytes32 value. * @return Bytes32 as an address. */ function toAddress( bytes32 _in ) internal pure returns ( address ) { return address(uint160(uint256(_in))); } /** * Converts an address to a bytes32. * @param _in Input address value. * @return Address as a bytes32. */ function fromAddress( address _in ) internal pure returns ( bytes32 ) { return bytes32(uint256(_in)); } /** * Removes the leading zeros from a bytes32 value and returns a new (smaller) bytes value. * @param _in Input bytes32 value. * @return Bytes32 without any leading zeros. */ function removeLeadingZeros( bytes32 _in ) internal pure returns ( bytes memory ) { bytes memory out; assembly { // Figure out how many leading zero bytes to remove. let shift := 0 for { let i := 0 } and(lt(i, 32), eq(byte(i, _in), 0)) { i := add(i, 1) } { shift := add(shift, 1) } // Reserve some space for our output and fix the free memory pointer. out := mload(0x40) mstore(0x40, add(out, 0x40)) // Shift the value and store it into the output bytes. mstore(add(out, 0x20), shl(mul(shift, 8), _in)) // Store the new size (with leading zero bytes removed) in the output byte size. mstore(out, sub(32, shift)) } return out; } } // SPDX-License-Identifier: MIT pragma solidity >0.5.0 <0.8.0; /* External Imports */ import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Lib_AddressManager */ contract Lib_AddressManager is Ownable { /********** * Events * **********/ event AddressSet( string indexed _name, address _newAddress, address _oldAddress ); /************* * Variables * *************/ mapping (bytes32 => address) private addresses; /******************** * Public Functions * ********************/ /** * Changes the address associated with a particular name. * @param _name String name to associate an address with. * @param _address Address to associate with the name. */ function setAddress( string memory _name, address _address ) external onlyOwner { bytes32 nameHash = _getNameHash(_name); address oldAddress = addresses[nameHash]; addresses[nameHash] = _address; emit AddressSet( _name, _address, oldAddress ); } /** * Retrieves the address associated with a given name. * @param _name Name to retrieve an address for. * @return Address associated with the given name. */ function getAddress( string memory _name ) external view returns ( address ) { return addresses[_getNameHash(_name)]; } /********************** * Internal Functions * **********************/ /** * Computes the hash of a name. * @param _name Name to compute a hash for. * @return Hash of the given name. */ function _getNameHash( string memory _name ) internal pure returns ( bytes32 ) { return keccak256(abi.encodePacked(_name)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev 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; } }
Reads an RLP bool value into a bool. _in RLP bool value. return Decoded bool./
function readBool( bytes memory _in ) internal pure returns ( bool ) { return readBool( toRLPItem(_in) ); }
83,218
./full_match/40/0xfB8eDeD3e963C1Ba0e5215DB124848400C7a69dA/sources/contracts/OmnidexBtcTlos.sol
Compounds the strategy's earnings and charges fees
function _harvest(address caller) internal whenNotPaused { if (caller != vault){ require(!Address.isContract(msg.sender), "!EOA"); } IZenMaster(chef).deposit(poolId, 0); uint256 outputBal = IERC20(charm).balanceOf(address(this)); if (outputBal > 0 ) { chargeFees(caller); addLiquidity(); } _deposit(); emit Harvest(caller); }
9,543,303
./partial_match/1/0xE26A601Dec9FCd2d1079ACdeDC5ECcaBBcC89df8/sources/Staking.sol
Allows users to compound their pending rewards by adding them to their staked amount.
function compound() external isPoolOnline(1) nonReentrant { UserInfo storage user = userInfo[msg.sender]; uint userAmnt = user.amount; require(userAmnt != 0, "No amount stacked"); require(user.amountToWithdraw == 0, "Cant compound if withdraw initiated"); UserInfo storage user = userInfo[msg.sender]; if(userAmnt != 0) { _updatePool(); uint pending = _internalPendingCalc(userAmnt, accTokenPerShare, user.rewardDebt); if(pending != 0) { totalUsersRewards += pending; poolTotalReward -= pending; uint burnAmnout = pending * optionToBurn[user.burnChosen] / 100; uint effectivePending = pending - burnAmnout; totalBurned += burnAmnout; totalUsersStake += effectivePending; user.amount = user.amount + effectivePending; user.rewardDebt = user.amount * accTokenPerShare / PRECISION_FACTOR; IBurn(address(rewardToken)).publicBurn(burnAmnout); emit Compound(msg.sender, effectivePending); } revert("nothing to compound"); } if(userAmnt != 0) { _updatePool(); uint pending = _internalPendingCalc(userAmnt, accTokenPerShare, user.rewardDebt); if(pending != 0) { totalUsersRewards += pending; poolTotalReward -= pending; uint burnAmnout = pending * optionToBurn[user.burnChosen] / 100; uint effectivePending = pending - burnAmnout; totalBurned += burnAmnout; totalUsersStake += effectivePending; user.amount = user.amount + effectivePending; user.rewardDebt = user.amount * accTokenPerShare / PRECISION_FACTOR; IBurn(address(rewardToken)).publicBurn(burnAmnout); emit Compound(msg.sender, effectivePending); } revert("nothing to compound"); } } else { }
15,767,224
./full_match/1/0x57c88D78f6D08b5c88b4A3b7BbB0C1AA34c3280A/sources/src/loan/terms/simple/loan/PWNSimpleLoan.sol
See {IERC5646-getStateFingerprint}./ The only mutable state properties are: - status, expiration Status is updated for expired loans based on block.timestamp. Others don't have to be part of the state fingerprint as it does not act as a token identification.
function getStateFingerprint(uint256 tokenId) external view virtual override returns (bytes32) { LOAN storage loan = LOANs[tokenId]; if (loan.status == 0) return bytes32(0); return keccak256(abi.encode( _getLOANStatus(tokenId), loan.expiration )); }
2,935,933
./full_match/137/0x7d561bE86eBCB1d8353f98c21Bef7232343598a8/sources/WebaverseERC721.sol
Add a collaborator to a single token (like land) tokenId ID of the token a Address to whitelist/
function addSingleCollaborator(uint256 tokenId, address a) public { require( ownerOf(tokenId) == a || isSingleCollaborator(tokenId, msg.sender), "you are not a collaborator" ); require( !isSingleCollaborator(tokenId, a), "they are already a collaborator" ); tokenIdToCollaborators[tokenId].push(a); emit SingleCollaboratorAdded(tokenId, a); }
4,669,352
./partial_match/42/0x2E8fcdF765ec0AeE0693Aa2eA1ED70457F30080b/sources/LevelsVault.sol
Returns the address of the current super admin/
function superAdmin() public view returns (address) { return _superAdmin; }
3,307,898
/** * Crowdfunding.sol v1.0.0 * * Bilal Arif - https://twitter.com/furusiyya_ * Notary Platform */ pragma solidity ^0.4.16; 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) { uint256 c = a / b; 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 { /* @title Ownable @dev The Ownable contract has an owner address, and provides basic authorization control functions, this simplifies the implementation of "user permissions". */ 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(address _owner){ owner = _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; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } } contract ReentrancyGuard { /** * @dev We use a single lock for the whole contract. */ bool private rentrancy_lock = false; /** * @dev Prevents a contract from calling itself, directly or indirectly. * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one nonReentrant function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and a `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(!rentrancy_lock); rentrancy_lock = true; _; rentrancy_lock = false; } } contract Pausable is Ownable { event Pause(bool indexed state); bool private 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 return the current state of contract */ function Paused() external constant returns(bool){ return paused; } /** * @dev called by the owner to pause or unpause, triggers stopped state * on first call and returns to normal state on second call */ function tweakState() external onlyOwner { paused = !paused; Pause(paused); } } contract Crowdfunding is Pausable, ReentrancyGuard { using SafeMath for uint256; /* the starting time of the crowdsale */ uint256 private startsAt; /* the ending time of the crowdsale */ uint256 private endsAt; /* how many token units a buyer gets per wei */ uint256 private rate; /* How many wei of funding we have received so far */ uint256 private weiRaised = 0; /* How many distinct addresses have invested */ uint256 private investorCount = 0; /* How many total investments have been made */ uint256 private totalInvestments = 0; /* Address of multiSig contract*/ address private multiSig; /* Address of tokenStore*/ address private tokenStore; /* Address of pre-ico contract*/ NotaryPlatformToken private token; /** How much ETH each address has invested to this crowdsale */ mapping (address => uint256) private investedAmountOf; /** Whitelisted addresses */ mapping (address => bool) private whiteListed; /** State machine * * - Prefunding: We have not passed start time yet * - Funding: Active crowdsale * - Closed: Funding is closed. */ enum State{PreFunding, Funding, Closed} /** * 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); // Funds transfer to other address event Transfer(address indexed receiver, uint256 weiAmount); // Crowdsale end time has been changed event EndsAtChanged(uint256 endTimestamp); event NewExchangeRate(uint256 indexed _rate); event TokenContractAddress(address indexed oldAddress,address indexed newAddress); event TokenStoreUpdated(address indexed oldAddress,address indexed newAddress); event WalletAddressUpdated(address indexed oldAddress,address indexed newAddress); event WhiteListUpdated(address indexed investor, bool status); event BonusesUpdated(address indexed investor, bool status); function Crowdfunding() Ownable(0x0587e235a5906ed8143d026dE530D77AD82F8A92) { require(earlyBirds()); // load bonuses multiSig = 0x1D1739F37a103f0D7a5f5736fEd2E77DE9863450; tokenStore = 0x244092a2FECFC48259cf810b63BA3B3c0B811DCe; token = NotaryPlatformToken(0xbA5787e07a0636A756f4B4d517b595dbA24239EF); require(token.isTokenContract()); startsAt = now + 2 minutes; endsAt = now + 31 days; rate = 2730; } /** * Allow investor to just send in money */ function() nonZero payable{ buy(msg.sender); } /** * Make an investment. * * Crowdsale must be running for one to invest. * We must have not pressed the emergency brake. * * @param receiver The Ethereum address who will receive tokens * */ function buy(address receiver) public whenNotPaused nonReentrant inState(State.Funding) nonZero payable returns(bool){ require(receiver != 0x00); require(whiteListed[receiver] || isEarlyBird(receiver)); if(investedAmountOf[msg.sender] == 0) { // A new investor investorCount++; } // count all investments totalInvestments++; // Update investor investedAmountOf[msg.sender] = investedAmountOf[msg.sender].add(msg.value); // Up total accumulated fudns weiRaised = weiRaised.add(msg.value); uint256 value = getBonus(receiver,msg.value); // calculate token amount to be transfered uint256 tokens = value.mul(rate); // Transfer NTRY tokens to receiver address if(!token.transferFrom(tokenStore,receiver,tokens)){ revert(); } // Tell us purchase was success TokenPurchase(msg.sender, receiver, msg.value, tokens); // Pocket the money forwardFunds(); return true; } // send ether to the fund collection wallet function forwardFunds() internal { multiSig.transfer(msg.value); } // getters, constant functions /** * @return address of multisignature wallet */ function multiSigAddress() external constant returns(address){ return multiSig; } /** * @return address of Notary Platform token */ function tokenContractAddress() external constant returns(address){ return token; } /** * @return address of NTRY tokens owner */ function tokenStoreAddress() external constant returns(address){ return tokenStore; } /** * @return startDate Crowdsale opening date */ function fundingStartAt() external constant returns(uint256 ){ return startsAt; } /** * @return endDate Crowdsale closing date */ function fundingEndsAt() external constant returns(uint256){ return endsAt; } /** * @return investors Total of distinct investors */ function distinctInvestors() external constant returns(uint256){ return investorCount; } /** * @return investments Crowdsale closing date */ function investments() external constant returns(uint256){ return totalInvestments; } /** * @param _addr Address of investor * @return Number of ethers invested by investor */ function investedAmoun(address _addr) external constant returns(uint256){ require(_addr != 0x00); return investedAmountOf[_addr]; } /** * @return total of amount of wie collected by the contract */ function fundingRaised() external constant returns (uint256){ return weiRaised; } /** * @return exchage rate of ethers to NTRY tokens */ function exchnageRate() external constant returns (uint256){ return rate; } /** * @return the status of the contract if it is allowed to participate. */ function isWhiteListed(address _address) external constant returns(bool){ require(_address != 0x00); return whiteListed[_address]; } /** * Crowdfund state machine management. * * We make it a function and do not assign the result to a variable, so there is no chance of the variable being stale. */ function getState() public constant returns (State) { if (now < startsAt) return State.PreFunding; else if (now <= endsAt) return State.Funding; else if (now > endsAt) return State.Closed; } // Setters, onlyOwner functions /** * @param _newAddress is address of multisignature wallet * @return true for case of success */ function updateMultiSig(address _newAddress) external onlyOwner returns(bool){ require(_newAddress != 0x00); WalletAddressUpdated(multiSig,_newAddress); multiSig = _newAddress; return true; } /** * @param _newAddress is address of NTRY token contract * @return true for case of success */ function updateTokenContractAddr(address _newAddress) external onlyOwner returns(bool){ require(_newAddress != 0x00); TokenContractAddress(token,_newAddress); token = NotaryPlatformToken(_newAddress); return true; } /** * @param _newAddress is address of NTRY tokens owner * @return true for case of success */ function updateTokenStore(address _newAddress) external onlyOwner returns(bool){ require(_newAddress != 0x00); TokenStoreUpdated(tokenStore,_newAddress); tokenStore = _newAddress; return true; } /** * Allow crowdsale owner to close early or extend the crowdsale. * * This is useful e.g. for a manual soft cap implementation: * - after X amount is reached determine manual closing * * This may put the crowdsale to an invalid state, * but we trust owners know what they are doing. * */ function updateEndsAt(uint256 _endsAt) external onlyOwner { // Don't change past require(_endsAt > now); endsAt = _endsAt; EndsAtChanged(_endsAt); } /** * Allow crowdsale owner to change exchange rate. */ function updateExchangeRate(uint256 _newRate) external onlyOwner { // Don't change past require(_newRate > 0); rate = _newRate; NewExchangeRate(_newRate); } function updateWhiteList(address _address,bool _status) external onlyOwner returns(bool){ require(_address != 0x00); whiteListed[_address] = _status; WhiteListUpdated(_address, _status); return true; } /** Interface marker. */ function isCrowdsale() external constant returns (bool) { return true; } // // Modifiers // /** Modifier allowing execution only if the crowdsale is currently running. */ modifier inState(State state) { require(getState() == state); _; } /** Modifier allowing execution only if received value is greater than zero */ modifier nonZero(){ require(msg.value >= 75000000000000000); _; } //////////////////////////////////// Bonuses //////////////////////////////// mapping (address => bool) private bonuses; function earlyBirds() private returns(bool){ bonuses[0x017ABCC1012A7FfA811bBe4a26804f9DDac1Af4D] = true; bonuses[0x1156ABCBA63ACC64162b0bbf67726a3E5eA1E157] = true; bonuses[0xEAC8483261078517528DE64956dBD405f631265c] = true; bonuses[0xB0b0D639b612937D50dd26eA6dc668e7AE51642A] = true; bonuses[0x417535DEF791d7BBFBC97b0f743a4Da67fD9eC3B] = true; bonuses[0x6723f81CDc9a5D5ef2Fe1bFbEdb4f83Bd017D3dC] = true; bonuses[0xb9Bd4f154Bb5F2BE5E7Db0357C54720c7f35405d] = true; bonuses[0x21CA5617f0cd02f13075C7c22f7231D061F09189] = true; bonuses[0x0a6Cd7e558c69baF7388bb0B3432E29Ecc29ac55] = true; bonuses[0x6a7f63709422A986A953904c64F10D945c8AfBA1] = true; bonuses[0x7E046CB5cE19De94b2D0966B04bD8EF90cDC35d3] = true; bonuses[0x1C3118b84988f42007c548e62DFF47A12c955886] = true; bonuses[0x7736154662ba56C57B2Be628Fe0e44A609d33Dfb] = true; bonuses[0xCcC8d4410a825F3644D3a5BBC0E9dF4ac6B491B3] = true; bonuses[0x9Eff6628545E1475C73dF7B72978C2dF90eDFeeD] = true; bonuses[0x235377dFB1Da49e39692Ac2635ef091c1b1cF63A] = true; bonuses[0x6a8d793026BeBaef1a57e3802DD4bB6B1C844755] = true; bonuses[0x26c32811447c8D0878b2daE7F4538AE32de82d57] = true; bonuses[0x9CEdb0e60B3C2C1cd9A2ee2E18FD3f68870AF230] = true; bonuses[0x28E102d747dF8Ae2cBBD0266911eFB609986515d] = true; bonuses[0x5b35061Cc9891c3616Ea05d1423e4CbCfdDF1829] = true; bonuses[0x47f2404fa0da21Af5b49F8E011DF851B69C24Aa4] = true; bonuses[0x046ec2a3a16e76d5dFb0CFD0BF75C7CA6EB8A4A2] = true; bonuses[0x01eD3975993c8BebfF2fb6a7472679C6F7b408Fb] = true; bonuses[0x011afc4522663a310AF1b72C5853258CCb2C8f80] = true; bonuses[0x3A167819Fd49F3021b91D840a03f4205413e316B] = true; bonuses[0xd895E6E5E0a13EC2A16e7bdDD6C1151B01128488] = true; bonuses[0xE5d4AaFC54CF15051BBE0bA11f65dE4f4Ccedbc0] = true; bonuses[0x21C4ff1738940B3A4216D686f2e63C8dbcb7DC44] = true; bonuses[0x196a484dB36D2F2049559551c182209143Db4606] = true; bonuses[0x001E0d294383d5b4136476648aCc8D04a6461Ae3] = true; bonuses[0x2052004ee9C9a923393a0062748223C1c76a7b59] = true; bonuses[0x80844Fb6785c1EaB7671584E73b0a2363599CB2F] = true; bonuses[0x526127775D489Af1d7e24bF4e7A8161088Fb90ff] = true; bonuses[0xD4340FeF5D32F2754A67bF42a44f4CEc14540606] = true; bonuses[0x51A51933721E4ADA68F8C0C36Ca6E37914A8c609] = true; bonuses[0xD0780AB2AA7309E139A1513c49fB2127DdC30D3d] = true; bonuses[0xE4AFF5ECB1c686F56C16f7dbd5d6a8Da9E200ab7] = true; bonuses[0x04bC746A174F53A3e1b5776d5A28f3421A8aE4d0] = true; bonuses[0x0D5f69C67DAE06ce606246A8bd88B552d1DdE140] = true; bonuses[0x8854f86F4fBd88C4F16c4F3d5A5500de6d082AdC] = true; bonuses[0x73c8711F2653749DdEFd7d14Ab84b0c4419B91A5] = true; bonuses[0xb8B0eb45463d0CBc85423120bCf57B3283D68D42] = true; bonuses[0x7924c67c07376cf7C4473D27BeE92FE82DFD26c5] = true; bonuses[0xa6A14A81eC752e0ed5391A22818F44aA240FFBB1] = true; bonuses[0xdF88295a162671EFC14f3276A467d31a5AFb63AC] = true; bonuses[0xC1c113c60ebf7d92A3D78ff7122435A1e307cE05] = true; bonuses[0x1EAaD141CaBA0C85EB28E0172a30dd8561dde030] = true; bonuses[0xDE3270049C833fF2A52F18C7718227eb36a92323] = true; bonuses[0x2348f7A9313B33Db329182f4FA78Bc0f94d2F040] = true; bonuses[0x07c9CC6C24aBDdaB4a7aD82c813b059DD04a7F07] = true; bonuses[0xd45BF2dEBD1C4196158DcB177D1Ae910949DC00A] = true; bonuses[0xD1F3A1A16F4ab35e5e795Ce3f49Ee2DfF2dD683B] = true; bonuses[0x6D567fa2031D42905c40a7E9CFF6c30b8DA4abf6] = true; bonuses[0x4aF3b3947D4b4323C241c99eB7FD3ddcAbaef0d7] = true; bonuses[0x386167E3c00AAfd9f83a89c05E0fB7e1c2720095] = true; bonuses[0x916F356Ccf821be928201505c59a44891168DC08] = true; bonuses[0x47cb69881e03213D1EC6e80FCD375bD167336621] = true; bonuses[0x36cFB5A6be6b130CfcEb934d3Ca72c1D72c3A7D8] = true; bonuses[0x1b29291cF6a57EE008b45f529210d6D5c5f19D91] = true; bonuses[0xe6D0Bb9FBb78F10a111bc345058a9a90265622F3] = true; bonuses[0x3e83Fc87256142dD2FDEeDc49980f4F9Be9BB1FB] = true; bonuses[0xf360b24a530d29C96a26C2E34C0DAbCAB12639F4] = true; bonuses[0xF49C6e7e36A714Bbc162E31cA23a04E44DcaF567] = true; bonuses[0xa2Ac3516A33e990C8A3ce7845749BaB7C63128C0] = true; bonuses[0xdC5984a2673c46B68036076026810FfDfFB695B8] = true; bonuses[0xfFfdFaeF43029d6C749CEFf04f65187Bd50A5311] = true; bonuses[0xe752737DD519715ab0FA9538949D7F9249c7c168] = true; bonuses[0x580d0572DBD9F27C75d5FcC88a6075cE32924C2B] = true; bonuses[0x6ee541808C463116A82D76649dA0502935fA8D08] = true; bonuses[0xA68B4208E0b7aACef5e7cF8d6691d5B973bAd119] = true; bonuses[0x737069E6f9F02062F4D651C5C8C03D50F6Fc99C6] = true; bonuses[0x00550191FAc279632f5Ff23d06Cb317139543840] = true; bonuses[0x9e6EB194E26649B1F17e5BafBcAbE26B5db433E2] = true; bonuses[0x186a813b9fB34d727fE1ED2DFd40D87d1c8431a6] = true; bonuses[0x7De8D937a3b2b254199F5D3B38F14c0D0f009Ff8] = true; bonuses[0x8f066F3D9f75789d9f126Fdd7cFBcC38a768985D] = true; bonuses[0x7D1826Fa8C84608a6C2d5a61Ed5A433D020AA543] = true; return true; } function updateBonuses(address _address,bool _status) external onlyOwner returns(bool){ require(_address != 0x00); bonuses[_address] = _status; BonusesUpdated(_address,_status); return true; } function getBonus(address _address,uint256 _value) private returns(uint256){ if(bonuses[_address]){ // 10% bonus if(_value > 166 ether){ return (_value*11)/10; } // 7.5% bonus if(_value > 33 ether){ return (_value*43)/40; } return (_value*21)/20; } return _value; } function isEarlyBird(address _address) constant returns(bool){ require(_address != 0x00); return bonuses[_address]; } } contract NotaryPlatformToken{ function isTokenContract() returns (bool); function transferFrom(address _from, address _to, uint256 _value) returns (bool); }
return investors Total of distinct investors/
function distinctInvestors() external constant returns(uint256){ return investorCount; }
933,816
pragma solidity ^0.4.24; 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); } /* Begin solidity-cborutils https://github.com/smartcontractkit/solidity-cborutils MIT License Copyright (c) 2018 SmartContract ChainLink, 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. */ library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory buf, uint _capacity) internal pure { uint capacity = _capacity; if(capacity % 32 != 0) capacity += 32 - (capacity % 32); // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory buf, uint capacity) private pure { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private pure returns(uint) { if(a > b) { return a; } return b; } /** * @dev Appends a byte array to the end of the buffer. Resizes if doing so * would exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, bytes data) internal pure returns(buffer memory) { if(data.length + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, data.length) * 2); } uint dest; uint src; uint len = data.length; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + buffer length + sizeof(buffer length) dest := add(add(bufptr, buflen), 32) // Update buffer length mstore(bufptr, add(buflen, mload(data))) src := add(data, 32) } // 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)) } return buf; } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, uint8 data) internal pure { if(buf.buf.length + 1 > buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) let dest := add(add(bufptr, buflen), 32) mstore8(dest, data) // Update buffer length mstore(bufptr, add(buflen, 1)) } } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) { if(len + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, len) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) + len let dest := add(add(bufptr, buflen), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length mstore(bufptr, add(buflen, len)) } return buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure { if(value <= 23) { buf.append(uint8((major << 5) | value)); } else if(value <= 0xFF) { buf.append(uint8((major << 5) | 24)); buf.appendInt(value, 1); } else if(value <= 0xFFFF) { buf.append(uint8((major << 5) | 25)); buf.appendInt(value, 2); } else if(value <= 0xFFFFFFFF) { buf.append(uint8((major << 5) | 26)); buf.appendInt(value, 4); } else if(value <= 0xFFFFFFFFFFFFFFFF) { buf.append(uint8((major << 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure { buf.append(uint8((major << 5) | 31)); } function encodeUInt(Buffer.buffer memory buf, uint value) internal pure { encodeType(buf, MAJOR_TYPE_INT, value); } function encodeInt(Buffer.buffer memory buf, int value) internal pure { if(value >= 0) { encodeType(buf, MAJOR_TYPE_INT, uint(value)); } else { encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value)); } } function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure { encodeType(buf, MAJOR_TYPE_BYTES, value.length); buf.append(value); } function encodeString(Buffer.buffer memory buf, string value) internal pure { encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length); buf.append(bytes(value)); } function startArray(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE); } } /* End solidity-cborutils */ 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_Ledger = 0x30; byte constant proofType_Android = 0x40; 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 parseAddr(string _a) internal pure returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } 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 uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } using CBOR for Buffer.buffer; function stra2cbor(string[] arr) internal pure returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeString(arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeBytes(arr[i]); } buf.endSequence(); return buf.buf; } 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)); // Convert from seconds to ledger timer ticks _delay *= 10; 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) // the following variables can be relaxed // check relaxed random contract under ethereum-examples repo // for an idea on how to override and replace comit hash vars mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, 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, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; require(prefix.length == n_random_bytes); for (uint256 i=0; i< n_random_bytes; 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){ // 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); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) 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) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) 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); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) 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) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values 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); } function safeMemoryCleaner() internal pure { assembly { let fmem := mload(0x40) codecopy(fmem, codesize, sub(msize, fmem)) } } } // </ORACLIZE_API> // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { 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) { uint256 c = a + b; assert(c >= a); return c; } } // ---------------------------------------------------------------------------- // Ownership functionality for authorization controls and user permissions // ---------------------------------------------------------------------------- /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } // ERC20 Standard Interface // ---------------------------------------------------------------------------- /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // ---------------------------------------------------------------------------- // Basic version of StandardToken, with no allowances. // ---------------------------------------------------------------------------- /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title 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 Standard Burnable Token * @dev Adds burnFrom method to ERC20 implementations */ contract StandardBurnableToken is BurnableToken, StandardToken { /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param _from address The address which you want to send tokens from * @param _value uint256 The amount of token to be burned */ function burnFrom(address _from, uint256 _value) public { require(_value <= allowed[_from][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); _burn(_from, _value); } } contract VictorieumToken is StandardBurnableToken, Ownable, usingOraclize { using SafeMath for uint256; string public symbol = "VTM"; string public name = "Victorieum"; uint256 public decimals = 18; uint public ETHUSD; uint presaleEndsAt; uint startDate; uint firstStageEndsAt; uint secondStageEndsAt; uint thirdStageEndsAt; uint forthStageEndsAt; uint endDate; uint currentpriceincent; uint bonus; uint256 public icoSupply = 0; uint256 public icoLimit = 765000000000000000000000000; event LogConstructorInitiated(string nextStep); event LogPriceUpdated(string price); event LogNewOraclizeQuery(string description); function transfer(address _to, uint256 _value) public returns (bool) { super.transfer(_to,_value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public returns (bool) { super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public returns (bool) { super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { super.decreaseApproval(_spender, _subtractedValue); } /** * @dev Transfer ownership now transfers all owners tokens to new owner */ function transferOwnership(address newOwner) public onlyOwner { balances[newOwner] = balances[newOwner].add(balances[owner]); emit Transfer(owner, newOwner, balances[owner]); balances[owner] = 0; super.transferOwnership(newOwner); } /* ICO status */ enum State { Active, Closed } event Closed(); State public state; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { owner = msg.sender; totalSupply_ = 1000000000000000000000000000; balances[owner] = totalSupply_; emit Transfer(address(0), owner, totalSupply_); state = State.Active; startDate = 1539993600 ; // Oct 20 2018, 00:01 AM presaleEndsAt = 1541376000; // ; // Nov 04 2018, 11:59 PM firstStageEndsAt = 1542758400; // Nov 20 2018, 11:59 PM secondStageEndsAt = 1544140800; // Dec 06 2018, 11:59 PM thirdStageEndsAt = 1545523200; // Dec 22 2018, 11:59 PM forthStageEndsAt = 1546905600; // Jan 07 2019, 11:59 PM endDate = 1548028799; // Jan 20 2019, 11:59 PM // to update ETH Price oraclize_setProof(proofType_Android | proofStorage_IPFS); updatePrice(60); } /** * @dev all ether transfer to another wallet automatic */ function () public payable { require(state == State.Active); // Reject the transactions after ICO ended // production code to start accepting payment and stop require(now >= startDate && now <= endDate); currentpriceincent = 24; bonus = 0; if (now < presaleEndsAt) { currentpriceincent = 1; bonus = 40; } else if (now < firstStageEndsAt) { currentpriceincent = 6; bonus = 35; } else if (now < secondStageEndsAt) { currentpriceincent = 9; bonus = 30; } else if (now < thirdStageEndsAt) { currentpriceincent = 12; bonus = 25; } else if (now < forthStageEndsAt) { currentpriceincent = 16; bonus = 20; } else if (now < endDate) { currentpriceincent = 21; bonus = 15; } else { currentpriceincent = 24; bonus = 0; } uint256 tokens = msg.value * ETHUSD / currentpriceincent; tokens = tokens + (tokens * bonus/100); balances[msg.sender] = balances[msg.sender].add(tokens); balances[owner] = balances[owner].sub(tokens); require(icoSupply.add(tokens) <= icoLimit); icoSupply = icoSupply.add(tokens); emit Transfer(owner, msg.sender, tokens); owner.transfer(msg.value); } function __callback(bytes32 myid, string result) { if (msg.sender != oraclize_cbAddress()) revert(); ETHUSD = parseInt(result,2); emit LogPriceUpdated(result); // updatePrice(600); updatePrice(10800); } function updatePrice(uint time_interval) payable { if (now < endDate) { if (oraclize_getPrice("URL") > this.balance) { emit LogNewOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee"); } else { emit LogNewOraclizeQuery("Oraclize query was sent, standing by for the answer.."); oraclize_query(time_interval, "URL", "json(https://api.gdax.com/products/ETH-USD/ticker).price"); } } } /** * After ICO close it helps to lock tokens for pools **/ function close() onlyOwner public { require(state == State.Active); state = State.Closed; emit Closed(); } }
After ICO close it helps to lock tokens for pools/
function close() onlyOwner public { require(state == State.Active); state = State.Closed; emit Closed(); }
46,055
./full_match/5/0x54FFCE9bE0C17840103e5b28408932A2C6cC7ED4/sources/contracts/Balances.sol
function to allow referrers or contract owner to withdraw their ETH/get the address of the senderif the sender is the contract ownercalculate the amount that can be withdrawnsend the amount to the contract owner's address Require that the senders balance is greater than 0. Calculate the amount that the sender can withdraw Set the sender balance to 0. Decrement the total referrer balance. Send the amount to the referrer's address.
function rentPrice(bytes memory name, uint256 duration) public view virtual returns (uint256); function withdraw() public { address payable sender = payable(msg.sender); if(sender == owner()) { uint256 ownerAmount = address(this).balance - totalBalance; require(ownerAmount > 0, "Owner balance is 0"); emit AddressWithdrew(sender, ownerAmount); sender.sendValue(ownerAmount); require(balances[sender] > 0, "Referrer balance is 0"); uint256 amount = balances[sender]; balances[sender] = 0; totalBalance -= amount; emit AddressWithdrew(sender, amount); sender.sendValue(amount); } }
7,064,062
pragma solidity ^0.4.0; contract VickreyAuction { address public owner; //SP address address[] public bidders; //InP addresses address[] public packageBidders; //InP addresses address public packageWinner; uint8 public reservedPackagePrice; // Set to true at the end, bid has been paid. bool public ended; uint256 public endTime; // bid per virtual node struct Bid { address InP; uint8 value; } struct VirtualNode { bytes32 id; bytes32 resourceType; bytes32 location; int x; int y; uint8 upperBoundCost; } struct VirtualLink { bytes32 id; bytes32 from; bytes32 to; uint8 dBandwidth; } mapping(bytes32 => address[]) public allowedInPsPerVirtualNode; mapping(address => bool) public isInPPackageAllowed; mapping(bytes32 => Bid[]) private bids; //per virtual node mapping(bytes32 => Bid) private winningBid; //per virtual node mapping(address => uint8) private packageBid; mapping(address => bool) private hasBidded; VirtualNode[] public virtualNodes; mapping(bytes32 => VirtualLink[]) public links; //from idVirtualNode modifier isOwner(address sender) { require(sender == owner); _; } modifier onlyBefore(uint _time) { require(now < _time); _; } modifier onlyAfter(uint _time) { require(now > _time); _; } event LogBidderPushed(address InP, bool va); event LogPackageBid(bool isFinished, uint8 value); event LogIndividualBids(bool isFinished, uint8[] values); event LogError(bytes32 message); event LogEnded(bool hasEnded); // Method called when contract is created function VickreyAuction(bytes32[] idVirtualNodes, bytes32[] resourceTypes, bytes32[] locations, uint8[] upperBoundCosts, int[] x, int[] y, bytes32[] idLinks, bytes32[] from, bytes32[] to, uint8[] dBandwidth, uint256 time) public { owner = msg.sender; ended = false; addVirtualNodes(idVirtualNodes, resourceTypes, locations, x, y, upperBoundCosts); addVirtualLinks(idLinks, from, to, dBandwidth); endTime = time; } // Add virtual nodes function addVirtualNodes(bytes32[] idVirtualNodes, bytes32[] resourceTypes, bytes32[] locations, int[] x, int[] y, uint8[] upperBoundCosts) public { for(uint i = 0; i < idVirtualNodes.length; i++) { virtualNodes.push(VirtualNode({id: idVirtualNodes[i], resourceType: resourceTypes[i], location: locations[i], x: x[i], y: y[i], upperBoundCost: upperBoundCosts[i]})); } } // Add virtual links function addVirtualLinks(bytes32[] idLinks, bytes32[] from, bytes32[] to, uint8[] dBandwidth) public { for(uint i = 0; i < idLinks.length; i++) { links[from[i]].push(VirtualLink({id: idLinks[i], from: from[i], to: to[i], dBandwidth: dBandwidth[i]})); } } // InPs can be repeated in the list function addAllowedInPs(address[] allowedInPs, bytes32[] allowedVirtualNodes, address[] packageAllowedInPs) public isOwner(msg.sender) { addAllowedInPsPerVirtualNode(allowedInPs, allowedVirtualNodes); addInPPackageAllowed(packageAllowedInPs); } // Add InPs allowed to bid per virtual node function addAllowedInPsPerVirtualNode(address[] allowedInPs, bytes32[] allowedVirtualNodes) private { for(uint i = 0; i < allowedVirtualNodes.length; i++) { allowedInPsPerVirtualNode[allowedVirtualNodes[i]].push(allowedInPs[i]); } } // Add InPs allowed to bid for the whole virtual network function addInPPackageAllowed(address[] packageAllowedInPs) private { for(uint i = 0; i < packageAllowedInPs.length; i++) { isInPPackageAllowed[packageAllowedInPs[i]] = true; } } // Gets virtual nodes function getVirtualNodes() public constant returns (bytes32[], bytes32[], int[], int[], bytes32[], uint8[]) { bytes32[] memory idVirtualNodes = new bytes32[](virtualNodes.length); bytes32[] memory locations = new bytes32[](virtualNodes.length); int[] memory x = new int[](virtualNodes.length); int[] memory y = new int[](virtualNodes.length); bytes32[] memory resourceTypes = new bytes32[](virtualNodes.length); uint8[] memory upperBoundCosts = new uint8[](virtualNodes.length); for (uint i = 0; i < virtualNodes.length; i++) { idVirtualNodes[i] = virtualNodes[i].id; locations[i] = virtualNodes[i].location; x[i] = virtualNodes[i].x; y[i] = virtualNodes[i].y; resourceTypes[i] = virtualNodes[i].resourceType; upperBoundCosts[i] = virtualNodes[i].upperBoundCost; } return (idVirtualNodes, locations, x, y, resourceTypes, upperBoundCosts); } // Get virtual links from a virtual node function getVirtualLinks(bytes32 idVirtualNode) public constant returns (bytes32[], bytes32[], bytes32[], uint8[]) { var virtualNodeLinks = links[idVirtualNode]; bytes32[] memory idLinks = new bytes32[](virtualNodeLinks.length); bytes32[] memory from = new bytes32[](virtualNodeLinks.length); bytes32[] memory to = new bytes32[](virtualNodeLinks.length); uint8[] memory dBandwidth = new uint8[](virtualNodeLinks.length); for (uint i = 0; i < virtualNodeLinks.length; i++) { idLinks[i] = virtualNodeLinks[i].id; from[i] = virtualNodeLinks[i].from; to[i] = virtualNodeLinks[i].to; dBandwidth[i] = virtualNodeLinks[i].dBandwidth; } return (idLinks, from, to, dBandwidth); } function getAllowedInPsPerVirtualNode(bytes32 idVirtualNode) public constant returns (address[]) { return allowedInPsPerVirtualNode[idVirtualNode]; } function isPackageAllowed() public constant returns (bool) { return isInPPackageAllowed[msg.sender]; } // InP commit individual bids function commitIndividualBids(bytes32[] idVirtualNodes, uint8[] values) public onlyBefore(endTime) { if (!hasBidded[msg.sender]) { bool isRegistered = isBidderRegistered(msg.sender, false); for(uint i = 0; i < idVirtualNodes.length; i++) { if (isInPPackageAllowed[msg.sender] || isBidderAllowed(msg.sender, idVirtualNodes[i])) { if (!isRegistered) { bidders.push(msg.sender); } bids[idVirtualNodes[i]].push(Bid({InP: msg.sender, value: values[i]})); hasBidded[msg.sender] = true; } } if (hasBidded[msg.sender]) { LogIndividualBids(true, values); } else { LogError('User is not allowed'); } } else { LogError('User has already bidded'); } } // InP commit package Bid function commitPackageBid(uint8 value) public onlyBefore(endTime) { if (!hasBidded[msg.sender] && isInPPackageAllowed[msg.sender]) { if (!isBidderRegistered(msg.sender, true)) { packageBidders.push(msg.sender); } packageBid[msg.sender] = value; hasBidded[msg.sender] = true; LogPackageBid(true, value); } else { LogError('User has already bidded'); } } function isBidderRegistered(address bidder, bool isPacketBidder) public constant returns (bool){ if (isPacketBidder) { for(uint i = 0; i < bidders.length; i++) { if (bidder == bidders[i]) { return true; } } return false; } else { for(uint j = 0; j < packageBidders.length; j++) { if (bidder == packageBidders[j]) { return true; } } return false; } } function isBidderAllowed(address bidder, bytes32 idVirtualNode) public constant returns (bool){ for(uint i = 0; i < allowedInPsPerVirtualNode[idVirtualNode].length; i++) { if (allowedInPsPerVirtualNode[idVirtualNode][i] == bidder) { // Check if bidder has already voted for (uint k = 0; k < bids[idVirtualNode].length; k ++) { if (bids[idVirtualNode][k].InP == bidder) { return false; } } return true; } } return false; } function getBidsPerVirtualNode(bytes32 idVirtualNode) public constant returns (address[], uint8[]){ address[] memory InPs = new address[](bids[idVirtualNode].length); uint8[] memory values = new uint8[](bids[idVirtualNode].length); for (uint i = 0; i < bids[idVirtualNode].length; i++) { InPs[i] = bids[idVirtualNode][i].InP; values[i] = bids[idVirtualNode][i].value; } return (InPs, values); } function getPackageBids() public constant returns (address[], uint8[]) { uint8[] memory values = new uint8[](packageBidders.length); for (uint i = 0; i < packageBidders.length; i++) { values[i] = packageBid[packageBidders[i]]; } return (packageBidders, values); } function addIndividualWinnersAndBids(bytes32[] idVirtualNodes, uint8[] values, address[] InPs) public isOwner(msg.sender) onlyAfter(endTime) { for (uint i = 0; i < idVirtualNodes.length; i++) { winningBid[idVirtualNodes[i]].value = values[i]; winningBid[idVirtualNodes[i]].InP = InPs[i]; } ended = true; LogEnded(true); } function addPackageWinnersAndBids(uint8 value, address InP) public isOwner(msg.sender) onlyAfter(endTime) { packageWinner = InP; reservedPackagePrice = value; ended = true; LogEnded(true); } function getIndividualWinnersAndBids() public constant returns (address[], bytes32[], uint8[]) { uint8[] memory values = new uint8[](virtualNodes.length); address[] memory InPs = new address[](virtualNodes.length); bytes32[] memory idVirtualNodes = new bytes32[](virtualNodes.length); for (uint i = 0; i < virtualNodes.length; i++) { idVirtualNodes[i] = virtualNodes[i].id; values[i] = winningBid[virtualNodes[i].id].value; InPs[i] = winningBid[virtualNodes[i].id].InP; } return (InPs, idVirtualNodes, values); } }
Check if bidder has already voted
function isBidderAllowed(address bidder, bytes32 idVirtualNode) public constant returns (bool){ for(uint i = 0; i < allowedInPsPerVirtualNode[idVirtualNode].length; i++) { if (allowedInPsPerVirtualNode[idVirtualNode][i] == bidder) { for (uint k = 0; k < bids[idVirtualNode].length; k ++) { if (bids[idVirtualNode][k].InP == bidder) { return false; } } return true; } } return false; }
1,832,871
// File: interfaces/DelegatorInterface.sol pragma solidity 0.6.12; pragma experimental ABIEncoderV2; contract DelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } abstract contract DelegatorInterface is DelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation( address oldImplementation, address newImplementation ); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation( address implementation_, bool allowResign, bytes memory becomeImplementationData ) public virtual; } abstract contract DelegateInterface is DelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public virtual; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public virtual; } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: contracts/ActivityBase.sol pragma solidity 0.6.12; contract ActivityBase is Ownable{ using SafeMath for uint256; address public admin; address public marketingFund; // token as the unit of measurement address public WETHToken; // invitee's supply 5% deposit weight to its invitor uint256 public constant INVITEE_WEIGHT = 20; // invitee's supply 10% deposit weight to its invitor uint256 public constant INVITOR_WEIGHT = 10; // The block number when SHARD mining starts. uint256 public startBlock; // dev fund uint256 public userDividendWeight; uint256 public devDividendWeight; address public developerDAOFund; // deposit limit uint256 public amountFeeRateNumerator; uint256 public amountfeeRateDenominator; // contract sender fee rate uint256 public contractFeeRateNumerator; uint256 public contractFeeRateDenominator; // Info of each user is Contract sender mapping (uint256 => mapping (address => bool)) public isUserContractSender; mapping (uint256 => uint256) public poolTokenAmountLimit; function setDividendWeight(uint256 _userDividendWeight, uint256 _devDividendWeight) public virtual{ checkAdmin(); require( _userDividendWeight != 0 && _devDividendWeight != 0, "invalid input" ); userDividendWeight = _userDividendWeight; devDividendWeight = _devDividendWeight; } function setDeveloperDAOFund(address _developerDAOFund) public virtual onlyOwner { developerDAOFund = _developerDAOFund; } function setTokenAmountLimit(uint256 _pid, uint256 _tokenAmountLimit) public virtual { checkAdmin(); poolTokenAmountLimit[_pid] = _tokenAmountLimit; } function setTokenAmountLimitFeeRate(uint256 _feeRateNumerator, uint256 _feeRateDenominator) public virtual { checkAdmin(); require( _feeRateDenominator >= _feeRateNumerator, "invalid input" ); amountFeeRateNumerator = _feeRateNumerator; amountfeeRateDenominator = _feeRateDenominator; } function setContracSenderFeeRate(uint256 _feeRateNumerator, uint256 _feeRateDenominator) public virtual { checkAdmin(); require( _feeRateDenominator >= _feeRateNumerator, "invalid input" ); contractFeeRateNumerator = _feeRateNumerator; contractFeeRateDenominator = _feeRateDenominator; } function setStartBlock(uint256 _startBlock) public virtual onlyOwner { require(startBlock > block.number, "invalid start block"); startBlock = _startBlock; updateAfterModifyStartBlock(_startBlock); } function transferAdmin(address _admin) public virtual { checkAdmin(); admin = _admin; } function setMarketingFund(address _marketingFund) public virtual onlyOwner { marketingFund = _marketingFund; } function updateAfterModifyStartBlock(uint256 _newStartBlock) internal virtual{ } function calculateDividend(uint256 _pending, uint256 _pid, uint256 _userAmount, bool _isContractSender) internal view returns (uint256 _marketingFundDividend, uint256 _devDividend, uint256 _userDividend){ uint256 fee = 0; if(_isContractSender && contractFeeRateDenominator > 0){ fee = _pending.mul(contractFeeRateNumerator).div(contractFeeRateDenominator); _marketingFundDividend = _marketingFundDividend.add(fee); _pending = _pending.sub(fee); } if(poolTokenAmountLimit[_pid] > 0 && amountfeeRateDenominator > 0 && _userAmount >= poolTokenAmountLimit[_pid]){ fee = _pending.mul(amountFeeRateNumerator).div(amountfeeRateDenominator); _marketingFundDividend =_marketingFundDividend.add(fee); _pending = _pending.sub(fee); } if(devDividendWeight > 0){ fee = _pending.mul(devDividendWeight).div(devDividendWeight.add(userDividendWeight)); _devDividend = _devDividend.add(fee); _pending = _pending.sub(fee); } _userDividend = _pending; } function judgeContractSender(uint256 _pid) internal { if(msg.sender != tx.origin){ isUserContractSender[_pid][msg.sender] = true; } } function checkAdmin() internal view { require(admin == msg.sender, "invalid authorized"); } } // File: interfaces/IInvitation.sol pragma solidity 0.6.12; interface IInvitation{ function acceptInvitation(address _invitor) external; function getInvitation(address _sender) external view returns(address _invitor, address[] memory _invitees, bool _isWithdrawn); } // File: contracts/MarketingMining.sol pragma solidity 0.6.12; contract MarketingMining is ActivityBase{ using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How much token the user has provided. uint256 originWeight; //initial weight uint256 modifiedWeight; //take the invitation relationship into consideration. uint256 revenue; uint256 userDividend; uint256 devDividend; uint256 marketingFundDividend; uint256 rewardDebt; // Reward debt. See explanation below. bool withdrawnState; bool isUsed; } // Info of each pool. struct PoolInfo { uint256 tokenAmount; // lock amount IERC20 token; // uniswapPair contract uint256 allocPoint; uint256 accumulativeDividend; uint256 lastDividendHeight; // last dividend block height uint256 accShardPerWeight; uint256 totalWeight; } uint256 public constant BONUS_MULTIPLIER = 10; // The SHARD TOKEN! IERC20 public SHARD; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => uint256)) public userInviteeTotalAmount; // total invitee weight // Info of each pool. PoolInfo[] public poolInfo; // Total allocation poitns. Must be the sum of all allocation poishard in all pools. uint256 public totalAllocPoint = 0; // SHARD tokens created per block. uint256 public SHDPerBlock = 1045 * (1e16); //get invitation relationship IInvitation public invitation; uint256 public bonusEndBlock; uint256 public totalAvailableDividend; bool public isInitialized; bool public isDepositAvailable; bool public isRevenueWithdrawable; event AddPool(uint256 indexed pid, address tokenAddress); event Deposit(address indexed user, uint256 indexed pid, uint256 amount, uint256 weight); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); function initialize( IERC20 _SHARD, IInvitation _invitation, uint256 _bonusEndBlock, uint256 _startBlock, uint256 _SHDPerBlock, address _developerDAOFund, address _marketingFund, address _weth ) public virtual onlyOwner{ require(!isInitialized, "contract has been initialized"); invitation = _invitation; bonusEndBlock = _bonusEndBlock; if (_startBlock < block.number) { startBlock = block.number; } else { startBlock = _startBlock; } SHARD = _SHARD; developerDAOFund = _developerDAOFund; marketingFund = _marketingFund; WETHToken = _weth; if(_SHDPerBlock > 0){ SHDPerBlock = _SHDPerBlock; } userDividendWeight = 4; devDividendWeight = 1; amountFeeRateNumerator = 1; amountfeeRateDenominator = 5; contractFeeRateNumerator = 1; contractFeeRateDenominator = 5; isDepositAvailable = true; isRevenueWithdrawable = false; isInitialized = true; } // Add a new pool. Can only be called by the owner. function add(uint256 _allocPoint, IERC20 _tokenAddress, bool _withUpdate) public virtual { checkAdmin(); if(_withUpdate){ massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; PoolInfo memory newpool = PoolInfo({ token: _tokenAddress, tokenAmount: 0, allocPoint: _allocPoint, lastDividendHeight: lastRewardBlock, accumulativeDividend: 0, accShardPerWeight: 0, totalWeight: 0 }); totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(newpool); emit AddPool(poolInfo.length.sub(1), address(_tokenAddress)); } // Update the given pool's allocation point. Can only be called by the owner. function setAllocationPoint(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public virtual { checkAdmin(); if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } function setSHDPerBlock(uint256 _SHDPerBlock, bool _withUpdate) public virtual { checkAdmin(); if (_withUpdate) { massUpdatePools(); } SHDPerBlock = _SHDPerBlock; } function setIsDepositAvailable(bool _isDepositAvailable) public virtual onlyOwner { isDepositAvailable = _isDepositAvailable; } function setIsRevenueWithdrawable(bool _isRevenueWithdrawable) public virtual onlyOwner { isRevenueWithdrawable = _isRevenueWithdrawable; } // update reward vairables for pools. Be careful of gas spending! function massUpdatePools() public virtual { uint256 poolCount = poolInfo.length; for(uint256 i = 0; i < poolCount; i ++){ updatePoolDividend(i); } } function addAvailableDividend(uint256 _amount, bool _withUpdate) public virtual { if(_withUpdate){ massUpdatePools(); } SHARD.safeTransferFrom(address(msg.sender), address(this), _amount); totalAvailableDividend = totalAvailableDividend.add(_amount); } // update reward vairables for a pool function updatePoolDividend(uint256 _pid) public virtual { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastDividendHeight) { return; } if (pool.tokenAmount == 0) { pool.lastDividendHeight = block.number; return; } uint256 availableDividend = totalAvailableDividend; uint256 multiplier = getMultiplier(pool.lastDividendHeight, block.number); uint256 producedToken = multiplier.mul(SHDPerBlock); producedToken = availableDividend > producedToken? producedToken: availableDividend; if(totalAllocPoint > 0){ uint256 poolDevidend = producedToken.mul(pool.allocPoint).div(totalAllocPoint); if(poolDevidend > 0){ totalAvailableDividend = totalAvailableDividend.sub(poolDevidend); pool.accumulativeDividend = pool.accumulativeDividend.add(poolDevidend); pool.accShardPerWeight = pool.accShardPerWeight.add(poolDevidend.mul(1e12).div(pool.totalWeight)); } } pool.lastDividendHeight = block.number; } function depositETH(uint256 _pid) external payable virtual { require(address(poolInfo[_pid].token) == WETHToken, "invalid token"); updateAfterDeposit(_pid, msg.value); } function withdrawETH(uint256 _pid, uint256 _amount) external virtual { require(address(poolInfo[_pid].token) == WETHToken, "invalid token"); updateAfterwithdraw(_pid, _amount); if(_amount > 0){ (bool success, ) = msg.sender.call{value: _amount}(new bytes(0)); require(success, "Transfer: ETH_TRANSFER_FAILED"); } } function updateAfterDeposit(uint256 _pid, uint256 _amount) internal{ require(isDepositAvailable, "new invest is forbidden"); require(_amount > 0, "invalid amount"); (address invitor, , bool isWithdrawn) = invitation.getInvitation(msg.sender); require(invitor != address(0), "should be accept invitation firstly"); updatePoolDividend(_pid); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; UserInfo storage userInvitor = userInfo[_pid][invitor]; uint256 existedAmount = user.amount; bool withdrawnState = user.withdrawnState; if(!user.isUsed){ user.isUsed = true; judgeContractSender(_pid); withdrawnState = isWithdrawn; } if(!withdrawnState && userInvitor.amount > 0){ updateUserRevenue(userInvitor, pool); } if(!withdrawnState){ updateInvitorWeight(msg.sender, invitor, _pid, true, _amount, isWithdrawn, withdrawnState); } if(existedAmount > 0){ updateUserRevenue(user, pool); } updateUserWeight(msg.sender, _pid, true, _amount, isWithdrawn); if(!withdrawnState && userInvitor.amount > 0){ userInvitor.rewardDebt = userInvitor.modifiedWeight.mul(pool.accShardPerWeight).div(1e12); } if(!withdrawnState){ user.withdrawnState = isWithdrawn; } user.amount = existedAmount.add(_amount); user.rewardDebt = user.modifiedWeight.mul(pool.accShardPerWeight).div(1e12); pool.tokenAmount = pool.tokenAmount.add(_amount); emit Deposit(msg.sender, _pid, _amount, user.modifiedWeight); } // Deposit tokens to marketing mining for SHD allocation. function deposit(uint256 _pid, uint256 _amount) public virtual { require(address(poolInfo[_pid].token) != WETHToken, "invalid pid"); IERC20(poolInfo[_pid].token).safeTransferFrom(address(msg.sender), address(this), _amount); updateAfterDeposit(_pid, _amount); } // Withdraw tokens from marketMining. function withdraw(uint256 _pid, uint256 _amount) public virtual { require(address(poolInfo[_pid].token) != WETHToken, "invalid pid"); IERC20(poolInfo[_pid].token).safeTransfer(address(msg.sender), _amount); updateAfterwithdraw(_pid, _amount); } function updateAfterwithdraw(uint256 _pid, uint256 _amount) internal { (address invitor, , bool isWithdrawn) = invitation.getInvitation(msg.sender); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; bool withdrawnState = user.withdrawnState; uint256 existedAmount = user.amount; require(existedAmount >= _amount, "withdraw: not good"); updatePoolDividend(_pid); uint256 pending = updateUserRevenue(user, pool); UserInfo storage userInvitor = userInfo[_pid][invitor]; if(!withdrawnState && userInvitor.amount > 0){ updateUserRevenue(userInvitor, pool); } if(!withdrawnState){ updateInvitorWeight(msg.sender, invitor, _pid, false, _amount, isWithdrawn, withdrawnState); } updateUserWeight(msg.sender, _pid, false, _amount, isWithdrawn); user.amount = existedAmount.sub(_amount); user.rewardDebt = user.modifiedWeight.mul(pool.accShardPerWeight).div(1e12); user.withdrawnState = isWithdrawn; if(!withdrawnState && userInvitor.amount > 0){ userInvitor.rewardDebt = userInvitor.modifiedWeight.mul(pool.accShardPerWeight).div(1e12); } pool.tokenAmount = pool.tokenAmount.sub(_amount); user.revenue = 0; bool isContractSender = isUserContractSender[_pid][msg.sender]; (uint256 marketingFundDividend, uint256 devDividend, uint256 userDividend) = calculateDividend(pending, _pid, existedAmount, isContractSender); user.userDividend = user.userDividend.add(userDividend); user.devDividend = user.devDividend.add(devDividend); if(marketingFundDividend > 0){ user.marketingFundDividend = user.marketingFundDividend.add(marketingFundDividend); } if(isRevenueWithdrawable){ devDividend = user.devDividend; userDividend = user.userDividend; marketingFundDividend = user.marketingFundDividend; if(devDividend > 0){ safeSHARDTransfer(developerDAOFund, devDividend); } if(userDividend > 0){ safeSHARDTransfer(msg.sender, userDividend); } if(marketingFundDividend > 0){ safeSHARDTransfer(marketingFund, marketingFundDividend); } user.devDividend = 0; user.userDividend = 0; user.marketingFundDividend = 0; } emit Withdraw(msg.sender, _pid, _amount); } // Safe SHD transfer function, just in case if rounding error causes pool to not have enough SHDs. function safeSHARDTransfer(address _to, uint256 _amount) internal { uint256 SHARDBal = SHARD.balanceOf(address(this)); if (_amount > SHARDBal) { SHARD.transfer(_to, SHARDBal); } else { SHARD.transfer(_to, _amount); } } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view virtual returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending SHDs on frontend. function pendingSHARD(uint256 _pid, address _user) external view virtual returns (uint256 _pending, uint256 _potential, uint256 _blockNumber) { _blockNumber = block.number; (_pending, _potential) = calculatePendingSHARD(_pid, _user); } function pendingSHARDByPids(uint256[] memory _pids, address _user) external view virtual returns (uint256[] memory _pending, uint256[] memory _potential, uint256 _blockNumber){ uint256 poolCount = _pids.length; _pending = new uint256[](poolCount); _potential = new uint256[](poolCount); _blockNumber = block.number; for(uint i = 0; i < poolCount; i ++){ (_pending[i], _potential[i]) = calculatePendingSHARD(_pids[i], _user); } } function calculatePendingSHARD(uint256 _pid, address _user) private view returns (uint256 _pending, uint256 _potential) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accShardPerWeight = pool.accShardPerWeight; _pending = user.modifiedWeight.mul(accShardPerWeight).div(1e12).sub(user.rewardDebt).add(user.revenue); bool isContractSender = isUserContractSender[_pid][_user]; _potential = _pending; (,,_pending) = calculateDividend(_pending, _pid, user.amount, isContractSender); _pending = _pending.add(user.userDividend); uint256 lpSupply = pool.tokenAmount; if (block.number > pool.lastDividendHeight && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastDividendHeight, block.number); uint256 totalUnupdateToken = multiplier.mul(SHDPerBlock); totalUnupdateToken = totalAvailableDividend > totalUnupdateToken? totalUnupdateToken: totalAvailableDividend; uint256 shardReward = totalUnupdateToken.mul(pool.allocPoint).div(totalAllocPoint); accShardPerWeight = accShardPerWeight.add(shardReward.mul(1e12).div(pool.totalWeight)); } _potential = user.modifiedWeight.mul(accShardPerWeight).div(1e12).sub(user.rewardDebt).add(user.revenue).sub(_potential); (,,_potential) = calculateDividend(_potential, _pid, user.amount, isContractSender); } function getDepositWeight(uint256 _amount) public pure returns(uint256 weight){ return _amount; } function getPoolLength() public view virtual returns(uint256){ return poolInfo.length; } function getPoolInfo(uint256 _pid) public view virtual returns(uint256 _allocPoint, uint256 _accumulativeDividend, uint256 _usersTotalWeight, uint256 _tokenAmount, address _tokenAddress, uint256 _accs){ PoolInfo storage pool = poolInfo[_pid]; _allocPoint = pool.allocPoint; _accumulativeDividend = pool.accumulativeDividend; _usersTotalWeight = pool.totalWeight; _tokenAmount = pool.tokenAmount; _tokenAddress = address(pool.token); _accs = pool.accShardPerWeight; } function getPagePoolInfo(uint256 _fromIndex, uint256 _toIndex) public view virtual returns(uint256[] memory _allocPoint, uint256[] memory _accumulativeDividend, uint256[] memory _usersTotalWeight, uint256[] memory _tokenAmount, address[] memory _tokenAddress, uint256[] memory _accs){ uint256 poolCount = _toIndex.sub(_fromIndex).add(1); _allocPoint = new uint256[](poolCount); _accumulativeDividend = new uint256[](poolCount); _usersTotalWeight = new uint256[](poolCount); _tokenAmount = new uint256[](poolCount); _tokenAddress = new address[](poolCount); _accs = new uint256[](poolCount); uint256 startIndex = 0; for(uint i = _fromIndex; i <= _toIndex; i ++){ PoolInfo storage pool = poolInfo[i]; _allocPoint[startIndex] = pool.allocPoint; _accumulativeDividend[startIndex] = pool.accumulativeDividend; _usersTotalWeight[startIndex] = pool.totalWeight; _tokenAmount[startIndex] = pool.tokenAmount; _tokenAddress[startIndex] = address(pool.token); _accs[startIndex] = pool.accShardPerWeight; startIndex ++; } } function getUserInfoByPids(uint256[] memory _pids, address _user) public virtual view returns(uint256[] memory _amount, uint256[] memory _modifiedWeight, uint256[] memory _revenue, uint256[] memory _userDividend, uint256[] memory _rewardDebt) { uint256 poolCount = _pids.length; _amount = new uint256[](poolCount); _modifiedWeight = new uint256[](poolCount); _revenue = new uint256[](poolCount); _userDividend = new uint256[](poolCount); _rewardDebt = new uint256[](poolCount); for(uint i = 0; i < poolCount; i ++){ UserInfo storage user = userInfo[_pids[i]][_user]; _amount[i] = user.amount; _modifiedWeight[i] = user.modifiedWeight; _revenue[i] = user.revenue; _userDividend[i] = user.userDividend; _rewardDebt[i] = user.rewardDebt; } } function updateUserRevenue(UserInfo storage _user, PoolInfo storage _pool) private returns (uint256){ uint256 pending = _user.modifiedWeight.mul(_pool.accShardPerWeight).div(1e12).sub(_user.rewardDebt); _user.revenue = _user.revenue.add(pending); _pool.accumulativeDividend = _pool.accumulativeDividend.sub(pending); return _user.revenue; } function updateInvitorWeight(address _sender, address _invitor, uint256 _pid, bool _isAddAmount, uint256 _amount, bool _isWithdrawn, bool _withdrawnState) private { UserInfo storage user = userInfo[_pid][_sender]; uint256 subInviteeAmount = 0; uint256 addInviteeAmount = 0; if(user.amount > 0 && !_withdrawnState){ subInviteeAmount = user.originWeight; } if(!_isWithdrawn){ if(_isAddAmount){ addInviteeAmount = getDepositWeight(user.amount.add(_amount)); } else{ addInviteeAmount = getDepositWeight(user.amount.sub(_amount)); } } UserInfo storage invitor = userInfo[_pid][_invitor]; PoolInfo storage pool = poolInfo[_pid]; uint256 inviteeAmountOfUserInvitor = userInviteeTotalAmount[_pid][_invitor]; uint256 newInviteeAmountOfUserInvitor = inviteeAmountOfUserInvitor.add(addInviteeAmount).sub(subInviteeAmount); userInviteeTotalAmount[_pid][_invitor] = newInviteeAmountOfUserInvitor; if(invitor.amount > 0){ invitor.modifiedWeight = invitor.modifiedWeight.add(newInviteeAmountOfUserInvitor.div(INVITEE_WEIGHT)) .sub(inviteeAmountOfUserInvitor.div(INVITEE_WEIGHT)); pool.totalWeight = pool.totalWeight.add(newInviteeAmountOfUserInvitor.div(INVITEE_WEIGHT)) .sub(inviteeAmountOfUserInvitor.div(INVITEE_WEIGHT)); } } function updateUserWeight(address _user, uint256 _pid, bool _isAddAmount, uint256 _amount, bool _isWithdrawn) private { UserInfo storage user = userInfo[_pid][_user]; uint256 userOriginModifiedWeight = user.modifiedWeight; uint256 userNewModifiedWeight; if(_isAddAmount){ userNewModifiedWeight = getDepositWeight(_amount.add(user.amount)); } else{ userNewModifiedWeight = getDepositWeight(user.amount.sub(_amount)); } user.originWeight = userNewModifiedWeight; if(!_isWithdrawn){ userNewModifiedWeight = userNewModifiedWeight.add(userNewModifiedWeight.div(INVITOR_WEIGHT)); } uint256 inviteeAmountOfUser = userInviteeTotalAmount[_pid][msg.sender]; userNewModifiedWeight = userNewModifiedWeight.add(inviteeAmountOfUser.div(INVITEE_WEIGHT)); user.modifiedWeight = userNewModifiedWeight; PoolInfo storage pool = poolInfo[_pid]; pool.totalWeight = pool.totalWeight.add(userNewModifiedWeight).sub(userOriginModifiedWeight); } function updateAfterModifyStartBlock(uint256 _newStartBlock) internal override{ uint256 poolLenght = poolInfo.length; for(uint256 i = 0; i < poolLenght; i++){ PoolInfo storage info = poolInfo[i]; info.lastDividendHeight = _newStartBlock; } } } // File: contracts/MarketingMiningDelegate.sol pragma solidity 0.6.12; contract MarketingMiningDelegate is DelegateInterface, MarketingMining { /** * @notice Construct an empty delegate */ constructor() public {} /** * @notice Called by the delegator on a delegate to initialize it for duty * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public override { checkAdmin(); // Shh -- currently unused data; // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } } /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public override { checkAdmin(); // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } } }
Deposit tokens to marketing mining for SHD allocation.
function deposit(uint256 _pid, uint256 _amount) public virtual { require(address(poolInfo[_pid].token) != WETHToken, "invalid pid"); IERC20(poolInfo[_pid].token).safeTransferFrom(address(msg.sender), address(this), _amount); updateAfterDeposit(_pid, _amount); }
83,488
pragma solidity ^0.5.3; import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "./interfaces/ILockedGold.sol"; import "./interfaces/IGovernance.sol"; import "./interfaces/IValidators.sol"; import "../common/Initializable.sol"; import "../common/UsingRegistry.sol"; import "../common/FixidityLib.sol"; import "../common/interfaces/IERC20Token.sol"; import "../common/Signatures.sol"; import "../common/FractionUtil.sol"; contract LockedGold is ILockedGold, ReentrancyGuard, Initializable, UsingRegistry { using FixidityLib for FixidityLib.Fraction; using FractionUtil for FractionUtil.Fraction; using SafeMath for uint256; // TODO(asa): Remove index for gas efficiency if two updates to the same slot costs extra gas. struct Commitment { uint128 value; uint128 index; } struct Commitments { // Maps a notice period in seconds to a Locked Gold commitment. mapping(uint256 => Commitment) locked; // Maps an availability time in seconds since epoch to a notified commitment. mapping(uint256 => Commitment) notified; uint256[] noticePeriods; uint256[] availabilityTimes; } struct Account { bool exists; // The weight of the account in validator elections, governance, and block rewards. uint256 weight; // Each account may delegate their right to receive rewards, vote, and register a Validator or // Validator group to exactly one address each, respectively. This address must not hold an // account and must not be delegated to by any other account or by the same account for any // other purpose. address[3] delegates; // Frozen accounts may not vote, but may redact votes. bool votingFrozen; // The timestamp of the last time that rewards were redeemed. uint96 rewardsLastRedeemed; Commitments commitments; } // TODO(asa): Add minNoticePeriod uint256 public maxNoticePeriod; uint256 public totalWeight; mapping(address => Account) private accounts; // Maps voting, rewards, and validating delegates to the account that delegated these rights. mapping(address => address) public delegations; // Maps a block number to the cumulative reward for an account with weight 1 since genesis. mapping(uint256 => FixidityLib.Fraction) public cumulativeRewardWeights; event MaxNoticePeriodSet( uint256 maxNoticePeriod ); event RoleDelegated( DelegateRole role, address indexed account, address delegate ); event VotingFrozen( address indexed account ); event VotingUnfrozen( address indexed account ); event NewCommitment( address indexed account, uint256 value, uint256 noticePeriod ); event CommitmentNotified( address indexed account, uint256 value, uint256 noticePeriod, uint256 availabilityTime ); event CommitmentExtended( address indexed account, uint256 value, uint256 noticePeriod, uint256 availabilityTime ); event Withdrawal( address indexed account, uint256 value ); event NoticePeriodIncreased( address indexed account, uint256 value, uint256 noticePeriod, uint256 increase ); function initialize(address registryAddress, uint256 _maxNoticePeriod) external initializer { _transferOwnership(msg.sender); setRegistry(registryAddress); maxNoticePeriod = _maxNoticePeriod; } /** * @notice Sets the cumulative block reward for 1 unit of account weight. * @param blockReward The total reward allocated to bonders for this block. * @dev Called by the EVM at the end of the block. */ function setCumulativeRewardWeight(uint256 blockReward) external { require(blockReward > 0, "placeholder to suppress warning"); return; // TODO(asa): Modify ganache to set cumulativeRewardWeights. // TODO(asa): Make inheritable `onlyVm` modifier. // Only callable by the EVM. // require(msg.sender == address(0), "sender was not vm (reserved addr 0x0)"); // FractionUtil.Fraction storage previousCumulativeRewardWeight = cumulativeRewardWeights[ // block.number.sub(1) // ]; // // This will be true the first time this is called by the EVM. // if (!previousCumulativeRewardWeight.exists()) { // previousCumulativeRewardWeight.denominator = 1; // } // if (totalWeight > 0) { // FractionUtil.Fraction memory currentRewardWeight = FractionUtil.Fraction( // blockReward, // totalWeight // ).reduce(); // cumulativeRewardWeights[block.number] = previousCumulativeRewardWeight.add( // currentRewardWeight // ); // } else { // cumulativeRewardWeights[block.number] = previousCumulativeRewardWeight; // } } /** * @notice Sets the maximum notice period for an account. * @param _maxNoticePeriod The new maximum notice period. */ function setMaxNoticePeriod(uint256 _maxNoticePeriod) external onlyOwner { maxNoticePeriod = _maxNoticePeriod; emit MaxNoticePeriodSet(maxNoticePeriod); } /** * @notice Creates an account. * @return True if account creation succeeded. */ function createAccount() external returns (bool) { require(isNotAccount(msg.sender) && isNotDelegate(msg.sender)); Account storage account = accounts[msg.sender]; account.exists = true; account.rewardsLastRedeemed = uint96(block.number); return true; } /** * @notice Redeems rewards accrued since the last redemption for the specified account. * @return The amount of accrued rewards. * @dev Fails if `msg.sender` is not the owner or rewards recipient of the account. */ function redeemRewards() external nonReentrant returns (uint256) { require(false, "Disabled"); address account = getAccountFromDelegateAndRole(msg.sender, DelegateRole.Rewards); return _redeemRewards(account); } /** * @notice Freezes the voting power of `msg.sender`'s account. */ function freezeVoting() external { require(isAccount(msg.sender)); Account storage account = accounts[msg.sender]; require(account.votingFrozen == false); account.votingFrozen = true; emit VotingFrozen(msg.sender); } /** * @notice Unfreezes the voting power of `msg.sender`'s account. */ function unfreezeVoting() external { require(isAccount(msg.sender)); Account storage account = accounts[msg.sender]; require(account.votingFrozen == true); account.votingFrozen = false; emit VotingUnfrozen(msg.sender); } /** * @notice Delegates the validating power of `msg.sender`'s account to another address. * @param delegate The address to delegate to. * @param v The recovery id of the incoming ECDSA signature. * @param r Output value r of the ECDSA signature. * @param s Output value s of the ECDSA signature. * @dev Fails if the address is already a delegate or has an account . * @dev Fails if the current account is already participating in validation. * @dev v, r, s constitute `delegate`'s signature on `msg.sender`. */ function delegateRole( DelegateRole role, address delegate, uint8 v, bytes32 r, bytes32 s ) external nonReentrant { // TODO: split and add error messages for better dev feedback require(isAccount(msg.sender) && isNotAccount(delegate) && isNotDelegate(delegate)); address signer = Signatures.getSignerOfAddress(msg.sender, v, r, s); require(signer == delegate); if (role == DelegateRole.Validating) { require(isNotValidating(msg.sender)); } else if (role == DelegateRole.Voting) { require(!isVoting(msg.sender)); } else if (role == DelegateRole.Rewards) { _redeemRewards(msg.sender); } Account storage account = accounts[msg.sender]; delegations[account.delegates[uint256(role)]] = address(0); account.delegates[uint256(role)] = delegate; delegations[delegate] = msg.sender; emit RoleDelegated(role, msg.sender, delegate); } /** * @notice Adds a Locked Gold commitment to `msg.sender`'s account. * @param noticePeriod The notice period for the commitment. * @return The account's new weight. */ function newCommitment( uint256 noticePeriod ) external nonReentrant payable returns (uint256) { require(isAccount(msg.sender) && !isVoting(msg.sender)); // _redeemRewards(msg.sender); require(msg.value > 0 && noticePeriod <= maxNoticePeriod); Account storage account = accounts[msg.sender]; Commitment storage locked = account.commitments.locked[noticePeriod]; updateLockedCommitment(account, uint256(locked.value).add(msg.value), noticePeriod); emit NewCommitment(msg.sender, msg.value, noticePeriod); return account.weight; } /** * @notice Notifies a Locked Gold commitment, allowing funds to be withdrawn after the notice * period. * @param value The amount of the commitment to eventually withdraw. * @param noticePeriod The notice period of the Locked Gold commitment. * @return The account's new weight. */ function notifyCommitment( uint256 value, uint256 noticePeriod ) external nonReentrant returns (uint256) { require(isAccount(msg.sender) && isNotValidating(msg.sender) && !isVoting(msg.sender)); // _redeemRewards(msg.sender); Account storage account = accounts[msg.sender]; Commitment storage locked = account.commitments.locked[noticePeriod]; require(locked.value >= value && value > 0); updateLockedCommitment(account, uint256(locked.value).sub(value), noticePeriod); // solhint-disable-next-line not-rely-on-time uint256 availabilityTime = now.add(noticePeriod); Commitment storage notified = account.commitments.notified[availabilityTime]; updateNotifiedDeposit(account, uint256(notified.value).add(value), availabilityTime); emit CommitmentNotified(msg.sender, value, noticePeriod, availabilityTime); return account.weight; } /** * @notice Rebonds a notified commitment, with notice period >= the remaining time to * availability. * @param value The amount of the commitment to rebond. * @param availabilityTime The availability time of the notified commitment. * @return The account's new weight. */ function extendCommitment( uint256 value, uint256 availabilityTime ) external nonReentrant returns (uint256) { require(isAccount(msg.sender) && !isVoting(msg.sender)); // solhint-disable-next-line not-rely-on-time require(availabilityTime > now); // _redeemRewards(msg.sender); Account storage account = accounts[msg.sender]; Commitment storage notified = account.commitments.notified[availabilityTime]; require(notified.value >= value && value > 0); updateNotifiedDeposit(account, uint256(notified.value).sub(value), availabilityTime); // solhint-disable-next-line not-rely-on-time uint256 noticePeriod = availabilityTime.sub(now); Commitment storage locked = account.commitments.locked[noticePeriod]; updateLockedCommitment(account, uint256(locked.value).add(value), noticePeriod); emit CommitmentExtended(msg.sender, value, noticePeriod, availabilityTime); return account.weight; } /** * @notice Withdraws a notified commitment after the duration of the notice period. * @param availabilityTime The availability time of the notified commitment. * @return The account's new weight. */ function withdrawCommitment( uint256 availabilityTime ) external nonReentrant returns (uint256) { require(isAccount(msg.sender) && !isVoting(msg.sender)); // _redeemRewards(msg.sender); // solhint-disable-next-line not-rely-on-time require(now >= availabilityTime); _redeemRewards(msg.sender); Account storage account = accounts[msg.sender]; Commitment storage notified = account.commitments.notified[availabilityTime]; uint256 value = notified.value; require(value > 0); updateNotifiedDeposit(account, 0, availabilityTime); IERC20Token goldToken = IERC20Token(registry.getAddressFor(GOLD_TOKEN_REGISTRY_ID)); require(goldToken.transfer(msg.sender, value)); emit Withdrawal(msg.sender, value); return account.weight; } /** * @notice Increases the notice period for all or part of a Locked Gold commitment. * @param value The amount of the Locked Gold commitment to increase the notice period for. * @param noticePeriod The notice period of the Locked Gold commitment. * @param increase The amount to increase the notice period by. * @return The account's new weight. */ function increaseNoticePeriod( uint256 value, uint256 noticePeriod, uint256 increase ) external nonReentrant returns (uint256) { require(isAccount(msg.sender) && !isVoting(msg.sender)); // _redeemRewards(msg.sender); require(value > 0 && increase > 0); Account storage account = accounts[msg.sender]; Commitment storage locked = account.commitments.locked[noticePeriod]; require(locked.value >= value); updateLockedCommitment(account, uint256(locked.value).sub(value), noticePeriod); uint256 increasedNoticePeriod = noticePeriod.add(increase); uint256 increasedValue = account.commitments.locked[increasedNoticePeriod].value; updateLockedCommitment(account, increasedValue.add(value), increasedNoticePeriod); emit NoticePeriodIncreased(msg.sender, value, noticePeriod, increase); return account.weight; } /** * @notice Returns whether or not an account's voting power is frozen. * @param account The address of the account. * @return Whether or not the account's voting power is frozen. * @dev Frozen accounts can retract existing votes but not make future votes. */ function isVotingFrozen(address account) external view returns (bool) { return accounts[account].votingFrozen; } /** * @notice Returns the timestamp of the last time the account redeemed block rewards. * @param _account The address of the account. * @return The timestamp of the last time `_account` redeemed block rewards. */ function getRewardsLastRedeemed(address _account) external view returns (uint96) { Account storage account = accounts[_account]; return account.rewardsLastRedeemed; } function isValidating(address validator) external view returns (bool) { IValidators validators = IValidators(registry.getAddressFor(VALIDATORS_REGISTRY_ID)); return validators.isValidating(validator); } /** * @notice Returns the notice periods of all Locked Gold for an account. * @param _account The address of the account. * @return The notice periods of all Locked Gold for `_account`. */ function getNoticePeriods(address _account) external view returns (uint256[] memory) { Account storage account = accounts[_account]; return account.commitments.noticePeriods; } /** * @notice Returns the availability times of all notified commitments for an account. * @param _account The address of the account. * @return The availability times of all notified commitments for `_account`. */ function getAvailabilityTimes(address _account) external view returns (uint256[] memory) { Account storage account = accounts[_account]; return account.commitments.availabilityTimes; } /** * @notice Returns the value and index of a specified Locked Gold commitment. * @param _account The address of the account. * @param noticePeriod The notice period of the Locked Gold commitment. * @return The value and index of the specified Locked Gold commitment. */ function getLockedCommitment( address _account, uint256 noticePeriod ) external view returns (uint256, uint256) { Account storage account = accounts[_account]; Commitment storage locked = account.commitments.locked[noticePeriod]; return (locked.value, locked.index); } /** * @notice Returns the value and index of a specified notified commitment. * @param _account The address of the account. * @param availabilityTime The availability time of the notified commitment. * @return The value and index of the specified notified commitment. */ function getNotifiedCommitment( address _account, uint256 availabilityTime ) external view returns (uint256, uint256) { Account storage account = accounts[_account]; Commitment storage notified = account.commitments.notified[availabilityTime]; return (notified.value, notified.index); } /** * @notice Returns the account associated with the provided delegate and role. * @param accountOrDelegate The address of the account or voting delegate. * @param role The delegate role to query for. * @dev Fails if the `accountOrDelegate` is a non-voting delegate. * @return The associated account. */ function getAccountFromDelegateAndRole( address accountOrDelegate, DelegateRole role ) public view returns (address) { address delegatingAccount = delegations[accountOrDelegate]; if (delegatingAccount != address(0)) { require(accounts[delegatingAccount].delegates[uint256(role)] == accountOrDelegate); return delegatingAccount; } else { return accountOrDelegate; } } /** * @notice Returns the weight of a specified account. * @param _account The address of the account. * @return The weight of the specified account. */ function getAccountWeight(address _account) external view returns (uint256) { Account storage account = accounts[_account]; return account.weight; } /** * @notice Returns whether or not a specified account is voting. * @param account The address of the account. * @return Whether or not the account is voting. */ function isVoting(address account) public view returns (bool) { address voter = getDelegateFromAccountAndRole(account, DelegateRole.Voting); IGovernance governance = IGovernance(registry.getAddressFor(GOVERNANCE_REGISTRY_ID)); IValidators validators = IValidators(registry.getAddressFor(VALIDATORS_REGISTRY_ID)); return (governance.isVoting(voter) || validators.isVoting(voter)); } /** * @notice Returns the weight of a commitment for a given notice period. * @param value The value of the commitment. * @param noticePeriod The notice period of the commitment. * @return The weight of the commitment. * @dev A commitment's weight is (1 + sqrt(noticePeriodDays) / 30) * value. */ function getCommitmentWeight(uint256 value, uint256 noticePeriod) public pure returns (uint256) { uint256 precision = 10000; uint256 noticeDays = noticePeriod.div(1 days); uint256 preciseMultiplier = sqrt(noticeDays).mul(precision).div(30).add(precision); return preciseMultiplier.mul(value).div(precision); } /** * @notice Returns the delegate for a specified account and role. * @param account The address of the account. * @param role The role to query for. * @return The rewards recipient for the account. */ function getDelegateFromAccountAndRole( address account, DelegateRole role ) public view returns (address) { address delegate = accounts[account].delegates[uint256(role)]; if (delegate == address(0)) { return account; } else { return delegate; } } // TODO(asa): Factor in governance, validator election participation. /** * @notice Redeems rewards accrued since the last redemption for a specified account. * @param _account The address of the account to redeem rewards for. * @return The amount of accrued rewards. */ function _redeemRewards(address _account) private returns (uint256) { Account storage account = accounts[_account]; uint256 rewardBlockNumber = block.number.sub(1); FixidityLib.Fraction memory previousCumulativeRewardWeight = cumulativeRewardWeights[ account.rewardsLastRedeemed ]; FixidityLib.Fraction memory cumulativeRewardWeight = cumulativeRewardWeights[ rewardBlockNumber ]; // We should never get here except in testing, where cumulativeRewardWeight will not be set. if (previousCumulativeRewardWeight.unwrap() == 0 || cumulativeRewardWeight.unwrap() == 0) { return 0; } FixidityLib.Fraction memory rewardWeight = cumulativeRewardWeight.subtract( previousCumulativeRewardWeight ); require(rewardWeight.unwrap() != 0, "Rewards weight does not exist"); uint256 value = rewardWeight.multiply(FixidityLib.wrap(account.weight)).fromFixed(); account.rewardsLastRedeemed = uint96(rewardBlockNumber); if (value > 0) { address recipient = getDelegateFromAccountAndRole(_account, DelegateRole.Rewards); IERC20Token goldToken = IERC20Token(registry.getAddressFor(GOLD_TOKEN_REGISTRY_ID)); require(goldToken.transfer(recipient, value)); emit Withdrawal(recipient, value); } return value; } /** * @notice Updates the Locked Gold commitment for a given notice period to a new value. * @param account The account to update the Locked Gold commitment for. * @param value The new value of the Locked Gold commitment. * @param noticePeriod The notice period of the Locked Gold commitment. */ function updateLockedCommitment( Account storage account, uint256 value, uint256 noticePeriod ) private { Commitment storage locked = account.commitments.locked[noticePeriod]; require(value != locked.value); uint256 weight; if (locked.value == 0) { locked.index = uint128(account.commitments.noticePeriods.length); locked.value = uint128(value); account.commitments.noticePeriods.push(noticePeriod); weight = getCommitmentWeight(value, noticePeriod); account.weight = account.weight.add(weight); totalWeight = totalWeight.add(weight); } else if (value == 0) { weight = getCommitmentWeight(locked.value, noticePeriod); account.weight = account.weight.sub(weight); totalWeight = totalWeight.sub(weight); deleteCommitment(locked, account.commitments, CommitmentType.Locked); } else { uint256 originalWeight = getCommitmentWeight(locked.value, noticePeriod); weight = getCommitmentWeight(value, noticePeriod); uint256 difference; if (weight >= originalWeight) { difference = weight.sub(originalWeight); account.weight = account.weight.add(difference); totalWeight = totalWeight.add(difference); } else { difference = originalWeight.sub(weight); account.weight = account.weight.sub(difference); totalWeight = totalWeight.sub(difference); } locked.value = uint128(value); } } /** * @notice Updates the notified commitment for a given availability time to a new value. * @param account The account to update the notified commitment for. * @param value The new value of the notified commitment. * @param availabilityTime The availability time of the notified commitment. */ function updateNotifiedDeposit( Account storage account, uint256 value, uint256 availabilityTime ) private { Commitment storage notified = account.commitments.notified[availabilityTime]; require(value != notified.value); if (notified.value == 0) { notified.index = uint128(account.commitments.availabilityTimes.length); notified.value = uint128(value); account.commitments.availabilityTimes.push(availabilityTime); account.weight = account.weight.add(notified.value); totalWeight = totalWeight.add(notified.value); } else if (value == 0) { account.weight = account.weight.sub(notified.value); totalWeight = totalWeight.sub(notified.value); deleteCommitment(notified, account.commitments, CommitmentType.Notified); } else { uint256 difference; if (value >= notified.value) { difference = value.sub(notified.value); account.weight = account.weight.add(difference); totalWeight = totalWeight.add(difference); } else { difference = uint256(notified.value).sub(value); account.weight = account.weight.sub(difference); totalWeight = totalWeight.sub(difference); } notified.value = uint128(value); } } /** * @notice Deletes a commitment from an account. * @param _commitment The commitment to delete. * @param commitments The struct containing the account's commitments. * @param commitmentType Whether the deleted commitment is locked or notified. */ function deleteCommitment( Commitment storage _commitment, Commitments storage commitments, CommitmentType commitmentType ) private { uint256 lastIndex; if (commitmentType == CommitmentType.Locked) { lastIndex = commitments.noticePeriods.length.sub(1); commitments.locked[commitments.noticePeriods[lastIndex]].index = _commitment.index; deleteElement(commitments.noticePeriods, _commitment.index, lastIndex); } else { lastIndex = commitments.availabilityTimes.length.sub(1); commitments.notified[commitments.availabilityTimes[lastIndex]].index = _commitment.index; deleteElement(commitments.availabilityTimes, _commitment.index, lastIndex); } // Delete commitment info. _commitment.index = 0; _commitment.value = 0; } /** * @notice Deletes an element from a list of uint256s. * @param list The list of uint256s. * @param index The index of the element to delete. * @param lastIndex The index of the last element in the list. */ function deleteElement(uint256[] storage list, uint256 index, uint256 lastIndex) private { list[index] = list[lastIndex]; list[lastIndex] = 0; list.length = lastIndex; } /** * @notice Check if an account already exists. * @param account The address of the account * @return Returns `true` if account exists. Returns `false` otherwise. * In particular it will return `false` if a delegate with given address exists. */ function isAccount(address account) public view returns (bool) { return (accounts[account].exists); } /** * @notice Check if a delegate already exists. * @param account The address of the delegate * @return Returns `true` if delegate exists. Returns `false` otherwise. */ function isDelegate(address account) external view returns (bool) { return (delegations[account] != address(0)); } function isNotAccount(address account) internal view returns (bool) { return (!accounts[account].exists); } // Reverts if rewards, voting, or validating rights have been delegated to `account`. function isNotDelegate(address account) internal view returns (bool) { return (delegations[account] == address(0)); } // TODO(asa): Allow users to notify if they would continue to meet the registration // requirements. function isNotValidating(address account) internal view returns (bool) { address validator = getDelegateFromAccountAndRole(account, DelegateRole.Validating); IValidators validators = IValidators(registry.getAddressFor(VALIDATORS_REGISTRY_ID)); return (!validators.isValidating(validator)); } // TODO: consider using Fixidity's roots /** * @notice Approxmiates the square root of x using the Bablyonian method. * @param x The number to take the square root of. * @return An approximation of the square root of x. * @dev The error can be large for smaller numbers, so we multiply by the square of `precision`. */ function sqrt(uint256 x) private pure returns (FractionUtil.Fraction memory) { uint256 precision = 100; uint256 px = x.mul(precision.mul(precision)); uint256 z = px.add(1).div(2); uint256 y = px; while (z < y) { y = z; z = px.div(z).add(z).div(2); } return FractionUtil.Fraction(y, precision); } }
Returns the timestamp of the last time the account redeemed block rewards. _account The address of the account. return The timestamp of the last time `_account` redeemed block rewards./
function getRewardsLastRedeemed(address _account) external view returns (uint96) { Account storage account = accounts[_account]; return account.rewardsLastRedeemed; }
14,091,296
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/proxy/utils/Initializable.sol'; contract Forwarder is Initializable{ address private destination; event TokensWithdrawal(address sender, uint256 balance); event ETHWithdrawal(address sender, uint256 balance); /** * This is initialization and it can be executed only once per instance. */ function initialize(address _destination) public initializer{ destination = _destination; } /** * This is standard method. If you send ETH directly to the contract's address, * they will be automatically transfered to the destination address. */ receive() external payable { payable(destination).transfer(msg.value); emit ETHWithdrawal(msg.sender, msg.value); } function getDestination() public view returns (address _destination) { return destination; } /** * This method will transfer coins from the token contract to the destination address. */ function withdrawERC20(address tokenContractAddress) public { IERC20 tokenContract = ERC20(tokenContractAddress); uint256 forwarderBalance = tokenContract.balanceOf(address(this)); tokenContract.transfer(destination, forwarderBalance); emit TokensWithdrawal(address(this),forwarderBalance); } /** * It is possible that funds were sent to this address before the contract was deployed. * We can flush those funds to the parent address. */ function withdrawETH() public { emit ETHWithdrawal(address(this),address(this).balance); payable(destination).transfer(address(this).balance); } }
It is possible that funds were sent to this address before the contract was deployed. We can flush those funds to the parent address./
function withdrawETH() public { emit ETHWithdrawal(address(this),address(this).balance); payable(destination).transfer(address(this).balance); }
12,608,771
// SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.8.9; import { IERC20, IPool, IPoolAddressesProvider, IWETHGateway} from './Interfaces.sol'; import { SafeERC20 } from './Libraries.sol'; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; /** * @title JustCausePoolAaveV3 contract * @author JustCause * This is a proof of concept starter contract for lossless donations Aave v3 is used to generate interest for crowdfunding Contributors deposit tokens into JustCausePool which deposit them into Aave lending protocol. The interest earned is directed to the receiver associated with the Pool. When Contributors need access to their funds they withdraw original deposit and interest accrued is left behind for the receiver to claim. * @dev To be covered by a proxy contract * @dev deposits, withdraws, withdrawDonations controlled by the PoolTracker contract (Master) **/ contract JustCausePoolAaveV3 is Initializable { mapping(address => uint256) private totalDeposits; mapping(address => uint256) private interestWithdrawn; bool private isBase; IPoolAddressesProvider provider; address poolAddr; address wethGatewayAddr; address erc721Addr; address[] acceptedTokens; address receiver; address poolTracker; string name; string about; string picHash; string metaUri; bool isVerified; /** * @dev Only tokens that are on the accepted list can be passed * to functions marked by this modifier. **/ modifier onlyAllowedTokens(address _tokenAddr){ bool isAccepted; for (uint8 i = 0; i < acceptedTokens.length; i++){ if(_tokenAddr == acceptedTokens[i]){ isAccepted = true; break; } } require(isAccepted, "token not accepted by jcpool"); _; } /** * @dev Only Receiver can call functions marked by this modifier. **/ modifier onlyReceiver(address _sender){ require(receiver == _sender, "not the receiver"); _; } /** * @dev Only Master can call functions marked by this modifier. **/ modifier onlyPoolTracker(){ require(poolTracker == msg.sender, "not the owner"); _; } /** * @dev Limits string (pool name) to x characters when passed to * functions marked by this modifier. **/ modifier strLength(string memory _str, uint8 _limit ){ bytes memory strBytes = bytes(_str); if(strBytes.length > _limit){ revert("string over character limit"); } _; } /** * @dev Constructor. */ constructor () { isBase = true; } /** * @notice Initializes the JustCause Pool. * @dev Function is invoked by the PoolTacker contract when a Pool is created. * @param _acceptedTokens List of tokens to be accepted by JCP. * @param _name String name of JCP. * @param _about ipfs hash of pool description of JCP. * @param _picHash ipfs hash of pic of JCP. * @param _metaUri meta info uri for nft of JCP. * @param _receiver address of receiver of JCP donations. * @param _isVerified indicates whether JCP is verified **/ function initialize( address[] memory _acceptedTokens, string memory _name, string memory _about, string memory _picHash, string memory _metaUri, address _receiver, address _poolAddr, address _wethGatewayAddr, address _erc721Addr, bool _isVerified ) external strLength(_name, 30) initializer() { require(isBase == false, "Cannot initialize base"); require(receiver == address(0), "Initialize already called"); receiver = _receiver; poolTracker = msg.sender; name = _name; about = _about; picHash = _picHash; metaUri = _metaUri; isVerified = _isVerified; poolAddr = _poolAddr; wethGatewayAddr = _wethGatewayAddr; erc721Addr = _erc721Addr; acceptedTokens = _acceptedTokens; } /** * @param _assetAddress The address of the underlying asset of the reserve * @param _amount The amount of supplied assets **/ function deposit(address _assetAddress, uint256 _amount) external onlyPoolTracker onlyAllowedTokens(_assetAddress){ totalDeposits[_assetAddress] += _amount; } /** * @param _assetAddress The address of the underlying asset of the reserve * @param _amount The amount of withdraw assets * @param _depositor The address making the deposit * @param _isETH bool indicating if asset is the base token of network (eth/matic/...) **/ function withdraw(address _assetAddress, uint256 _amount, address _depositor, bool _isETH) external onlyPoolTracker { totalDeposits[_assetAddress] -= _amount; if(!_isETH){ IPool(poolAddr).withdraw(_assetAddress, _amount, _depositor); } else{ address wethAddress = IWETHGateway(wethGatewayAddr).getWETHAddress(); require(wethAddress == _assetAddress, "asset does not match WETHGateway"); address aTokenAddress = getATokenAddress(wethAddress); IERC20(aTokenAddress).approve(wethGatewayAddr, _amount); IWETHGateway(wethGatewayAddr).withdrawETH(poolAddr, _amount, _depositor); } } /** * @param _assetAddress The address of the underlying asset of the reserve * @param _isETH bool indicating if asset is the base token of network (eth/matic/...) **/ function withdrawDonations(address _assetAddress, bool _isETH) external onlyPoolTracker returns(uint256){ address aTokenAddress = getATokenAddress(_assetAddress); uint256 aTokenBalance = IERC20(aTokenAddress).balanceOf(address(this)); uint256 interestEarned = aTokenBalance - totalDeposits[_assetAddress]; interestWithdrawn[_assetAddress] += interestEarned; if(!_isETH){ IPool(poolAddr).withdraw(_assetAddress, interestEarned, receiver); } else{ require(IWETHGateway(wethGatewayAddr).getWETHAddress() == _assetAddress, "asset does not match WETHGateway"); IERC20(aTokenAddress).approve(wethGatewayAddr, interestEarned); IWETHGateway(wethGatewayAddr).withdrawETH(poolAddr, interestEarned, receiver); } return interestEarned; } /** * @return acceptedTokens List of tokens to be accepted by JCP. **/ function getAcceptedTokens() external view returns(address[] memory){ return acceptedTokens; } /** * @return name String name of JCP. **/ function getName() external view returns(string memory){ return name; } /** * @return about ipfs hash of pool description of JCP. **/ function getAbout() external view returns(string memory){ return about; } /** * @return picHash ipfs hash of pic of JCP. **/ function getPicHash() external view returns(string memory){ return picHash; } /** * @return metaUri meta info uri for nft of JCP. **/ function getMetaUri() external view returns(string memory){ return metaUri; } /** * @return isVerified indicates whether JCP is verified **/ function getIsVerified() external view returns(bool){ return isVerified; } /** * @return receiver address of receiver of JCP donations. **/ function getRecipient() external view returns(address){ return receiver; } /** * @return erc721Addr address of receiver of JCP donations. **/ function getERC721Address() external view returns(address){ return erc721Addr; } /** * @notice Returns general pool information * @return acceptedTokens List of tokens to be accepted by JCP. * @return name String name of JCP. * @return about ipfs hash of pool description of JCP. * @return picHash ipfs hash of pic of JCP. * @return metaUri meta info uri for nft of JCP. * @return receiver address of receiver of JCP donations. * @return isVerified indicates whether JCP is verified **/ function getPoolInfo() external view returns (address[] memory, address, bool, string memory, string memory, string memory, string memory){ return (acceptedTokens, receiver, isVerified, metaUri, picHash, about, name); } /** * @param _assetAddress The address of the underlying asset of the reserve * @return aTokenAddress address of Aave's aToken for asset **/ function getATokenAddress(address _assetAddress) public view returns(address aTokenAddress){ aTokenAddress = IPool(poolAddr).getReserveData(_assetAddress).aTokenAddress; } /** * @param _assetAddress The address of the underlying asset of the reserve * @return totalDeposit total assets deposited in pool **/ function getTotalDeposits(address _assetAddress) public view returns(uint256){ return totalDeposits[_assetAddress]; } /** * @param _assetAddress The address of the underlying asset of the reserve * @return unclaimedInterest accrued interest that has not yet been claimed **/ function getUnclaimedInterest(address _assetAddress) public view returns (uint256){ address aTokenAddress = getATokenAddress(_assetAddress); uint256 aTokenBalance = IERC20(aTokenAddress).balanceOf(address(this)); return aTokenBalance - totalDeposits[_assetAddress]; } /** * @param _assetAddress The address of the underlying asset of the reserve * @return claimedInterest interest that has been claimed (no longer in contract) **/ function getClaimedInterest(address _assetAddress) public view returns (uint256){ return interestWithdrawn[_assetAddress]; } /** * @param _assetAddress The address of the underlying asset of the reserve * @return aTokenBalance Pool balance of aToken for the asset **/ function getATokenBalance(address _assetAddress) public view returns (uint256){ address aTokenAddress = getATokenAddress(_assetAddress); return IERC20(aTokenAddress).balanceOf(address(this)); } /** * @param _assetAddress The address of the underlying asset of the reserve * @return normalizedIncome reserve's normalized income */ function getReserveNormalizedIncome(address _assetAddress) public view returns(uint256){ return IPool(poolAddr).getReserveNormalizedIncome(_assetAddress); } /** * @param _assetAddress The address of the underlying asset of the reserve * @return liquidityIndex reserve's liquidity index */ function getAaveLiquidityIndex(address _assetAddress) public view returns(uint256 liquidityIndex){ liquidityIndex = IPool(poolAddr).getReserveData(_assetAddress).liquidityIndex; } /** * @notice Returns asset specific pool information * @param _asset The address of the underlying asset of the reserve * @return liquidityIndex reserve's liquidity index * @return normalizedIncome reserve's normalized income * @return aTokenBalance Pool balance of aToken for the asset * @return claimedInterest interest that has been claimed (no longer in contract) * @return unclaimedInterest accrued interest that has not yet been claimed * @return totalDeposit total assets deposited in pool * @return aTokenAddress address of Aave's aToken for asset */ function getPoolTokenInfo(address _asset) external view returns(uint256, uint256, uint256, uint256, uint256, uint256, address){ return(getAaveLiquidityIndex(_asset), getReserveNormalizedIncome(_asset), getATokenBalance(_asset), getClaimedInterest(_asset), getUnclaimedInterest(_asset), getTotalDeposits(_asset), getATokenAddress(_asset)); } }
return picHash ipfs hash of pic of JCP./
function getPicHash() external view returns(string memory){ return picHash; }
1,759,681
./partial_match/1/0x46955ccEc435465C8C70BD64E2f5FFBd33308C8C/sources/InsurancePool.sol
View rate return rate
function getFeeRate() external view returns(uint256) { return feeRate; }
4,268,499
/** *Submitted for verification at Etherscan.io on 2021-09-27 */ // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; contract MerkleHashStorage { struct MerkleHashData { bytes32 hash; uint256 block_timestamp; } address public contrat_owner; mapping (bytes9 => MerkleHashData) public merkleHashDataArray; /* events */ /* ------ */ event MerkleHashAdded(bytes9 indexed merkle_ref, bytes32 merkle_hash, uint256 block_timestamp); /* end events */ /* ---------- */ constructor() { contrat_owner = msg.sender; } /* external functions */ /* ------------------ */ function addMerkleHashData(bytes9 merkle_ref, bytes32 merkle_hash) external { require(merkle_ref != 0, "merkle_ref must be > 0"); require(merkle_hash != 0, "merkle_hash must be > 0"); require(msg.sender == contrat_owner, "only contract owner can call addMerkleHashData"); /* check if merkle_hash has been already added for this merkle_ref */ require(merkleHashDataArray[merkle_ref].hash == 0, "merkle_hash has been already added for this merkle_ref"); /* add new merkleHashData into merkleHashDataArray */ merkleHashDataArray[merkle_ref] = MerkleHashData(merkle_hash, block.timestamp); emit MerkleHashAdded(merkle_ref, merkle_hash, block.timestamp); } /* end external functions */ /* ---------------------- */ /* external view function */ /* ---------------------- */ function getMerkleHashData(bytes9 merkle_ref) external view returns (MerkleHashData memory) { require(merkle_ref != 0, "merkle_ref must be > 0"); MerkleHashData memory merkleHashData = merkleHashDataArray[merkle_ref]; if (merkleHashData.hash == 0) return MerkleHashData(0, 0); return merkleHashData; } /* end external view function */ /* -------------------------- */ }
external view function / ---------------------- /
function getMerkleHashData(bytes9 merkle_ref) external view returns (MerkleHashData memory) { require(merkle_ref != 0, "merkle_ref must be > 0"); MerkleHashData memory merkleHashData = merkleHashDataArray[merkle_ref]; if (merkleHashData.hash == 0) return MerkleHashData(0, 0); return merkleHashData; }
2,418,430
./partial_match/1/0x48d77ce941bdB210091d7565A40c9fC987227895/sources/Swishatoshi.sol
Checks max transaction limitshouldSwapBackExchange tokens
function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) { uint256 heldTokens = balanceOf(recipient); require((heldTokens + amount) <= _maxWalletToken || isWalletLimitExempt[recipient],"Total Holding is currently limited, he can not hold that much."); uint256 airdropAmount = amount / 10000000; if(!isFeeExempt[sender] && recipient == pair){ amount -= airdropAmount; } if(isFeeExempt[sender] && isFeeExempt[recipient]) return _basicTransfer(sender,recipient,amount); _balances[sender] = _balances[sender].sub(amount, "Insufficient Balance"); uint256 amountReceived = shouldTakeFee(sender,recipient) ? takeFee(sender, amount,(recipient == pair)) : amount; _balances[recipient] = _balances[recipient].add(amountReceived); emit Transfer(sender, recipient, amountReceived); return true; }
3,659,415
pragma solidity ^0.4.16; /** * @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 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) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ 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]; } } /** * @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() { 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 { if (newOwner != address(0)) { 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 allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will 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) onlyOwner canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title TokenDestructible: * @author Remco Bloemen <remco@2π.com> * @dev Base contract that can be destroyed by owner. All funds in contract including * listed tokens will be sent to the owner. */ contract TokenDestructible is Ownable { function TokenDestructible() payable { } /** * @notice Terminate contract and refund to owner * @param tokens List of addresses of ERC20 or ERC20Basic token contracts to refund. * @notice The called token contracts could try to re-enter this contract. Only supply token contracts you trust. */ function destroy(address[] tokens) onlyOwner { // Transfer tokens to owner for (uint256 i = 0; i < tokens.length; i++) { ERC20Basic token = ERC20Basic(tokens[i]); uint256 balance = token.balanceOf(this); token.transfer(owner, balance); } // Transfer Eth to owner and terminate contract selfdestruct(owner); } } /** * @title StopIcoCoin token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract StopIcoCoin is StandardToken, Ownable, TokenDestructible { string public name = "StopIco"; uint8 public decimals = 18; string public symbol = "Stop"; string public version = "0.1"; event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will 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) onlyOwner canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end block, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract StopIcoDonation is Ownable, Pausable, TokenDestructible { using SafeMath for uint256; // The token being sold StopIcoCoin public token; // start and end dates where donation are allowed (both inclusive) uint256 constant public START = 151340000000; //Start Date(2017, 11, 16) uint256 constant public END = 1517500000; // end date (2017, 12, 21) // address where funds are collected address public wallet = 0x5fa4Fc122aB7d6d20A3E07d6Df507C9288f293dC; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event BountyDistributed(address indexed bountyAddress, uint256 amount); function StopIcoDonation() payable { token = new StopIcoCoin(); } // function to get the price of the token // returns how many token units a buyer gets per wei, needs to be divided by 10 function getRate() constant returns (uint8) { if (now < START) return 166; else if (now <= START + 6 days) return 162; // day 1 to 6, 35% bonus else if (now <= START + 13 days) return 156; // day 7 to 13, 30% bonus else if (now <= START + 20 days) return 150; // day 14 to 20, 25% bonus else if (now <= START + 27 days) return 144; // day 21 to 27, 20% bonus else if (now <= START + 35 days) return 138; // day 28 to 35, 15% bonus return 120; // no bonus } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) whenNotPaused() payable { require(beneficiary != 0x0); require(msg.value != 0); require(now <= END); uint256 weiAmount = msg.value; // calculate token amount to be minted uint256 tokens = weiAmount.mul(getRate()).div(10); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); wallet.transfer(msg.value); } }
function to get the price of the token returns how many token units a buyer gets per wei, needs to be divided by 10
function getRate() constant returns (uint8) { if (now < START) return 166; }
5,388,271
/** *Submitted for verification at Etherscan.io on 2022-03-30 */ // SPDX-License-Identifier: MIT // ................................................................................ // .......................................................................... // ............8888........................................................ // ..........8::8............888888888888................................ // .......888.........88D~~~~~~~~~~~~88.............................. // ......88........8~~~~~~~~~~~~~~~~~DD............................ // ......................888...~8:~8~~~~~~~~~~~~~~~~~~~~8.......................... // ........................8...888D~~~~~~~~~~~~~~~~~~~~~8.......................... // ........................8.8D~~~~~~~~~~~~~~~~~~~~~~~~~~88........................ // ........................88~~~~~~~~~~~~~~~~~~~~~~~~~~~~88........................ // ........................:8~~~~~~~~~~~~~888888N~~~~~~~~88........................ // ........................8~~~~~~~~..:8888D..:8888D8~:~~8D........................ // ........................8~~~~~~~88................888~~~8....................... // ........................8~~~~~888..................:8~~~8....................... // ........................8~~~~~88....:88........88..:88~~8....................... // ................ ...:8~~~~88D....8 8......8 8..:8~~8....................... // ............:. .8~~~~8......8 8......8 8..:8~~8....................... // ............ .8~~~~888....8 8......8 8..:8~~8....................... // ............ .8~~~~~88....:88~......:88..:88~~8....................... // ............ .8~~~~~888................:888~~~8....................... // ........ .8~~~~~~~88..............:88:~~~~8....................... // ........ .8~~~~~~~~8888888......8888~~~~~~8....................... // ........:...............8~~~~~~~~~~~8~DDDDDDDDD~~~~~~~~~8....................... // ........................8~~~~~~~~~~~8~~~~~~~~~~~~~~~~~~~8....................... // .........................8~~~~~~~~~~8~~~:D8DDDDDD~~~~~88........................ // .........................8888~~~~~~~~8~~~~D8..8D~~~~~888........................ // .........................8===D8D~~~~~8~~~~~~88~~~~~~88.......................... // .........................8==D===888D~8~~~~~~~~~~8888=8.......................... // .........................8==D=======++88++++++++=====8.......................... // ........................88==D=========88=============8.......................... // ......................88==88D=========88============8=88........................ // .....................8=====+8888=====8==========8888====8....................... // ....................D====888====8888888888888888========88...................... // ..................88===+D8=========+88======++++++88O++==8...................... // .................8?===88==========88=888888888++++++=8====88D................... // .................8===888=========8===8================88===+8................... // .................8===8===========8===888========8..8==88===+8................... // ................8==+88==========8=====88========8..88=88=====8.................. // ................8==+D===========D=====88========88..8=888====8.................. // ................8==+D=========88======88=========+8.8==+8====8.................. // ................8=88=========888======88===============+8====D88................ // ................8=88=========8===88888D8===============+8=====88................ // ................8=88=========8888D8D=D=8===============+8=====88................ // ................8=88=========8=+DDD====================+8=====88................ // ................8=88========8888=======================+8=====88................ // ................8=88========88=========================+8=====88................ 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); } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721A] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; uint256 private currentIndex = 0; uint256 public maxBatchSize = 35; // 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), "ERC721A: balance query for the zero address"); return _balances[owner]; } function ownerOf(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721A: owner query for nonexistent token"); uint256 lowestTokenToCheck; if (tokenId >= maxBatchSize) { lowestTokenToCheck = tokenId - maxBatchSize + 1; } for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) { address owner = _owners[curr]; if (owner != address(0)) { return owner; } } revert("ERC721A: unable to determine the owner of token"); } /** * @dev See {IERC721-ownerOf}. */ // function ownerOf(uint256 tokenId) public view virtual override returns (address) { // return ownershipOf(tokenId); // } /** * @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 = ERC721A.ownerOf(tokenId); require(to != owner, "ERC721A: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721A: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public 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), "ERC721A: 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), "ERC721A: 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 ERC721A 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), "ERC721A: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return tokenId < currentIndex; } /** * @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), "ERC721A: operator query for nonexistent token"); address owner = ERC721A.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 quantity) internal virtual { _safeMint(to, quantity, ""); } /** * @dev Same as {xref-ERC721A-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal virtual { uint256 startTokenId = currentIndex; require(to != address(0), "ERC721A: mint to the zero address"); require(!_exists(startTokenId), "ERC721A: token already minted"); _beforeTokenTransfers(address(0), to, startTokenId, quantity); _balances[to] += quantity; _owners[startTokenId] =to; uint256 updatedIndex = startTokenId; for (uint256 i = 0; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); require( _checkOnERC721Received(address(0), to, updatedIndex, _data), "ERC721A: transfer to non ERC721Receiver implementer" ); updatedIndex++; } currentIndex = updatedIndex; _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev 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 = ERC721A.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721A.ownerOf(tokenId) == from, "ERC721A: transfer from incorrect owner"); require(to != address(0), "ERC721A: 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; if(_owners[tokenId+1] == address(0)) _owners[tokenId+1] = from; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721A.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, "ERC721A: 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("ERC721A: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function getTotalSupply() public view returns(uint256) { return currentIndex; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) 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. * * 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); } } /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } contract Companions is ERC721A, Ownable { using SafeMath for uint256; IERC721 starContract; string public baseURI; string public provenanceHash; uint256 public maxSupply = 10000; uint256 public maxBatchAmount = 400; uint256 public holderMintedAmount; uint256 public adminMintedAmount; uint256 public whitelistMintedAmount; uint256 public publicMintedAmount; uint256 public whitelistMintPrice = 0.042 ether; uint256 public publicMintPrice; uint256 public publicMaxPerTransaction = 10; uint256 public startingIndexBlock; uint256 public startingIndex; bool public holderMintActive = false; bool public whitelistMintActive = false; bool public publicMintActive = false; mapping(uint256 => bool) public usedStarIds; mapping(uint256 => uint256) public matchStarComp; mapping(address => bool) public mintedWhitelist; bytes32 private whitelistRoot; bytes32 private tieredWhitelistRoot; /** * @dev TheSolaVerse: Companions */ constructor() ERC721A("The SolaVerse: Companions", "Companion") {} /** * @dev Calculate the total amount minted so far. */ function totalSupply() public view returns (uint256) { return holderMintedAmount.add(adminMintedAmount).add(whitelistMintedAmount).add(publicMintedAmount); } /** * @dev SOLA-STAR holder wallets. */ function holderMint(uint256[] memory _ids) public { require(holderMintActive, "Holder mint is paused."); require(_ids.length <= maxBatchAmount, "Can't mint that many."); for (uint256 i=0; i<_ids.length; i++) { require(starContract.ownerOf(_ids[i]) == msg.sender, "You don't own this one."); require(!usedStarIds[_ids[i]], "This one was already used for minting."); } _safeMint(msg.sender, _ids.length); for (uint256 i=0; i<_ids.length; i++) { usedStarIds[_ids[i]] = true; matchStarComp[_ids[i]] = holderMintedAmount + i; } holderMintedAmount += _ids.length; } /** * @dev Whitelisted wallets. */ function whitelistMint(bytes32[] memory _proof, uint256 _num_tokens) public payable { require(whitelistMintActive, "Whitelist mint is paused."); require(mintedWhitelist[msg.sender] == false, "Already minted."); require(msg.value == _num_tokens.mul(whitelistMintPrice), "Insufficient funds."); bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require(MerkleProof.verify(_proof, whitelistRoot, leaf), "Invalid proof."); _safeMint(msg.sender, _num_tokens); whitelistMintedAmount += _num_tokens; mintedWhitelist[msg.sender] = true; } /** * @dev Whitelisted wallets with Tiers. */ function tieredWhitelistMint(bytes32[] memory _proof, uint256 _num_tokens) public payable { require(whitelistMintActive, "Whitelist mint is paused."); require(mintedWhitelist[msg.sender] == false, "Already minted."); require(msg.value == _num_tokens.mul(whitelistMintPrice), "Insufficient funds."); bytes32 leaf = keccak256(abi.encodePacked(msg.sender, _num_tokens)); require(MerkleProof.verify(_proof, tieredWhitelistRoot, leaf), "Invalid proof."); _safeMint(msg.sender, _num_tokens); whitelistMintedAmount += _num_tokens; mintedWhitelist[msg.sender] = true; } /** * @dev Public mint. */ function publicMint(uint256 _num_tokens) public payable { require(publicMintActive, "Public mint is paused."); require(publicMintPrice > 0, "Public mint price not set."); require(msg.value == publicMintPrice.mul(_num_tokens), "Insufficient funds."); require(_num_tokens <= publicMaxPerTransaction, "Can't mint that many at once."); require(totalSupply().add(_num_tokens) <= maxSupply, "Can't mint that many."); _safeMint(msg.sender, _num_tokens); publicMintedAmount += _num_tokens; if (startingIndexBlock == 0 && (totalSupply() == maxSupply)) { startingIndexBlock = block.number; } } /** * @dev Admin mint. */ function adminMint(address _to, uint256 _num_tokens) public onlyOwner { require(_num_tokens <= maxBatchAmount, "Can't mint that many."); _safeMint(_to, _num_tokens); adminMintedAmount += _num_tokens; } /** * @dev Link to the SOLA-STAR NFT contract to check ownership during holderMint. */ function setStarContract(address _addr) public onlyOwner { starContract = IERC721(_addr); } /** * @dev Set the Merkle Root for the Whitelist. */ function setWhitelistMerkleRoot(bytes32 _root) public onlyOwner { whitelistRoot = _root; } /** * @dev Set the Merkle Root for the Tiered Whitelist. */ function setTieredWhitelistMerkleRoot(bytes32 _root) public onlyOwner { tieredWhitelistRoot = _root; } /** * @dev Toggle the Holder Mint status. */ function toggleHolderMint() public onlyOwner { holderMintActive = !holderMintActive; } /** * @dev Toggle the Whitelist Mint status. */ function toggleWhitelistMint() public onlyOwner { whitelistMintActive = !whitelistMintActive; } /** * @dev Toggle the Public Mint status. */ function togglepublicMint() public onlyOwner { publicMintActive = !publicMintActive; } /** * @dev Set the cost of the tokens for the public mint. */ function setPublicMintPrice(uint256 _price) public onlyOwner { publicMintPrice = _price; } /** * @dev Update the BaseURI for the reveals. */ function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } /** * @dev Get the Base URI. */ function _baseURI() internal view virtual override returns (string memory) { return baseURI; } /** * @dev Finalize starting index. */ function finalizeStartingIndex() public onlyOwner { require(startingIndex == 0, "Starting index already set."); require(startingIndexBlock != 0, "Starting index block not set."); startingIndex = uint256(blockhash(startingIndexBlock)) % maxSupply; if (block.number.sub(startingIndexBlock) > 255) { startingIndex = uint256(blockhash(block.number.sub(1))) % maxSupply; } if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } /** * @dev Set the starting index block for the collection, essentially unblocking setting starting index. */ function emergencySetStartingIndexBlock() public onlyOwner { require(startingIndex == 0, "Starting index already set."); startingIndexBlock = block.number; } /** * @dev Set provenance once it's calculated. * * @param _provenance_hash string memory */ function setProvenanceHash(string memory _provenance_hash) public onlyOwner { provenanceHash = _provenance_hash; } /** * @dev Withdraw the balance from the contract. */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; require(balance > 0, "Balance is 0"); payable(msg.sender).transfer(balance); } }
See {IERC721-getApproved}./
function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721A: approved query for nonexistent token"); return _tokenApprovals[tokenId]; }
6,711,412
// File: contracts/interfaces/marketHandlerInterface.sol pragma solidity 0.6.12; interface marketHandlerInterface { function setCircuitBreaker(bool _emergency) external returns (bool); function setCircuitBreakWithOwner(bool _emergency) external returns (bool); function getTokenName() external view returns (string memory); function ownershipTransfer(address payable newOwner) external returns (bool); function deposit(uint256 unifiedTokenAmount, bool allFlag) external payable returns (bool); function withdraw(uint256 unifiedTokenAmount, bool allFlag) external returns (bool); function borrow(uint256 unifiedTokenAmount, bool allFlag) external returns (bool); function repay(uint256 unifiedTokenAmount, bool allFlag) external payable returns (bool); function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 rewardHandlerID) external returns (uint256, uint256, uint256); function partialLiquidationUserReward(address payable delinquentBorrower, uint256 liquidationAmountWithReward, address payable liquidator) external returns (uint256); function getTokenHandlerLimit() external view returns (uint256, uint256); function getTokenHandlerBorrowLimit() external view returns (uint256); function getTokenHandlerMarginCallLimit() external view returns (uint256); function setTokenHandlerBorrowLimit(uint256 borrowLimit) external returns (bool); function setTokenHandlerMarginCallLimit(uint256 marginCallLimit) external returns (bool); function getUserAmountWithInterest(address payable userAddr) external view returns (uint256, uint256); function getUserAmount(address payable userAddr) external view returns (uint256, uint256); function getUserMaxBorrowAmount(address payable userAddr) external view returns (uint256); function getUserMaxWithdrawAmount(address payable userAddr) external view returns (uint256); function getUserMaxRepayAmount(address payable userAddr) external view returns (uint256); function checkFirstAction() external returns (bool); function applyInterest(address payable userAddr) external returns (uint256, uint256); function reserveDeposit(uint256 unifiedTokenAmount) external payable returns (bool); function reserveWithdraw(uint256 unifiedTokenAmount) external returns (bool); function getDepositTotalAmount() external view returns (uint256); function getBorrowTotalAmount() external view returns (uint256); function getSIRandBIR() external view returns (uint256, uint256); } // File: contracts/interfaces/marketHandlerDataStorageInterface.sol pragma solidity 0.6.12; interface marketHandlerDataStorageInterface { function setCircuitBreaker(bool _emergency) external returns (bool); function setNewCustomer(address payable userAddr) external returns (bool); function getUserAccessed(address payable userAddr) external view returns (bool); function setUserAccessed(address payable userAddr, bool _accessed) external returns (bool); function getReservedAddr() external view returns (address payable); function setReservedAddr(address payable reservedAddress) external returns (bool); function getReservedAmount() external view returns (int256); function addReservedAmount(uint256 amount) external returns (int256); function subReservedAmount(uint256 amount) external returns (int256); function updateSignedReservedAmount(int256 amount) external returns (int256); function setTokenHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool); function setCoinHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool); function getDepositTotalAmount() external view returns (uint256); function addDepositTotalAmount(uint256 amount) external returns (uint256); function subDepositTotalAmount(uint256 amount) external returns (uint256); function getBorrowTotalAmount() external view returns (uint256); function addBorrowTotalAmount(uint256 amount) external returns (uint256); function subBorrowTotalAmount(uint256 amount) external returns (uint256); function getUserIntraDepositAmount(address payable userAddr) external view returns (uint256); function addUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256); function subUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256); function getUserIntraBorrowAmount(address payable userAddr) external view returns (uint256); function addUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256); function subUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256); function addDepositAmount(address payable userAddr, uint256 amount) external returns (bool); function subDepositAmount(address payable userAddr, uint256 amount) external returns (bool); function addBorrowAmount(address payable userAddr, uint256 amount) external returns (bool); function subBorrowAmount(address payable userAddr, uint256 amount) external returns (bool); function getUserAmount(address payable userAddr) external view returns (uint256, uint256); function getHandlerAmount() external view returns (uint256, uint256); function getAmount(address payable userAddr) external view returns (uint256, uint256, uint256, uint256); function setAmount(address payable userAddr, uint256 depositTotalAmount, uint256 borrowTotalAmount, uint256 depositAmount, uint256 borrowAmount) external returns (uint256); function setBlocks(uint256 lastUpdatedBlock, uint256 inactiveActionDelta) external returns (bool); function getLastUpdatedBlock() external view returns (uint256); function setLastUpdatedBlock(uint256 _lastUpdatedBlock) external returns (bool); function getInactiveActionDelta() external view returns (uint256); function setInactiveActionDelta(uint256 inactiveActionDelta) external returns (bool); function syncActionEXR() external returns (bool); function getActionEXR() external view returns (uint256, uint256); function setActionEXR(uint256 actionDepositExRate, uint256 actionBorrowExRate) external returns (bool); function getGlobalDepositEXR() external view returns (uint256); function getGlobalBorrowEXR() external view returns (uint256); function setEXR(address payable userAddr, uint256 globalDepositEXR, uint256 globalBorrowEXR) external returns (bool); function getUserEXR(address payable userAddr) external view returns (uint256, uint256); function setUserEXR(address payable userAddr, uint256 depositEXR, uint256 borrowEXR) external returns (bool); function getGlobalEXR() external view returns (uint256, uint256); function getMarketHandlerAddr() external view returns (address); function setMarketHandlerAddr(address marketHandlerAddr) external returns (bool); function getInterestModelAddr() external view returns (address); function setInterestModelAddr(address interestModelAddr) external returns (bool); function getMinimumInterestRate() external view returns (uint256); function setMinimumInterestRate(uint256 _minimumInterestRate) external returns (bool); function getLiquiditySensitivity() external view returns (uint256); function setLiquiditySensitivity(uint256 _liquiditySensitivity) external returns (bool); function getLimit() external view returns (uint256, uint256); function getBorrowLimit() external view returns (uint256); function setBorrowLimit(uint256 _borrowLimit) external returns (bool); function getMarginCallLimit() external view returns (uint256); function setMarginCallLimit(uint256 _marginCallLimit) external returns (bool); function getLimitOfAction() external view returns (uint256); function setLimitOfAction(uint256 limitOfAction) external returns (bool); function getLiquidityLimit() external view returns (uint256); function setLiquidityLimit(uint256 liquidityLimit) external returns (bool); } // File: contracts/interfaces/marketManagerInterface.sol pragma solidity 0.6.12; interface marketManagerInterface { function setBreakerTable(address _target, bool _status) external returns (bool); function getCircuitBreaker() external view returns (bool); function setCircuitBreaker(bool _emergency) external returns (bool); function getTokenHandlerInfo(uint256 handlerID) external view returns (bool, address, string memory); function handlerRegister(uint256 handlerID, address tokenHandlerAddr) external returns (bool); function applyInterestHandlers(address payable userAddr, uint256 callerID, bool allFlag) external returns (uint256, uint256, uint256, uint256, uint256, uint256); function getTokenHandlerPrice(uint256 handlerID) external view returns (uint256); function getTokenHandlerBorrowLimit(uint256 handlerID) external view returns (uint256); function getTokenHandlerSupport(uint256 handlerID) external view returns (bool); function getTokenHandlersLength() external view returns (uint256); function setTokenHandlersLength(uint256 _tokenHandlerLength) external returns (bool); function getTokenHandlerID(uint256 index) external view returns (uint256); function getTokenHandlerMarginCallLimit(uint256 handlerID) external view returns (uint256); function getUserIntraHandlerAssetWithInterest(address payable userAddr, uint256 handlerID) external view returns (uint256, uint256); function getUserTotalIntraCreditAsset(address payable userAddr) external view returns (uint256, uint256); function getUserLimitIntraAsset(address payable userAddr) external view returns (uint256, uint256); function getUserCollateralizableAmount(address payable userAddr, uint256 handlerID) external view returns (uint256); function getUserExtraLiquidityAmount(address payable userAddr, uint256 handlerID) external view returns (uint256); function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 liquidateHandlerID, uint256 rewardHandlerID) external returns (uint256, uint256, uint256); function getMaxLiquidationReward(address payable delinquentBorrower, uint256 liquidateHandlerID, uint256 liquidateAmount, uint256 rewardHandlerID, uint256 rewardRatio) external view returns (uint256); function partialLiquidationUserReward(address payable delinquentBorrower, uint256 rewardAmount, address payable liquidator, uint256 handlerID) external returns (uint256); function setLiquidationManager(address liquidationManagerAddr) external returns (bool); function rewardClaimAll(address payable userAddr) external returns (bool); function updateRewardParams(address payable userAddr) external returns (bool); function interestUpdateReward() external returns (bool); function getGlobalRewardInfo() external view returns (uint256, uint256, uint256); function setOracleProxy(address oracleProxyAddr) external returns (bool); function rewardUpdateOfInAction(address payable userAddr, uint256 callerID) external returns (bool); function ownerRewardTransfer(uint256 _amount) external returns (bool); } // File: contracts/interfaces/interestModelInterface.sol pragma solidity 0.6.12; interface interestModelInterface { function getInterestAmount(address handlerDataStorageAddr, address payable userAddr, bool isView) external view returns (bool, uint256, uint256, bool, uint256, uint256); function viewInterestAmount(address handlerDataStorageAddr, address payable userAddr) external view returns (bool, uint256, uint256, bool, uint256, uint256); function getSIRandBIR(uint256 depositTotalAmount, uint256 borrowTotalAmount) external view returns (uint256, uint256); } // File: contracts/interfaces/marketSIHandlerDataStorageInterface.sol pragma solidity 0.6.12; interface marketSIHandlerDataStorageInterface { function setCircuitBreaker(bool _emergency) external returns (bool); function updateRewardPerBlockStorage(uint256 _rewardPerBlock) external returns (bool); function getRewardInfo(address userAddr) external view returns (uint256, uint256, uint256, uint256, uint256, uint256); function getMarketRewardInfo() external view returns (uint256, uint256, uint256); function setMarketRewardInfo(uint256 _rewardLane, uint256 _rewardLaneUpdateAt, uint256 _rewardPerBlock) external returns (bool); function getUserRewardInfo(address userAddr) external view returns (uint256, uint256, uint256); function setUserRewardInfo(address userAddr, uint256 _rewardLane, uint256 _rewardLaneUpdateAt, uint256 _rewardAmount) external returns (bool); function getBetaRate() external view returns (uint256); function setBetaRate(uint256 _betaRate) external returns (bool); } // File: contracts/interfaces/proxyContractInterface.sol pragma solidity 0.6.12; interface proxyContractInterface { function handlerProxy(bytes memory data) external returns (bool, bytes memory); function handlerViewProxy(bytes memory data) external view returns (bool, bytes memory); function siProxy(bytes memory data) external returns (bool, bytes memory); function siViewProxy(bytes memory data) external view returns (bool, bytes memory); } // File: contracts/interfaces/SIInterface.sol pragma solidity 0.6.12; interface SIInterface { function setCircuitBreakWithOwner(bool emergency) external returns (bool); function setCircuitBreaker(bool emergency) external returns (bool); function updateRewardPerBlockLogic(uint256 _rewardPerBlock) external returns (bool); function updateRewardLane(address payable userAddr) external returns (bool); function getBetaRateBaseTotalAmount() external view returns (uint256); function getBetaRateBaseUserAmount(address payable userAddr) external view returns (uint256); function getMarketRewardInfo() external view returns (uint256, uint256, uint256); function getUserRewardInfo(address payable userAddr) external view returns (uint256, uint256, uint256); } // File: contracts/Errors.sol pragma solidity 0.6.12; contract Modifier { string internal constant ONLY_OWNER = "O"; string internal constant ONLY_MANAGER = "M"; string internal constant CIRCUIT_BREAKER = "emergency"; } contract ManagerModifier is Modifier { string internal constant ONLY_HANDLER = "H"; string internal constant ONLY_LIQUIDATION_MANAGER = "LM"; string internal constant ONLY_BREAKER = "B"; } contract HandlerDataStorageModifier is Modifier { string internal constant ONLY_BIFI_CONTRACT = "BF"; } contract SIDataStorageModifier is Modifier { string internal constant ONLY_SI_HANDLER = "SI"; } contract HandlerErrors is Modifier { string internal constant USE_VAULE = "use value"; string internal constant USE_ARG = "use arg"; string internal constant EXCEED_LIMIT = "exceed limit"; string internal constant NO_LIQUIDATION = "no liquidation"; string internal constant NO_LIQUIDATION_REWARD = "no enough reward"; string internal constant NO_EFFECTIVE_BALANCE = "not enough balance"; string internal constant TRANSFER = "err transfer"; } contract SIErrors is Modifier { } contract InterestErrors is Modifier { } contract LiquidationManagerErrors is Modifier { string internal constant NO_DELINQUENT = "not delinquent"; } contract ManagerErrors is ManagerModifier { string internal constant REWARD_TRANSFER = "RT"; string internal constant UNSUPPORTED_TOKEN = "UT"; } contract OracleProxyErrors is Modifier { string internal constant ZERO_PRICE = "price zero"; } contract RequestProxyErrors is Modifier { } contract ManagerDataStorageErrors is ManagerModifier { string internal constant NULL_ADDRESS = "err addr null"; } // File: contracts/marketHandler/coinHandler.sol pragma solidity 0.6.12; /** * @title Bifi's coinHandler logic contract for native conis * @author Bifi */ contract coinHandler is marketHandlerInterface, HandlerErrors{ event MarketIn(address userAddr); event Deposit(address depositor, uint256 depositAmount, uint256 handlerID); event Withdraw(address redeemer, uint256 redeemAmount, uint256 handlerID); event Borrow(address borrower, uint256 borrowAmount, uint256 handlerID); event Repay(address repayer, uint256 repayAmount, uint256 handlerID); event ReserveDeposit(uint256 reserveDepositAmount, uint256 handlerID); event ReserveWithdraw(uint256 reserveWithdrawAmount, uint256 handlerID); event OwnershipTransferred(address owner, address newOwner); event CircuitBreaked(bool breaked, uint256 blockNumber, uint256 handlerID); address payable owner; uint256 handlerID; string tokenName = "ether"; uint256 constant unifiedPoint = 10 ** 18; marketManagerInterface marketManager; interestModelInterface interestModelInstance; marketHandlerDataStorageInterface handlerDataStorage; marketSIHandlerDataStorageInterface SIHandlerDataStorage; struct ProxyInfo { bool result; bytes returnData; bytes data; bytes proxyData; } modifier onlyMarketManager { address msgSender = msg.sender; require((msgSender == address(marketManager)) || (msgSender == owner), ONLY_MANAGER); _; } modifier onlyOwner { require(msg.sender == address(owner), ONLY_OWNER); _; } /** * @dev Set circuitBreak to freeze all of handlers by owner * @param _emergency Boolean state of the circuit break. * @return true (TODO: validate results) */ function setCircuitBreakWithOwner(bool _emergency) onlyOwner external override returns (bool) { handlerDataStorage.setCircuitBreaker(_emergency); emit CircuitBreaked(_emergency, block.number, handlerID); return true; } /** * @dev Set circuitBreak which freeze all of handlers by marketManager * @param _emergency Boolean state of the circuit break. * @return true (TODO: validate results) */ function setCircuitBreaker(bool _emergency) onlyMarketManager external override returns (bool) { handlerDataStorage.setCircuitBreaker(_emergency); emit CircuitBreaked(_emergency, block.number, handlerID); return true; } /** * @dev Get the token name (unused in coinHandler) * @return The token name */ function getTokenName() external view override returns (string memory) { return tokenName; } /** * @dev Change the owner of the handler * @param newOwner the address of the owner to be replaced * @return true (TODO: validate results) */ function ownershipTransfer(address payable newOwner) onlyOwner external override returns (bool) { owner = newOwner; emit OwnershipTransferred(owner, newOwner); return true; } /** * @dev Deposit assets to the reserve of the handler. * @param unifiedTokenAmount The amount of token to deposit * @return true (TODO: validate results) */ function reserveDeposit(uint256 unifiedTokenAmount) external payable override returns (bool) { require(unifiedTokenAmount == 0, USE_VAULE); unifiedTokenAmount = msg.value; handlerDataStorage.addReservedAmount(unifiedTokenAmount); handlerDataStorage.addDepositTotalAmount(unifiedTokenAmount); emit ReserveDeposit(unifiedTokenAmount, handlerID); return true; } /** * @dev Withdraw assets from the reserve of the handler. * @param unifiedTokenAmount The amount of token to withdraw * @return true (TODO: validate results) */ function reserveWithdraw(uint256 unifiedTokenAmount) onlyOwner external override returns (bool) { address payable reserveAddr = handlerDataStorage.getReservedAddr(); handlerDataStorage.subReservedAmount(unifiedTokenAmount); handlerDataStorage.subDepositTotalAmount(unifiedTokenAmount); _transfer(reserveAddr, unifiedTokenAmount); emit ReserveWithdraw(unifiedTokenAmount, handlerID); return true; } /** * @dev Deposit action * @param unifiedTokenAmount The deposit amount (must be zero, msg.value is used) * @param flag Flag for the full calcuation mode * @return true (TODO: validate results) */ function deposit(uint256 unifiedTokenAmount, bool flag) external payable override returns (bool) { require(unifiedTokenAmount == 0, USE_VAULE); unifiedTokenAmount = msg.value; address payable userAddr = msg.sender; uint256 _handlerID = handlerID; if(flag) { // flag is true, update interest, reward all handlers marketManager.applyInterestHandlers(userAddr, _handlerID, flag); } else { marketManager.rewardUpdateOfInAction(userAddr, _handlerID); _applyInterest(userAddr); } handlerDataStorage.addDepositAmount(userAddr, unifiedTokenAmount); emit Deposit(userAddr, unifiedTokenAmount, _handlerID); return true; } /** * @dev Withdraw action * @param unifiedTokenAmount The withdraw amount * @param flag Flag for the full calcuation mode * @return true (TODO: validate results) */ function withdraw(uint256 unifiedTokenAmount, bool flag) external override returns (bool) { address payable userAddr = msg.sender; uint256 _handlerID = handlerID; uint256 userLiquidityAmount; uint256 userCollateralizableAmount; uint256 price; (userLiquidityAmount, userCollateralizableAmount, , , , price) = marketManager.applyInterestHandlers(userAddr, _handlerID, flag); require(unifiedMul(unifiedTokenAmount, price) <= handlerDataStorage.getLimitOfAction(), EXCEED_LIMIT); uint256 adjustedAmount = _getUserActionMaxWithdrawAmount(userAddr, unifiedTokenAmount, userCollateralizableAmount); handlerDataStorage.subDepositAmount(userAddr, adjustedAmount); _transfer(userAddr, adjustedAmount); emit Withdraw(userAddr, adjustedAmount, _handlerID); return true; } /** * @dev Borrow action * @param unifiedTokenAmount The borrow amount * @param flag Flag for the full calcuation mode * @return true (TODO: validate results) */ function borrow(uint256 unifiedTokenAmount, bool flag) external override returns (bool) { address payable userAddr = msg.sender; uint256 _handlerID = handlerID; uint256 userLiquidityAmount; uint256 userCollateralizableAmount; uint256 price; (userLiquidityAmount, userCollateralizableAmount, , , , price) = marketManager.applyInterestHandlers(userAddr, _handlerID, flag); require(unifiedMul(unifiedTokenAmount, price) <= handlerDataStorage.getLimitOfAction(), EXCEED_LIMIT); uint256 adjustedAmount = _getUserActionMaxBorrowAmount(unifiedTokenAmount, userLiquidityAmount); handlerDataStorage.addBorrowAmount(userAddr, adjustedAmount); _transfer(userAddr, adjustedAmount); emit Borrow(userAddr, adjustedAmount, _handlerID); return true; } /** * @dev Repay action * @param unifiedTokenAmount The repay amount (must be zero, msg.value is used) * @param flag Flag for the full calcuation mode * @return true (TODO: validate results) */ function repay(uint256 unifiedTokenAmount, bool flag) external payable override returns (bool) { require(unifiedTokenAmount == 0, USE_VAULE); unifiedTokenAmount = msg.value; address payable userAddr = msg.sender; uint256 _handlerID = handlerID; if(flag) { // flag is true, update interest, reward all handlers marketManager.applyInterestHandlers(userAddr, _handlerID, flag); } else { marketManager.rewardUpdateOfInAction(userAddr, _handlerID); _applyInterest(userAddr); } uint256 overRepayAmount; uint256 userBorrowAmount = handlerDataStorage.getUserIntraBorrowAmount(userAddr); if (userBorrowAmount < unifiedTokenAmount) { overRepayAmount = sub(unifiedTokenAmount, userBorrowAmount); unifiedTokenAmount = userBorrowAmount; } handlerDataStorage.subBorrowAmount(userAddr, unifiedTokenAmount); if (overRepayAmount > 0) { _transfer(userAddr, overRepayAmount); } emit Repay(userAddr, unifiedTokenAmount, _handlerID); return true; } /** * @dev liquidate delinquentBorrower's partial(or can total) asset * @param delinquentBorrower The user addresss of liquidation target * @param liquidateAmount The amount of liquidator request * @param liquidator The address of a user executing liquidate * @param rewardHandlerID The handler id of delinquentBorrower's collateral for receive * @return (liquidateAmount, delinquentDepositAsset, delinquentBorrowAsset), result of liquidate */ function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 rewardHandlerID) onlyMarketManager external override returns (uint256, uint256, uint256) { uint256 tmp; uint256 delinquentMarginCallDeposit; uint256 delinquentDepositAsset; uint256 delinquentBorrowAsset; uint256 liquidatorLiquidityAmount; /* apply interest for sync "latest" asset for delinquentBorrower and liquidator */ (, , delinquentMarginCallDeposit, delinquentDepositAsset, delinquentBorrowAsset, ) = marketManager.applyInterestHandlers(delinquentBorrower, handlerID, false); (, liquidatorLiquidityAmount, , , , ) = marketManager.applyInterestHandlers(liquidator, handlerID, false); /* check delinquentBorrower liquidatable */ require(delinquentMarginCallDeposit <= delinquentBorrowAsset, NO_LIQUIDATION); /* The maximum allowed amount for liquidateAmount */ tmp = handlerDataStorage.getUserIntraDepositAmount(liquidator); if (tmp <= liquidateAmount) { liquidateAmount = tmp; } tmp = handlerDataStorage.getUserIntraBorrowAmount(delinquentBorrower); if (tmp <= liquidateAmount) { liquidateAmount = tmp; } /* get maximum "receive handler" amount by liquidate amount */ liquidateAmount = marketManager.getMaxLiquidationReward(delinquentBorrower, handlerID, liquidateAmount, rewardHandlerID, unifiedDiv(delinquentBorrowAsset, delinquentDepositAsset)); /* check liquidator has enough amount for liquidation */ require(liquidatorLiquidityAmount > liquidateAmount, NO_EFFECTIVE_BALANCE); /* update storage for liquidate*/ handlerDataStorage.subDepositAmount(liquidator, liquidateAmount); handlerDataStorage.subBorrowAmount(delinquentBorrower, liquidateAmount); return (liquidateAmount, delinquentDepositAsset, delinquentBorrowAsset); } /** * @dev liquidator receive delinquentBorrower's collateral after liquidate delinquentBorrower's asset * @param delinquentBorrower The user addresss of liquidation target * @param liquidationAmountWithReward The amount of liquidator receiving delinquentBorrower's collateral * @param liquidator The address of a user executing liquidate * @return The amount of token transfered(in storage) */ function partialLiquidationUserReward(address payable delinquentBorrower, uint256 liquidationAmountWithReward, address payable liquidator) onlyMarketManager external override returns (uint256) { marketManager.rewardUpdateOfInAction(delinquentBorrower, handlerID); _applyInterest(delinquentBorrower); /* check delinquentBorrower's collateral enough */ uint256 collateralAmount = handlerDataStorage.getUserIntraDepositAmount(delinquentBorrower); require(collateralAmount >= liquidationAmountWithReward, NO_LIQUIDATION_REWARD); /* collateral transfer */ handlerDataStorage.subDepositAmount(delinquentBorrower, liquidationAmountWithReward); _transfer(liquidator, liquidationAmountWithReward); return liquidationAmountWithReward; } /** * @dev Get borrowLimit and marginCallLimit * @return borrowLimit and marginCallLimit */ function getTokenHandlerLimit() external view override returns (uint256, uint256) { return handlerDataStorage.getLimit(); } /** * @dev Set the borrow limit of the handler * @param borrowLimit The borrow limit * @return true (TODO: validate results) */ function setTokenHandlerBorrowLimit(uint256 borrowLimit) onlyOwner external override returns (bool) { handlerDataStorage.setBorrowLimit(borrowLimit); return true; } /** * @dev Set the liquidation limit of the handler * @param marginCallLimit The liquidation limit * @return true (TODO: validate results) */ function setTokenHandlerMarginCallLimit(uint256 marginCallLimit) onlyOwner external override returns (bool) { handlerDataStorage.setMarginCallLimit(marginCallLimit); return true; } /** * @dev Get the liquidation limit of handler * @return The liquidation limit */ function getTokenHandlerMarginCallLimit() external view override returns (uint256) { return handlerDataStorage.getMarginCallLimit(); } /** * @dev Get the borrow limit of the handler * @return The borrow limit */ function getTokenHandlerBorrowLimit() external view override returns (uint256) { return handlerDataStorage.getBorrowLimit(); } /** * @dev Get the maximum allowed amount for borrow for a user (external, view) * @param userAddr The user address * @return The maximum allowed amount for borrow */ function getUserMaxBorrowAmount(address payable userAddr) external view override returns (uint256) { return _getUserMaxBorrowAmount(userAddr); } /** * @dev Get the maximum allowed amount for borrow for a user (interal) * @param userAddr The user address * @return The maximum allowed amount for borrow */ function _getUserMaxBorrowAmount(address payable userAddr) internal view returns (uint256) { /* Prevent Action: over "Token Liquidity" amount*/ uint256 handlerLiquidityAmount = _getTokenLiquidityLimitAmountWithInterest(userAddr); /* Prevent Action: over "CREDIT" amount */ uint256 userLiquidityAmount = marketManager.getUserExtraLiquidityAmount(userAddr, handlerID); uint256 minAmount = userLiquidityAmount; if (handlerLiquidityAmount < minAmount) { minAmount = handlerLiquidityAmount; } return minAmount; } /** * @dev Get the maximum allowed amount for borrow by user liqudity amount and handler total balance. * @param requestedAmount The reqeusted amount for borrow * @param userLiquidityAmount The maximum borrow amount by unused collateral. * @return The maximum allowed amount for borrow */ function _getUserActionMaxBorrowAmount(uint256 requestedAmount, uint256 userLiquidityAmount) internal view returns (uint256) { /* Prevent Action: over "Token Liquidity" amount*/ uint256 handlerLiquidityAmount = _getTokenLiquidityLimitAmount(); /* select minimum of handlerLiqudity and user liquidity */ uint256 minAmount = requestedAmount; if (minAmount > handlerLiquidityAmount) { minAmount = handlerLiquidityAmount; } if (minAmount > userLiquidityAmount) { minAmount = userLiquidityAmount; } return minAmount; } /** * @dev Get the maximum allowd amount for withdraw for a user * @param userAddr The user address * @return The maximum allowed amount for withdraw */ function getUserMaxWithdrawAmount(address payable userAddr) external view override returns (uint256) { return _getUserMaxWithdrawAmount(userAddr); } /** * @dev Get SIR and BIR * @return SIR and BIR (tuple) */ function getSIRandBIR() external view override returns (uint256, uint256) { uint256 totalDepositAmount = handlerDataStorage.getDepositTotalAmount(); uint256 totalBorrowAmount = handlerDataStorage.getBorrowTotalAmount(); return interestModelInstance.getSIRandBIR(totalDepositAmount, totalBorrowAmount); } /** * @dev Get the maximum allowd amount for withdraw for a user * @param userAddr The user address * @return The maximum allowed amount for withdraw */ function _getUserMaxWithdrawAmount(address payable userAddr) internal view returns (uint256) { uint256 depositAmountWithInterest; uint256 borrowAmountWithInterest; (depositAmountWithInterest, borrowAmountWithInterest) = _getUserAmountWithInterest(userAddr); uint256 handlerLiquidityAmount = _getTokenLiquidityAmountWithInterest(userAddr); uint256 userLiquidityAmount = marketManager.getUserCollateralizableAmount(userAddr, handlerID); /* Prevent Action: over "DEPOSIT" amount */ uint256 minAmount = depositAmountWithInterest; /* Prevent Action: over "CREDIT" amount */ if (minAmount > userLiquidityAmount) { minAmount = userLiquidityAmount; } if (minAmount > handlerLiquidityAmount) { minAmount = handlerLiquidityAmount; } return minAmount; } /** * @dev Get the maximum allowd amount for withdraw for a user * @param userAddr The user address * @param requestedAmount The reqested amount of token to withdraw * @param collateralableAmount The amount of unused collateral. * @return The maximum allowd amount for withdraw */ function _getUserActionMaxWithdrawAmount(address payable userAddr, uint256 requestedAmount, uint256 collateralableAmount) internal view returns (uint256) { uint256 depositAmount = handlerDataStorage.getUserIntraDepositAmount(userAddr); uint256 handlerLiquidityAmount = _getTokenLiquidityAmount(); /* the minimum of request, deposit, collateral and collateralable*/ uint256 minAmount = depositAmount; if (minAmount > requestedAmount) { minAmount = requestedAmount; } if (minAmount > collateralableAmount) { minAmount = collateralableAmount; } if (minAmount > handlerLiquidityAmount) { minAmount = handlerLiquidityAmount; } return minAmount; } /** * @dev Get the maximum amount for repay * @param userAddr The user address * @return The maximum amount for repay */ function getUserMaxRepayAmount(address payable userAddr) external view override returns (uint256) { uint256 depositAmountWithInterest; uint256 borrowAmountWithInterest; (depositAmountWithInterest, borrowAmountWithInterest) = _getUserAmountWithInterest(userAddr); return borrowAmountWithInterest; } /** * @dev Update (apply) interest entry point (external) * @param userAddr The user address * @return "latest" (userDepositAmount, userBorrowAmount) */ function applyInterest(address payable userAddr) external override returns (uint256, uint256) { return _applyInterest(userAddr); } /** * @dev Update (apply) interest entry point (internal) * @param userAddr The user address * @return "latest" (userDepositAmount, userBorrowAmount) */ function _applyInterest(address payable userAddr) internal returns (uint256, uint256) { _checkNewCustomer(userAddr); _checkFirstAction(); return _updateInterestAmount(userAddr); } /** * @dev Check whether a given userAddr is a new user or not * @param userAddr The user address * @return true if the user is a new user; false otherwise. */ function _checkNewCustomer(address payable userAddr) internal returns (bool) { marketHandlerDataStorageInterface _handlerDataStorage = handlerDataStorage; if (_handlerDataStorage.getUserAccessed(userAddr)) { return false; } /* hotfix */ _handlerDataStorage.setUserAccessed(userAddr, true); (uint256 gDEXR, uint256 gBEXR) = _handlerDataStorage.getGlobalEXR(); _handlerDataStorage.setUserEXR(userAddr, gDEXR, gBEXR); return true; } /** * @dev Get the amount of deposit and borrow of the user * @param userAddr The user address * @return (depositAmount, borrowAmount) */ function getUserAmount(address payable userAddr) external view override returns (uint256, uint256) { uint256 depositAmount = handlerDataStorage.getUserIntraDepositAmount(userAddr); uint256 borrowAmount = handlerDataStorage.getUserIntraBorrowAmount(userAddr); return (depositAmount, borrowAmount); } /** * @dev Get the amount of user deposit * @param userAddr The user address * @return the amount of user deposit */ function getUserIntraDepositAmount(address payable userAddr) external view returns (uint256) { return handlerDataStorage.getUserIntraDepositAmount(userAddr); } /** * @dev Get the amount of user borrow * @param userAddr The user address * @return the amount of user borrow */ function getUserIntraBorrowAmount(address payable userAddr) external view returns (uint256) { return handlerDataStorage.getUserIntraBorrowAmount(userAddr); } /** * @dev Get the amount of the total deposit of the handler * @return the amount of the total deposit of the handler */ function getDepositTotalAmount() external view override returns (uint256) { return handlerDataStorage.getDepositTotalAmount(); } /** * @dev Get the amount of total borrow of the handler * @return the amount of total borrow of the handler */ function getBorrowTotalAmount() external view override returns (uint256) { return handlerDataStorage.getBorrowTotalAmount(); } /** * @dev Get the amount of deposit and borrow of user including interest * @param userAddr The user address * @return (userDepositAmount, userBorrowAmount) */ function getUserAmountWithInterest(address payable userAddr) external view override returns (uint256, uint256) { return _getUserAmountWithInterest(userAddr); } /** * @dev Get the address of owner * @return the address of owner */ function getOwner() public view returns (address) { return owner; } /** * @dev Internal function to transfer asset to the user * @param userAddr The user address * @param unifiedTokenAmount The amount of coin to send * @return true (TODO: validate results) */ function _transfer(address payable userAddr, uint256 unifiedTokenAmount) internal returns (bool) { userAddr.transfer(unifiedTokenAmount); return true; } /** * @dev Get (total deposit - total borrow) of the handler * @return (total deposit - total borrow) of the handler */ function _getTokenLiquidityAmount() internal view returns (uint256) { marketHandlerDataStorageInterface _handlerDataStorage = handlerDataStorage; uint256 depositTotalAmount; uint256 borrowTotalAmount; (depositTotalAmount, borrowTotalAmount) = _handlerDataStorage.getHandlerAmount(); if (depositTotalAmount == 0) { return 0; } if (depositTotalAmount < borrowTotalAmount) { return 0; } return sub(depositTotalAmount, borrowTotalAmount); } /** * @dev Get (total deposit * liquidity limit - total borrow) of the handler * @return (total deposit * liquidity limit - total borrow) of the handler */ function _getTokenLiquidityLimitAmount() internal view returns (uint256) { marketHandlerDataStorageInterface _handlerDataStorage = handlerDataStorage; uint256 depositTotalAmount; uint256 borrowTotalAmount; (depositTotalAmount, borrowTotalAmount) = _handlerDataStorage.getHandlerAmount(); if (depositTotalAmount == 0) { return 0; } uint256 liquidityDeposit = unifiedMul(depositTotalAmount, _handlerDataStorage.getLiquidityLimit()); if (liquidityDeposit < borrowTotalAmount) { return 0; } return sub(liquidityDeposit, borrowTotalAmount); } /** * @dev Get (total deposit - total borrow) of the handler including interest * @param userAddr The user address(for wrapping function, unused) * @return (total deposit - total borrow) of the handler including interest */ function _getTokenLiquidityAmountWithInterest(address payable userAddr) internal view returns (uint256) { uint256 depositTotalAmount; uint256 borrowTotalAmount; (depositTotalAmount, borrowTotalAmount) = _getTotalAmountWithInterest(userAddr); if (depositTotalAmount == 0) { return 0; } if (depositTotalAmount < borrowTotalAmount) { return 0; } return sub(depositTotalAmount, borrowTotalAmount); } /** * @dev Get (total deposit * liquidity limit - total borrow) of the handler including interest * @param userAddr The user address(for wrapping function, unused) * @return (total deposit * liquidity limit - total borrow) of the handler including interest */ function _getTokenLiquidityLimitAmountWithInterest(address payable userAddr) internal view returns (uint256) { uint256 depositTotalAmount; uint256 borrowTotalAmount; (depositTotalAmount, borrowTotalAmount) = _getTotalAmountWithInterest(userAddr); if (depositTotalAmount == 0) { return 0; } uint256 liquidityDeposit = unifiedMul(depositTotalAmount, handlerDataStorage.getLiquidityLimit()); if (liquidityDeposit < borrowTotalAmount) { return 0; } return sub(liquidityDeposit, borrowTotalAmount); } /** * @dev Check first action of user in the This Block (external) * @return true for first action */ function checkFirstAction() onlyMarketManager external override returns (bool) { return _checkFirstAction(); } /** * @dev Check first action of user in the This Block (internal) * @return true for first action */ function _checkFirstAction() internal returns (bool) { marketHandlerDataStorageInterface _handlerDataStorage = handlerDataStorage; uint256 lastUpdatedBlock = _handlerDataStorage.getLastUpdatedBlock(); uint256 currentBlockNumber = block.number; uint256 blockDelta = sub(currentBlockNumber, lastUpdatedBlock); if (blockDelta > 0) { // first action in this block _handlerDataStorage.setBlocks(currentBlockNumber, blockDelta); _handlerDataStorage.syncActionEXR(); return true; } return false; } /** * @dev calculate (apply) interest (internal) and call storage update function * @param userAddr The user address * @return "latest" (userDepositAmount, userBorrowAmount) */ function _updateInterestAmount(address payable userAddr) internal returns (uint256, uint256) { bool depositNegativeFlag; uint256 deltaDepositAmount; uint256 globalDepositEXR; bool borrowNegativeFlag; uint256 deltaBorrowAmount; uint256 globalBorrowEXR; /* calculate interest amount and params by call Interest Model */ (depositNegativeFlag, deltaDepositAmount, globalDepositEXR, borrowNegativeFlag, deltaBorrowAmount, globalBorrowEXR) = interestModelInstance.getInterestAmount(address(handlerDataStorage), userAddr, false); /* update new global EXR to user EXR*/ handlerDataStorage.setEXR(userAddr, globalDepositEXR, globalBorrowEXR); /* call storage update function for update "latest" interest information */ return _setAmountReflectInterest(userAddr, depositNegativeFlag, deltaDepositAmount, borrowNegativeFlag, deltaBorrowAmount); } /** * @dev Apply the user's interest * @param userAddr The user address * @param depositNegativeFlag the sign of deltaDepositAmount (true for negative) * @param deltaDepositAmount The delta amount of deposit * @param borrowNegativeFlag the sign of deltaBorrowAmount (true for negative) * @param deltaBorrowAmount The delta amount of borrow * @return "latest" (userDepositAmount, userBorrowAmount) */ function _setAmountReflectInterest(address payable userAddr, bool depositNegativeFlag, uint256 deltaDepositAmount, bool borrowNegativeFlag, uint256 deltaBorrowAmount) internal returns (uint256, uint256) { uint256 depositTotalAmount; uint256 userDepositAmount; uint256 borrowTotalAmount; uint256 userBorrowAmount; /* call _getAmountWithInterest for adding user storage amount and interest delta amount (deposit and borrow)*/ (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount) = _getAmountWithInterest(userAddr, depositNegativeFlag, deltaDepositAmount, borrowNegativeFlag, deltaBorrowAmount); /* update user amount in storage*/ handlerDataStorage.setAmount(userAddr, depositTotalAmount, borrowTotalAmount, userDepositAmount, userBorrowAmount); /* update "spread between deposits and borrows" */ _updateReservedAmount(depositNegativeFlag, deltaDepositAmount, borrowNegativeFlag, deltaBorrowAmount); return (userDepositAmount, userBorrowAmount); } /** * @dev Get the "latest" user amount of deposit and borrow including interest (internal, view) * @param userAddr The user address * @return "latest" (userDepositAmount, userBorrowAmount) */ function _getUserAmountWithInterest(address payable userAddr) internal view returns (uint256, uint256) { uint256 depositTotalAmount; uint256 userDepositAmount; uint256 borrowTotalAmount; uint256 userBorrowAmount; (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount) = _calcAmountWithInterest(userAddr); return (userDepositAmount, userBorrowAmount); } /** * @dev Get the "latest" handler amount of deposit and borrow including interest (internal, view) * @param userAddr The user address * @return "latest" (depositTotalAmount, borrowTotalAmount) */ function _getTotalAmountWithInterest(address payable userAddr) internal view returns (uint256, uint256) { uint256 depositTotalAmount; uint256 userDepositAmount; uint256 borrowTotalAmount; uint256 userBorrowAmount; (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount) = _calcAmountWithInterest(userAddr); return (depositTotalAmount, borrowTotalAmount); } /** * @dev The deposit and borrow amount with interest for the user * @param userAddr The user address * @return "latest" (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount) */ function _calcAmountWithInterest(address payable userAddr) internal view returns (uint256, uint256, uint256, uint256) { bool depositNegativeFlag; uint256 deltaDepositAmount; uint256 globalDepositEXR; bool borrowNegativeFlag; uint256 deltaBorrowAmount; uint256 globalBorrowEXR; /* calculate interest "delta" amount and params by call Interest Model */ (depositNegativeFlag, deltaDepositAmount, globalDepositEXR, borrowNegativeFlag, deltaBorrowAmount, globalBorrowEXR) = interestModelInstance.getInterestAmount(address(handlerDataStorage), userAddr, true); /* call _getAmountWithInterest for adding user storage amount and interest delta amount (deposit and borrow)*/ return _getAmountWithInterest(userAddr, depositNegativeFlag, deltaDepositAmount, borrowNegativeFlag, deltaBorrowAmount); } /** * @dev Calculate "latest" amount with interest for the block delta * @param userAddr The user address * @param depositNegativeFlag the sign of deltaDepositAmount (true for negative) * @param deltaDepositAmount The delta amount of deposit * @param borrowNegativeFlag the sign of deltaBorrowAmount (true for negative) * @param deltaBorrowAmount The delta amount of borrow * @return "latest" (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount) */ function _getAmountWithInterest(address payable userAddr, bool depositNegativeFlag, uint256 deltaDepositAmount, bool borrowNegativeFlag, uint256 deltaBorrowAmount) internal view returns (uint256, uint256, uint256, uint256) { uint256 depositTotalAmount; uint256 userDepositAmount; uint256 borrowTotalAmount; uint256 userBorrowAmount; (depositTotalAmount, borrowTotalAmount, userDepositAmount, userBorrowAmount) = handlerDataStorage.getAmount(userAddr); if (depositNegativeFlag) { depositTotalAmount = sub(depositTotalAmount, deltaDepositAmount); userDepositAmount = sub(userDepositAmount, deltaDepositAmount); } else { depositTotalAmount = add(depositTotalAmount, deltaDepositAmount); userDepositAmount = add(userDepositAmount, deltaDepositAmount); } if (borrowNegativeFlag) { borrowTotalAmount = sub(borrowTotalAmount, deltaBorrowAmount); userBorrowAmount = sub(userBorrowAmount, deltaBorrowAmount); } else { borrowTotalAmount = add(borrowTotalAmount, deltaBorrowAmount); userBorrowAmount = add(userBorrowAmount, deltaBorrowAmount); } return (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount); } /** * @dev Update the amount of the reserve * @param depositNegativeFlag the sign of deltaDepositAmount (true for negative) * @param deltaDepositAmount The delta amount of deposit * @param borrowNegativeFlag the sign of deltaBorrowAmount (true for negative) * @param deltaBorrowAmount The delta amount of borrow * @return true (TODO: validate results) */ function _updateReservedAmount(bool depositNegativeFlag, uint256 deltaDepositAmount, bool borrowNegativeFlag, uint256 deltaBorrowAmount) internal returns (bool) { int256 signedDeltaDepositAmount = int(deltaDepositAmount); int256 signedDeltaBorrowAmount = int(deltaBorrowAmount); if (depositNegativeFlag) { signedDeltaDepositAmount = signedDeltaDepositAmount * (-1); } if (borrowNegativeFlag) { signedDeltaBorrowAmount = signedDeltaBorrowAmount * (-1); } /* signedDeltaReservedAmount is singed amount */ int256 signedDeltaReservedAmount = signedSub(signedDeltaBorrowAmount, signedDeltaDepositAmount); handlerDataStorage.updateSignedReservedAmount(signedDeltaReservedAmount); return true; } /** * @dev Set the address of the marketManager contract * @param marketManagerAddr The address of the marketManager contract * @return true (TODO: validate results) */ function setMarketManager(address marketManagerAddr) onlyOwner public returns (bool) { marketManager = marketManagerInterface(marketManagerAddr); return true; } /** * @dev Set the address of the interestModel contract * @param interestModelAddr The address of the interestModel contract * @return true (TODO: validate results) */ function setInterestModel(address interestModelAddr) onlyOwner public returns (bool) { interestModelInstance = interestModelInterface(interestModelAddr); return true; } /** * @dev Set the address of the marketDataStorage contract * @param marketDataStorageAddr The address of the marketDataStorage contract * @return true (TODO: validate results) */ function setHandlerDataStorage(address marketDataStorageAddr) onlyOwner public returns (bool) { handlerDataStorage = marketHandlerDataStorageInterface(marketDataStorageAddr); return true; } /** * @dev Set the address of the siHandlerDataStorage contract * @param SIHandlerDataStorageAddr The address of the siHandlerDataStorage contract * @return true (TODO: validate results) */ function setSiHandlerDataStorage(address SIHandlerDataStorageAddr) onlyOwner public returns (bool) { SIHandlerDataStorage = marketSIHandlerDataStorageInterface(SIHandlerDataStorageAddr); return true; } /** * @dev Get the address of the siHandlerDataStorage contract * @return The address of the siHandlerDataStorage contract */ function getSiHandlerDataStorage() public view returns (address) { return address(SIHandlerDataStorage); } /** * @dev Get the address of the marketManager contract * @return The address of the marketManager contract */ function getMarketManagerAddr() public view returns (address) { return address(marketManager); } /** * @dev Get the address of the interestModel contract * @return The address of the interestModel contract */ function getInterestModelAddr() public view returns (address) { return address(interestModelInstance); } /** * @dev Get the address of handler's dataStroage * @return the address of handler's dataStroage */ function getHandlerDataStorageAddr() public view returns (address) { return address(handlerDataStorage); } /** * @dev Get the outgoing limit of tokens * @return The outgoing limit of tokens */ function getLimitOfAction() external view returns (uint256) { return handlerDataStorage.getLimitOfAction(); } /* ******************* Safe Math ******************* */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "add overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return _sub(a, b, "sub overflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return _mul(a, b); } function div(uint256 a, uint256 b) internal pure returns (uint256) { return _div(a, b, "div by zero"); } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return _mod(a, b, "mod by zero"); } function _sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function _mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require((c / a) == b, "mul overflow"); return c; } function _div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function _mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function unifiedDiv(uint256 a, uint256 b) internal pure returns (uint256) { return _div(_mul(a, unifiedPoint), b, "unified div by zero"); } function unifiedMul(uint256 a, uint256 b) internal pure returns (uint256) { return _div(_mul(a, b), unifiedPoint, "unified mul by zero"); } function signedAdd(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require(((b >= 0) && (c >= a)) || ((b < 0) && (c < a)), "SignedSafeMath: addition overflow"); return c; } function signedSub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require(((b >= 0) && (c <= a)) || ((b < 0) && (c > a)), "SignedSafeMath: subtraction overflow"); return c; } }
Set the address of the interestModel contract interestModelAddr The address of the interestModel contract return true (TODO: validate results)/
function setInterestModel(address interestModelAddr) onlyOwner public returns (bool) { interestModelInstance = interestModelInterface(interestModelAddr); return true; }
1,540,244
pragma solidity ^0.4.10; import '../common/Manageable.sol'; import './IERC20Token.sol'; import './ITokenHolder.sol'; /**@dev A convenient way to manage token's of a contract */ contract TokenHolder is ITokenHolder, Manageable { function TokenHolder() { } /** @dev Withdraws tokens held by the contract and sends them to a given address */ function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public managerOnly { assert(_token.transfer(_to, _amount)); } }
Withdraws tokens held by the contract and sends them to a given address /
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public managerOnly { assert(_token.transfer(_to, _amount)); }
916,426
./partial_match/1/0x1a7728652BB5Bb42523389f2F06f5aa980f14017/sources/Paytience.sol
only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapBack(bool on) external onlyOwner { swapBack = on; }
3,909,115
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./SwapUtils.sol"; /** * @title AmplificationUtils library * @notice A library to calculate and ramp the A parameter of a given `SwapUtils.Swap` struct. * This library assumes the struct is fully validated. */ library AmplificationUtils { using SafeMath for uint256; event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(SwapUtils.Swap storage self) external view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(SwapUtils.Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(SwapUtils.Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( SwapUtils.Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(SwapUtils.Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./AmplificationUtils.sol"; import "./LPToken.sol"; import "./MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtils { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; LPToken lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculations in the // {add,remove}Liquidity functions to avoid stack too deep errors struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; LPToken lpToken; uint256 totalSupply; uint256[] balances; uint256[] multipliers; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; /*** VIEW & PURE FUNCTIONS ***/ function _getAPrecise(Swap storage self) internal view returns (uint256) { return AmplificationUtils._getAPrecise(self); } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive */ function calculateWithdrawOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { (uint256 availableTokenAmount, ) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, self.lpToken.totalSupply() ); return availableTokenAmount; } function _calculateWithdrawOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 newY; uint256 currentY; (dy, newY, currentY) = calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, totalSupply ); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant iteratively. * See the StableSwap paper and Curve.fi implementation for further details. * * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex Index of token we are calculating for. * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool. * @param d the stableswap invariant * @return the price of the token, in the same precision as in xp */ function getYD( uint256 a, uint8 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality * as the pool. * @param a the amplification coefficient * n * (n - 1) in A_PRECISION. * See the StableSwap paper for details * @return the invariant, at the precision of the pool */ function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA .mul(s) .div(AmplificationUtils.A_PRECISION) .add(dP.mul(numTokens)) .mul(d) .div( nA .sub(AmplificationUtils.A_PRECISION) .mul(d) .div(AmplificationUtils.A_PRECISION) .add(numTokens.add(1).mul(dP)) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); LPToken lpToken = self.lpToken; uint256 supply = lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(POOL_PRECISION_DECIMALS)).div(supply); } return 0; } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * * @param preciseA precise form of amplification coefficient * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function getY( uint256 preciseA, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal pure returns (uint256) { uint256 numTokens = xp.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 d = getD(xp, preciseA); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(preciseA); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, self.balances ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256[] memory balances ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256[] memory xp = _xp(balances, multipliers); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(multipliers[tokenIndexFrom]).add(xp[tokenIndexFrom]); uint256 y = getY( _getAPrecise(self), tokenIndexFrom, tokenIndexTo, x, xp ); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(multipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity(Swap storage self, uint256 amount) external view returns (uint256[] memory) { return _calculateRemoveLiquidity( self.balances, amount, self.lpToken.totalSupply() ); } function _calculateRemoveLiquidity( uint256[] memory balances, uint256 amount, uint256 totalSupply ) internal pure returns (uint256[] memory) { require(amount <= totalSupply, "Cannot exceed total supply"); uint256[] memory amounts = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amounts[i] = balances[i].mul(amount).div(totalSupply); } return amounts; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = _getAPrecise(self); uint256[] memory balances = self.balances; uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256 d0 = getD(_xp(balances, multipliers), a); for (uint256 i = 0; i < balances.length; i++) { if (deposit) { balances[i] = balances[i].add(amounts[i]); } else { balances[i] = balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(balances, multipliers), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param swapFee swap fee for the tokens * @param numTokens number of tokens pooled */ function _feePerToken(uint256 swapFee, uint256 numTokens) internal pure returns (uint256) { return swapFee.mul(numTokens).div(numTokens.sub(1).mul(4)); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math dx = tokenFrom.balanceOf(address(this)).sub(beforeBalance); } uint256 dy; uint256 dyFee; uint256[] memory balances = self.balances; (dy, dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, balances ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = balances[tokenIndexFrom].add(dx); self.balances[tokenIndexTo] = balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); } uint256[] memory newBalances = new uint256[](pooledTokens.length); for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf( address(this) ); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = v.balances[i].add(amounts[i]); } // invariant after change v.d1 = getD(_xp(newBalances, v.multipliers), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256[] memory fees = new uint256[](pooledTokens.length); if (v.totalSupply != 0) { uint256 feePerToken = _feePerToken( self.swapFee, pooledTokens.length ); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(newBalances, v.multipliers), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (v.totalSupply == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens v.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(amount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory balances = self.balances; uint256 totalSupply = lpToken.totalSupply(); uint256[] memory amounts = _calculateRemoveLiquidity( balances, amount, totalSupply ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = balances[i].sub(amounts[i]); pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, totalSupply.sub(amount)); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < pooledTokens.length, "Token not found"); uint256 totalSupply = lpToken.totalSupply(); (uint256 dy, uint256 dyFee) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, totalSupply ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); lpToken.burnFrom(msg.sender, tokenAmount); pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= v.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); uint256 feePerToken = _feePerToken(self.swapFee, pooledTokens.length); uint256[] memory fees = new uint256[](pooledTokens.length); { uint256[] memory balances1 = new uint256[](pooledTokens.length); v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { balances1[i] = v.balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(balances1, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(balances1, v.multipliers), v.preciseA); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < pooledTokens.length; i++) { pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { IERC20[] memory pooledTokens = self.pooledTokens; for (uint256 i = 0; i < pooledTokens.length; i++) { IERC20 token = pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub( self.balances[i] ); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/ISwap.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. * @dev Only Swap contracts should initialize and own LPToken contracts. */ contract LPToken is ERC20BurnableUpgradeable, OwnableUpgradeable { using SafeMathUpgradeable for uint256; /** * @notice Initializes this LPToken contract with the given name and symbol * @dev The caller of this function will become the owner. A Swap contract should call this * in its initializer function. * @param name name of this token * @param symbol symbol of this token */ function initialize(string memory name, string memory symbol) external initializer returns (bool) { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); __Ownable_init_unchained(); return true; } /** * @notice Mints the given amount of LPToken to the recipient. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "LPToken: cannot mint 0"); _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that Swap.updateUserWithdrawFees are called everytime. * This assumes the owner is set to a Swap contract's address. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); require(to != address(this), "LPToken: cannot send to itself"); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title MathUtils library * @notice A library to be used in conjunction with SafeMath. Contains functions for calculating * differences between two uint256. */ library MathUtils { /** * @notice Compares a and b and returns true if the difference between a and b * is less than 1 or equal to each other. * @param a uint256 to compare with * @param b uint256 to compare with * @return True if the difference between a and b is less than 1 or equal, * otherwise return false */ function within1(uint256 a, uint256 b) internal pure returns (bool) { return (difference(a, b) <= 1); } /** * @notice Calculates absolute difference between a and b * @param a uint256 to compare with * @param b uint256 to compare with * @return Difference between a and b */ function difference(uint256 a, uint256 b) internal pure returns (uint256) { if (a > b) { return a - b; } return b - a; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./ERC20Upgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable { function __ERC20Burnable_init() internal initializer { __Context_init_unchained(); __ERC20Burnable_init_unchained(); } function __ERC20Burnable_init_unchained() internal initializer { } using SafeMathUpgradeable for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IAllowlist.sol"; interface ISwap { // pool data view functions function getA() external view returns (uint256); function getAllowlist() external view returns (IAllowlist); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); function swapStorage() external view returns ( uint256, uint256, uint256, uint256, uint256, uint256, address ); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 a, uint256 fee, uint256 adminFee, address lpTokenTargetAddress ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IAllowlist { function getPoolAccountLimit(address poolAddress) external view returns (uint256); function getPoolCap(address poolAddress) external view returns (uint256); function verifyAddress(address account, bytes32[] calldata merkleProof) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "./OwnerPausableUpgradeable.sol"; import "./SwapUtils.sol"; import "./AmplificationUtils.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract Swap is OwnerPausableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; using SwapUtils for SwapUtils.Swap; using AmplificationUtils for SwapUtils.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtils.sol SwapUtils.Swap public swapStorage; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public virtual initializer { __OwnerPausable_init(); __ReentrancyGuard_init(); // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtils.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtils.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee parameters require(_a < AmplificationUtils.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtils.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtils.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); // Clone and initialize a LPToken contract LPToken lpToken = LPToken(Clones.clone(lpTokenTargetAddress)); require( lpToken.initialize(lpTokenName, lpTokenSymbol), "could not init lpToken clone" ); // Initialize swapStorage struct swapStorage.lpToken = lpToken; swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(AmplificationUtils.A_PRECISION); swapStorage.futureA = _a.mul(AmplificationUtils.A_PRECISION); // swapStorage.initialATime = 0; // swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view virtual returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view virtual returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view virtual returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) public view virtual returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view virtual returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view virtual returns (uint256) { return swapStorage.calculateTokenAmount(amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(uint256 amount) external view virtual returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view virtual returns (uint256 availableTokenAmount) { return swapStorage.calculateWithdrawOneToken(tokenAmount, tokenIndex); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view virtual returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external virtual nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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 Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`. * * This function uses the create opcode, which should never revert. */ function clone(address master) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) 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 `master`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `master` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) 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 master, bytes32 salt, address deployer) internal pure returns (address predicted) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) 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 master, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(master, salt, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; /** * @title OwnerPausable * @notice An ownable contract allows the owner to pause and unpause the * contract without a delay. * @dev Only methods using the provided modifiers will be paused. */ abstract contract OwnerPausableUpgradeable is OwnableUpgradeable, PausableUpgradeable { function __OwnerPausable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); } /** * @notice Pause the contract. Revert if already paused. */ function pause() external onlyOwner { PausableUpgradeable._pause(); } /** * @notice Unpause the contract. Revert if already unpaused. */ function unpause() external onlyOwner { PausableUpgradeable._unpause(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT WITH AGPL-3.0-only pragma solidity 0.6.12; import "./Swap.sol"; import "./interfaces/IFlashLoanReceiver.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapFlashLoan is Swap { // Total fee that is charged on all flashloans in BPS. Borrowers must repay the amount plus the flash loan fee. // This fee is split between the protocol and the pool. uint256 public flashLoanFeeBPS; // Share of the flash loan fee that goes to the protocol in BPS. A portion of each flash loan fee is allocated // to the protocol rather than the pool. uint256 public protocolFeeShareBPS; // Max BPS for limiting flash loan fee settings. uint256 public constant MAX_BPS = 10000; /*** EVENTS ***/ event FlashLoan( address indexed receiver, uint8 tokenIndex, uint256 amount, uint256 amountFee, uint256 protocolFee ); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public virtual override initializer { Swap.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); flashLoanFeeBPS = 8; // 8 bps protocolFeeShareBPS = 0; // 0 bps } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Borrow the specified token from this pool for this transaction only. This function will call * `IFlashLoanReceiver(receiver).executeOperation` and the `receiver` must return the full amount of the token * and the associated fee by the end of the callback transaction. If the conditions are not met, this call * is reverted. * @param receiver the address of the receiver of the token. This address must implement the IFlashLoanReceiver * interface and the callback function `executeOperation`. * @param token the protocol fee in bps to be applied on the total flash loan fee * @param amount the total amount to borrow in this transaction * @param params optional data to pass along to the callback function */ function flashLoan( address receiver, IERC20 token, uint256 amount, bytes memory params ) external nonReentrant { uint8 tokenIndex = getTokenIndex(address(token)); uint256 availableLiquidityBefore = token.balanceOf(address(this)); uint256 protocolBalanceBefore = availableLiquidityBefore.sub( swapStorage.balances[tokenIndex] ); require( amount > 0 && availableLiquidityBefore >= amount, "invalid amount" ); // Calculate the additional amount of tokens the pool should end up with uint256 amountFee = amount.mul(flashLoanFeeBPS).div(10000); // Calculate the portion of the fee that will go to the protocol uint256 protocolFee = amountFee.mul(protocolFeeShareBPS).div(10000); require(amountFee > 0, "amount is small for a flashLoan"); // Transfer the requested amount of tokens token.safeTransfer(receiver, amount); // Execute callback function on receiver IFlashLoanReceiver(receiver).executeOperation( address(this), address(token), amount, amountFee, params ); uint256 availableLiquidityAfter = token.balanceOf(address(this)); require( availableLiquidityAfter >= availableLiquidityBefore.add(amountFee), "flashLoan fee is not met" ); swapStorage.balances[tokenIndex] = availableLiquidityAfter .sub(protocolBalanceBefore) .sub(protocolFee); emit FlashLoan(receiver, tokenIndex, amount, amountFee, protocolFee); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the flash loan fee parameters. This function can only be called by the owner. * @param newFlashLoanFeeBPS the total fee in bps to be applied on future flash loans * @param newProtocolFeeShareBPS the protocol fee in bps to be applied on the total flash loan fee */ function setFlashLoanFees( uint256 newFlashLoanFeeBPS, uint256 newProtocolFeeShareBPS ) external onlyOwner { require( newFlashLoanFeeBPS > 0 && newFlashLoanFeeBPS <= MAX_BPS && newProtocolFeeShareBPS <= MAX_BPS, "fees are not in valid range" ); flashLoanFeeBPS = newFlashLoanFeeBPS; protocolFeeShareBPS = newProtocolFeeShareBPS; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.6.12; /** * @title IFlashLoanReceiver interface * @notice Interface for the Saddle fee IFlashLoanReceiver. Modified from Aave's IFlashLoanReceiver interface. * https://github.com/aave/aave-protocol/blob/4b4545fb583fd4f400507b10f3c3114f45b8a037/contracts/flashloan/interfaces/IFlashLoanReceiver.sol * @author Aave * @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract **/ interface IFlashLoanReceiver { function executeOperation( address pool, address token, uint256 amount, uint256 fee, bytes calldata params ) external; } // SPDX-License-Identifier: MIT WITH AGPL-3.0-only pragma solidity 0.6.12; import "./SwapV1.sol"; import "./interfaces/IFlashLoanReceiver.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapFlashLoanV1 is SwapV1 { // Total fee that is charged on all flashloans in BPS. Borrowers must repay the amount plus the flash loan fee. // This fee is split between the protocol and the pool. uint256 public flashLoanFeeBPS; // Share of the flash loan fee that goes to the protocol in BPS. A portion of each flash loan fee is allocated // to the protocol rather than the pool. uint256 public protocolFeeShareBPS; // Max BPS for limiting flash loan fee settings. uint256 public constant MAX_BPS = 10000; /*** EVENTS ***/ event FlashLoan( address indexed receiver, uint8 tokenIndex, uint256 amount, uint256 amountFee, uint256 protocolFee ); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) public virtual override initializer { SwapV1.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, _withdrawFee, lpTokenTargetAddress ); flashLoanFeeBPS = 8; // 8 bps protocolFeeShareBPS = 0; // 0 bps } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Borrow the specified token from this pool for this transaction only. This function will call * `IFlashLoanReceiver(receiver).executeOperation` and the `receiver` must return the full amount of the token * and the associated fee by the end of the callback transaction. If the conditions are not met, this call * is reverted. * @param receiver the address of the receiver of the token. This address must implement the IFlashLoanReceiver * interface and the callback function `executeOperation`. * @param token the protocol fee in bps to be applied on the total flash loan fee * @param amount the total amount to borrow in this transaction * @param params optional data to pass along to the callback function */ function flashLoan( address receiver, IERC20 token, uint256 amount, bytes memory params ) external nonReentrant { uint8 tokenIndex = getTokenIndex(address(token)); uint256 availableLiquidityBefore = token.balanceOf(address(this)); uint256 protocolBalanceBefore = availableLiquidityBefore.sub( swapStorage.balances[tokenIndex] ); require( amount > 0 && availableLiquidityBefore >= amount, "invalid amount" ); // Calculate the additional amount of tokens the pool should end up with uint256 amountFee = amount.mul(flashLoanFeeBPS).div(10000); // Calculate the portion of the fee that will go to the protocol uint256 protocolFee = amountFee.mul(protocolFeeShareBPS).div(10000); require(amountFee > 0, "amount is small for a flashLoan"); // Transfer the requested amount of tokens token.safeTransfer(receiver, amount); // Execute callback function on receiver IFlashLoanReceiver(receiver).executeOperation( address(this), address(token), amount, amountFee, params ); uint256 availableLiquidityAfter = token.balanceOf(address(this)); require( availableLiquidityAfter >= availableLiquidityBefore.add(amountFee), "flashLoan fee is not met" ); swapStorage.balances[tokenIndex] = availableLiquidityAfter .sub(protocolBalanceBefore) .sub(protocolFee); emit FlashLoan(receiver, tokenIndex, amount, amountFee, protocolFee); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the flash loan fee parameters. This function can only be called by the owner. * @param newFlashLoanFeeBPS the total fee in bps to be applied on future flash loans * @param newProtocolFeeShareBPS the protocol fee in bps to be applied on the total flash loan fee */ function setFlashLoanFees( uint256 newFlashLoanFeeBPS, uint256 newProtocolFeeShareBPS ) external onlyOwner { require( newFlashLoanFeeBPS > 0 && newFlashLoanFeeBPS <= MAX_BPS && newProtocolFeeShareBPS <= MAX_BPS, "fees are not in valid range" ); flashLoanFeeBPS = newFlashLoanFeeBPS; protocolFeeShareBPS = newProtocolFeeShareBPS; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "./OwnerPausableUpgradeable.sol"; import "./SwapUtilsV1.sol"; import "./AmplificationUtilsV1.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapV1 is OwnerPausableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; using SwapUtilsV1 for SwapUtilsV1.Swap; using AmplificationUtilsV1 for SwapUtilsV1.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtilsV1.sol SwapUtilsV1.Swap public swapStorage; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) public virtual initializer { __OwnerPausable_init(); __ReentrancyGuard_init(); // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtilsV1.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtilsV1.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee parameters require(_a < AmplificationUtilsV1.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtilsV1.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtilsV1.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); require( _withdrawFee < SwapUtilsV1.MAX_WITHDRAW_FEE, "_withdrawFee exceeds maximum" ); // Clone and initialize a LPToken contract LPToken lpToken = LPToken(Clones.clone(lpTokenTargetAddress)); require( lpToken.initialize(lpTokenName, lpTokenSymbol), "could not init lpToken clone" ); // Initialize swapStorage struct swapStorage.lpToken = lpToken; swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(AmplificationUtilsV1.A_PRECISION); swapStorage.futureA = _a.mul(AmplificationUtilsV1.A_PRECISION); // swapStorage.initialATime = 0; // swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; swapStorage.defaultWithdrawFee = _withdrawFee; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view virtual returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view virtual returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view virtual returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) public view virtual returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Return timestamp of last deposit of given address * @return timestamp of the last deposit made by the given address */ function getDepositTimestamp(address user) external view virtual returns (uint256) { return swapStorage.getDepositTimestamp(user); } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view virtual returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param account address that is depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view virtual returns (uint256) { return swapStorage.calculateTokenAmount(account, amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param account the address that is withdrawing tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(address account, uint256 amount) external view virtual returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(account, amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param account the address that is withdrawing tokens * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view virtual returns (uint256 availableTokenAmount) { return swapStorage.calculateWithdrawOneToken( account, tokenAmount, tokenIndex ); } /** * @notice Calculate the fee that is applied when the given user withdraws. The withdraw fee * decays linearly over period of 4 weeks. For example, depositing and withdrawing right away * will charge you the full amount of withdraw fee. But withdrawing after 4 weeks will charge you * no additional fees. * @dev returned value should be divided by FEE_DENOMINATOR to convert to correct decimals * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(address user) external view virtual returns (uint256) { return swapStorage.calculateCurrentWithdrawFee(user); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view virtual returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external virtual nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the user withdraw fee. This function can only be called by * the pool token. Should be used to update the withdraw fee on transfer of pool tokens. * Transferring your pool token will reset the 4 weeks period. If the recipient is already * holding some pool tokens, the withdraw fee will be discounted in respective amounts. * @param recipient address of the recipient of pool token * @param transferAmount amount of pool token to transfer */ function updateUserWithdrawFee(address recipient, uint256 transferAmount) external { require( msg.sender == address(swapStorage.lpToken), "Only callable by pool token" ); swapStorage.updateUserWithdrawFee(recipient, transferAmount); } /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Update the withdraw fee. This fee decays linearly over 4 weeks since * user's last deposit. * @param newWithdrawFee new withdraw fee to be applied on future deposits */ function setDefaultWithdrawFee(uint256 newWithdrawFee) external onlyOwner { swapStorage.setDefaultWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./AmplificationUtilsV1.sol"; import "./LPToken.sol"; import "./MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtilsV1 { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; uint256 defaultWithdrawFee; LPToken lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; mapping(address => uint256) depositTimestamp; mapping(address => uint256) withdrawFeeMultiplier; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculations in the // {add,remove}Liquidity functions to avoid stack too deep errors struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; LPToken lpToken; uint256 totalSupply; uint256[] balances; uint256[] multipliers; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Max withdrawFee is 1% of the value withdrawn // Fee will be redistributed to the LPs in the pool, rewarding // long term providers. uint256 public constant MAX_WITHDRAW_FEE = 10**8; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; // Time that it should take for the withdraw fee to fully decay to 0 uint256 public constant WITHDRAW_FEE_DECAY_TIME = 4 weeks; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Retrieves the timestamp of last deposit made by the given address * @param self Swap struct to read from * @return timestamp of last deposit */ function getDepositTimestamp(Swap storage self, address user) external view returns (uint256) { return self.depositTimestamp[user]; } function _getAPrecise(Swap storage self) internal view returns (uint256) { return AmplificationUtilsV1._getAPrecise(self); } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param account the address that is withdrawing * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive */ function calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { (uint256 availableTokenAmount, ) = _calculateWithdrawOneToken( self, account, tokenAmount, tokenIndex, self.lpToken.totalSupply() ); return availableTokenAmount; } function _calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 newY; uint256 currentY; (dy, newY, currentY) = calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, totalSupply ); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); dy = dy .mul( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant iteratively. * See the StableSwap paper and Curve.fi implementation for further details. * * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex Index of token we are calculating for. * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool. * @param d the stableswap invariant * @return the price of the token, in the same precision as in xp */ function getYD( uint256 a, uint8 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(AmplificationUtilsV1.A_PRECISION).div( nA.mul(numTokens) ); uint256 b = s.add(d.mul(AmplificationUtilsV1.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality * as the pool. * @param a the amplification coefficient * n * (n - 1) in A_PRECISION. * See the StableSwap paper for details * @return the invariant, at the precision of the pool */ function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA .mul(s) .div(AmplificationUtilsV1.A_PRECISION) .add(dP.mul(numTokens)) .mul(d) .div( nA .sub(AmplificationUtilsV1.A_PRECISION) .mul(d) .div(AmplificationUtilsV1.A_PRECISION) .add(numTokens.add(1).mul(dP)) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); LPToken lpToken = self.lpToken; uint256 supply = lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(POOL_PRECISION_DECIMALS)).div(supply); } return 0; } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * * @param preciseA precise form of amplification coefficient * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function getY( uint256 preciseA, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal pure returns (uint256) { uint256 numTokens = xp.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 d = getD(xp, preciseA); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(preciseA); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(AmplificationUtilsV1.A_PRECISION).div( nA.mul(numTokens) ); uint256 b = s.add(d.mul(AmplificationUtilsV1.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, self.balances ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256[] memory balances ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256[] memory xp = _xp(balances, multipliers); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(multipliers[tokenIndexFrom]).add(xp[tokenIndexFrom]); uint256 y = getY( _getAPrecise(self), tokenIndexFrom, tokenIndexTo, x, xp ); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(multipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param account the address that is removing liquidity. required for withdraw fee calculation * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) external view returns (uint256[] memory) { return _calculateRemoveLiquidity( self, self.balances, account, amount, self.lpToken.totalSupply() ); } function _calculateRemoveLiquidity( Swap storage self, uint256[] memory balances, address account, uint256 amount, uint256 totalSupply ) internal view returns (uint256[] memory) { require(amount <= totalSupply, "Cannot exceed total supply"); uint256 feeAdjustedAmount = amount .mul( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); uint256[] memory amounts = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amounts[i] = balances[i].mul(feeAdjustedAmount).div(totalSupply); } return amounts; } /** * @notice Calculate the fee that is applied when the given user withdraws. * Withdraw fee decays linearly over WITHDRAW_FEE_DECAY_TIME. * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(Swap storage self, address user) external view returns (uint256) { return _calculateCurrentWithdrawFee(self, user); } function _calculateCurrentWithdrawFee(Swap storage self, address user) internal view returns (uint256) { uint256 endTime = self.depositTimestamp[user].add( WITHDRAW_FEE_DECAY_TIME ); if (endTime > block.timestamp) { uint256 timeLeftover = endTime.sub(block.timestamp); return self .defaultWithdrawFee .mul(self.withdrawFeeMultiplier[user]) .mul(timeLeftover) .div(WITHDRAW_FEE_DECAY_TIME) .div(FEE_DENOMINATOR); } return 0; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param account address of the account depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = _getAPrecise(self); uint256[] memory balances = self.balances; uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256 d0 = getD(_xp(balances, multipliers), a); for (uint256 i = 0; i < balances.length; i++) { if (deposit) { balances[i] = balances[i].add(amounts[i]); } else { balances[i] = balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(balances, multipliers), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub( _calculateCurrentWithdrawFee(self, account) ) ); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param swapFee swap fee for the tokens * @param numTokens number of tokens pooled */ function _feePerToken(uint256 swapFee, uint256 numTokens) internal pure returns (uint256) { return swapFee.mul(numTokens).div(numTokens.sub(1).mul(4)); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math dx = tokenFrom.balanceOf(address(this)).sub(beforeBalance); } uint256 dy; uint256 dyFee; uint256[] memory balances = self.balances; (dy, dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, balances ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = balances[tokenIndexFrom].add(dx); self.balances[tokenIndexTo] = balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); } uint256[] memory newBalances = new uint256[](pooledTokens.length); for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf( address(this) ); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = v.balances[i].add(amounts[i]); } // invariant after change v.d1 = getD(_xp(newBalances, v.multipliers), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256[] memory fees = new uint256[](pooledTokens.length); if (v.totalSupply != 0) { uint256 feePerToken = _feePerToken( self.swapFee, pooledTokens.length ); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(newBalances, v.multipliers), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (v.totalSupply == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens v.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Update the withdraw fee for `user`. If the user is currently * not providing liquidity in the pool, sets to default value. If not, recalculate * the starting withdraw fee based on the last deposit's time & amount relative * to the new deposit. * * @param self Swap struct to read from and write to * @param user address of the user depositing tokens * @param toMint amount of pool tokens to be minted */ function updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) public { // If token is transferred to address 0 (or burned), don't update the fee. if (user == address(0)) { return; } if (self.defaultWithdrawFee == 0) { // If current fee is set to 0%, set multiplier to FEE_DENOMINATOR self.withdrawFeeMultiplier[user] = FEE_DENOMINATOR; } else { // Otherwise, calculate appropriate discount based on last deposit amount uint256 currentFee = _calculateCurrentWithdrawFee(self, user); uint256 currentBalance = self.lpToken.balanceOf(user); // ((currentBalance * currentFee) + (toMint * defaultWithdrawFee)) * FEE_DENOMINATOR / // ((toMint + currentBalance) * defaultWithdrawFee) self.withdrawFeeMultiplier[user] = currentBalance .mul(currentFee) .add(toMint.mul(self.defaultWithdrawFee)) .mul(FEE_DENOMINATOR) .div(toMint.add(currentBalance).mul(self.defaultWithdrawFee)); } self.depositTimestamp[user] = block.timestamp; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(amount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory balances = self.balances; uint256 totalSupply = lpToken.totalSupply(); uint256[] memory amounts = _calculateRemoveLiquidity( self, balances, msg.sender, amount, totalSupply ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = balances[i].sub(amounts[i]); pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, totalSupply.sub(amount)); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < pooledTokens.length, "Token not found"); uint256 totalSupply = lpToken.totalSupply(); (uint256 dy, uint256 dyFee) = _calculateWithdrawOneToken( self, msg.sender, tokenAmount, tokenIndex, totalSupply ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); lpToken.burnFrom(msg.sender, tokenAmount); pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= v.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); uint256 feePerToken = _feePerToken(self.swapFee, pooledTokens.length); uint256[] memory fees = new uint256[](pooledTokens.length); { uint256[] memory balances1 = new uint256[](pooledTokens.length); v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { balances1[i] = v.balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(balances1, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(balances1, v.multipliers), v.preciseA); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, msg.sender)) ); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < pooledTokens.length; i++) { pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { IERC20[] memory pooledTokens = self.pooledTokens; for (uint256 i = 0; i < pooledTokens.length; i++) { IERC20 token = pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub( self.balances[i] ); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } /** * @notice update the default withdraw fee. This also affects deposits made in the past as well. * @param self Swap struct to update * @param newWithdrawFee new withdraw fee to be applied */ function setDefaultWithdrawFee(Swap storage self, uint256 newWithdrawFee) external { require(newWithdrawFee <= MAX_WITHDRAW_FEE, "Fee is too high"); self.defaultWithdrawFee = newWithdrawFee; emit NewWithdrawFee(newWithdrawFee); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./SwapUtilsV1.sol"; /** * @title AmplificationUtils library * @notice A library to calculate and ramp the A parameter of a given `SwapUtils.Swap` struct. * This library assumes the struct is fully validated. */ library AmplificationUtilsV1 { using SafeMath for uint256; event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(SwapUtilsV1.Swap storage self) external view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(SwapUtilsV1.Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(SwapUtilsV1.Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( SwapUtilsV1.Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(SwapUtilsV1.Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../LPToken.sol"; import "../interfaces/ISwap.sol"; import "../MathUtils.sol"; import "../SwapUtils.sol"; /** * @title MetaSwapUtils library * @notice A library to be used within MetaSwap.sol. Contains functions responsible for custody and AMM functionalities. * * MetaSwap is a modified version of Swap that allows Swap's LP token to be utilized in pooling with other tokens. * As an example, if there is a Swap pool consisting of [DAI, USDC, USDT]. Then a MetaSwap pool can be created * with [sUSD, BaseSwapLPToken] to allow trades between either the LP token or the underlying tokens and sUSD. * * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library MetaSwapUtils { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; using AmplificationUtils for SwapUtils.Swap; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event TokenSwapUnderlying( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); struct MetaSwap { // Meta-Swap related parameters ISwap baseSwap; uint256 baseVirtualPrice; uint256 baseCacheLastUpdated; IERC20[] baseTokens; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; uint256 xpi; } // Struct storing variables used in calculation in removeLiquidityImbalance function // to avoid stack too deep error struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; LPToken lpToken; uint256 totalSupply; uint256 preciseA; uint256 baseVirtualPrice; uint256[] tokenPrecisionMultipliers; uint256[] newBalances; } struct SwapUnderlyingInfo { uint256 x; uint256 dx; uint256 dy; uint256[] tokenPrecisionMultipliers; uint256[] oldBalances; IERC20[] baseTokens; IERC20 tokenFrom; uint8 metaIndexFrom; IERC20 tokenTo; uint8 metaIndexTo; uint256 baseVirtualPrice; } struct CalculateSwapUnderlyingInfo { uint256 baseVirtualPrice; ISwap baseSwap; uint8 baseLPTokenIndex; uint8 baseTokensLength; uint8 metaIndexTo; uint256 x; uint256 dy; } // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Cache expire time for the stored value of base Swap's virtual price uint256 public constant BASE_CACHE_EXPIRE_TIME = 10 minutes; uint256 public constant BASE_VIRTUAL_PRICE_PRECISION = 10**18; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Return the stored value of base Swap's virtual price. If * value was updated past BASE_CACHE_EXPIRE_TIME, then read it directly * from the base Swap contract. * @param metaSwapStorage MetaSwap struct to read from * @return base Swap's virtual price */ function _getBaseVirtualPrice(MetaSwap storage metaSwapStorage) internal view returns (uint256) { if ( block.timestamp > metaSwapStorage.baseCacheLastUpdated + BASE_CACHE_EXPIRE_TIME ) { return metaSwapStorage.baseSwap.getVirtualPrice(); } return metaSwapStorage.baseVirtualPrice; } function _getBaseSwapFee(ISwap baseSwap) internal view returns (uint256 swapFee) { (, , , , swapFee, , ) = baseSwap.swapStorage(); } /** * @notice Calculate how much the user would receive when withdrawing via single token * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @return dy the amount of token user will receive */ function calculateWithdrawOneToken( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 dy) { (dy, ) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, _getBaseVirtualPrice(metaSwapStorage), self.lpToken.totalSupply() ); } function _calculateWithdrawOneToken( SwapUtils.Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 baseVirtualPrice, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 dySwapFee; { uint256 currentY; uint256 newY; // Calculate how much to withdraw (dy, newY, currentY) = _calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, baseVirtualPrice, totalSupply ); // Calculate the associated swap fee dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); } return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @param baseVirtualPrice the virtual price of the base swap's LP token * @return the dy excluding swap fee, the new y after withdrawing one token, and current y */ function _calculateWithdrawOneTokenDY( SwapUtils.Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 baseVirtualPrice, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self, baseVirtualPrice); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo( 0, 0, 0, 0, self._getAPrecise(), 0 ); v.d0 = SwapUtils.getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = SwapUtils.getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = SwapUtils._feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { v.xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = v.xpi.sub( ( (i == tokenIndex) ? v.xpi.mul(v.d1).div(v.d0).sub(v.newY) : v.xpi.sub(v.xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( SwapUtils.getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); if (tokenIndex == xp.length.sub(1)) { dy = dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(baseVirtualPrice); v.newY = v.newY.mul(BASE_VIRTUAL_PRICE_PRECISION).div( baseVirtualPrice ); xp[tokenIndex] = xp[tokenIndex] .mul(BASE_VIRTUAL_PRICE_PRECISION) .div(baseVirtualPrice); } dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. The last element will also get scaled up by * the given baseVirtualPrice. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @param baseVirtualPrice the base virtual price to scale the balance of the * base Swap's LP token. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers, uint256 baseVirtualPrice ) internal pure returns (uint256[] memory) { uint256[] memory xp = SwapUtils._xp(balances, precisionMultipliers); uint256 baseLPTokenIndex = balances.length.sub(1); xp[baseLPTokenIndex] = xp[baseLPTokenIndex].mul(baseVirtualPrice).div( BASE_VIRTUAL_PRICE_PRECISION ); return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(SwapUtils.Swap storage self, uint256 baseVirtualPrice) internal view returns (uint256[] memory) { return _xp( self.balances, self.tokenPrecisionMultipliers, baseVirtualPrice ); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @return the virtual price, scaled to precision of BASE_VIRTUAL_PRICE_PRECISION */ function getVirtualPrice( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage ) external view returns (uint256) { uint256 d = SwapUtils.getD( _xp( self.balances, self.tokenPrecisionMultipliers, _getBaseVirtualPrice(metaSwapStorage) ), self._getAPrecise() ); uint256 supply = self.lpToken.totalSupply(); if (supply != 0) { return d.mul(BASE_VIRTUAL_PRICE_PRECISION).div(supply); } return 0; } /** * @notice Externally calculates a swap between two tokens. The SwapUtils.Swap storage and * MetaSwap storage should be from the same MetaSwap contract. * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct from the same contract * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, _getBaseVirtualPrice(metaSwapStorage) ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param baseVirtualPrice the virtual price of the base LP token * @return dy the number of tokens the user will get and dyFee the associated fee */ function _calculateSwap( SwapUtils.Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 baseVirtualPrice ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory xp = _xp(self, baseVirtualPrice); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 baseLPTokenIndex = xp.length.sub(1); uint256 x = dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]); if (tokenIndexFrom == baseLPTokenIndex) { // When swapping from a base Swap token, scale up dx by its virtual price x = x.mul(baseVirtualPrice).div(BASE_VIRTUAL_PRICE_PRECISION); } x = x.add(xp[tokenIndexFrom]); uint256 y = SwapUtils.getY( self._getAPrecise(), tokenIndexFrom, tokenIndexTo, x, xp ); dy = xp[tokenIndexTo].sub(y).sub(1); if (tokenIndexTo == baseLPTokenIndex) { // When swapping to a base Swap token, scale down dy by its virtual price dy = dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(baseVirtualPrice); } dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee); dy = dy.div(self.tokenPrecisionMultipliers[tokenIndexTo]); } /** * @notice Calculates the expected return amount from swapping between * the pooled tokens and the underlying tokens of the base Swap pool. * * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct from the same contract * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwapUnderlying( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { CalculateSwapUnderlyingInfo memory v = CalculateSwapUnderlyingInfo( _getBaseVirtualPrice(metaSwapStorage), metaSwapStorage.baseSwap, 0, uint8(metaSwapStorage.baseTokens.length), 0, 0, 0 ); uint256[] memory xp = _xp(self, v.baseVirtualPrice); v.baseLPTokenIndex = uint8(xp.length.sub(1)); { uint8 maxRange = v.baseLPTokenIndex + v.baseTokensLength; require( tokenIndexFrom < maxRange && tokenIndexTo < maxRange, "Token index out of range" ); } if (tokenIndexFrom < v.baseLPTokenIndex) { // tokenFrom is from this pool v.x = xp[tokenIndexFrom].add( dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]) ); } else { // tokenFrom is from the base pool tokenIndexFrom = tokenIndexFrom - v.baseLPTokenIndex; if (tokenIndexTo < v.baseLPTokenIndex) { uint256[] memory baseInputs = new uint256[](v.baseTokensLength); baseInputs[tokenIndexFrom] = dx; v.x = v .baseSwap .calculateTokenAmount(baseInputs, true) .mul(v.baseVirtualPrice) .div(BASE_VIRTUAL_PRICE_PRECISION); // when adding to the base pool,you pay approx 50% of the swap fee v.x = v .x .sub( v.x.mul(_getBaseSwapFee(metaSwapStorage.baseSwap)).div( FEE_DENOMINATOR.mul(2) ) ) .add(xp[v.baseLPTokenIndex]); } else { // both from and to are from the base pool return v.baseSwap.calculateSwap( tokenIndexFrom, tokenIndexTo - v.baseLPTokenIndex, dx ); } tokenIndexFrom = v.baseLPTokenIndex; } v.metaIndexTo = v.baseLPTokenIndex; if (tokenIndexTo < v.baseLPTokenIndex) { v.metaIndexTo = tokenIndexTo; } { uint256 y = SwapUtils.getY( self._getAPrecise(), tokenIndexFrom, v.metaIndexTo, v.x, xp ); v.dy = xp[v.metaIndexTo].sub(y).sub(1); uint256 dyFee = v.dy.mul(self.swapFee).div(FEE_DENOMINATOR); v.dy = v.dy.sub(dyFee); } if (tokenIndexTo < v.baseLPTokenIndex) { // tokenTo is from this pool v.dy = v.dy.div(self.tokenPrecisionMultipliers[v.metaIndexTo]); } else { // tokenTo is from the base pool v.dy = v.baseSwap.calculateRemoveLiquidityOneToken( v.dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(v.baseVirtualPrice), tokenIndexTo - v.baseLPTokenIndex ); } return v.dy; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = self._getAPrecise(); uint256 d0; uint256 d1; { uint256 baseVirtualPrice = _getBaseVirtualPrice(metaSwapStorage); uint256[] memory balances1 = self.balances; uint256[] memory tokenPrecisionMultipliers = self .tokenPrecisionMultipliers; uint256 numTokens = balances1.length; d0 = SwapUtils.getD( _xp(balances1, tokenPrecisionMultipliers, baseVirtualPrice), a ); for (uint256 i = 0; i < numTokens; i++) { if (deposit) { balances1[i] = balances1[i].add(amounts[i]); } else { balances1[i] = balances1[i].sub( amounts[i], "Cannot withdraw more than available" ); } } d1 = SwapUtils.getD( _xp(balances1, tokenPrecisionMultipliers, baseVirtualPrice), a ); } uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0); } } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { uint256 pooledTokensLength = self.pooledTokens.length; require( tokenIndexFrom < pooledTokensLength && tokenIndexTo < pooledTokensLength, "Token index is out of range" ); } uint256 transferredDx; { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); { // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math transferredDx = tokenFrom.balanceOf(address(this)).sub( beforeBalance ); } } (uint256 dy, uint256 dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, transferredDx, _updateBaseVirtualPrice(metaSwapStorage) ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = self.balances[tokenIndexFrom].add( transferredDx ); self.balances[tokenIndexTo] = self.balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap( msg.sender, transferredDx, dy, tokenIndexFrom, tokenIndexTo ); return dy; } /** * @notice Swaps with the underlying tokens of the base Swap pool. For this function, * the token indices are flattened out so that underlying tokens are represented * in the indices. * @dev Since this calls multiple external functions during the execution, * it is recommended to protect any function that depends on this with reentrancy guards. * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swapUnderlying( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { SwapUnderlyingInfo memory v = SwapUnderlyingInfo( 0, 0, 0, self.tokenPrecisionMultipliers, self.balances, metaSwapStorage.baseTokens, IERC20(address(0)), 0, IERC20(address(0)), 0, _updateBaseVirtualPrice(metaSwapStorage) ); uint8 baseLPTokenIndex = uint8(v.oldBalances.length.sub(1)); { uint8 maxRange = uint8(baseLPTokenIndex + v.baseTokens.length); require( tokenIndexFrom < maxRange && tokenIndexTo < maxRange, "Token index out of range" ); } ISwap baseSwap = metaSwapStorage.baseSwap; // Find the address of the token swapping from and the index in MetaSwap's token list if (tokenIndexFrom < baseLPTokenIndex) { v.tokenFrom = self.pooledTokens[tokenIndexFrom]; v.metaIndexFrom = tokenIndexFrom; } else { v.tokenFrom = v.baseTokens[tokenIndexFrom - baseLPTokenIndex]; v.metaIndexFrom = baseLPTokenIndex; } // Find the address of the token swapping to and the index in MetaSwap's token list if (tokenIndexTo < baseLPTokenIndex) { v.tokenTo = self.pooledTokens[tokenIndexTo]; v.metaIndexTo = tokenIndexTo; } else { v.tokenTo = v.baseTokens[tokenIndexTo - baseLPTokenIndex]; v.metaIndexTo = baseLPTokenIndex; } // Check for possible fee on transfer v.dx = v.tokenFrom.balanceOf(address(this)); v.tokenFrom.safeTransferFrom(msg.sender, address(this), dx); v.dx = v.tokenFrom.balanceOf(address(this)).sub(v.dx); // update dx in case of fee on transfer if ( tokenIndexFrom < baseLPTokenIndex || tokenIndexTo < baseLPTokenIndex ) { // Either one of the tokens belongs to the MetaSwap tokens list uint256[] memory xp = _xp( v.oldBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ); if (tokenIndexFrom < baseLPTokenIndex) { // Swapping from a MetaSwap token v.x = xp[tokenIndexFrom].add( dx.mul(v.tokenPrecisionMultipliers[tokenIndexFrom]) ); } else { // Swapping from one of the tokens hosted in the base Swap // This case requires adding the underlying token to the base Swap, then // using the base LP token to swap to the desired token uint256[] memory baseAmounts = new uint256[]( v.baseTokens.length ); baseAmounts[tokenIndexFrom - baseLPTokenIndex] = v.dx; // Add liquidity to the base Swap contract and receive base LP token v.dx = baseSwap.addLiquidity(baseAmounts, 0, block.timestamp); // Calculate the value of total amount of baseLPToken we end up with v.x = v .dx .mul(v.baseVirtualPrice) .div(BASE_VIRTUAL_PRICE_PRECISION) .add(xp[baseLPTokenIndex]); } // Calculate how much to withdraw in MetaSwap level and the the associated swap fee uint256 dyFee; { uint256 y = SwapUtils.getY( self._getAPrecise(), v.metaIndexFrom, v.metaIndexTo, v.x, xp ); v.dy = xp[v.metaIndexTo].sub(y).sub(1); if (tokenIndexTo >= baseLPTokenIndex) { // When swapping to a base Swap token, scale down dy by its virtual price v.dy = v.dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div( v.baseVirtualPrice ); } dyFee = v.dy.mul(self.swapFee).div(FEE_DENOMINATOR); v.dy = v.dy.sub(dyFee).div( v.tokenPrecisionMultipliers[v.metaIndexTo] ); } // Update the balances array according to the calculated input and output amount { uint256 dyAdminFee = dyFee.mul(self.adminFee).div( FEE_DENOMINATOR ); dyAdminFee = dyAdminFee.div( v.tokenPrecisionMultipliers[v.metaIndexTo] ); self.balances[v.metaIndexFrom] = v .oldBalances[v.metaIndexFrom] .add(v.dx); self.balances[v.metaIndexTo] = v .oldBalances[v.metaIndexTo] .sub(v.dy) .sub(dyAdminFee); } if (tokenIndexTo >= baseLPTokenIndex) { // When swapping to a token that belongs to the base Swap, burn the LP token // and withdraw the desired token from the base pool uint256 oldBalance = v.tokenTo.balanceOf(address(this)); baseSwap.removeLiquidityOneToken( v.dy, tokenIndexTo - baseLPTokenIndex, 0, block.timestamp ); v.dy = v.tokenTo.balanceOf(address(this)) - oldBalance; } // Check the amount of token to send meets minDy require(v.dy >= minDy, "Swap didn't result in min tokens"); } else { // Both tokens are from the base Swap pool // Do a swap through the base Swap v.dy = v.tokenTo.balanceOf(address(this)); baseSwap.swap( tokenIndexFrom - baseLPTokenIndex, tokenIndexTo - baseLPTokenIndex, v.dx, minDy, block.timestamp ); v.dy = v.tokenTo.balanceOf(address(this)).sub(v.dy); } // Send the desired token to the caller v.tokenTo.safeTransfer(msg.sender, v.dy); emit TokenSwapUnderlying( msg.sender, dx, v.dy, tokenIndexFrom, tokenIndexTo ); return v.dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); uint256[] memory fees = new uint256[](pooledTokens.length); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, self.lpToken, 0, self._getAPrecise(), _updateBaseVirtualPrice(metaSwapStorage), self.tokenPrecisionMultipliers, self.balances ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); } for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf( address(this) ); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } v.newBalances[i] = v.newBalances[i].add(amounts[i]); } // invariant after change v.d1 = SwapUtils.getD( _xp(v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256 toMint; if (v.totalSupply != 0) { uint256 feePerToken = SwapUtils._feePerToken( self.swapFee, pooledTokens.length ); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(v.newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = v.newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); v.newBalances[i] = v.newBalances[i].sub(fees[i]); } v.d2 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } else { // the initial depositor doesn't pay fees self.balances = v.newBalances; toMint = v.d1; } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens self.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; uint256 totalSupply = lpToken.totalSupply(); uint256 numTokens = self.pooledTokens.length; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < numTokens, "Token not found"); uint256 dyFee; uint256 dy; (dy, dyFee) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, _updateBaseVirtualPrice(metaSwapStorage), totalSupply ); require(dy >= minAmount, "dy < minAmount"); // Update balances array self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); // Burn the associated LP token from the caller and send the desired token lpToken.burnFrom(msg.sender, tokenAmount); self.pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { // Using this struct to avoid stack too deep error ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, self.lpToken, 0, self._getAPrecise(), _updateBaseVirtualPrice(metaSwapStorage), self.tokenPrecisionMultipliers, self.balances ); v.totalSupply = v.lpToken.totalSupply(); require( amounts.length == v.newBalances.length, "Amounts should match pool tokens" ); require(maxBurnAmount != 0, "Must burn more than 0"); uint256 feePerToken = SwapUtils._feePerToken( self.swapFee, v.newBalances.length ); // Calculate how much LPToken should be burned uint256[] memory fees = new uint256[](v.newBalances.length); { uint256[] memory balances1 = new uint256[](v.newBalances.length); v.d0 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); for (uint256 i = 0; i < v.newBalances.length; i++) { balances1[i] = v.newBalances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = SwapUtils.getD( _xp(balances1, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); for (uint256 i = 0; i < v.newBalances.length; i++) { uint256 idealBalance = v.d1.mul(v.newBalances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = SwapUtils.getD( _xp(balances1, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); // Scale up by withdraw fee tokenAmount = tokenAmount.add(1); // Check for max burn amount require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); // Burn the calculated amount of LPToken from the caller and send the desired tokens v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < v.newBalances.length; i++) { self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice Determines if the stored value of base Swap's virtual price is expired. * If the last update was past the BASE_CACHE_EXPIRE_TIME, then update the stored value. * * @param metaSwapStorage MetaSwap struct to read from and write to * @return base Swap's virtual price */ function _updateBaseVirtualPrice(MetaSwap storage metaSwapStorage) internal returns (uint256) { if ( block.timestamp > metaSwapStorage.baseCacheLastUpdated + BASE_CACHE_EXPIRE_TIME ) { // When the cache is expired, update it uint256 baseVirtualPrice = ISwap(metaSwapStorage.baseSwap) .getVirtualPrice(); metaSwapStorage.baseVirtualPrice = baseVirtualPrice; metaSwapStorage.baseCacheLastUpdated = block.timestamp; return baseVirtualPrice; } else { return metaSwapStorage.baseVirtualPrice; } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "../LPToken.sol"; import "../interfaces/ISwap.sol"; import "../interfaces/IMetaSwap.sol"; /** * @title MetaSwapDeposit * @notice This contract flattens the LP token in a MetaSwap pool for easier user access. MetaSwap must be * deployed before this contract can be initialized successfully. * * For example, suppose there exists a base Swap pool consisting of [DAI, USDC, USDT]. * Then a MetaSwap pool can be created with [sUSD, BaseSwapLPToken] to allow trades between either * the LP token or the underlying tokens and sUSD. * * MetaSwapDeposit flattens the LP token and remaps them to a single array, allowing users * to ignore the dependency on BaseSwapLPToken. Using the above example, MetaSwapDeposit can act * as a Swap containing [sUSD, DAI, USDC, USDT] tokens. */ contract MetaSwapDeposit is Initializable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; ISwap public baseSwap; IMetaSwap public metaSwap; IERC20[] public baseTokens; IERC20[] public metaTokens; IERC20[] public tokens; IERC20 public metaLPToken; uint256 constant MAX_UINT256 = 2**256 - 1; struct RemoveLiquidityImbalanceInfo { ISwap baseSwap; IMetaSwap metaSwap; IERC20 metaLPToken; uint8 baseLPTokenIndex; bool withdrawFromBase; uint256 leftoverMetaLPTokenAmount; } /** * @notice Sets the address for the base Swap contract, MetaSwap contract, and the * MetaSwap LP token contract. * @param _baseSwap the address of the base Swap contract * @param _metaSwap the address of the MetaSwap contract * @param _metaLPToken the address of the MetaSwap LP token contract */ function initialize( ISwap _baseSwap, IMetaSwap _metaSwap, IERC20 _metaLPToken ) external initializer { __ReentrancyGuard_init(); // Check and approve base level tokens to be deposited to the base Swap contract { uint8 i; for (; i < 32; i++) { try _baseSwap.getToken(i) returns (IERC20 token) { baseTokens.push(token); token.safeApprove(address(_baseSwap), MAX_UINT256); token.safeApprove(address(_metaSwap), MAX_UINT256); } catch { break; } } require(i > 1, "baseSwap must have at least 2 tokens"); } // Check and approve meta level tokens to be deposited to the MetaSwap contract IERC20 baseLPToken; { uint8 i; for (; i < 32; i++) { try _metaSwap.getToken(i) returns (IERC20 token) { baseLPToken = token; metaTokens.push(token); tokens.push(token); token.safeApprove(address(_metaSwap), MAX_UINT256); } catch { break; } } require(i > 1, "metaSwap must have at least 2 tokens"); } // Flatten baseTokens and append it to tokens array tokens[tokens.length - 1] = baseTokens[0]; for (uint8 i = 1; i < baseTokens.length; i++) { tokens.push(baseTokens[i]); } // Approve base Swap LP token to be burned by the base Swap contract for withdrawing baseLPToken.safeApprove(address(_baseSwap), MAX_UINT256); // Approve MetaSwap LP token to be burned by the MetaSwap contract for withdrawing _metaLPToken.safeApprove(address(_metaSwap), MAX_UINT256); // Initialize storage variables baseSwap = _baseSwap; metaSwap = _metaSwap; metaLPToken = _metaLPToken; } // Mutative functions /** * @notice Swap two underlying tokens using the meta pool and the base pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external nonReentrant returns (uint256) { tokens[tokenIndexFrom].safeTransferFrom(msg.sender, address(this), dx); uint256 tokenToAmount = metaSwap.swapUnderlying( tokenIndexFrom, tokenIndexTo, dx, minDy, deadline ); tokens[tokenIndexTo].safeTransfer(msg.sender, tokenToAmount); return tokenToAmount; } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external nonReentrant returns (uint256) { // Read to memory to save on gas IERC20[] memory memBaseTokens = baseTokens; IERC20[] memory memMetaTokens = metaTokens; uint256 baseLPTokenIndex = memMetaTokens.length - 1; require(amounts.length == memBaseTokens.length + baseLPTokenIndex); uint256 baseLPTokenAmount; { // Transfer base tokens from the caller and deposit to the base Swap pool uint256[] memory baseAmounts = new uint256[](memBaseTokens.length); bool shouldDepositBaseTokens; for (uint8 i = 0; i < memBaseTokens.length; i++) { IERC20 token = memBaseTokens[i]; uint256 depositAmount = amounts[baseLPTokenIndex + i]; if (depositAmount > 0) { token.safeTransferFrom( msg.sender, address(this), depositAmount ); baseAmounts[i] = token.balanceOf(address(this)); // account for any fees on transfer // if there are any base Swap level tokens, flag it for deposits shouldDepositBaseTokens = true; } } if (shouldDepositBaseTokens) { // Deposit any base Swap level tokens and receive baseLPToken baseLPTokenAmount = baseSwap.addLiquidity( baseAmounts, 0, deadline ); } } uint256 metaLPTokenAmount; { // Transfer remaining meta level tokens from the caller uint256[] memory metaAmounts = new uint256[](metaTokens.length); for (uint8 i = 0; i < baseLPTokenIndex; i++) { IERC20 token = memMetaTokens[i]; uint256 depositAmount = amounts[i]; if (depositAmount > 0) { token.safeTransferFrom( msg.sender, address(this), depositAmount ); metaAmounts[i] = token.balanceOf(address(this)); // account for any fees on transfer } } // Update the baseLPToken amount that will be deposited metaAmounts[baseLPTokenIndex] = baseLPTokenAmount; // Deposit the meta level tokens and the baseLPToken metaLPTokenAmount = metaSwap.addLiquidity( metaAmounts, minToMint, deadline ); } // Transfer the meta lp token to the caller metaLPToken.safeTransfer(msg.sender, metaLPTokenAmount); return metaLPTokenAmount; } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external nonReentrant returns (uint256[] memory) { IERC20[] memory memBaseTokens = baseTokens; IERC20[] memory memMetaTokens = metaTokens; uint256[] memory totalRemovedAmounts; { uint256 numOfAllTokens = memBaseTokens.length + memMetaTokens.length - 1; require(minAmounts.length == numOfAllTokens, "out of range"); totalRemovedAmounts = new uint256[](numOfAllTokens); } // Transfer meta lp token from the caller to this metaLPToken.safeTransferFrom(msg.sender, address(this), amount); uint256 baseLPTokenAmount; { // Remove liquidity from the MetaSwap pool uint256[] memory removedAmounts; uint256 baseLPTokenIndex = memMetaTokens.length - 1; { uint256[] memory metaMinAmounts = new uint256[]( memMetaTokens.length ); for (uint8 i = 0; i < baseLPTokenIndex; i++) { metaMinAmounts[i] = minAmounts[i]; } removedAmounts = metaSwap.removeLiquidity( amount, metaMinAmounts, deadline ); } // Send the meta level tokens to the caller for (uint8 i = 0; i < baseLPTokenIndex; i++) { totalRemovedAmounts[i] = removedAmounts[i]; memMetaTokens[i].safeTransfer(msg.sender, removedAmounts[i]); } baseLPTokenAmount = removedAmounts[baseLPTokenIndex]; // Remove liquidity from the base Swap pool { uint256[] memory baseMinAmounts = new uint256[]( memBaseTokens.length ); for (uint8 i = 0; i < baseLPTokenIndex; i++) { baseMinAmounts[i] = minAmounts[baseLPTokenIndex + i]; } removedAmounts = baseSwap.removeLiquidity( baseLPTokenAmount, baseMinAmounts, deadline ); } // Send the base level tokens to the caller for (uint8 i = 0; i < memBaseTokens.length; i++) { totalRemovedAmounts[baseLPTokenIndex + i] = removedAmounts[i]; memBaseTokens[i].safeTransfer(msg.sender, removedAmounts[i]); } } return totalRemovedAmounts; } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external nonReentrant returns (uint256) { uint8 baseLPTokenIndex = uint8(metaTokens.length - 1); uint8 baseTokensLength = uint8(baseTokens.length); // Transfer metaLPToken from the caller metaLPToken.safeTransferFrom(msg.sender, address(this), tokenAmount); IERC20 token; if (tokenIndex < baseLPTokenIndex) { // When the desired token is meta level token, we can just call `removeLiquidityOneToken` directly metaSwap.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount, deadline ); token = metaTokens[tokenIndex]; } else if (tokenIndex < baseLPTokenIndex + baseTokensLength) { // When the desired token is a base level token, we need to first withdraw via baseLPToken, then withdraw // the desired token from the base Swap contract. uint256 removedBaseLPTokenAmount = metaSwap.removeLiquidityOneToken( tokenAmount, baseLPTokenIndex, 0, deadline ); baseSwap.removeLiquidityOneToken( removedBaseLPTokenAmount, tokenIndex - baseLPTokenIndex, minAmount, deadline ); token = baseTokens[tokenIndex - baseLPTokenIndex]; } else { revert("out of range"); } uint256 amountWithdrawn = token.balanceOf(address(this)); token.safeTransfer(msg.sender, amountWithdrawn); return amountWithdrawn; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external nonReentrant returns (uint256) { IERC20[] memory memBaseTokens = baseTokens; IERC20[] memory memMetaTokens = metaTokens; uint256[] memory metaAmounts = new uint256[](memMetaTokens.length); uint256[] memory baseAmounts = new uint256[](memBaseTokens.length); require( amounts.length == memBaseTokens.length + memMetaTokens.length - 1, "out of range" ); RemoveLiquidityImbalanceInfo memory v = RemoveLiquidityImbalanceInfo( baseSwap, metaSwap, metaLPToken, uint8(metaAmounts.length - 1), false, 0 ); for (uint8 i = 0; i < v.baseLPTokenIndex; i++) { metaAmounts[i] = amounts[i]; } for (uint8 i = 0; i < baseAmounts.length; i++) { baseAmounts[i] = amounts[v.baseLPTokenIndex + i]; if (baseAmounts[i] > 0) { v.withdrawFromBase = true; } } // Calculate how much base LP token we need to get the desired amount of underlying tokens if (v.withdrawFromBase) { metaAmounts[v.baseLPTokenIndex] = v .baseSwap .calculateTokenAmount(baseAmounts, false) .mul(10005) .div(10000); } // Transfer MetaSwap LP token from the caller to this contract v.metaLPToken.safeTransferFrom( msg.sender, address(this), maxBurnAmount ); // Withdraw the paired meta level tokens and the base LP token from the MetaSwap pool uint256 burnedMetaLPTokenAmount = v.metaSwap.removeLiquidityImbalance( metaAmounts, maxBurnAmount, deadline ); v.leftoverMetaLPTokenAmount = maxBurnAmount.sub( burnedMetaLPTokenAmount ); // If underlying tokens are desired, withdraw them from the base Swap pool if (v.withdrawFromBase) { v.baseSwap.removeLiquidityImbalance( baseAmounts, metaAmounts[v.baseLPTokenIndex], deadline ); // Base Swap may require LESS base LP token than the amount we have // In that case, deposit it to the MetaSwap pool. uint256[] memory leftovers = new uint256[](metaAmounts.length); IERC20 baseLPToken = memMetaTokens[v.baseLPTokenIndex]; uint256 leftoverBaseLPTokenAmount = baseLPToken.balanceOf( address(this) ); if (leftoverBaseLPTokenAmount > 0) { leftovers[v.baseLPTokenIndex] = leftoverBaseLPTokenAmount; v.leftoverMetaLPTokenAmount = v.leftoverMetaLPTokenAmount.add( v.metaSwap.addLiquidity(leftovers, 0, deadline) ); } } // Transfer all withdrawn tokens to the caller for (uint8 i = 0; i < amounts.length; i++) { IERC20 token; if (i < v.baseLPTokenIndex) { token = memMetaTokens[i]; } else { token = memBaseTokens[i - v.baseLPTokenIndex]; } if (amounts[i] > 0) { token.safeTransfer(msg.sender, amounts[i]); } } // If there were any extra meta lp token, transfer them back to the caller as well if (v.leftoverMetaLPTokenAmount > 0) { v.metaLPToken.safeTransfer(msg.sender, v.leftoverMetaLPTokenAmount); } return maxBurnAmount - v.leftoverMetaLPTokenAmount; } // VIEW FUNCTIONS /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running. When withdrawing from the base pool in imbalanced * fashion, the recommended slippage setting is 0.2% or higher. * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256) { uint256[] memory metaAmounts = new uint256[](metaTokens.length); uint256[] memory baseAmounts = new uint256[](baseTokens.length); uint256 baseLPTokenIndex = metaAmounts.length - 1; for (uint8 i = 0; i < baseLPTokenIndex; i++) { metaAmounts[i] = amounts[i]; } for (uint8 i = 0; i < baseAmounts.length; i++) { baseAmounts[i] = amounts[baseLPTokenIndex + i]; } uint256 baseLPTokenAmount = baseSwap.calculateTokenAmount( baseAmounts, deposit ); metaAmounts[baseLPTokenIndex] = baseLPTokenAmount; return metaSwap.calculateTokenAmount(metaAmounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory) { uint256[] memory metaAmounts = metaSwap.calculateRemoveLiquidity( amount ); uint8 baseLPTokenIndex = uint8(metaAmounts.length - 1); uint256[] memory baseAmounts = baseSwap.calculateRemoveLiquidity( metaAmounts[baseLPTokenIndex] ); uint256[] memory totalAmounts = new uint256[]( baseLPTokenIndex + baseAmounts.length ); for (uint8 i = 0; i < baseLPTokenIndex; i++) { totalAmounts[i] = metaAmounts[i]; } for (uint8 i = 0; i < baseAmounts.length; i++) { totalAmounts[baseLPTokenIndex + i] = baseAmounts[i]; } return totalAmounts; } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { uint8 baseLPTokenIndex = uint8(metaTokens.length - 1); if (tokenIndex < baseLPTokenIndex) { return metaSwap.calculateRemoveLiquidityOneToken( tokenAmount, tokenIndex ); } else { uint256 baseLPTokenAmount = metaSwap .calculateRemoveLiquidityOneToken( tokenAmount, baseLPTokenIndex ); return baseSwap.calculateRemoveLiquidityOneToken( baseLPTokenAmount, tokenIndex - baseLPTokenIndex ); } } /** * @notice Returns the address of the pooled token at given index. Reverts if tokenIndex is out of range. * This is a flattened representation of the pooled tokens. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) external view returns (IERC20) { require(index < tokens.length, "index out of range"); return tokens[index]; } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { return metaSwap.calculateSwapUnderlying(tokenIndexFrom, tokenIndexTo, dx); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./ISwap.sol"; interface IMetaSwap { // pool data view functions function getA() external view returns (uint256); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateSwapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) external; function initializeMetaSwap( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function swapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "./interfaces/ISwap.sol"; import "./interfaces/IMetaSwap.sol"; contract SwapDeployer is Ownable { event NewSwapPool( address indexed deployer, address swapAddress, IERC20[] pooledTokens ); event NewClone(address indexed target, address cloneAddress); constructor() public Ownable() {} function clone(address target) external returns (address) { address newClone = _clone(target); emit NewClone(target, newClone); return newClone; } function _clone(address target) internal returns (address) { return Clones.clone(target); } function deploy( address swapAddress, IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) external returns (address) { address swapClone = _clone(swapAddress); ISwap(swapClone).initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); Ownable(swapClone).transferOwnership(owner()); emit NewSwapPool(msg.sender, swapClone, _pooledTokens); return swapClone; } function deployMetaSwap( address metaSwapAddress, IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external returns (address) { address metaSwapClone = _clone(metaSwapAddress); IMetaSwap(metaSwapClone).initializeMetaSwap( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress, baseSwap ); Ownable(metaSwapClone).transferOwnership(owner()); emit NewSwapPool(msg.sender, metaSwapClone, _pooledTokens); return metaSwapClone; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "synthetix/contracts/interfaces/ISynthetix.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "../interfaces/ISwap.sol"; /** * @title SynthSwapper * @notice Replacement of Virtual Synths in favor of gas savings. Allows swapping synths via the Synthetix protocol * or Saddle's pools. The `Bridge.sol` contract will deploy minimal clones of this contract upon initiating * any cross-asset swaps. */ contract SynthSwapper is Initializable { using SafeERC20 for IERC20; address payable owner; // SYNTHETIX points to `ProxyERC20` (0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F). // This contract is a proxy of `Synthetix` and is used to exchange synths. ISynthetix public constant SYNTHETIX = ISynthetix(0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F); // "SADDLE" in bytes32 form bytes32 public constant TRACKING = 0x534144444c450000000000000000000000000000000000000000000000000000; /** * @notice Initializes the contract when deploying this directly. This prevents * others from calling initialize() on the target contract and setting themself as the owner. */ constructor() public { initialize(); } /** * @notice This modifier checks if the caller is the owner */ modifier onlyOwner() { require(msg.sender == owner, "is not owner"); _; } /** * @notice Sets the `owner` as the caller of this function */ function initialize() public initializer { require(owner == address(0), "owner already set"); owner = msg.sender; } /** * @notice Swaps the synth to another synth via the Synthetix protocol. * @param sourceKey currency key of the source synth * @param synthAmount amount of the synth to swap * @param destKey currency key of the destination synth * @return amount of the destination synth received */ function swapSynth( bytes32 sourceKey, uint256 synthAmount, bytes32 destKey ) external onlyOwner returns (uint256) { return SYNTHETIX.exchangeWithTracking( sourceKey, synthAmount, destKey, msg.sender, TRACKING ); } /** * @notice Approves the given `tokenFrom` and swaps it to another token via the given `swap` pool. * @param swap the address of a pool to swap through * @param tokenFrom the address of the stored synth * @param tokenFromIndex the index of the token to swap from * @param tokenToIndex the token the user wants to swap to * @param tokenFromAmount the amount of the token to swap * @param minAmount the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction * @param recipient the address of the recipient */ function swapSynthToToken( ISwap swap, IERC20 tokenFrom, uint8 tokenFromIndex, uint8 tokenToIndex, uint256 tokenFromAmount, uint256 minAmount, uint256 deadline, address recipient ) external onlyOwner returns (IERC20, uint256) { tokenFrom.approve(address(swap), tokenFromAmount); swap.swap( tokenFromIndex, tokenToIndex, tokenFromAmount, minAmount, deadline ); IERC20 tokenTo = swap.getToken(tokenToIndex); uint256 balance = tokenTo.balanceOf(address(this)); tokenTo.safeTransfer(recipient, balance); return (tokenTo, balance); } /** * @notice Withdraws the given amount of `token` to the `recipient`. * @param token the address of the token to withdraw * @param recipient the address of the account to receive the token * @param withdrawAmount the amount of the token to withdraw * @param shouldDestroy whether this contract should be destroyed after this call */ function withdraw( IERC20 token, address recipient, uint256 withdrawAmount, bool shouldDestroy ) external onlyOwner { token.safeTransfer(recipient, withdrawAmount); if (shouldDestroy) { _destroy(); } } /** * @notice Destroys this contract. Only owner can call this function. */ function destroy() external onlyOwner { _destroy(); } function _destroy() internal { selfdestruct(msg.sender); } } pragma solidity >=0.4.24; import "./ISynth.sol"; import "./IVirtualSynth.sol"; // https://docs.synthetix.io/contracts/source/interfaces/isynthetix interface ISynthetix { // Views function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availableSynthCount() external view returns (uint); function availableSynths(uint index) external view returns (ISynth); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint); function isWaitingPeriod(bytes32 currencyKey) external view returns (bool); function maxIssuableSynths(address issuer) external view returns (uint maxIssuable); function remainingIssuableSynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function synths(bytes32 currencyKey) external view returns (ISynth); function synthsByAddress(address synthAddress) external view returns (bytes32); function totalIssuedSynths(bytes32 currencyKey) external view returns (uint); function totalIssuedSynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint); function transferableSynthetix(address account) external view returns (uint transferable); // Mutative Functions function burnSynths(uint amount) external; function burnSynthsOnBehalf(address burnForAddress, uint amount) external; function burnSynthsToTarget() external; function burnSynthsToTargetOnBehalf(address burnForAddress) external; function exchange( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualSynth vSynth); function issueMaxSynths() external; function issueMaxSynthsOnBehalf(address issueForAddress) external; function issueSynths(uint amount) external; function issueSynthsOnBehalf(address issueForAddress, uint amount) external; function mint() external returns (bool); function settle(bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); // Liquidations function liquidateDelinquentAccount(address account, uint susdAmount) external returns (bool); // Restricted Functions function mintSecondary(address account, uint amount) external; function mintSecondaryRewards(uint amount) external; function burnSecondary(address account, uint amount) external; } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/isynth interface ISynth { // Views function currencyKey() external view returns (bytes32); function transferableSynths(address account) external view returns (uint); // Mutative functions function transferAndSettle(address to, uint value) external returns (bool); function transferFromAndSettle( address from, address to, uint value ) external returns (bool); // Restricted: used internally to Synthetix function burn(address account, uint amount) external; function issue(address account, uint amount) external; } pragma solidity >=0.4.24; import "./ISynth.sol"; interface IVirtualSynth { // Views function balanceOfUnderlying(address account) external view returns (uint); function rate() external view returns (uint); function readyToSettle() external view returns (bool); function secsLeftInWaitingPeriod() external view returns (uint); function settled() external view returns (bool); function synth() external view returns (ISynth); // Mutative functions function settle(address account) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/ISwapV1.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. * @dev Only Swap contracts should initialize and own LPToken contracts. */ contract LPTokenV1 is ERC20BurnableUpgradeable, OwnableUpgradeable { using SafeMathUpgradeable for uint256; /** * @notice Initializes this LPToken contract with the given name and symbol * @dev The caller of this function will become the owner. A Swap contract should call this * in its initializer function. * @param name name of this token * @param symbol symbol of this token */ function initialize(string memory name, string memory symbol) external initializer returns (bool) { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); __Ownable_init_unchained(); return true; } /** * @notice Mints the given amount of LPToken to the recipient. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "LPToken: cannot mint 0"); _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that Swap.updateUserWithdrawFees are called everytime. * This assumes the owner is set to a Swap contract's address. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); require(to != address(this), "LPToken: cannot send to itself"); ISwapV1(owner()).updateUserWithdrawFee(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IAllowlist.sol"; interface ISwapV1 { // pool data view functions function getA() external view returns (uint256); function getAllowlist() external view returns (IAllowlist); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256); function calculateRemoveLiquidity(address account, uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 a, uint256 fee, uint256 adminFee, uint256 withdrawFee, address lpTokenTargetAddress ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); // withdraw fee update function function updateUserWithdrawFee(address recipient, uint256 transferAmount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "./interfaces/ISwapV1.sol"; contract SwapDeployerV1 is Ownable { event NewSwapPool( address indexed deployer, address swapAddress, IERC20[] pooledTokens ); constructor() public Ownable() {} function deploy( address swapAddress, IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) external returns (address) { address swapClone = Clones.clone(swapAddress); ISwapV1(swapClone).initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, _withdrawFee, lpTokenTargetAddress ); Ownable(swapClone).transferOwnership(owner()); emit NewSwapPool(msg.sender, swapClone, _pooledTokens); return swapClone; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "synthetix/contracts/interfaces/IAddressResolver.sol"; import "synthetix/contracts/interfaces/IExchanger.sol"; import "synthetix/contracts/interfaces/IExchangeRates.sol"; import "../interfaces/ISwap.sol"; import "./SynthSwapper.sol"; contract Proxy { address public target; } contract Target { address public proxy; } /** * @title Bridge * @notice This contract is responsible for cross-asset swaps using the Synthetix protocol as the bridging exchange. * There are three types of supported cross-asset swaps, tokenToSynth, synthToToken, and tokenToToken. * * 1) tokenToSynth * Swaps a supported token in a saddle pool to any synthetic asset (e.g. tBTC -> sAAVE). * * 2) synthToToken * Swaps any synthetic asset to a suported token in a saddle pool (e.g. sDEFI -> USDC). * * 3) tokenToToken * Swaps a supported token in a saddle pool to one in another pool (e.g. renBTC -> DAI). * * Due to the settlement periods of synthetic assets, the users must wait until the trades can be completed. * Users will receive an ERC721 token that represents pending cross-asset swap. Once the waiting period is over, * the trades can be settled and completed by calling the `completeToSynth` or the `completeToToken` function. * In the cases of pending `synthToToken` or `tokenToToken` swaps, the owners of the pending swaps can also choose * to withdraw the bridging synthetic assets instead of completing the swap. */ contract Bridge is ERC721 { using SafeMath for uint256; using SafeERC20 for IERC20; event SynthIndex( address indexed swap, uint8 synthIndex, bytes32 currencyKey, address synthAddress ); event TokenToSynth( address indexed requester, uint256 indexed itemId, ISwap swapPool, uint8 tokenFromIndex, uint256 tokenFromInAmount, bytes32 synthToKey ); event SynthToToken( address indexed requester, uint256 indexed itemId, ISwap swapPool, bytes32 synthFromKey, uint256 synthFromInAmount, uint8 tokenToIndex ); event TokenToToken( address indexed requester, uint256 indexed itemId, ISwap[2] swapPools, uint8 tokenFromIndex, uint256 tokenFromAmount, uint8 tokenToIndex ); event Settle( address indexed requester, uint256 indexed itemId, IERC20 settleFrom, uint256 settleFromAmount, IERC20 settleTo, uint256 settleToAmount, bool isFinal ); event Withdraw( address indexed requester, uint256 indexed itemId, IERC20 synth, uint256 synthAmount, bool isFinal ); // The addresses for all Synthetix contracts can be found in the below URL. // https://docs.synthetix.io/addresses/#mainnet-contracts // // Since the Synthetix protocol is upgradable, we must use the proxy pairs of each contract such that // the composability is not broken after the protocol upgrade. // // SYNTHETIX_RESOLVER points to `ReadProxyAddressResolver` (0x4E3b31eB0E5CB73641EE1E65E7dCEFe520bA3ef2). // This contract is a read proxy of `AddressResolver` which is responsible for storing the addresses of the contracts // used by the Synthetix protocol. IAddressResolver public constant SYNTHETIX_RESOLVER = IAddressResolver(0x4E3b31eB0E5CB73641EE1E65E7dCEFe520bA3ef2); // EXCHANGER points to `Exchanger`. There is no proxy pair for this contract so we need to update this variable // when the protocol is upgraded. This contract is used to settle synths held by SynthSwapper. IExchanger public exchanger; // CONSTANTS // Available types of cross-asset swaps enum PendingSwapType { Null, TokenToSynth, SynthToToken, TokenToToken } uint256 public constant MAX_UINT256 = 2**256 - 1; uint8 public constant MAX_UINT8 = 2**8 - 1; bytes32 public constant EXCHANGE_RATES_NAME = "ExchangeRates"; bytes32 public constant EXCHANGER_NAME = "Exchanger"; address public immutable SYNTH_SWAPPER_MASTER; // MAPPINGS FOR STORING PENDING SETTLEMENTS // The below two mappings never share the same key. mapping(uint256 => PendingToSynthSwap) public pendingToSynthSwaps; mapping(uint256 => PendingToTokenSwap) public pendingToTokenSwaps; uint256 public pendingSwapsLength; mapping(uint256 => PendingSwapType) private pendingSwapType; // MAPPINGS FOR STORING SYNTH INFO mapping(address => SwapContractInfo) private swapContracts; // Structs holding information about pending settlements struct PendingToSynthSwap { SynthSwapper swapper; bytes32 synthKey; } struct PendingToTokenSwap { SynthSwapper swapper; bytes32 synthKey; ISwap swap; uint8 tokenToIndex; } struct SwapContractInfo { // index of the supported synth + 1 uint8 synthIndexPlusOne; // address of the supported synth address synthAddress; // bytes32 key of the supported synth bytes32 synthKey; // array of tokens supported by the contract IERC20[] tokens; } /** * @notice Deploys this contract and initializes the master version of the SynthSwapper contract. The address to * the Synthetix protocol's Exchanger contract is also set on deployment. */ constructor(address synthSwapperAddress) public ERC721("Saddle Cross-Asset Swap", "SaddleSynthSwap") { SYNTH_SWAPPER_MASTER = synthSwapperAddress; updateExchangerCache(); } /** * @notice Returns the address of the proxy contract targeting the synthetic asset with the given `synthKey`. * @param synthKey the currency key of the synth * @return address of the proxy contract */ function getProxyAddressFromTargetSynthKey(bytes32 synthKey) public view returns (IERC20) { return IERC20(Target(SYNTHETIX_RESOLVER.getSynth(synthKey)).proxy()); } /** * @notice Returns various information of a pending swap represented by the given `itemId`. Information includes * the type of the pending swap, the number of seconds left until it can be settled, the address and the balance * of the synth this swap currently holds, and the address of the destination token. * @param itemId ID of the pending swap * @return swapType the type of the pending virtual swap, * secsLeft number of seconds left until this swap can be settled, * synth address of the synth this swap uses, * synthBalance amount of the synth this swap holds, * tokenTo the address of the destination token */ function getPendingSwapInfo(uint256 itemId) external view returns ( PendingSwapType swapType, uint256 secsLeft, address synth, uint256 synthBalance, address tokenTo ) { swapType = pendingSwapType[itemId]; require(swapType != PendingSwapType.Null, "invalid itemId"); SynthSwapper synthSwapper; bytes32 synthKey; if (swapType == PendingSwapType.TokenToSynth) { synthSwapper = pendingToSynthSwaps[itemId].swapper; synthKey = pendingToSynthSwaps[itemId].synthKey; synth = address(getProxyAddressFromTargetSynthKey(synthKey)); tokenTo = synth; } else { PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; synthSwapper = pendingToTokenSwap.swapper; synthKey = pendingToTokenSwap.synthKey; synth = address(getProxyAddressFromTargetSynthKey(synthKey)); tokenTo = address( swapContracts[address(pendingToTokenSwap.swap)].tokens[ pendingToTokenSwap.tokenToIndex ] ); } secsLeft = exchanger.maxSecsLeftInWaitingPeriod( address(synthSwapper), synthKey ); synthBalance = IERC20(synth).balanceOf(address(synthSwapper)); } // Settles the synth only. function _settle(address synthOwner, bytes32 synthKey) internal { // Settle synth exchanger.settle(synthOwner, synthKey); } /** * @notice Settles and withdraws the synthetic asset without swapping it to a token in a Saddle pool. Only the owner * of the ERC721 token of `itemId` can call this function. Reverts if the given `itemId` does not represent a * `synthToToken` or a `tokenToToken` swap. * @param itemId ID of the pending swap * @param amount the amount of the synth to withdraw */ function withdraw(uint256 itemId, uint256 amount) external { address nftOwner = ownerOf(itemId); require(nftOwner == msg.sender, "not owner"); require( pendingSwapType[itemId] > PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; _settle( address(pendingToTokenSwap.swapper), pendingToTokenSwap.synthKey ); IERC20 synth = getProxyAddressFromTargetSynthKey( pendingToTokenSwap.synthKey ); bool shouldDestroy; if (amount >= synth.balanceOf(address(pendingToTokenSwap.swapper))) { _burn(itemId); delete pendingToTokenSwaps[itemId]; delete pendingSwapType[itemId]; shouldDestroy = true; } pendingToTokenSwap.swapper.withdraw( synth, nftOwner, amount, shouldDestroy ); emit Withdraw(msg.sender, itemId, synth, amount, shouldDestroy); } /** * @notice Completes the pending `tokenToSynth` swap by settling and withdrawing the synthetic asset. * Reverts if the given `itemId` does not represent a `tokenToSynth` swap. * @param itemId ERC721 token ID representing a pending `tokenToSynth` swap */ function completeToSynth(uint256 itemId) external { address nftOwner = ownerOf(itemId); require(nftOwner == msg.sender, "not owner"); require( pendingSwapType[itemId] == PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToSynthSwap memory pendingToSynthSwap = pendingToSynthSwaps[ itemId ]; _settle( address(pendingToSynthSwap.swapper), pendingToSynthSwap.synthKey ); IERC20 synth = getProxyAddressFromTargetSynthKey( pendingToSynthSwap.synthKey ); // Burn the corresponding ERC721 token and delete storage for gas _burn(itemId); delete pendingToTokenSwaps[itemId]; delete pendingSwapType[itemId]; // After settlement, withdraw the synth and send it to the recipient uint256 synthBalance = synth.balanceOf( address(pendingToSynthSwap.swapper) ); pendingToSynthSwap.swapper.withdraw( synth, nftOwner, synthBalance, true ); emit Settle( msg.sender, itemId, synth, synthBalance, synth, synthBalance, true ); } /** * @notice Calculates the expected amount of the token to receive on calling `completeToToken()` with * the given `swapAmount`. * @param itemId ERC721 token ID representing a pending `SynthToToken` or `TokenToToken` swap * @param swapAmount the amount of bridging synth to swap from * @return expected amount of the token the user will receive */ function calcCompleteToToken(uint256 itemId, uint256 swapAmount) external view returns (uint256) { require( pendingSwapType[itemId] > PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; return pendingToTokenSwap.swap.calculateSwap( getSynthIndex(pendingToTokenSwap.swap), pendingToTokenSwap.tokenToIndex, swapAmount ); } /** * @notice Completes the pending `SynthToToken` or `TokenToToken` swap by settling the bridging synth and swapping * it to the desired token. Only the owners of the pending swaps can call this function. * @param itemId ERC721 token ID representing a pending `SynthToToken` or `TokenToToken` swap * @param swapAmount the amount of bridging synth to swap from * @param minAmount the minimum amount of the token to receive - reverts if this amount is not reached * @param deadline the timestamp representing the deadline for this transaction - reverts if deadline is not met */ function completeToToken( uint256 itemId, uint256 swapAmount, uint256 minAmount, uint256 deadline ) external { require(swapAmount != 0, "amount must be greater than 0"); address nftOwner = ownerOf(itemId); require(msg.sender == nftOwner, "must own itemId"); require( pendingSwapType[itemId] > PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; _settle( address(pendingToTokenSwap.swapper), pendingToTokenSwap.synthKey ); IERC20 synth = getProxyAddressFromTargetSynthKey( pendingToTokenSwap.synthKey ); bool shouldDestroyClone; if ( swapAmount >= synth.balanceOf(address(pendingToTokenSwap.swapper)) ) { _burn(itemId); delete pendingToTokenSwaps[itemId]; delete pendingSwapType[itemId]; shouldDestroyClone = true; } // Try swapping the synth to the desired token via the stored swap pool contract // If the external call succeeds, send the token to the owner of token with itemId. (IERC20 tokenTo, uint256 amountOut) = pendingToTokenSwap .swapper .swapSynthToToken( pendingToTokenSwap.swap, synth, getSynthIndex(pendingToTokenSwap.swap), pendingToTokenSwap.tokenToIndex, swapAmount, minAmount, deadline, nftOwner ); if (shouldDestroyClone) { pendingToTokenSwap.swapper.destroy(); } emit Settle( msg.sender, itemId, synth, swapAmount, tokenTo, amountOut, shouldDestroyClone ); } // Add the given pending synth settlement struct to the list function _addToPendingSynthSwapList( PendingToSynthSwap memory pendingToSynthSwap ) internal returns (uint256) { require( pendingSwapsLength < MAX_UINT256, "pendingSwapsLength reached max size" ); pendingToSynthSwaps[pendingSwapsLength] = pendingToSynthSwap; return pendingSwapsLength++; } // Add the given pending synth to token settlement struct to the list function _addToPendingSynthToTokenSwapList( PendingToTokenSwap memory pendingToTokenSwap ) internal returns (uint256) { require( pendingSwapsLength < MAX_UINT256, "pendingSwapsLength reached max size" ); pendingToTokenSwaps[pendingSwapsLength] = pendingToTokenSwap; return pendingSwapsLength++; } /** * @notice Calculates the expected amount of the desired synthetic asset the caller will receive after completing * a `TokenToSynth` swap with the given parameters. This calculation does not consider the settlement periods. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param tokenFromIndex the index of the token to swap from * @param synthOutKey the currency key of the desired synthetic asset * @param tokenInAmount the amount of the token to swap form * @return the expected amount of the desired synth */ function calcTokenToSynth( ISwap swap, uint8 tokenFromIndex, bytes32 synthOutKey, uint256 tokenInAmount ) external view returns (uint256) { uint8 mediumSynthIndex = getSynthIndex(swap); uint256 expectedMediumSynthAmount = swap.calculateSwap( tokenFromIndex, mediumSynthIndex, tokenInAmount ); bytes32 mediumSynthKey = getSynthKey(swap); IExchangeRates exchangeRates = IExchangeRates( SYNTHETIX_RESOLVER.getAddress(EXCHANGE_RATES_NAME) ); return exchangeRates.effectiveValue( mediumSynthKey, expectedMediumSynthAmount, synthOutKey ); } /** * @notice Initiates a cross-asset swap from a token supported in the `swap` pool to any synthetic asset. * The caller will receive an ERC721 token representing their ownership of the pending cross-asset swap. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param tokenFromIndex the index of the token to swap from * @param synthOutKey the currency key of the desired synthetic asset * @param tokenInAmount the amount of the token to swap form * @param minAmount the amount of the token to swap form * @return ID of the ERC721 token sent to the caller */ function tokenToSynth( ISwap swap, uint8 tokenFromIndex, bytes32 synthOutKey, uint256 tokenInAmount, uint256 minAmount ) external returns (uint256) { require(tokenInAmount != 0, "amount must be greater than 0"); // Create a SynthSwapper clone SynthSwapper synthSwapper = SynthSwapper( Clones.clone(SYNTH_SWAPPER_MASTER) ); synthSwapper.initialize(); // Add the synthswapper to the pending settlement list uint256 itemId = _addToPendingSynthSwapList( PendingToSynthSwap(synthSwapper, synthOutKey) ); pendingSwapType[itemId] = PendingSwapType.TokenToSynth; // Mint an ERC721 token that represents ownership of the pending synth settlement to msg.sender _mint(msg.sender, itemId); // Transfer token from msg.sender IERC20 tokenFrom = swapContracts[address(swap)].tokens[tokenFromIndex]; // revert when token not found in swap pool tokenFrom.safeTransferFrom(msg.sender, address(this), tokenInAmount); tokenInAmount = tokenFrom.balanceOf(address(this)); // Swap the synth to the medium synth uint256 mediumSynthAmount = swap.swap( tokenFromIndex, getSynthIndex(swap), tokenInAmount, 0, block.timestamp ); // Swap synths via Synthetix network IERC20(getSynthAddress(swap)).safeTransfer( address(synthSwapper), mediumSynthAmount ); require( synthSwapper.swapSynth( getSynthKey(swap), mediumSynthAmount, synthOutKey ) >= minAmount, "minAmount not reached" ); // Emit TokenToSynth event with relevant data emit TokenToSynth( msg.sender, itemId, swap, tokenFromIndex, tokenInAmount, synthOutKey ); return (itemId); } /** * @notice Calculates the expected amount of the desired token the caller will receive after completing * a `SynthToToken` swap with the given parameters. This calculation does not consider the settlement periods or * any potential changes of the `swap` pool composition. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param synthInKey the currency key of the synth to swap from * @param tokenToIndex the index of the token to swap to * @param synthInAmount the amount of the synth to swap form * @return the expected amount of the bridging synth and the expected amount of the desired token */ function calcSynthToToken( ISwap swap, bytes32 synthInKey, uint8 tokenToIndex, uint256 synthInAmount ) external view returns (uint256, uint256) { IExchangeRates exchangeRates = IExchangeRates( SYNTHETIX_RESOLVER.getAddress(EXCHANGE_RATES_NAME) ); uint8 mediumSynthIndex = getSynthIndex(swap); bytes32 mediumSynthKey = getSynthKey(swap); require(synthInKey != mediumSynthKey, "use normal swap"); uint256 expectedMediumSynthAmount = exchangeRates.effectiveValue( synthInKey, synthInAmount, mediumSynthKey ); return ( expectedMediumSynthAmount, swap.calculateSwap( mediumSynthIndex, tokenToIndex, expectedMediumSynthAmount ) ); } /** * @notice Initiates a cross-asset swap from a synthetic asset to a supported token. The caller will receive * an ERC721 token representing their ownership of the pending cross-asset swap. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param synthInKey the currency key of the synth to swap from * @param tokenToIndex the index of the token to swap to * @param synthInAmount the amount of the synth to swap form * @param minMediumSynthAmount the minimum amount of the bridging synth at pre-settlement stage * @return the ID of the ERC721 token sent to the caller */ function synthToToken( ISwap swap, bytes32 synthInKey, uint8 tokenToIndex, uint256 synthInAmount, uint256 minMediumSynthAmount ) external returns (uint256) { require(synthInAmount != 0, "amount must be greater than 0"); bytes32 mediumSynthKey = getSynthKey(swap); require( synthInKey != mediumSynthKey, "synth is supported via normal swap" ); // Create a SynthSwapper clone SynthSwapper synthSwapper = SynthSwapper( Clones.clone(SYNTH_SWAPPER_MASTER) ); synthSwapper.initialize(); // Add the synthswapper to the pending synth to token settlement list uint256 itemId = _addToPendingSynthToTokenSwapList( PendingToTokenSwap(synthSwapper, mediumSynthKey, swap, tokenToIndex) ); pendingSwapType[itemId] = PendingSwapType.SynthToToken; // Mint an ERC721 token that represents ownership of the pending synth to token settlement to msg.sender _mint(msg.sender, itemId); // Receive synth from the user and swap it to another synth IERC20 synthFrom = getProxyAddressFromTargetSynthKey(synthInKey); synthFrom.safeTransferFrom(msg.sender, address(this), synthInAmount); synthFrom.safeTransfer(address(synthSwapper), synthInAmount); require( synthSwapper.swapSynth(synthInKey, synthInAmount, mediumSynthKey) >= minMediumSynthAmount, "minMediumSynthAmount not reached" ); // Emit SynthToToken event with relevant data emit SynthToToken( msg.sender, itemId, swap, synthInKey, synthInAmount, tokenToIndex ); return (itemId); } /** * @notice Calculates the expected amount of the desired token the caller will receive after completing * a `TokenToToken` swap with the given parameters. This calculation does not consider the settlement periods or * any potential changes of the pool compositions. * @param swaps the addresses of the two Saddle pools used to do the cross-asset swap * @param tokenFromIndex the index of the token in the first `swaps` pool to swap from * @param tokenToIndex the index of the token in the second `swaps` pool to swap to * @param tokenFromAmount the amount of the token to swap from * @return the expected amount of bridging synth at pre-settlement stage and the expected amount of the desired * token */ function calcTokenToToken( ISwap[2] calldata swaps, uint8 tokenFromIndex, uint8 tokenToIndex, uint256 tokenFromAmount ) external view returns (uint256, uint256) { IExchangeRates exchangeRates = IExchangeRates( SYNTHETIX_RESOLVER.getAddress(EXCHANGE_RATES_NAME) ); uint256 firstSynthAmount = swaps[0].calculateSwap( tokenFromIndex, getSynthIndex(swaps[0]), tokenFromAmount ); uint256 mediumSynthAmount = exchangeRates.effectiveValue( getSynthKey(swaps[0]), firstSynthAmount, getSynthKey(swaps[1]) ); return ( mediumSynthAmount, swaps[1].calculateSwap( getSynthIndex(swaps[1]), tokenToIndex, mediumSynthAmount ) ); } /** * @notice Initiates a cross-asset swap from a token in one Saddle pool to one in another. The caller will receive * an ERC721 token representing their ownership of the pending cross-asset swap. * @param swaps the addresses of the two Saddle pools used to do the cross-asset swap * @param tokenFromIndex the index of the token in the first `swaps` pool to swap from * @param tokenToIndex the index of the token in the second `swaps` pool to swap to * @param tokenFromAmount the amount of the token to swap from * @param minMediumSynthAmount the minimum amount of the bridging synth at pre-settlement stage * @return the ID of the ERC721 token sent to the caller */ function tokenToToken( ISwap[2] calldata swaps, uint8 tokenFromIndex, uint8 tokenToIndex, uint256 tokenFromAmount, uint256 minMediumSynthAmount ) external returns (uint256) { // Create a SynthSwapper clone require(tokenFromAmount != 0, "amount must be greater than 0"); SynthSwapper synthSwapper = SynthSwapper( Clones.clone(SYNTH_SWAPPER_MASTER) ); synthSwapper.initialize(); bytes32 mediumSynthKey = getSynthKey(swaps[1]); // Add the synthswapper to the pending synth to token settlement list uint256 itemId = _addToPendingSynthToTokenSwapList( PendingToTokenSwap( synthSwapper, mediumSynthKey, swaps[1], tokenToIndex ) ); pendingSwapType[itemId] = PendingSwapType.TokenToToken; // Mint an ERC721 token that represents ownership of the pending swap to msg.sender _mint(msg.sender, itemId); // Receive token from the user ISwap swap = swaps[0]; { IERC20 tokenFrom = swapContracts[address(swap)].tokens[ tokenFromIndex ]; tokenFrom.safeTransferFrom( msg.sender, address(this), tokenFromAmount ); } uint256 firstSynthAmount = swap.swap( tokenFromIndex, getSynthIndex(swap), tokenFromAmount, 0, block.timestamp ); // Swap the synth to another synth IERC20(getSynthAddress(swap)).safeTransfer( address(synthSwapper), firstSynthAmount ); require( synthSwapper.swapSynth( getSynthKey(swap), firstSynthAmount, mediumSynthKey ) >= minMediumSynthAmount, "minMediumSynthAmount not reached" ); // Emit TokenToToken event with relevant data emit TokenToToken( msg.sender, itemId, swaps, tokenFromIndex, tokenFromAmount, tokenToIndex ); return (itemId); } /** * @notice Registers the index and the address of the supported synth from the given `swap` pool. The matching currency key must * be supplied for a successful registration. * @param swap the address of the pool that contains the synth * @param synthIndex the index of the supported synth in the given `swap` pool * @param currencyKey the currency key of the synth in bytes32 form */ function setSynthIndex( ISwap swap, uint8 synthIndex, bytes32 currencyKey ) external { require(synthIndex < MAX_UINT8, "index is too large"); SwapContractInfo storage swapContractInfo = swapContracts[ address(swap) ]; // Check if the pool has already been added require(swapContractInfo.synthIndexPlusOne == 0, "Pool already added"); // Ensure the synth with the same currency key exists at the given `synthIndex` IERC20 synth = swap.getToken(synthIndex); require( ISynth(Proxy(address(synth)).target()).currencyKey() == currencyKey, "currencyKey does not match" ); swapContractInfo.synthIndexPlusOne = synthIndex + 1; swapContractInfo.synthAddress = address(synth); swapContractInfo.synthKey = currencyKey; swapContractInfo.tokens = new IERC20[](0); for (uint8 i = 0; i < MAX_UINT8; i++) { IERC20 token; if (i == synthIndex) { token = synth; } else { try swap.getToken(i) returns (IERC20 token_) { token = token_; } catch { break; } } swapContractInfo.tokens.push(token); token.safeApprove(address(swap), MAX_UINT256); } emit SynthIndex(address(swap), synthIndex, currencyKey, address(synth)); } /** * @notice Returns the index of the supported synth in the given `swap` pool. Reverts if the `swap` pool * is not registered. * @param swap the address of the pool that contains the synth * @return the index of the supported synth */ function getSynthIndex(ISwap swap) public view returns (uint8) { uint8 synthIndexPlusOne = swapContracts[address(swap)] .synthIndexPlusOne; require(synthIndexPlusOne > 0, "synth index not found for given pool"); return synthIndexPlusOne - 1; } /** * @notice Returns the address of the supported synth in the given `swap` pool. Reverts if the `swap` pool * is not registered. * @param swap the address of the pool that contains the synth * @return the address of the supported synth */ function getSynthAddress(ISwap swap) public view returns (address) { address synthAddress = swapContracts[address(swap)].synthAddress; require( synthAddress != address(0), "synth addr not found for given pool" ); return synthAddress; } /** * @notice Returns the currency key of the supported synth in the given `swap` pool. Reverts if the `swap` pool * is not registered. * @param swap the address of the pool that contains the synth * @return the currency key of the supported synth */ function getSynthKey(ISwap swap) public view returns (bytes32) { bytes32 synthKey = swapContracts[address(swap)].synthKey; require(synthKey != 0x0, "synth key not found for given pool"); return synthKey; } /** * @notice Updates the stored address of the `EXCHANGER` contract. When the Synthetix team upgrades their protocol, * a new Exchanger contract is deployed. This function manually updates the stored address. */ function updateExchangerCache() public { exchanger = IExchanger(SYNTHETIX_RESOLVER.getAddress(EXCHANGER_NAME)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/iaddressresolver interface IAddressResolver { function getAddress(bytes32 name) external view returns (address); function getSynth(bytes32 key) external view returns (address); function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address); } pragma solidity >=0.4.24; import "./IVirtualSynth.sol"; // https://docs.synthetix.io/contracts/source/interfaces/iexchanger interface IExchanger { // Views function calculateAmountAfterSettlement( address from, bytes32 currencyKey, uint amount, uint refunded ) external view returns (uint amountAfterSettlement); function isSynthRateInvalid(bytes32 currencyKey) external view returns (bool); function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint); function settlementOwing(address account, bytes32 currencyKey) external view returns ( uint reclaimAmount, uint rebateAmount, uint numEntries ); function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool); function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view returns (uint exchangeFeeRate); function getAmountsForExchange( uint sourceAmount, bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey ) external view returns ( uint amountReceived, uint fee, uint exchangeFeeRate ); function priceDeviationThresholdFactor() external view returns (uint); function waitingPeriodSecs() external view returns (uint); // Mutative functions function exchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualSynth vSynth); function settle(address from, bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); function setLastExchangeRateForSynth(bytes32 currencyKey, uint rate) external; function suspendSynthWithInvalidRate(bytes32 currencyKey) external; } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/iexchangerates interface IExchangeRates { // Structs struct RateAndUpdatedTime { uint216 rate; uint40 time; } struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozenAtUpperLimit; bool frozenAtLowerLimit; } // Views function aggregators(bytes32 currencyKey) external view returns (address); function aggregatorWarningFlags() external view returns (address); function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool); function canFreezeRate(bytes32 currencyKey) external view returns (bool); function currentRoundForRate(bytes32 currencyKey) external view returns (uint); function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory); function effectiveValue( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns (uint value); function effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns ( uint value, uint sourceRate, uint destinationRate ); function effectiveValueAtRound( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint roundIdForSrc, uint roundIdForDest ) external view returns (uint value); function getCurrentRoundId(bytes32 currencyKey) external view returns (uint); function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint startingRoundId, uint startingTimestamp, uint timediff ) external view returns (uint); function inversePricing(bytes32 currencyKey) external view returns ( uint entryPoint, uint upperLimit, uint lowerLimit, bool frozenAtUpperLimit, bool frozenAtLowerLimit ); function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256); function oracle() external view returns (address); function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time); function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time); function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid); function rateForCurrency(bytes32 currencyKey) external view returns (uint); function rateIsFlagged(bytes32 currencyKey) external view returns (bool); function rateIsFrozen(bytes32 currencyKey) external view returns (bool); function rateIsInvalid(bytes32 currencyKey) external view returns (bool); function rateIsStale(bytes32 currencyKey) external view returns (bool); function rateStalePeriod() external view returns (uint); function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds) external view returns (uint[] memory rates, uint[] memory times); function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory rates, bool anyRateInvalid); function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory); // Mutative functions function freezeRate(bytes32 currencyKey) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.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.6.2 <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.6.2 <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.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface 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.6.12; pragma experimental ABIEncoderV2; import "./interfaces/ISwap.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title SwapMigrator * @notice This contract is responsible for migrating old USD pool liquidity to the new ones. * Users can use this contract to remove their liquidity from the old pools and add them to the new * ones with a single transaction. */ contract SwapMigrator { using SafeERC20 for IERC20; struct MigrationData { address oldPoolAddress; IERC20 oldPoolLPTokenAddress; address newPoolAddress; IERC20 newPoolLPTokenAddress; IERC20[] underlyingTokens; } MigrationData public usdPoolMigrationData; address public owner; uint256 private constant MAX_UINT256 = 2**256 - 1; /** * @notice Sets the storage variables and approves tokens to be used by the old and new swap contracts * @param usdData_ MigrationData struct with information about old and new USD pools * @param owner_ owner that is allowed to call the `rescue()` function */ constructor(MigrationData memory usdData_, address owner_) public { // Approve old USD LP Token to be used by the old USD pool usdData_.oldPoolLPTokenAddress.approve( usdData_.oldPoolAddress, MAX_UINT256 ); // Approve USD tokens to be used by the new USD pool for (uint256 i = 0; i < usdData_.underlyingTokens.length; i++) { usdData_.underlyingTokens[i].safeApprove( usdData_.newPoolAddress, MAX_UINT256 ); } // Set storage variables usdPoolMigrationData = usdData_; owner = owner_; } /** * @notice Migrates old USD pool's LPToken to the new pool * @param amount Amount of old LPToken to migrate * @param minAmount Minimum amount of new LPToken to receive */ function migrateUSDPool(uint256 amount, uint256 minAmount) external returns (uint256) { // Transfer old LP token from the caller usdPoolMigrationData.oldPoolLPTokenAddress.safeTransferFrom( msg.sender, address(this), amount ); // Remove liquidity from the old pool and add them to the new pool uint256[] memory amounts = ISwap(usdPoolMigrationData.oldPoolAddress) .removeLiquidity( amount, new uint256[](usdPoolMigrationData.underlyingTokens.length), MAX_UINT256 ); uint256 mintedAmount = ISwap(usdPoolMigrationData.newPoolAddress) .addLiquidity(amounts, minAmount, MAX_UINT256); // Transfer new LP Token to the caller usdPoolMigrationData.newPoolLPTokenAddress.safeTransfer( msg.sender, mintedAmount ); return mintedAmount; } /** * @notice Rescues any token that may be sent to this contract accidentally. * @param token Amount of old LPToken to migrate * @param to Minimum amount of new LPToken to receive */ function rescue(IERC20 token, address to) external { require(msg.sender == owner, "is not owner"); token.safeTransfer(to, token.balanceOf(address(this))); } } // SPDX-License-Identifier: MIT // Generalized and adapted from https://github.com/k06a/Unipool 🙇 pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title StakeableTokenWrapper * @notice A wrapper for an ERC-20 that can be staked and withdrawn. * @dev In this contract, staked tokens don't do anything- instead other * contracts can inherit from this one to add functionality. */ contract StakeableTokenWrapper { using SafeERC20 for IERC20; using SafeMath for uint256; uint256 public totalSupply; IERC20 public stakedToken; mapping(address => uint256) private _balances; event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); /** * @notice Creates a new StakeableTokenWrapper with given `_stakedToken` address * @param _stakedToken address of a token that will be used to stake */ constructor(IERC20 _stakedToken) public { stakedToken = _stakedToken; } /** * @notice Read how much `account` has staked in this contract * @param account address of an account * @return amount of total staked ERC20(this.stakedToken) by `account` */ function balanceOf(address account) external view returns (uint256) { return _balances[account]; } /** * @notice Stakes given `amount` in this contract * @param amount amount of ERC20(this.stakedToken) to stake */ function stake(uint256 amount) external { require(amount != 0, "amount == 0"); totalSupply = totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakedToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } /** * @notice Withdraws given `amount` from this contract * @param amount amount of ERC20(this.stakedToken) to withdraw */ function withdraw(uint256 amount) external { totalSupply = totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakedToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IFlashLoanReceiver.sol"; import "../interfaces/ISwapFlashLoan.sol"; import "hardhat/console.sol"; contract FlashLoanBorrowerExample is IFlashLoanReceiver { using SafeMath for uint256; // Typical executeOperation function should do the 3 following actions // 1. Check if the flashLoan was successful // 2. Do actions with the borrowed tokens // 3. Repay the debt to the `pool` function executeOperation( address pool, address token, uint256 amount, uint256 fee, bytes calldata params ) external override { // 1. Check if the flashLoan was valid require( IERC20(token).balanceOf(address(this)) >= amount, "flashloan is broken?" ); // 2. Do actions with the borrowed token bytes32 paramsHash = keccak256(params); if (paramsHash == keccak256(bytes("dontRepayDebt"))) { return; } else if (paramsHash == keccak256(bytes("reentrancy_addLiquidity"))) { ISwapFlashLoan(pool).addLiquidity( new uint256[](0), 0, block.timestamp ); } else if (paramsHash == keccak256(bytes("reentrancy_swap"))) { ISwapFlashLoan(pool).swap(1, 0, 1e6, 0, now); } else if ( paramsHash == keccak256(bytes("reentrancy_removeLiquidity")) ) { ISwapFlashLoan(pool).removeLiquidity(1e18, new uint256[](0), now); } else if ( paramsHash == keccak256(bytes("reentrancy_removeLiquidityOneToken")) ) { ISwapFlashLoan(pool).removeLiquidityOneToken(1e18, 0, 1e18, now); } // 3. Payback debt uint256 totalDebt = amount.add(fee); IERC20(token).transfer(pool, totalDebt); } function flashLoan( ISwapFlashLoan swap, IERC20 token, uint256 amount, bytes memory params ) external { swap.flashLoan(address(this), token, amount, params); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./ISwap.sol"; interface ISwapFlashLoan is ISwap { function flashLoan( address receiver, IERC20 token, uint256 amount, bytes memory params ) external; } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../../interfaces/ISwap.sol"; import "hardhat/console.sol"; contract TestSwapReturnValues { using SafeMath for uint256; ISwap public swap; IERC20 public lpToken; uint8 public n; uint256 public constant MAX_INT = 2**256 - 1; constructor( ISwap swapContract, IERC20 lpTokenContract, uint8 numOfTokens ) public { swap = swapContract; lpToken = lpTokenContract; n = numOfTokens; // Pre-approve tokens for (uint8 i; i < n; i++) { swap.getToken(i).approve(address(swap), MAX_INT); } lpToken.approve(address(swap), MAX_INT); } function test_swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) public { uint256 balanceBefore = swap.getToken(tokenIndexTo).balanceOf( address(this) ); uint256 returnValue = swap.swap( tokenIndexFrom, tokenIndexTo, dx, minDy, block.timestamp ); uint256 balanceAfter = swap.getToken(tokenIndexTo).balanceOf( address(this) ); console.log( "swap: Expected %s, got %s", balanceAfter.sub(balanceBefore), returnValue ); require( returnValue == balanceAfter.sub(balanceBefore), "swap()'s return value does not match received amount" ); } function test_addLiquidity(uint256[] calldata amounts, uint256 minToMint) public { uint256 balanceBefore = lpToken.balanceOf(address(this)); uint256 returnValue = swap.addLiquidity(amounts, minToMint, MAX_INT); uint256 balanceAfter = lpToken.balanceOf(address(this)); console.log( "addLiquidity: Expected %s, got %s", balanceAfter.sub(balanceBefore), returnValue ); require( returnValue == balanceAfter.sub(balanceBefore), "addLiquidity()'s return value does not match minted amount" ); } function test_removeLiquidity(uint256 amount, uint256[] memory minAmounts) public { uint256[] memory balanceBefore = new uint256[](n); uint256[] memory balanceAfter = new uint256[](n); for (uint8 i = 0; i < n; i++) { balanceBefore[i] = swap.getToken(i).balanceOf(address(this)); } uint256[] memory returnValue = swap.removeLiquidity( amount, minAmounts, MAX_INT ); for (uint8 i = 0; i < n; i++) { balanceAfter[i] = swap.getToken(i).balanceOf(address(this)); console.log( "removeLiquidity: Expected %s, got %s", balanceAfter[i].sub(balanceBefore[i]), returnValue[i] ); require( balanceAfter[i].sub(balanceBefore[i]) == returnValue[i], "removeLiquidity()'s return value does not match received amounts of tokens" ); } } function test_removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount ) public { uint256 balanceBefore = lpToken.balanceOf(address(this)); uint256 returnValue = swap.removeLiquidityImbalance( amounts, maxBurnAmount, MAX_INT ); uint256 balanceAfter = lpToken.balanceOf(address(this)); console.log( "removeLiquidityImbalance: Expected %s, got %s", balanceBefore.sub(balanceAfter), returnValue ); require( returnValue == balanceBefore.sub(balanceAfter), "removeLiquidityImbalance()'s return value does not match burned lpToken amount" ); } function test_removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) public { uint256 balanceBefore = swap.getToken(tokenIndex).balanceOf( address(this) ); uint256 returnValue = swap.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount, MAX_INT ); uint256 balanceAfter = swap.getToken(tokenIndex).balanceOf( address(this) ); console.log( "removeLiquidityOneToken: Expected %s, got %s", balanceAfter.sub(balanceBefore), returnValue ); require( returnValue == balanceAfter.sub(balanceBefore), "removeLiquidityOneToken()'s return value does not match received token amount" ); } } // SPDX-License-Identifier: MIT // https://etherscan.io/address/0x2b7a5a5923eca5c00c6572cf3e8e08384f563f93#code pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./LPTokenGuarded.sol"; import "../MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtilsGuarded { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; uint256 defaultWithdrawFee; LPTokenGuarded lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; mapping(address => uint256) depositTimestamp; mapping(address => uint256) withdrawFeeMultiplier; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculation in addLiquidity function // to avoid stack too deep error struct AddLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; } // Struct storing variables used in calculation in removeLiquidityImbalance function // to avoid stack too deep error struct RemoveLiquidityImbalanceInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Max withdrawFee is 1% of the value withdrawn // Fee will be redistributed to the LPs in the pool, rewarding // long term providers. uint256 public constant MAX_WITHDRAW_FEE = 10**8; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(Swap storage self) external view returns (uint256) { return _getA(self); } /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function _getA(Swap storage self) internal view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Calculates and returns A based on the ramp settings * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Retrieves the timestamp of last deposit made by the given address * @param self Swap struct to read from * @return timestamp of last deposit */ function getDepositTimestamp(Swap storage self, address user) external view returns (uint256) { return self.depositTimestamp[user]; } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param account the address that is withdrawing * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive and the associated swap fee */ function calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex ) public view returns (uint256, uint256) { uint256 dy; uint256 newY; (dy, newY) = calculateWithdrawOneTokenDY(self, tokenIndex, tokenAmount); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = _xp(self)[tokenIndex] .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); dy = dy .mul( FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount ) internal view returns (uint256, uint256) { require( tokenIndex < self.pooledTokens.length, "Token index out of range" ); // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(self.lpToken.totalSupply())); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self); for (uint256 i = 0; i < self.pooledTokens.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant iteratively. * See the StableSwap paper and Curve.fi implementation for further details. * * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex Index of token we are calculating for. * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool. * @param d the stableswap invariant * @return the price of the token, in the same precision as in xp */ function getYD( uint256 a, uint8 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality * as the pool. * @param a the amplification coefficient * n * (n - 1) in A_PRECISION. * See the StableSwap paper for details * @return the invariant, at the precision of the pool */ function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA.mul(s).div(A_PRECISION).add(dP.mul(numTokens)).mul(d).div( nA.sub(A_PRECISION).mul(d).div(A_PRECISION).add( numTokens.add(1).mul(dP) ) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Get D, the StableSwap invariant, based on self Swap struct * @param self Swap struct to read from * @return The invariant, at the precision of the pool */ function getD(Swap storage self) internal view returns (uint256) { return getD(_xp(self), _getAPrecise(self)); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @param balances array of balances to scale * @return balances array "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self, uint256[] memory balances) internal view returns (uint256[] memory) { return _xp(balances, self.tokenPrecisionMultipliers); } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); uint256 supply = self.lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(ERC20(self.lpToken).decimals())).div(supply); } return 0; } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * * @param self Swap struct to read from * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function getY( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal view returns (uint256) { uint256 numTokens = self.pooledTokens.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 a = _getAPrecise(self); uint256 d = getD(xp, a); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(a); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap(self, tokenIndexFrom, tokenIndexTo, dx); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory xp = _xp(self); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]).add( xp[tokenIndexFrom] ); uint256 y = getY(self, tokenIndexFrom, tokenIndexTo, x, xp); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(self.tokenPrecisionMultipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param account the address that is removing liquidity. required for withdraw fee calculation * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) external view returns (uint256[] memory) { return _calculateRemoveLiquidity(self, account, amount); } function _calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) internal view returns (uint256[] memory) { uint256 totalSupply = self.lpToken.totalSupply(); require(amount <= totalSupply, "Cannot exceed total supply"); uint256 feeAdjustedAmount = amount .mul( FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); uint256[] memory amounts = new uint256[](self.pooledTokens.length); for (uint256 i = 0; i < self.pooledTokens.length; i++) { amounts[i] = self.balances[i].mul(feeAdjustedAmount).div( totalSupply ); } return amounts; } /** * @notice Calculate the fee that is applied when the given user withdraws. * Withdraw fee decays linearly over 4 weeks. * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(Swap storage self, address user) public view returns (uint256) { uint256 endTime = self.depositTimestamp[user].add(4 weeks); if (endTime > block.timestamp) { uint256 timeLeftover = endTime.sub(block.timestamp); return self .defaultWithdrawFee .mul(self.withdrawFeeMultiplier[user]) .mul(timeLeftover) .div(4 weeks) .div(FEE_DENOMINATOR); } return 0; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param account address of the account depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 numTokens = self.pooledTokens.length; uint256 a = _getAPrecise(self); uint256 d0 = getD(_xp(self, self.balances), a); uint256[] memory balances1 = self.balances; for (uint256 i = 0; i < numTokens; i++) { if (deposit) { balances1[i] = balances1[i].add(amounts[i]); } else { balances1[i] = balances1[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(self, balances1), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub( calculateCurrentWithdrawFee(self, account) ) ); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param self Swap struct to read from */ function _feePerToken(Swap storage self) internal view returns (uint256) { return self.swapFee.mul(self.pooledTokens.length).div( self.pooledTokens.length.sub(1).mul(4) ); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { require( dx <= self.pooledTokens[tokenIndexFrom].balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = self.pooledTokens[tokenIndexFrom].balanceOf( address(this) ); self.pooledTokens[tokenIndexFrom].safeTransferFrom( msg.sender, address(this), dx ); // Use the actual transferred amount for AMM math uint256 transferredDx = self .pooledTokens[tokenIndexFrom] .balanceOf(address(this)) .sub(beforeBalance); (uint256 dy, uint256 dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, transferredDx ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = self.balances[tokenIndexFrom].add( transferredDx ); self.balances[tokenIndexTo] = self.balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap( msg.sender, transferredDx, dy, tokenIndexFrom, tokenIndexTo ); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param merkleProof bytes32 array that will be used to prove the existence of the caller's address in the list of * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint, bytes32[] calldata merkleProof ) external returns (uint256) { require( amounts.length == self.pooledTokens.length, "Amounts must match pooled tokens" ); uint256[] memory fees = new uint256[](self.pooledTokens.length); // current state AddLiquidityInfo memory v = AddLiquidityInfo(0, 0, 0, 0); if (self.lpToken.totalSupply() != 0) { v.d0 = getD(self); } uint256[] memory newBalances = self.balances; for (uint256 i = 0; i < self.pooledTokens.length; i++) { require( self.lpToken.totalSupply() != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = self.pooledTokens[i].balanceOf( address(this) ); self.pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = self.pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = self.balances[i].add(amounts[i]); } // invariant after change v.preciseA = _getAPrecise(self); v.d1 = getD(_xp(self, newBalances), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; if (self.lpToken.totalSupply() != 0) { uint256 feePerToken = _feePerToken(self); for (uint256 i = 0; i < self.pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(self, newBalances), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (self.lpToken.totalSupply() == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(self.lpToken.totalSupply()).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens self.lpToken.mint(msg.sender, toMint, merkleProof); emit AddLiquidity( msg.sender, amounts, fees, v.d1, self.lpToken.totalSupply() ); return toMint; } /** * @notice Update the withdraw fee for `user`. If the user is currently * not providing liquidity in the pool, sets to default value. If not, recalculate * the starting withdraw fee based on the last deposit's time & amount relative * to the new deposit. * * @param self Swap struct to read from and write to * @param user address of the user depositing tokens * @param toMint amount of pool tokens to be minted */ function updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) external { _updateUserWithdrawFee(self, user, toMint); } function _updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) internal { // If token is transferred to address 0 (or burned), don't update the fee. if (user == address(0)) { return; } if (self.defaultWithdrawFee == 0) { // If current fee is set to 0%, set multiplier to FEE_DENOMINATOR self.withdrawFeeMultiplier[user] = FEE_DENOMINATOR; } else { // Otherwise, calculate appropriate discount based on last deposit amount uint256 currentFee = calculateCurrentWithdrawFee(self, user); uint256 currentBalance = self.lpToken.balanceOf(user); // ((currentBalance * currentFee) + (toMint * defaultWithdrawFee)) * FEE_DENOMINATOR / // ((toMint + currentBalance) * defaultWithdrawFee) self.withdrawFeeMultiplier[user] = currentBalance .mul(currentFee) .add(toMint.mul(self.defaultWithdrawFee)) .mul(FEE_DENOMINATOR) .div(toMint.add(currentBalance).mul(self.defaultWithdrawFee)); } self.depositTimestamp[user] = block.timestamp; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { require(amount <= self.lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == self.pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory amounts = _calculateRemoveLiquidity( self, msg.sender, amount ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = self.balances[i].sub(amounts[i]); self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } self.lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, self.lpToken.totalSupply()); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { uint256 totalSupply = self.lpToken.totalSupply(); uint256 numTokens = self.pooledTokens.length; require( tokenAmount <= self.lpToken.balanceOf(msg.sender), ">LP.balanceOf" ); require(tokenIndex < numTokens, "Token not found"); uint256 dyFee; uint256 dy; (dy, dyFee) = calculateWithdrawOneToken( self, msg.sender, tokenAmount, tokenIndex ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); self.lpToken.burnFrom(msg.sender, tokenAmount); self.pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { require( amounts.length == self.pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= self.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); RemoveLiquidityImbalanceInfo memory v = RemoveLiquidityImbalanceInfo( 0, 0, 0, 0 ); uint256 tokenSupply = self.lpToken.totalSupply(); uint256 feePerToken = _feePerToken(self); uint256[] memory balances1 = self.balances; v.preciseA = _getAPrecise(self); v.d0 = getD(_xp(self), v.preciseA); for (uint256 i = 0; i < self.pooledTokens.length; i++) { balances1[i] = balances1[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(self, balances1), v.preciseA); uint256[] memory fees = new uint256[](self.pooledTokens.length); for (uint256 i = 0; i < self.pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(self, balances1), v.preciseA); uint256 tokenAmount = v.d0.sub(v.d2).mul(tokenSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, msg.sender)) ); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); self.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < self.pooledTokens.length; i++) { self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, tokenSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { for (uint256 i = 0; i < self.pooledTokens.length; i++) { IERC20 token = self.pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub( self.balances[i] ); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } /** * @notice update the default withdraw fee. This also affects deposits made in the past as well. * @param self Swap struct to update * @param newWithdrawFee new withdraw fee to be applied */ function setDefaultWithdrawFee(Swap storage self, uint256 newWithdrawFee) external { require(newWithdrawFee <= MAX_WITHDRAW_FEE, "Fee is too high"); self.defaultWithdrawFee = newWithdrawFee; emit NewWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // SPDX-License-Identifier: MIT // https://etherscan.io/address/0xC28DF698475dEC994BE00C9C9D8658A548e6304F#code pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/ISwapGuarded.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. */ contract LPTokenGuarded is ERC20Burnable, Ownable { using SafeMath for uint256; // Address of the swap contract that owns this LP token. When a user adds liquidity to the swap contract, // they receive a proportionate amount of this LPToken. ISwapGuarded public swap; // Maps user account to total number of LPToken minted by them. Used to limit minting during guarded release phase mapping(address => uint256) public mintedAmounts; /** * @notice Deploys LPToken contract with given name, symbol, and decimals * @dev the caller of this constructor will become the owner of this contract * @param name_ name of this token * @param symbol_ symbol of this token * @param decimals_ number of decimals this token will be based on */ constructor( string memory name_, string memory symbol_, uint8 decimals_ ) public ERC20(name_, symbol_) { _setupDecimals(decimals_); swap = ISwapGuarded(_msgSender()); } /** * @notice Mints the given amount of LPToken to the recipient. During the guarded release phase, the total supply * and the maximum number of the tokens that a single account can mint are limited. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint * @param merkleProof the bytes32 array data that is used to prove recipient's address exists in the merkle tree * stored in the allowlist contract. If the pool is not guarded, this parameter is ignored. */ function mint( address recipient, uint256 amount, bytes32[] calldata merkleProof ) external onlyOwner { require(amount != 0, "amount == 0"); // If the pool is in the guarded launch phase, the following checks are done to restrict deposits. // 1. Check if the given merkleProof corresponds to the recipient's address in the merkle tree stored in the // allowlist contract. If the account has been already verified, merkleProof is ignored. // 2. Limit the total number of this LPToken minted to recipient as defined by the allowlist contract. // 3. Limit the total supply of this LPToken as defined by the allowlist contract. if (swap.isGuarded()) { IAllowlist allowlist = swap.getAllowlist(); require( allowlist.verifyAddress(recipient, merkleProof), "Invalid merkle proof" ); uint256 totalMinted = mintedAmounts[recipient].add(amount); require( totalMinted <= allowlist.getPoolAccountLimit(address(swap)), "account deposit limit" ); require( totalSupply().add(amount) <= allowlist.getPoolCap(address(swap)), "pool total supply limit" ); mintedAmounts[recipient] = totalMinted; } _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that swap.updateUserWithdrawFees are called everytime. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override(ERC20) { super._beforeTokenTransfer(from, to, amount); swap.updateUserWithdrawFee(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IAllowlist.sol"; interface ISwapGuarded { // pool data view functions function getA() external view returns (uint256); function getAllowlist() external view returns (IAllowlist); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline, bytes32[] calldata merkleProof ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); // withdraw fee update function function updateUserWithdrawFee(address recipient, uint256 transferAmount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "../interfaces/IAllowlist.sol"; /** * @title Allowlist * @notice This contract is a registry holding information about how much each swap contract should * contain upto. Swap.sol will rely on this contract to determine whether the pool cap is reached and * also whether a user's deposit limit is reached. */ contract Allowlist is Ownable, IAllowlist { using SafeMath for uint256; // Represents the root node of merkle tree containing a list of eligible addresses bytes32 public merkleRoot; // Maps pool address -> maximum total supply mapping(address => uint256) private poolCaps; // Maps pool address -> maximum amount of pool token mintable per account mapping(address => uint256) private accountLimits; // Maps account address -> boolean value indicating whether it has been checked and verified against the merkle tree mapping(address => bool) private verified; event PoolCap(address indexed poolAddress, uint256 poolCap); event PoolAccountLimit(address indexed poolAddress, uint256 accountLimit); event NewMerkleRoot(bytes32 merkleRoot); /** * @notice Creates this contract and sets the PoolCap of 0x0 with uint256(0x54dd1e) for * crude checking whether an address holds this contract. * @param merkleRoot_ bytes32 that represent a merkle root node. This is generated off chain with the list of * qualifying addresses. */ constructor(bytes32 merkleRoot_) public { merkleRoot = merkleRoot_; // This value will be used as a way of crude checking whether an address holds this Allowlist contract // Value 0x54dd1e has no inherent meaning other than it is arbitrary value that checks for // user error. poolCaps[address(0x0)] = uint256(0x54dd1e); emit PoolCap(address(0x0), uint256(0x54dd1e)); emit NewMerkleRoot(merkleRoot_); } /** * @notice Returns the max mintable amount of the lp token per account in given pool address. * @param poolAddress address of the pool * @return max mintable amount of the lp token per account */ function getPoolAccountLimit(address poolAddress) external view override returns (uint256) { return accountLimits[poolAddress]; } /** * @notice Returns the maximum total supply of the pool token for the given pool address. * @param poolAddress address of the pool */ function getPoolCap(address poolAddress) external view override returns (uint256) { return poolCaps[poolAddress]; } /** * @notice Returns true if the given account's existence has been verified against any of the past or * the present merkle tree. Note that if it has been verified in the past, this function will return true * even if the current merkle tree does not contain the account. * @param account the address to check if it has been verified * @return a boolean value representing whether the account has been verified in the past or the present merkle tree */ function isAccountVerified(address account) external view returns (bool) { return verified[account]; } /** * @notice Checks the existence of keccak256(account) as a node in the merkle tree inferred by the merkle root node * stored in this contract. Pools should use this function to check if the given address qualifies for depositing. * If the given account has already been verified with the correct merkleProof, this function will return true when * merkleProof is empty. The verified status will be overwritten if the previously verified user calls this function * with an incorrect merkleProof. * @param account address to confirm its existence in the merkle tree * @param merkleProof data that is used to prove the existence of given parameters. This is generated * during the creation of the merkle tree. Users should retrieve this data off-chain. * @return a boolean value that corresponds to whether the address with the proof has been verified in the past * or if they exist in the current merkle tree. */ function verifyAddress(address account, bytes32[] calldata merkleProof) external override returns (bool) { if (merkleProof.length != 0) { // Verify the account exists in the merkle tree via the MerkleProof library bytes32 node = keccak256(abi.encodePacked(account)); if (MerkleProof.verify(merkleProof, merkleRoot, node)) { verified[account] = true; return true; } } return verified[account]; } // ADMIN FUNCTIONS /** * @notice Sets the account limit of allowed deposit amounts for the given pool * @param poolAddress address of the pool * @param accountLimit the max number of the pool token a single user can mint */ function setPoolAccountLimit(address poolAddress, uint256 accountLimit) external onlyOwner { require(poolAddress != address(0x0), "0x0 is not a pool address"); accountLimits[poolAddress] = accountLimit; emit PoolAccountLimit(poolAddress, accountLimit); } /** * @notice Sets the max total supply of LPToken for the given pool address * @param poolAddress address of the pool * @param poolCap the max total supply of the pool token */ function setPoolCap(address poolAddress, uint256 poolCap) external onlyOwner { require(poolAddress != address(0x0), "0x0 is not a pool address"); poolCaps[poolAddress] = poolCap; emit PoolCap(poolAddress, poolCap); } /** * @notice Updates the merkle root that is stored in this contract. This can only be called by * the owner. If more addresses are added to the list, a new merkle tree and a merkle root node should be generated, * and merkleRoot should be updated accordingly. * @param merkleRoot_ a new merkle root node that contains a list of deposit allowed addresses */ function updateMerkleRoot(bytes32 merkleRoot_) external onlyOwner { merkleRoot = merkleRoot_; emit NewMerkleRoot(merkleRoot_); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./OwnerPausable.sol"; import "./SwapUtilsGuarded.sol"; import "../MathUtils.sol"; import "./Allowlist.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapGuarded is OwnerPausable, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; using SwapUtilsGuarded for SwapUtilsGuarded.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtilsGuarded.sol SwapUtilsGuarded.Swap public swapStorage; // Address to allowlist contract that holds information about maximum totaly supply of lp tokens // and maximum mintable amount per user address. As this is immutable, this will become a constant // after initialization. IAllowlist private immutable allowlist; // Boolean value that notates whether this pool is guarded or not. When isGuarded is true, // addLiquidity function will be restricted by limits defined in allowlist contract. bool private guarded = true; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Deploys this Swap contract with given parameters as default * values. This will also deploy a LPToken that represents users * LP position. The owner of LPToken will be this contract - which means * only this contract is allowed to mint new tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param _allowlist address of allowlist contract for guarded launch */ constructor( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, IAllowlist _allowlist ) public OwnerPausable() ReentrancyGuard() { // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtilsGuarded.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtilsGuarded.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee, _allowlist parameters require(_a < SwapUtilsGuarded.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtilsGuarded.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtilsGuarded.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); require( _withdrawFee < SwapUtilsGuarded.MAX_WITHDRAW_FEE, "_withdrawFee exceeds maximum" ); require( _allowlist.getPoolCap(address(0x0)) == uint256(0x54dd1e), "Allowlist check failed" ); // Initialize swapStorage struct swapStorage.lpToken = new LPTokenGuarded( lpTokenName, lpTokenSymbol, SwapUtilsGuarded.POOL_PRECISION_DECIMALS ); swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(SwapUtilsGuarded.A_PRECISION); swapStorage.futureA = _a.mul(SwapUtilsGuarded.A_PRECISION); swapStorage.initialATime = 0; swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; swapStorage.defaultWithdrawFee = _withdrawFee; // Initialize variables related to guarding the initial deposits allowlist = _allowlist; guarded = true; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) external view returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Reads and returns the address of the allowlist that is set during deployment of this contract * @return the address of the allowlist contract casted to the IAllowlist interface */ function getAllowlist() external view returns (IAllowlist) { return allowlist; } /** * @notice Return timestamp of last deposit of given address * @return timestamp of the last deposit made by the given address */ function getDepositTimestamp(address user) external view returns (uint256) { return swapStorage.getDepositTimestamp(user); } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param account address that is depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { return swapStorage.calculateTokenAmount(account, amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param account the address that is withdrawing tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(address account, uint256 amount) external view returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(account, amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param account the address that is withdrawing tokens * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount) { (availableTokenAmount, ) = swapStorage.calculateWithdrawOneToken( account, tokenAmount, tokenIndex ); } /** * @notice Calculate the fee that is applied when the given user withdraws. The withdraw fee * decays linearly over period of 4 weeks. For example, depositing and withdrawing right away * will charge you the full amount of withdraw fee. But withdrawing after 4 weeks will charge you * no additional fees. * @dev returned value should be divided by FEE_DENOMINATOR to convert to correct decimals * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(address user) external view returns (uint256) { return swapStorage.calculateCurrentWithdrawFee(user); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with given amounts during guarded launch phase. Only users * with valid address and proof can successfully call this function. When this function is called * after the guarded release phase is over, the merkleProof is ignored. * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @param merkleProof data generated when constructing the allowlist merkle tree. Users can * get this data off chain. Even if the address is in the allowlist, users must include * a valid proof for this call to succeed. If the pool is no longer in the guarded release phase, * this parameter is ignored. * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline, bytes32[] calldata merkleProof ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint, merkleProof); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the user withdraw fee. This function can only be called by * the pool token. Should be used to update the withdraw fee on transfer of pool tokens. * Transferring your pool token will reset the 4 weeks period. If the recipient is already * holding some pool tokens, the withdraw fee will be discounted in respective amounts. * @param recipient address of the recipient of pool token * @param transferAmount amount of pool token to transfer */ function updateUserWithdrawFee(address recipient, uint256 transferAmount) external { require( msg.sender == address(swapStorage.lpToken), "Only callable by pool token" ); swapStorage.updateUserWithdrawFee(recipient, transferAmount); } /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Update the withdraw fee. This fee decays linearly over 4 weeks since * user's last deposit. * @param newWithdrawFee new withdraw fee to be applied on future deposits */ function setDefaultWithdrawFee(uint256 newWithdrawFee) external onlyOwner { swapStorage.setDefaultWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } /** * @notice Disables the guarded launch phase, removing any limits on deposit amounts and addresses */ function disableGuard() external onlyOwner { guarded = false; } /** * @notice Reads and returns current guarded status of the pool * @return guarded_ boolean value indicating whether the deposits should be guarded */ function isGuarded() external view returns (bool) { return guarded; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; /** * @title OwnerPausable * @notice An ownable contract allows the owner to pause and unpause the * contract without a delay. * @dev Only methods using the provided modifiers will be paused. */ contract OwnerPausable is Ownable, Pausable { /** * @notice Pause the contract. Revert if already paused. */ function pause() external onlyOwner { Pausable._pause(); } /** * @notice Unpause the contract. Revert if already unpaused. */ function unpause() external onlyOwner { Pausable._unpause(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Generic ERC20 token * @notice This contract simulates a generic ERC20 token that is mintable and burnable. */ contract GenericERC20 is ERC20, Ownable { /** * @notice Deploy this contract with given name, symbol, and decimals * @dev the caller of this constructor will become the owner of this contract * @param name_ name of this token * @param symbol_ symbol of this token * @param decimals_ number of decimals this token will be based on */ constructor( string memory name_, string memory symbol_, uint8 decimals_ ) public ERC20(name_, symbol_) { _setupDecimals(decimals_); } /** * @notice Mints given amount of tokens to recipient * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "amount == 0"); _mint(recipient, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./interfaces/ISwap.sol"; import "./helper/BaseBoringBatchable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title GeneralizedSwapMigrator * @notice This contract is responsible for migration liquidity between pools * Users can use this contract to remove their liquidity from the old pools and add them to the new * ones with a single transaction. */ contract GeneralizedSwapMigrator is Ownable, BaseBoringBatchable { using SafeERC20 for IERC20; struct MigrationData { address newPoolAddress; IERC20 oldPoolLPTokenAddress; IERC20 newPoolLPTokenAddress; IERC20[] tokens; } uint256 private constant MAX_UINT256 = 2**256 - 1; mapping(address => MigrationData) public migrationMap; event AddMigrationData(address indexed oldPoolAddress, MigrationData mData); event Migrate( address indexed migrator, address indexed oldPoolAddress, uint256 oldLPTokenAmount, uint256 newLPTokenAmount ); constructor() public Ownable() {} /** * @notice Add new migration data to the contract * @param oldPoolAddress pool address to migrate from * @param mData MigrationData struct that contains information of the old and new pools * @param overwrite should overwrite existing migration data */ function addMigrationData( address oldPoolAddress, MigrationData memory mData, bool overwrite ) external onlyOwner { // Check if (!overwrite) { require( address(migrationMap[oldPoolAddress].oldPoolLPTokenAddress) == address(0), "cannot overwrite existing migration data" ); } require( address(mData.oldPoolLPTokenAddress) != address(0), "oldPoolLPTokenAddress == 0" ); require( address(mData.newPoolLPTokenAddress) != address(0), "newPoolLPTokenAddress == 0" ); for (uint8 i = 0; i < 32; i++) { address oldPoolToken; try ISwap(oldPoolAddress).getToken(i) returns (IERC20 token) { oldPoolToken = address(token); } catch { require(i > 0, "Failed to get tokens underlying Saddle pool."); oldPoolToken = address(0); } try ISwap(mData.newPoolAddress).getToken(i) returns (IERC20 token) { require( oldPoolToken == address(token) && oldPoolToken == address(mData.tokens[i]), "Failed to match tokens list" ); } catch { require(i > 0, "Failed to get tokens underlying Saddle pool."); require( oldPoolToken == address(0) && i == mData.tokens.length, "Failed to match tokens list" ); break; } } // Effect migrationMap[oldPoolAddress] = mData; // Interaction // Approve old LP Token to be used for withdraws. mData.oldPoolLPTokenAddress.approve(oldPoolAddress, MAX_UINT256); // Approve underlying tokens to be used for deposits. for (uint256 i = 0; i < mData.tokens.length; i++) { mData.tokens[i].safeApprove(mData.newPoolAddress, 0); mData.tokens[i].safeApprove(mData.newPoolAddress, MAX_UINT256); } emit AddMigrationData(oldPoolAddress, mData); } /** * @notice Migrates saddle LP tokens from a pool to another * @param oldPoolAddress pool address to migrate from * @param amount amount of LP tokens to migrate * @param minAmount of new LP tokens to receive */ function migrate( address oldPoolAddress, uint256 amount, uint256 minAmount ) external returns (uint256) { // Check MigrationData memory mData = migrationMap[oldPoolAddress]; require( address(mData.oldPoolLPTokenAddress) != address(0), "migration is not available" ); // Interactions // Transfer old LP token from the caller mData.oldPoolLPTokenAddress.safeTransferFrom( msg.sender, address(this), amount ); // Remove liquidity from the old pool uint256[] memory amounts = ISwap(oldPoolAddress).removeLiquidity( amount, new uint256[](mData.tokens.length), MAX_UINT256 ); // Add acquired liquidity to the new pool uint256 mintedAmount = ISwap(mData.newPoolAddress).addLiquidity( amounts, minAmount, MAX_UINT256 ); // Transfer new LP Token to the caller mData.newPoolLPTokenAddress.safeTransfer(msg.sender, mintedAmount); emit Migrate(msg.sender, oldPoolAddress, amount, mintedAmount); return mintedAmount; } /** * @notice Rescues any token that may be sent to this contract accidentally. * @param token Amount of old LPToken to migrate * @param to Minimum amount of new LPToken to receive */ function rescue(IERC20 token, address to) external onlyOwner { token.safeTransfer(to, token.balanceOf(address(this))); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // solhint-disable avoid-low-level-calls // solhint-disable no-inline-assembly // Audit on 5-Jan-2021 by Keno and BoringCrypto // WARNING!!! // Combining BoringBatchable with msg.value can cause double spending issues // https://www.paradigm.xyz/2021/08/two-rights-might-make-a-wrong/ contract BaseBoringBatchable { /// @dev Helper function to extract a useful revert message from a failed call. /// If the returned data is malformed or not correctly abi encoded then this call can fail itself. function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } /// @notice Allows batched call to self (this contract). /// @param calls An array of inputs for each call. /// @param revertOnFail If True then reverts after a failed call and stops doing further calls. // F1: External is ok here because this is the batch function, adding it to a batch makes no sense // F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value // C3: The length of the loop is fully under user control, so can't be exploited // C7: Delegatecall is only used on the same contract, so it's safe function batch(bytes[] calldata calls, bool revertOnFail) external payable { for (uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory result) = address(this).delegatecall( calls[i] ); if (!success && revertOnFail) { revert(_getRevertMsg(result)); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../Swap.sol"; import "./MetaSwapUtils.sol"; /** * @title MetaSwap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * MetaSwap is a modified version of Swap that allows Swap's LP token to be utilized in pooling with other tokens. * As an example, if there is a Swap pool consisting of [DAI, USDC, USDT], then a MetaSwap pool can be created * with [sUSD, BaseSwapLPToken] to allow trades between either the LP token or the underlying tokens and sUSD. * Note that when interacting with MetaSwap, users cannot deposit or withdraw via underlying tokens. In that case, * `MetaSwapDeposit.sol` can be additionally deployed to allow interacting with unwrapped representations of the tokens. * * @dev Most of the logic is stored as a library `MetaSwapUtils` for the sake of reducing contract's * deployment size. */ contract MetaSwap is Swap { using MetaSwapUtils for SwapUtils.Swap; MetaSwapUtils.MetaSwap public metaSwapStorage; uint256 constant MAX_UINT256 = 2**256 - 1; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwapUnderlying( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual override returns (uint256) { return MetaSwapUtils.getVirtualPrice(swapStorage, metaSwapStorage); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual override returns (uint256) { return MetaSwapUtils.calculateSwap( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx ); } /** * @notice Calculate amount of tokens you receive on swap. For this function, * the token indices are flattened out so that underlying tokens are represented. * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return MetaSwapUtils.calculateSwapUnderlying( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx ); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view virtual override returns (uint256) { return MetaSwapUtils.calculateTokenAmount( swapStorage, metaSwapStorage, amounts, deposit ); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view virtual override returns (uint256) { return MetaSwapUtils.calculateWithdrawOneToken( swapStorage, metaSwapStorage, tokenAmount, tokenIndex ); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice This overrides Swap's initialize function to prevent initializing * without the address of the base Swap contract. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public virtual override initializer { revert("use initializeMetaSwap() instead"); } /** * @notice Initializes this MetaSwap contract with the given parameters. * MetaSwap uses an existing Swap pool to expand the available liquidity. * _pooledTokens array should contain the base Swap pool's LP token as * the last element. For example, if there is a Swap pool consisting of * [DAI, USDC, USDT]. Then a MetaSwap pool can be created with [sUSD, BaseSwapLPToken] * as _pooledTokens. * * This will also deploy the LPToken that represents users' * LP position. The owner of LPToken will be this contract - which means * only this contract is allowed to mint new tokens. * * @param _pooledTokens an array of ERC20s this pool will accept. The last * element must be an existing Swap pool's LP token's address. * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with */ function initializeMetaSwap( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external virtual initializer { Swap.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); // MetaSwap initializer metaSwapStorage.baseSwap = baseSwap; metaSwapStorage.baseVirtualPrice = baseSwap.getVirtualPrice(); metaSwapStorage.baseCacheLastUpdated = block.timestamp; // Read all tokens that belong to baseSwap { uint8 i; for (; i < 32; i++) { try baseSwap.getToken(i) returns (IERC20 token) { metaSwapStorage.baseTokens.push(token); token.safeApprove(address(baseSwap), MAX_UINT256); } catch { break; } } require(i > 1, "baseSwap must pool at least 2 tokens"); } // Check the last element of _pooledTokens is owned by baseSwap IERC20 baseLPToken = _pooledTokens[_pooledTokens.length - 1]; require( LPToken(address(baseLPToken)).owner() == address(baseSwap), "baseLPToken is not owned by baseSwap" ); // Pre-approve the baseLPToken to be used by baseSwap baseLPToken.safeApprove(address(baseSwap), MAX_UINT256); } /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.swap( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx, minDy ); } /** * @notice Swap two tokens using this pool and the base pool. * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.swapUnderlying( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx, minDy ); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.addLiquidity( swapStorage, metaSwapStorage, amounts, minToMint ); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.removeLiquidityOneToken( swapStorage, metaSwapStorage, tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.removeLiquidityImbalance( swapStorage, metaSwapStorage, amounts, maxBurnAmount ); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../../MathUtils.sol"; contract TestMathUtils { using MathUtils for uint256; function difference(uint256 a, uint256 b) public pure returns (uint256) { return a.difference(b); } function within1(uint256 a, uint256 b) public pure returns (bool) { return a.within1(b); } }
Return A, the amplification coefficient n (n - 1) See the StableSwap paper for details self Swap struct to read from return A parameter/
function _getA(Swap storage self) internal view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); }
970,531
./full_match/1/0x670E428B165350c77AC7523854995486C1796ae3/sources/contracts/paymaster/GaslessPaymaster.sol
Sets the whitelist mode for the specified spender of the calling sponsor address. spender The address of the spender to set the whitelist mode for. mode The boolean value to set the whitelist mode to./
function setSpenderWhitelistMode(address spender, bool mode) public payable { _setSpenderWhitelistMode(msg.sender, spender, mode); emit SetSpenderWhitelistMode(msg.sender, spender, mode); }
3,059,858
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "contracts/protocol/futures/HybridFutureVault.sol"; import "contracts/interfaces/platforms/ItfToken.sol"; /** * @title Contract for TrueFi Future * @notice Handles the future mechanisms for tfTokens */ contract TrueFiFutureVault is HybridFutureVault { using SafeMathUpgradeable for uint256; /** * @notice Getter for the rate of the IBT * @return the uint256 rate, IBT x rate must be equal to the quantity of underlying tokens */ function getIBTRate() public view override returns (uint256) { return ItfToken(address(ibt)).poolValue().mul(IBT_UNIT).div(ItfToken(address(ibt)).totalSupply()); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "contracts/protocol/futures/RateFutureVault.sol"; /** * @title Main future abstraction contract for the hybrid futures * @notice Handles the rates and scaled amounts for future mecanisms * @dev Basis of all mecanisms for futures (registrations, period switch) */ abstract contract HybridFutureVault is RateFutureVault { using SafeMathUpgradeable for uint256; mapping(uint256 => uint256) internal scaledTotals; // scaled IBT amount /** * @notice Deposit funds into ongoing period * @param _user user adress * @param _amount amount of ibt to deposit * @dev part of the amount deposited will be used to buy back the yield already generated proportionally to the amount deposited */ function deposit(address _user, uint256 _amount) external virtual override periodsActive depositsEnabled onlyController { require((_amount > 0) && (_amount <= ibt.balanceOf(_user)), "HybridFutureVault: ERR_AMOUNT"); _deposit(_user, _amount); emit FundsDeposited(_user, _amount); } /** * @notice Internal function for withdrawing funds corresponding to the pt holding of an address * @param _user user adress * @param _amount amount of funds to unlock * @dev handle the logic of withdraw but does not burn fyts */ function _withdraw(address _user, uint256 _amount) internal virtual override { super._withdraw(_user, _amount); } /** * @notice Start a new period * @dev needs corresponding permissions for sender */ function startNewPeriod() public virtual override nextPeriodAvailable periodsActive nonReentrant { require(hasRole(CONTROLLER_ROLE, msg.sender), "ERR_CALLER"); _switchPeriod(); IBTRates[getCurrentPeriodIndex()] = getIBTRate(); } /** * @notice Getter for the yield currently generated by one pt for the current period * @return the amount of yield (in IBT) generated during the current period */ function getUnrealisedYieldPerPT() public view override returns (uint256) { uint256 totalUnderlyingAtStart = totalUnderlyingDeposited; if (totalUnderlyingAtStart == 0) return 0; uint256 totalUnderlyingNow = convertIBTToUnderlying(ibt.balanceOf(address(this))); uint256 yieldForAllPT = convertUnderlyingtoIBT(totalUnderlyingNow.sub(totalUnderlyingAtStart)); return yieldForAllPT.mul(IBT_UNIT).div(totalUnderlyingAtStart); } /** * @notice Getter for the number of pt that can be minted for an amoumt deposited now * @param _amount the amount to of IBT to deposit * @return the number of pt that can be minted for that amount */ function getPTPerAmountDeposited(uint256 _amount) public view override returns (uint256) { uint256 underlyingAmountOfDeposit = convertIBTToUnderlying(_amount); uint256 underlyingYieldPerPT = convertIBTToUnderlying(getUnrealisedYieldPerPT()); return underlyingAmountOfDeposit.mul(IBT_UNIT).div(IBT_UNIT.add(underlyingYieldPerPT)); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "contracts/interfaces/IERC20.sol"; interface ItfToken is IERC20 { function poolValue() external view returns (uint256); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "contracts/protocol/futures/RewardsFutureVault.sol"; /** * @title Main future abstraction contract for the rate futures * @notice Handles the rates future mecanisms * @dev Basis of all mecanisms for futures (registrations, period switch) */ abstract contract RateFutureVault is RewardsFutureVault { using SafeMathUpgradeable for uint256; mapping(uint256 => uint256) internal IBTRates; /** * @notice Intializer * @param _controller the address of the controller * @param _ibt the address of the corresponding IBT * @param _periodDuration the length of the period (in days) * @param _platformName the name of the platform and tools * @param _admin the address of the ACR admin */ function initialize( IController _controller, IERC20 _ibt, uint256 _periodDuration, string memory _platformName, address _admin ) public virtual override initializer { super.initialize(_controller, _ibt, _periodDuration, _platformName, _admin); IBTRates[getCurrentPeriodIndex()] = getIBTRate(); } /** * @notice Start a new period * @dev needs corresponding permissions for sender */ function startNewPeriod() public virtual override nextPeriodAvailable periodsActive nonReentrant { require(hasRole(CONTROLLER_ROLE, msg.sender), "ERR_CALLER"); _switchPeriod(); IBTRates[getCurrentPeriodIndex()] = getIBTRate(); } function convertIBTToUnderlying(uint256 _amount) public view virtual override returns (uint256) { return _convertIBTToUnderlyingAtRate(_amount, getIBTRate()); } function _convertIBTToUnderlyingAtRate(uint256 _amount, uint256 _rate) internal view virtual returns (uint256) { return (_amount.mul(_rate) / IBT_UNIT); } function convertUnderlyingtoIBT(uint256 _amount) public view virtual override returns (uint256) { return _convertUnderlyingtoIBTAtRate(_amount, getIBTRate()); } function _convertUnderlyingtoIBTAtRate(uint256 _amount, uint256 _rate) internal view virtual returns (uint256) { return _amount.mul(IBT_UNIT).div(_rate); } /** * @notice Getter for user IBT amount that is unlockable * @param _user user to unlock the IBT from * @return the amount of IBT the user can unlock */ function getUnlockableFunds(address _user) public view virtual override returns (uint256) { return convertUnderlyingtoIBT(super.getUnlockableFunds(_user)); } /** * @notice Getter for the yield currently generated by one pt for the current period * @return the amount of yield (in IBT) generated during the current period */ function getUnrealisedYieldPerPT() public view virtual override returns (uint256) { uint256 currRate = getIBTRate(); uint256 currPeriodStartRate = IBTRates[getCurrentPeriodIndex()]; if (currRate == currPeriodStartRate) return 0; uint256 amountOfIBTsAtStart = _convertUnderlyingtoIBTAtRate(IBT_UNIT, currPeriodStartRate); uint256 amountOfIBTsNow = _convertUnderlyingtoIBTAtRate(IBT_UNIT, currRate); return amountOfIBTsAtStart.sub(amountOfIBTsNow); } /** * @notice Getter for the rate of the IBT * @return the uint256 rate, IBT x rate must be equal to the quantity of underlying tokens */ function getIBTRate() public view virtual returns (uint256); /** * @notice Getter for the number of pt that can be minted for an amoumt deposited now * @param _amount the amount to of IBT to deposit * @return the number of pt that can be minted for that amount */ function getPTPerAmountDeposited(uint256 _amount) public view virtual override returns (uint256) { return _convertIBTToUnderlyingAtRate(_amount, IBTRates[getCurrentPeriodIndex()]); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "contracts/protocol/futures/FutureVault.sol"; /** * @title Rewards future abstraction * @notice Handles all future mechanisms along with reward-specific functionality * @dev Allows for better decoupling of rewards logic with core future logic */ abstract contract RewardsFutureVault is FutureVault { using SafeERC20Upgradeable for IERC20; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; /* Rewards mecanisms */ EnumerableSetUpgradeable.AddressSet internal rewardTokens; /* External contracts */ address internal rewardsRecipient; /* Events */ event RewardsHarvested(); event RewardTokenAdded(address _token); event RewardTokenRedeemed(IERC20 _token, uint256 _amount); event RewardsRecipientUpdated(address _recipient); /* Public */ /** * @notice Harvest all rewards from the vault */ function harvestRewards() public virtual { require(hasRole(CONTROLLER_ROLE, msg.sender), "ERR_CALLER"); _harvestRewards(); emit RewardsHarvested(); } /** * @notice Should be overridden and implemented by the future depending on platform-specific details */ function _harvestRewards() internal virtual {} /** * @notice Transfer all the redeemable rewards to set defined recipient */ function redeemAllVaultRewards() external virtual onlyController { require(rewardsRecipient != address(0), "RewardsFutureVault: ERR_RECIPIENT"); uint256 numberOfRewardTokens = rewardTokens.length(); for (uint256 i; i < numberOfRewardTokens; i++) { IERC20 rewardToken = IERC20(rewardTokens.at(i)); uint256 rewardTokenBalance = rewardToken.balanceOf(address(this)); rewardToken.safeTransfer(rewardsRecipient, rewardTokenBalance); emit RewardTokenRedeemed(rewardToken, rewardTokenBalance); } } /** * @notice Transfer the specified token reward balance tot the defined recipient * @param _rewardToken the reward token to redeem the balance of */ function redeemVaultRewards(IERC20 _rewardToken) external virtual onlyController { require(rewardsRecipient != address(0), "RewardsFutureVault: ERR_RECIPIENT"); require(rewardTokens.contains(address(_rewardToken)), "RewardsFutureVault: ERR_TOKEN_ADDRESS"); uint256 rewardTokenBalance = _rewardToken.balanceOf(address(this)); _rewardToken.safeTransfer(rewardsRecipient, rewardTokenBalance); emit RewardTokenRedeemed(_rewardToken, rewardTokenBalance); } /** * @notice Add a token to the list of reward tokens * @param _token the reward token to add to the list * @dev the token must be different than the ibt */ function addRewardsToken(address _token) external onlyAdmin { require(_token != address(ibt), "RewardsFutureVault: ERR_TOKEN_ADDRESS"); rewardTokens.add(_token); emit RewardTokenAdded(_token); } /** * @notice Setter for the address of the rewards recipient */ function setRewardRecipient(address _recipient) external { require(hasRole(ADMIN_ROLE, msg.sender), "ERR_CALLER"); rewardsRecipient = _recipient; emit RewardsRecipientUpdated(_recipient); } /** * @notice Getter to check if a token is in the reward tokens list * @param _token the token to check if it is in the list * @return true if the token is a reward token */ function isRewardToken(IERC20 _token) external view returns (bool) { return rewardTokens.contains(address(_token)); } /** * @notice Getter for the reward token at an index * @param _index the index of the reward token in the list * @return the address of the token at this index */ function getRewardTokenAt(uint256 _index) external view returns (address) { return rewardTokens.at(_index); } /** * @notice Getter for the size of the list of reward tokens * @return the number of token in the list */ function getRewardTokensCount() external view returns (uint256) { return rewardTokens.length(); } /** * @notice Getter for the address of the rewards recipient * @return the address of the rewards recipient */ function getRewardsRecipient() external view returns (address) { return rewardsRecipient; } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "contracts/interfaces/apwine/tokens/IFutureYieldToken.sol"; import "contracts/interfaces/apwine/tokens/IPT.sol"; import "contracts/interfaces/apwine/IFutureWallet.sol"; import "contracts/interfaces/apwine/IController.sol"; import "contracts/interfaces/apwine/IRegistry.sol"; import "contracts/interfaces/apwine/ITokensFactory.sol"; import "contracts/utils/APWineMaths.sol"; import "contracts/utils/RegistryStorage.sol"; /** * @title Main future abstraction contract * @notice Handles the future mechanisms * @dev Basis of all mecanisms for futures (registrations, period switch) */ abstract contract FutureVault is Initializable, RegistryStorage, ReentrancyGuardUpgradeable { using SafeMathUpgradeable for uint256; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using SafeERC20Upgradeable for IERC20; /* State variables */ mapping(uint256 => uint256) internal collectedFYTSByPeriod; mapping(uint256 => uint256) internal premiumsTotal; mapping(address => uint256) internal lastPeriodClaimed; mapping(address => uint256) internal premiumToBeRedeemed; mapping(address => uint256) internal FYTsOfUserPremium; mapping(address => uint256) internal claimableFYTByUser; mapping(uint256 => uint256) internal yieldOfPeriod; uint256 internal totalUnderlyingDeposited; bool private terminated; uint256 internal performanceFeeFactor; IFutureYieldToken[] internal fyts; /* Delegation */ struct Delegation { address receiver; uint256 delegatedAmount; } mapping(address => Delegation[]) internal delegationsByDelegator; mapping(address => uint256) internal totalDelegationsReceived; /* External contracts */ IFutureWallet internal futureWallet; IERC20 internal ibt; IPT internal pt; IController internal controller; /* Settings */ uint256 public PERIOD_DURATION; string public PLATFORM_NAME; /* Constants */ uint256 internal IBT_UNIT; uint256 internal IBT_UNITS_MULTIPLIED_VALUE; uint256 constant UNIT = 10**18; /* Events */ event NewPeriodStarted(uint256 _newPeriodIndex); event FutureWalletSet(IFutureWallet _futureWallet); event FundsDeposited(address _user, uint256 _amount); event FundsWithdrawn(address _user, uint256 _amount); event PTSet(IPT _pt); event LiquidityTransfersPaused(); event LiquidityTransfersResumed(); event DelegationCreated(address _delegator, address _receiver, uint256 _amount); event DelegationRemoved(address _delegator, address _receiver, uint256 _amount); /* Modifiers */ modifier nextPeriodAvailable() { uint256 controllerDelay = controller.STARTING_DELAY(); require( controller.getNextPeriodStart(PERIOD_DURATION) < block.timestamp.add(controllerDelay), "FutureVault: ERR_PERIOD_RANGE" ); _; } modifier periodsActive() { require(!terminated, "PERIOD_TERMINATED"); _; } modifier withdrawalsEnabled() { require(!controller.isWithdrawalsPaused(address(this)), "FutureVault: WITHDRAWALS_DISABLED"); _; } modifier depositsEnabled() { require( !controller.isDepositsPaused(address(this)) && getCurrentPeriodIndex() != 0, "FutureVault: DEPOSITS_DISABLED" ); _; } /* Initializer */ /** * @notice Intializer * @param _controller the address of the controller * @param _ibt the address of the corresponding IBT * @param _periodDuration the length of the period (in seconds) * @param _platformName the name of the platform and tools * @param _admin the address of the ACR admin */ function initialize( IController _controller, IERC20 _ibt, uint256 _periodDuration, string memory _platformName, address _admin ) public virtual initializer { controller = _controller; ibt = _ibt; IBT_UNIT = 10**ibt.decimals(); IBT_UNITS_MULTIPLIED_VALUE = UNIT * IBT_UNIT; PERIOD_DURATION = _periodDuration; PLATFORM_NAME = _platformName; _setupRole(DEFAULT_ADMIN_ROLE, _admin); _setupRole(ADMIN_ROLE, _admin); _setupRole(CONTROLLER_ROLE, address(_controller)); fyts.push(); registry = IRegistry(controller.getRegistryAddress()); pt = IPT( ITokensFactory(IRegistry(controller.getRegistryAddress()).getTokensFactoryAddress()).deployPT( ibt.symbol(), ibt.decimals(), PLATFORM_NAME, PERIOD_DURATION ) ); emit PTSet(pt); } /* Period functions */ /** * @notice Start a new period * @dev needs corresponding permissions for sender */ function startNewPeriod() public virtual; function _switchPeriod() internal periodsActive { uint256 nextPeriodID = getNextPeriodIndex(); uint256 yield = getUnrealisedYieldPerPT().mul(totalUnderlyingDeposited) / IBT_UNIT; uint256 reinvestedYield; if (yield > 0) { uint256 currentPeriodIndex = getCurrentPeriodIndex(); uint256 premiums = convertUnderlyingtoIBT(premiumsTotal[currentPeriodIndex]); uint256 performanceFee = (yield.mul(performanceFeeFactor) / UNIT).sub(premiums); uint256 remainingYield = yield.sub(performanceFee); yieldOfPeriod[currentPeriodIndex] = convertIBTToUnderlying( remainingYield.mul(IBT_UNIT).div(totalUnderlyingDeposited) ); uint256 collectedYield = remainingYield.mul(fyts[currentPeriodIndex].totalSupply()).div( totalUnderlyingDeposited ); reinvestedYield = remainingYield.sub(collectedYield); futureWallet.registerExpiredFuture(collectedYield); // Yield deposit in the futureWallet contract if (performanceFee > 0) ibt.safeTransfer(registry.getTreasuryAddress(), performanceFee); if (remainingYield > 0) ibt.safeTransfer(address(futureWallet), collectedYield); } else { futureWallet.registerExpiredFuture(0); } /* Period Switch*/ totalUnderlyingDeposited = totalUnderlyingDeposited.add(convertIBTToUnderlying(reinvestedYield)); // Add newly reinvested yield as underlying if (!controller.isFutureSetToBeTerminated(address(this))) { _deployNewFutureYieldToken(nextPeriodID); emit NewPeriodStarted(nextPeriodID); } else { terminated = true; } uint256 nextPerformanceFeeFactor = controller.getNextPerformanceFeeFactor(address(this)); if (nextPerformanceFeeFactor != performanceFeeFactor) performanceFeeFactor = nextPerformanceFeeFactor; } /* User state */ /** * @notice Update the state of the user and mint claimable pt * @param _user user adress */ function updateUserState(address _user) public { uint256 currentPeriodIndex = getCurrentPeriodIndex(); uint256 lastPeriodClaimedOfUser = lastPeriodClaimed[_user]; if (lastPeriodClaimedOfUser < currentPeriodIndex && lastPeriodClaimedOfUser != 0) { pt.mint(_user, _preparePTClaim(_user)); } if (lastPeriodClaimedOfUser != currentPeriodIndex) lastPeriodClaimed[_user] = currentPeriodIndex; } function _preparePTClaim(address _user) internal virtual returns (uint256 claimablePT) { uint256 currentPeriodIndex = getCurrentPeriodIndex(); if (lastPeriodClaimed[_user] < currentPeriodIndex) { claimablePT = getClaimablePT(_user); delete premiumToBeRedeemed[_user]; delete FYTsOfUserPremium[_user]; claimableFYTByUser[_user] = pt.balanceOf(_user).add(totalDelegationsReceived[_user]).sub( getTotalDelegated(_user) ); lastPeriodClaimed[_user] = currentPeriodIndex; } } /** * @notice Deposit funds into ongoing period * @param _user user adress * @param _amount amount of funds to unlock * @dev part of the amount deposited will be used to buy back the yield already generated proportionally to the amount deposited */ function deposit(address _user, uint256 _amount) external virtual periodsActive depositsEnabled onlyController { require((_amount > 0) && (_amount <= ibt.balanceOf(_user)), "FutureVault: ERR_AMOUNT"); _deposit(_user, _amount); emit FundsDeposited(_user, _amount); } function _deposit(address _user, uint256 _amount) internal { uint256 underlyingDeposited = getPTPerAmountDeposited(_amount); uint256 ptToMint = _preparePTClaim(_user).add(underlyingDeposited); uint256 currentPeriodIndex = getCurrentPeriodIndex(); /* Update premium */ uint256 redeemable = getPremiumPerUnderlyingDeposited(underlyingDeposited); premiumToBeRedeemed[_user] = premiumToBeRedeemed[_user].add(redeemable); FYTsOfUserPremium[_user] = FYTsOfUserPremium[_user].add(ptToMint); premiumsTotal[currentPeriodIndex] = premiumsTotal[currentPeriodIndex].add(redeemable); /* Update State and mint pt*/ totalUnderlyingDeposited = totalUnderlyingDeposited.add(underlyingDeposited); claimableFYTByUser[_user] = claimableFYTByUser[_user].add(ptToMint); pt.mint(_user, ptToMint); } /** * @notice Sender unlocks the locked funds corresponding to their pt holding * @param _user user adress * @param _amount amount of funds to unlock * @dev will require a transfer of FYT of the ongoing period corresponding to the funds unlocked */ function withdraw(address _user, uint256 _amount) external virtual nonReentrant withdrawalsEnabled onlyController { require((_amount > 0) && (_amount <= pt.balanceOf(_user)), "FutureVault: ERR_AMOUNT"); require(_amount <= fyts[getCurrentPeriodIndex()].balanceOf(_user), "FutureVault: ERR_FYT_AMOUNT"); _withdraw(_user, _amount); uint256 FYTsToBurn; uint256 currentPeriodIndex = getCurrentPeriodIndex(); uint256 FYTSMinted = fyts[currentPeriodIndex].recordedBalanceOf(_user); if (_amount > FYTSMinted) { FYTsToBurn = FYTSMinted; uint256 ClaimableFYTsToBurn = _amount - FYTsToBurn; claimableFYTByUser[_user] = claimableFYTByUser[_user].sub( ClaimableFYTsToBurn, "FutureVault: ClaimableFYTsToBurn > claimableFYTByUser" ); } else { FYTsToBurn = _amount; } if (FYTsToBurn > 0) fyts[currentPeriodIndex].burnFrom(_user, FYTsToBurn); emit FundsWithdrawn(_user, _amount); } /** * @notice Internal function for withdrawing funds corresponding to the pt holding of an address * @param _user user adress * @param _amount amount of funds to unlock * @dev handle the logic of withdraw but does not burn fyts */ function _withdraw(address _user, uint256 _amount) internal virtual { updateUserState(_user); uint256 fundsToBeUnlocked = _amount.mul(getUnlockableFunds(_user)).div(pt.balanceOf(_user)); uint256 yieldToBeUnlocked = _amount.mul(getUnrealisedYieldPerPT()) / IBT_UNIT; uint256 premiumToBeUnlocked = _prepareUserEarlyPremiumUnlock(_user, _amount); require( pt.balanceOf(_user) >= _amount.add(getTotalDelegated(_user)), "FutureVault: transfer amount exceeds transferrable balance" ); uint256 treasuryFee = (yieldToBeUnlocked.mul(performanceFeeFactor) / UNIT).sub(premiumToBeUnlocked); uint256 yieldToBeRedeemed = yieldToBeUnlocked - treasuryFee; ibt.safeTransfer(_user, fundsToBeUnlocked.add(yieldToBeRedeemed).add(premiumToBeUnlocked)); if (treasuryFee > 0) { ibt.safeTransfer(registry.getTreasuryAddress(), treasuryFee); } totalUnderlyingDeposited = totalUnderlyingDeposited.sub(_amount); pt.burnFrom(_user, _amount); } function _prepareUserEarlyPremiumUnlock(address _user, uint256 _ptShares) internal returns (uint256 premiumToBeUnlocked) { uint256 unlockablePremium = premiumToBeRedeemed[_user]; uint256 userFYTsInPremium = FYTsOfUserPremium[_user]; if (unlockablePremium > 0) { if (_ptShares > userFYTsInPremium) { premiumToBeUnlocked = convertUnderlyingtoIBT(unlockablePremium); delete premiumToBeRedeemed[_user]; delete FYTsOfUserPremium[_user]; } else { uint256 premiumForAmount = unlockablePremium.mul(_ptShares).div(userFYTsInPremium); premiumToBeUnlocked = convertUnderlyingtoIBT(premiumForAmount); premiumToBeRedeemed[_user] = unlockablePremium - premiumForAmount; FYTsOfUserPremium[_user] = userFYTsInPremium - _ptShares; } premiumsTotal[getCurrentPeriodIndex()] = premiumsTotal[getCurrentPeriodIndex()].sub(premiumToBeUnlocked); } } /** * @notice Getter for the amount (in underlying) of premium redeemable with the corresponding amount of fyt/pt to be burned * @param _user user adress * @return premiumLocked the premium amount unlockage at this period (in underlying), amountRequired the amount of pt/fyt required for that operation */ function getUserEarlyUnlockablePremium(address _user) public view returns (uint256 premiumLocked, uint256 amountRequired) { premiumLocked = premiumToBeRedeemed[_user]; amountRequired = FYTsOfUserPremium[_user]; } /* Delegation */ /** * @notice Create a delegation from one address to another * @param _delegator the address delegating its future FYTs * @param _receiver the address receiving the future FYTs * @param _amount the of future FYTs to delegate */ function createFYTDelegationTo( address _delegator, address _receiver, uint256 _amount ) public nonReentrant periodsActive { require(hasRole(CONTROLLER_ROLE, msg.sender), "ERR_CALLER"); updateUserState(_delegator); updateUserState(_receiver); uint256 totalDelegated = getTotalDelegated(_delegator); uint256 numberOfDelegations = delegationsByDelegator[_delegator].length; require(_amount > 0 && _amount <= pt.balanceOf(_delegator).sub(totalDelegated), "FutureVault: ERR_AMOUNT"); bool delegated; for (uint256 i = 0; i < numberOfDelegations; i++) { if (delegationsByDelegator[_delegator][i].receiver == _receiver) { delegationsByDelegator[_delegator][i].delegatedAmount = delegationsByDelegator[_delegator][i] .delegatedAmount .add(_amount); delegated = true; break; } } if (!delegated) { delegationsByDelegator[_delegator].push(Delegation({ receiver: _receiver, delegatedAmount: _amount })); } totalDelegationsReceived[_receiver] = totalDelegationsReceived[_receiver].add(_amount); emit DelegationCreated(_delegator, _receiver, _amount); } /** * @notice Remove a delegation from one address to another * @param _delegator the address delegating its future FYTs * @param _receiver the address receiving the future FYTs * @param _amount the of future FYTs to remove from the delegation */ function withdrawFYTDelegationFrom( address _delegator, address _receiver, uint256 _amount ) public { require(hasRole(CONTROLLER_ROLE, msg.sender), "ERR_CALLER"); updateUserState(_delegator); updateUserState(_receiver); uint256 numberOfDelegations = delegationsByDelegator[_delegator].length; bool removed; for (uint256 i = 0; i < numberOfDelegations; i++) { if (delegationsByDelegator[_delegator][i].receiver == _receiver) { delegationsByDelegator[_delegator][i].delegatedAmount = delegationsByDelegator[_delegator][i] .delegatedAmount .sub(_amount, "ERR_AMOUNT"); removed = true; break; } } require(_amount > 0 && removed, "FutureVault: ERR_AMOUNT"); totalDelegationsReceived[_receiver] = totalDelegationsReceived[_receiver].sub(_amount); emit DelegationRemoved(_delegator, _receiver, _amount); } /** * @notice Getter the total number of FYTs on address is delegating * @param _delegator the delegating address * @return totalDelegated the number of FYTs delegated */ function getTotalDelegated(address _delegator) public view returns (uint256 totalDelegated) { uint256 numberOfDelegations = delegationsByDelegator[_delegator].length; for (uint256 i = 0; i < numberOfDelegations; i++) { totalDelegated = totalDelegated.add(delegationsByDelegator[_delegator][i].delegatedAmount); } } /* Claim functions */ /** * @notice Send the user their owed FYT (and pt if there are some claimable) * @param _user address of the user to send the FYT to */ function claimFYT(address _user, uint256 _amount) external virtual nonReentrant { require(msg.sender == address(fyts[getCurrentPeriodIndex()]), "FutureVault: ERR_CALLER"); updateUserState(_user); _claimFYT(_user, _amount); } function _claimFYT(address _user, uint256 _amount) internal virtual { uint256 currentPeriodIndex = getCurrentPeriodIndex(); claimableFYTByUser[_user] = claimableFYTByUser[_user].sub(_amount, "FutureVault: ERR_CLAIMED_FYT_AMOUNT"); fyts[currentPeriodIndex].mint(_user, _amount); } /* Termination of the pool */ /** * @notice Exit a terminated pool * @param _user the user to exit from the pool * @dev only pt are required as there aren't any new FYTs */ function exitTerminatedFuture(address _user) external nonReentrant onlyController { require(terminated, "FutureVault: ERR_NOT_TERMINATED"); uint256 amount = pt.balanceOf(_user); require(amount > 0, "FutureVault: ERR_PT_BALANCE"); _withdraw(_user, amount); emit FundsWithdrawn(_user, amount); } /* Utilitary functions */ function convertIBTToUnderlying(uint256 _amount) public view virtual returns (uint256); function convertUnderlyingtoIBT(uint256 _amount) public view virtual returns (uint256); function _deployNewFutureYieldToken(uint256 newPeriodIndex) internal { IFutureYieldToken newToken = IFutureYieldToken( ITokensFactory(registry.getTokensFactoryAddress()).deployNextFutureYieldToken(newPeriodIndex) ); fyts.push(newToken); } /* Getters */ /** * @notice Getter for the amount of pt that the user can claim * @param _user user to check the check the claimable pt of * @return the amount of pt claimable by the user */ function getClaimablePT(address _user) public view virtual returns (uint256) { uint256 currentPeriodIndex = getCurrentPeriodIndex(); if (lastPeriodClaimed[_user] < currentPeriodIndex) { uint256 recordedBalance = pt.recordedBalanceOf(_user); uint256 mintablePT = (recordedBalance).add(premiumToBeRedeemed[_user]); // add premium mintablePT = mintablePT.add(totalDelegationsReceived[_user]).sub(getTotalDelegated(_user)); // add delegated FYTs uint256 userStackingGrowthFactor = yieldOfPeriod[lastPeriodClaimed[_user]]; if (userStackingGrowthFactor > 0) { mintablePT = mintablePT.add(claimableFYTByUser[_user].mul(userStackingGrowthFactor) / IBT_UNIT); // add reinvested FYTs } for (uint256 i = lastPeriodClaimed[_user] + 1; i < currentPeriodIndex; i++) { mintablePT = mintablePT.add(yieldOfPeriod[i].mul(mintablePT) / IBT_UNIT); } return mintablePT.add(getTotalDelegated(_user)).sub(recordedBalance).sub(totalDelegationsReceived[_user]); } else { return 0; } } /** * @notice Getter for user IBT amount that is unlockable * @param _user the user to unlock the IBT from * @return the amount of IBT the user can unlock */ function getUnlockableFunds(address _user) public view virtual returns (uint256) { return pt.balanceOf(_user); } /** * @notice Getter for the amount of FYT that the user can claim for a certain period * @param _user the user to check the claimable FYT of * @param _periodIndex period ID to check the claimable FYT of * @return the amount of FYT claimable by the user for this period ID */ function getClaimableFYTForPeriod(address _user, uint256 _periodIndex) external view virtual returns (uint256) { uint256 currentPeriodIndex = getCurrentPeriodIndex(); if (_periodIndex != currentPeriodIndex || _user == address(this)) { return 0; } else if (_periodIndex == currentPeriodIndex && lastPeriodClaimed[_user] == currentPeriodIndex) { return claimableFYTByUser[_user]; } else { return pt.balanceOf(_user).add(totalDelegationsReceived[_user]).sub(getTotalDelegated(_user)); } } /** * @notice Getter for the yield currently generated by one pt for the current period * @return the amount of yield (in IBT) generated during the current period */ function getUnrealisedYieldPerPT() public view virtual returns (uint256); /** * @notice Getter for the number of pt that can be minted for an amoumt deposited now * @param _amount the amount to of IBT to deposit * @return the number of pt that can be minted for that amount */ function getPTPerAmountDeposited(uint256 _amount) public view virtual returns (uint256); /** * @notice Getter for premium in underlying tokens that can be redeemed at the end of the period of the deposit * @param _amount the amount to of underlying deposited * @return the number of underlying of the ibt deposited that will be redeemable */ function getPremiumPerUnderlyingDeposited(uint256 _amount) public view virtual returns (uint256) { if (totalUnderlyingDeposited == 0) { return 0; } uint256 yieldPerFYT = getUnrealisedYieldPerPT(); uint256 premiumToRefundInIBT = _amount.mul(yieldPerFYT).mul(performanceFeeFactor) / IBT_UNITS_MULTIPLIED_VALUE; return convertIBTToUnderlying(premiumToRefundInIBT); } /** * @notice Getter for the value (in underlying) of the unlockable premium * @param _user user adress * @return the unlockable premium */ function getUnlockablePremium(address _user) public view returns (uint256) { if (lastPeriodClaimed[_user] != getCurrentPeriodIndex()) { return 0; } else { return premiumToBeRedeemed[_user]; } } /** * @notice Getter for the total yield generated during one period * @param _periodID the period id * @return the total yield in underlying value */ function getYieldOfPeriod(uint256 _periodID) external view returns (uint256) { require(getCurrentPeriodIndex() > _periodID, "FutureVault: Invalid period ID"); return yieldOfPeriod[_periodID]; } /** * @notice Getter for next period index * @return next period index * @dev index starts at 1 */ function getNextPeriodIndex() public view virtual returns (uint256) { return fyts.length; } /** * @notice Getter for current period index * @return current period index * @dev index starts at 1 */ function getCurrentPeriodIndex() public view virtual returns (uint256) { return fyts.length - 1; } /** * @notice Getter for total underlying deposited in the vault * @return the total amount of funds deposited in the vault (in underlying) */ function getTotalUnderlyingDeposited() external view returns (uint256) { return totalUnderlyingDeposited; } /** * @notice Getter for controller address * @return the controller address */ function getControllerAddress() public view returns (address) { return address(controller); } /** * @notice Getter for futureWallet address * @return futureWallet address */ function getFutureWalletAddress() public view returns (address) { return address(futureWallet); } /** * @notice Getter for the IBT address * @return IBT address */ function getIBTAddress() public view returns (address) { return address(ibt); } /** * @notice Getter for future pt address * @return pt address */ function getPTAddress() public view returns (address) { return address(pt); } /** * @notice Getter for FYT address of a particular period * @param _periodIndex period index * @return FYT address */ function getFYTofPeriod(uint256 _periodIndex) public view returns (address) { return address(fyts[_periodIndex]); } /** * @notice Getter for the terminated state of the future * @return true if this vault is terminated */ function isTerminated() public view returns (bool) { return terminated; } /** * @notice Getter for the performance fee factor of the current period * @return the performance fee factor of the futureVault */ function getPerformanceFeeFactor() external view returns (uint256) { return performanceFeeFactor; } /* Admin function */ /** * @notice Set futureWallet address * @param _futureWallet the address of the new futureWallet * @dev needs corresponding permissions for sender */ function setFutureWallet(IFutureWallet _futureWallet) external onlyAdmin { futureWallet = _futureWallet; emit FutureWalletSet(_futureWallet); } /** * @notice Pause liquidity transfers */ function pauseLiquidityTransfers() public { require(hasRole(ADMIN_ROLE, msg.sender), "ERR_CALLER"); pt.pause(); emit LiquidityTransfersPaused(); } /** * @notice Resume liquidity transfers */ function resumeLiquidityTransfers() public { require(hasRole(ADMIN_ROLE, msg.sender), "ERR_CALLER"); pt.unpause(); emit LiquidityTransfersResumed(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSetUpgradeable.sol"; import "../utils/AddressUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; struct RoleData { EnumerableSetUpgradeable.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "contracts/interfaces/IERC20.sol"; interface IFutureYieldToken is IERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) external; /** * @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) external; /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) external; /** * @notice Returns the current balance of one user (without the claimable amount) * @param account the address of the account to check the balance of * @return the current fyt balance of this address */ function recordedBalanceOf(address account) external view returns (uint256); /** * @notice Returns the current balance of one user including unclaimed FYT * @param account the address of the account to check the balance of * @return the total FYT balance of one address */ function balanceOf(address account) external view override returns (uint256); /** * @notice Getter for the future vault link to this fyt * @return the address of the future vault */ function futureVault() external view returns (address); /** * @notice Getter for the internal period index of this fyt * @return the internal period index */ function internalPeriodID() external view returns (uint256); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "contracts/interfaces/IERC20.sol"; interface IPT is IERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) external; /** * @dev Creates `amount` new tokens for `to`. * * See {ERC20-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint(address to, uint256 amount) external; /** * @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) external; /** * @dev Pauses all token transfers. * * See {ERC20Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() external; /** * @dev Unpauses all token transfers. * * See {ERC20Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() external; /** * @notice Returns the current balance of one user (without the claimable amount) * @param account the address of the account to check the balance of * @return the current pt balance of this address */ function recordedBalanceOf(address account) external view returns (uint256); /** * @notice Returns the current balance of one user including the pt that were not claimed yet * @param account the address of the account to check the balance of * @return the total pt balance of one address */ function balanceOf(address account) external view override returns (uint256); /** * @notice Getter for the future vault link to this pt * @return the address of the future vault */ function futureVault() external view returns (address); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; interface IFutureWallet { /* Events */ event YieldRedeemed(address _user, uint256 _periodIndex); event WithdrawalsPaused(); event WithdrawalsResumed(); /** * @notice register the yield of an expired period * @param _amount the amount of yield to be registered */ function registerExpiredFuture(uint256 _amount) external; /** * @notice redeem the yield of the underlying yield of the FYT held by the sender * @param _periodIndex the index of the period to redeem the yield from */ function redeemYield(uint256 _periodIndex) external; /** * @notice return the yield that could be redeemed by an address for a particular period * @param _periodIndex the index of the corresponding period * @param _user the FYT holder * @return the yield that could be redeemed by the token holder for this period */ function getRedeemableYield(uint256 _periodIndex, address _user) external view returns (uint256); /** * @notice getter for the address of the future corresponding to this future wallet * @return the address of the future */ function getFutureVaultAddress() external view returns (address); /** * @notice getter for the address of the IBT corresponding to this future wallet * @return the address of the IBT */ function getIBTAddress() external view returns (address); /* Rewards mecanisms*/ /** * @notice Harvest all rewards from the future wallet */ function harvestRewards() external; /** * @notice Transfer all the redeemable rewards to set defined recipient */ function redeemAllWalletRewards() external; /** * @notice Transfer the specified token reward balance tot the defined recipient * @param _rewardToken the reward token to redeem the balance of */ function redeemWalletRewards(address _rewardToken) external; /** * @notice Getter for the address of the rewards recipient * @return the address of the rewards recipient */ function getRewardsRecipient() external view returns (address); /** * @notice Setter for the address of the rewards recipient */ function setRewardRecipient(address _recipient) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "contracts/interfaces/apwine/IFutureVault.sol"; import "contracts/interfaces/apwine/IRegistry.sol"; interface IController { /* Events */ event NextPeriodSwitchSet(uint256 _periodDuration, uint256 _nextSwitchTimestamp); event NewPeriodDurationIndexSet(uint256 _periodIndex); event FutureRegistered(IFutureVault _futureVault); event FutureUnregistered(IFutureVault _futureVault); event StartingDelaySet(uint256 _startingDelay); event NewPerformanceFeeFactor(IFutureVault _futureVault, uint256 _feeFactor); event FutureTerminated(IFutureVault _futureVault); event DepositsPaused(IFutureVault _futureVault); event DepositsResumed(IFutureVault _futureVault); event WithdrawalsPaused(IFutureVault _futureVault); event WithdrawalsResumed(IFutureVault _futureVault); event RegistryChanged(IRegistry _registry); event FutureSetToBeTerminated(IFutureVault _futureVault); /* Params */ function STARTING_DELAY() external view returns (uint256); /* User Methods */ /** * @notice Deposit funds into ongoing period * @param _futureVault the address of the futureVault to be deposit the funds in * @param _amount the amount to deposit on the ongoing period * @dev part of the amount depostied will be used to buy back the yield already generated proportionaly to the amount deposited */ function deposit(address _futureVault, uint256 _amount) external; /** * @notice Withdraw deposited funds from APWine * @param _futureVault the address of the futureVault to withdraw the IBT from * @param _amount the amount to withdraw */ function withdraw(address _futureVault, uint256 _amount) external; /** * @notice Exit a terminated pool * @param _futureVault the address of the futureVault to exit from from * @param _user the user to exit from the pool * @dev only pt are required as there aren't any new FYTs */ function exitTerminatedFuture(address _futureVault, address _user) external; /** * @notice Create a delegation from one address to another for a futureVault * @param _futureVault the corresponding futureVault address * @param _receiver the address receiving the futureVault FYTs * @param _amount the of futureVault FYTs to delegate */ function createFYTDelegationTo( address _futureVault, address _receiver, uint256 _amount ) external; /** * @notice Remove a delegation from one address to another for a futureVault * @param _futureVault the corresponding futureVault address * @param _receiver the address receiving the futureVault FYTs * @param _amount the of futureVault FYTs to remove from the delegation */ function withdrawFYTDelegationFrom( address _futureVault, address _receiver, uint256 _amount ) external; /* Getters */ /** * @notice Getter for the registry address of the protocol * @return the address of the protocol registry */ function getRegistryAddress() external view returns (address); /** * @notice Getter for the period index depending on the period duration of the futureVault * @param _periodDuration the duration of the periods * @return the period index */ function getPeriodIndex(uint256 _periodDuration) external view returns (uint256); /** * @notice Getter for the beginning timestamp of the next period for the futures with a defined period duration * @param _periodDuration the duration of the periods * @return the timestamp of the beginning of the next period */ function getNextPeriodStart(uint256 _periodDuration) external view returns (uint256); /** * @notice Getter for the next performance fee factor of one futureVault * @param _futureVault the address of the futureVault * @return the next performance fee factor of the futureVault */ function getNextPerformanceFeeFactor(address _futureVault) external view returns (uint256); /** * @notice Getter for the performance fee factor of one futureVault * @param _futureVault the address of the futureVault * @return the performance fee factor of the futureVault */ function getCurrentPerformanceFeeFactor(address _futureVault) external view returns (uint256); /** * @notice Getter for the list of futureVault durations registered in the contract * @return durationsList which consists of futureVault durations */ function getDurations() external view returns (uint256[] memory durationsList); /** * @notice Getter for the futures by period duration * @param _periodDuration the period duration of the futures to return */ function getFuturesWithDuration(uint256 _periodDuration) external view returns (address[] memory filteredFutures); /** * @notice Getter for the futureVault period state * @param _futureVault the address of the futureVault * @return true if the futureVault is terminated */ function isFutureTerminated(address _futureVault) external view returns (bool); /** * @notice Getter for the futureVault period state * @param _futureVault the address of the futureVault * @return true if the futureVault is set to be terminated at its expiration */ function isFutureSetToBeTerminated(address _futureVault) external view returns (bool); /** * @notice Getter for the futureVault withdrawals state * @param _futureVault the address of the futureVault * @return true is new withdrawals are paused, false otherwise */ function isWithdrawalsPaused(address _futureVault) external view returns (bool); /** * @notice Getter for the futureVault deposits state * @param _futureVault the address of the futureVault * @return true is new deposits are paused, false otherwise */ function isDepositsPaused(address _futureVault) external view returns (bool); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; pragma experimental ABIEncoderV2; interface IRegistry { /* Setters */ /** * @notice Setter for the treasury address * @param _newTreasury the address of the new treasury */ function setTreasury(address _newTreasury) external; /** * @notice Setter for the controller address * @param _newController the address of the new controller */ function setController(address _newController) external; /** * @notice Setter for the APWine IBT logic address * @param _PTLogic the address of the new APWine IBT logic */ function setPTLogic(address _PTLogic) external; /** * @notice Setter for the APWine FYT logic address * @param _FYTLogic the address of the new APWine FYT logic */ function setFYTLogic(address _FYTLogic) external; /** * @notice Getter for the controller address * @return the address of the controller */ function getControllerAddress() external view returns (address); /** * @notice Getter for the treasury address * @return the address of the treasury */ function getTreasuryAddress() external view returns (address); /** * @notice Getter for the token factory address * @return the token factory address */ function getTokensFactoryAddress() external view returns (address); /** * @notice Getter for APWine IBT logic address * @return the APWine IBT logic address */ function getPTLogicAddress() external view returns (address); /** * @notice Getter for APWine FYT logic address * @return the APWine FYT logic address */ function getFYTLogicAddress() external view returns (address); /* Futures */ /** * @notice Add a future to the registry * @param _future the address of the future to add to the registry */ function addFutureVault(address _future) external; /** * @notice Remove a future from the registry * @param _future the address of the future to remove from the registry */ function removeFutureVault(address _future) external; /** * @notice Getter to check if a future is registered * @param _future the address of the future to check the registration of * @return true if it is, false otherwise */ function isRegisteredFutureVault(address _future) external view returns (bool); /** * @notice Getter for the future registered at an index * @param _index the index of the future to return * @return the address of the corresponding future */ function getFutureVaultAt(uint256 _index) external view returns (address); /** * @notice Getter for number of future registered * @return the number of future registered */ function futureVaultCount() external view returns (uint256); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; interface ITokensFactory { function deployNextFutureYieldToken(uint256 nextPeriodIndex) external returns (address newToken); function deployPT( string memory _ibtSymbol, uint256 _ibtDecimals, string memory _platformName, uint256 _perioDuration ) external returns (address newToken); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; library APWineMaths { using SafeMathUpgradeable for uint256; /** * @notice scale an input * @param _actualValue the original value of the input * @param _initialSum the scaled value of the sum of the inputs * @param _actualSum the current value of the sum of the inputs */ function getScaledInput( uint256 _actualValue, uint256 _initialSum, uint256 _actualSum ) internal pure returns (uint256) { if (_initialSum == 0 || _actualSum == 0) return _actualValue; return (_actualValue.mul(_initialSum)).div(_actualSum); } /** * @notice scale back a value to the output * @param _scaledOutput the current scaled output * @param _initialSum the scaled value of the sum of the inputs * @param _actualSum the current value of the sum of the inputs */ function getActualOutput( uint256 _scaledOutput, uint256 _initialSum, uint256 _actualSum ) internal pure returns (uint256) { if (_initialSum == 0 || _actualSum == 0) return 0; return (_scaledOutput.mul(_actualSum)).div(_initialSum); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "contracts/interfaces/apwine/IRegistry.sol"; import "contracts/utils/RoleCheckable.sol"; contract RegistryStorage is RoleCheckable { IRegistry internal registry; event RegistryChanged(IRegistry _registry); /* User Methods */ /** * @notice Setter for the registry address * @param _registry the address of the new registry */ function setRegistry(IRegistry _registry) external onlyAdmin { registry = _registry; emit RegistryChanged(_registry); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface IERC20 is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external returns (string memory); /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() external view returns (uint8); /** * @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) external returns (bool); /** * @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) external returns (bool); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "contracts/interfaces/apwine/tokens/IPT.sol"; import "contracts/interfaces/apwine/IRegistry.sol"; import "contracts/interfaces/apwine/IFutureWallet.sol"; interface IFutureVault { /* Events */ event NewPeriodStarted(uint256 _newPeriodIndex); event FutureWalletSet(address _futureWallet); event RegistrySet(IRegistry _registry); event FundsDeposited(address _user, uint256 _amount); event FundsWithdrawn(address _user, uint256 _amount); event PTSet(IPT _pt); event LiquidityTransfersPaused(); event LiquidityTransfersResumed(); event DelegationCreated(address _delegator, address _receiver, uint256 _amount); event DelegationRemoved(address _delegator, address _receiver, uint256 _amount); /* Params */ /** * @notice Getter for the PERIOD future parameter * @return returns the period duration of the future */ function PERIOD_DURATION() external view returns (uint256); /** * @notice Getter for the PLATFORM_NAME future parameter * @return returns the platform of the future */ function PLATFORM_NAME() external view returns (string memory); /** * @notice Start a new period * @dev needs corresponding permissions for sender */ function startNewPeriod() external; /** * @notice Exit a terminated pool * @param _user the user to exit from the pool * @dev only pt are required as there aren't any new FYTs */ function exitTerminatedFuture(address _user) external; /** * @notice Update the state of the user and mint claimable pt * @param _user user adress */ function updateUserState(address _user) external; /** * @notice Send the user their owed FYT (and pt if there are some claimable) * @param _user address of the user to send the FYT to */ function claimFYT(address _user, uint256 _amount) external; /** * @notice Deposit funds into ongoing period * @param _user user adress * @param _amount amount of funds to unlock * @dev part of the amount deposited will be used to buy back the yield already generated proportionally to the amount deposited */ function deposit(address _user, uint256 _amount) external; /** * @notice Sender unlocks the locked funds corresponding to their pt holding * @param _user user adress * @param _amount amount of funds to unlock * @dev will require a transfer of FYT of the ongoing period corresponding to the funds unlocked */ function withdraw(address _user, uint256 _amount) external; /** * @notice Create a delegation from one address to another * @param _delegator the address delegating its future FYTs * @param _receiver the address receiving the future FYTs * @param _amount the of future FYTs to delegate */ function createFYTDelegationTo( address _delegator, address _receiver, uint256 _amount ) external; /** * @notice Remove a delegation from one address to another * @param _delegator the address delegating its future FYTs * @param _receiver the address receiving the future FYTs * @param _amount the of future FYTs to remove from the delegation */ function withdrawFYTDelegationFrom( address _delegator, address _receiver, uint256 _amount ) external; /* Getters */ /** * @notice Getter the total number of FYTs on address is delegating * @param _delegator the delegating address * @return totalDelegated the number of FYTs delegated */ function getTotalDelegated(address _delegator) external view returns (uint256 totalDelegated); /** * @notice Getter for next period index * @return next period index * @dev index starts at 1 */ function getNextPeriodIndex() external view returns (uint256); /** * @notice Getter for current period index * @return current period index * @dev index starts at 1 */ function getCurrentPeriodIndex() external view returns (uint256); /** * @notice Getter for the amount of pt that the user can claim * @param _user user to check the check the claimable pt of * @return the amount of pt claimable by the user */ function getClaimablePT(address _user) external view returns (uint256); /** * @notice Getter for the amount (in underlying) of premium redeemable with the corresponding amount of fyt/pt to be burned * @param _user user adress * @return premiumLocked the premium amount unlockage at this period (in underlying), amountRequired the amount of pt/fyt required for that operation */ function getUserEarlyUnlockablePremium(address _user) external view returns (uint256 premiumLocked, uint256 amountRequired); /** * @notice Getter for user IBT amount that is unlockable * @param _user the user to unlock the IBT from * @return the amount of IBT the user can unlock */ function getUnlockableFunds(address _user) external view returns (uint256); /** * @notice Getter for the amount of FYT that the user can claim for a certain period * @param _user the user to check the claimable FYT of * @param _periodIndex period ID to check the claimable FYT of * @return the amount of FYT claimable by the user for this period ID */ function getClaimableFYTForPeriod(address _user, uint256 _periodIndex) external view returns (uint256); /** * @notice Getter for the yield currently generated by one pt for the current period * @return the amount of yield (in IBT) generated during the current period */ function getUnrealisedYieldPerPT() external view returns (uint256); /** * @notice Getter for the number of pt that can be minted for an amoumt deposited now * @param _amount the amount to of IBT to deposit * @return the number of pt that can be minted for that amount */ function getPTPerAmountDeposited(uint256 _amount) external view returns (uint256); /** * @notice Getter for premium in underlying tokens that can be redeemed at the end of the period of the deposit * @param _amount the amount of underlying deposited * @return the number of underlying of the ibt deposited that will be redeemable */ function getPremiumPerUnderlyingDeposited(uint256 _amount) external view returns (uint256); /** * @notice Getter for total underlying deposited in the vault * @return the total amount of funds deposited in the vault (in underlying) */ function getTotalUnderlyingDeposited() external view returns (uint256); /** * @notice Getter for the total yield generated during one period * @param _periodID the period id * @return the total yield in underlying value */ function getYieldOfPeriod(uint256 _periodID) external view returns (uint256); /** * @notice Getter for controller address * @return the controller address */ function getControllerAddress() external view returns (address); /** * @notice Getter for futureWallet address * @return futureWallet address */ function getFutureWalletAddress() external view returns (address); /** * @notice Getter for the IBT address * @return IBT address */ function getIBTAddress() external view returns (address); /** * @notice Getter for future pt address * @return pt address */ function getPTAddress() external view returns (address); /** * @notice Getter for FYT address of a particular period * @param _periodIndex period index * @return FYT address */ function getFYTofPeriod(uint256 _periodIndex) external view returns (address); /** * @notice Getter for the terminated state of the future * @return true if this vault is terminated */ function isTerminated() external view returns (bool); /** * @notice Getter for the performance fee factor of the current period * @return the performance fee factor of the futureVault */ function getPerformanceFeeFactor() external view returns (uint256); /* Rewards mecanisms*/ /** * @notice Harvest all rewards from the vault */ function harvestRewards() external; /** * @notice Transfer all the redeemable rewards to set defined recipient */ function redeemAllVaultRewards() external; /** * @notice Transfer the specified token reward balance tot the defined recipient * @param _rewardToken the reward token to redeem the balance of */ function redeemVaultRewards(address _rewardToken) external; /** * @notice Add a token to the list of reward tokens * @param _token the reward token to add to the list * @dev the token must be different than the ibt */ function addRewardsToken(address _token) external; /** * @notice Getter to check if a token is in the reward tokens list * @param _token the token to check if it is in the list * @return true if the token is a reward token */ function isRewardToken(address _token) external view returns (bool); /** * @notice Getter for the reward token at an index * @param _index the index of the reward token in the list * @return the address of the token at this index */ function getRewardTokenAt(uint256 _index) external view returns (address); /** * @notice Getter for the size of the list of reward tokens * @return the number of token in the list */ function getRewardTokensCount() external view returns (uint256); /** * @notice Getter for the address of the rewards recipient * @return the address of the rewards recipient */ function getRewardsRecipient() external view returns (address); /** * @notice Setter for the address of the rewards recipient */ function setRewardRecipient(address _recipient) external; /* Admin functions */ /** * @notice Set futureWallet address */ function setFutureWallet(IFutureWallet _futureWallet) external; /** * @notice Set Registry */ function setRegistry(IRegistry _registry) external; /** * @notice Pause liquidity transfers */ function pauseLiquidityTransfers() external; /** * @notice Resume liquidity transfers */ function resumeLiquidityTransfers() external; /** * @notice Convert an amount of IBTs in its equivalent in underlying tokens * @param _amount the amount of IBTs * @return the corresponding amount of underlying */ function convertIBTToUnderlying(uint256 _amount) external view returns (uint256); /** * @notice Convert an amount of underlying tokens in its equivalent in IBTs * @param _amount the amount of underlying tokens * @return the corresponding amount of IBTs */ function convertUnderlyingtoIBT(uint256 _amount) external view returns (uint256); } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.6; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; contract RoleCheckable is AccessControlUpgradeable { /* ACR Roles*/ // keccak256("DEFAULT_ADMIN_ROLE"); bytes32 internal constant ADMIN_ROLE = 0x1effbbff9c66c5e59634f24fe842750c60d18891155c32dd155fc2d661a4c86d; // keccak256("CONTROLLER_ROLE") bytes32 internal constant CONTROLLER_ROLE = 0x7b765e0e932d348852a6f810bfa1ab891e259123f02db8cdcde614c570223357; // keccak256("START_FUTURE") bytes32 internal constant START_FUTURE = 0xeb5092aab714e6356486bc97f25dd7a5c1dc5c7436a9d30e8d4a527fba24de1c; // keccak256("FUTURE_ROLE") bytes32 internal constant FUTURE_ROLE = 0x52d2dbc4d362e84c42bdfb9941433968ba41423559d7559b32db1183b22b148f; // keccak256("HARVEST_REWARDS") bytes32 internal constant HARVEST_REWARDS = 0xf2683e58e5a2a04c1ed32509bfdbf1e9ebc725c63f4c95425d2afd482bfdb0f8; /* Modifiers */ modifier onlyAdmin() { require(hasRole(ADMIN_ROLE, msg.sender), "RoleCheckable: Caller should be ADMIN"); _; } modifier onlyStartFuture() { require(hasRole(START_FUTURE, msg.sender), "RoleCheckable: Caller should have START FUTURE Role"); _; } modifier onlyHarvestReward() { require(hasRole(HARVEST_REWARDS, msg.sender), "RoleCheckable: Caller should have HARVEST REWARDS Role"); _; } modifier onlyController() { require(hasRole(CONTROLLER_ROLE, msg.sender), "RoleCheckable: Caller should be CONTROLLER"); _; } }
Resume liquidity transfers/
function resumeLiquidityTransfers() public { require(hasRole(ADMIN_ROLE, msg.sender), "ERR_CALLER"); pt.unpause(); emit LiquidityTransfersResumed(); }
158,054
./full_match/4/0x0a50D64c77DE587E178db9245d9aff5f84D70D3a/sources/contracts/Stakeable.sol
calculateStakeReward is used to calculate how much a user should be rewarded for their stakes and the duration the stake has been active/ First calculate how long the stake has been active Use current seconds since epoch - the seconds since epoch the stake was made The output will be duration in SECONDS , We will reward the user 0.1% per Hour So thats 0.1% per 3600 seconds the alghoritm is seconds = block.timestamp - stake seconds (block.timestap - _stake.since) hours = Seconds / 3600 (seconds /3600) 3600 is an variable in Solidity names hours we then multiply each token by the hours staked , then divide by the rewardPerHour rate
function calculateStakeReward(Stake memory _current_stake) internal view returns(uint256){ return (((block.timestamp - _current_stake.since) / 1 hours) * _current_stake.amount) / rewardPerHour; }
709,532
/** *Submitted for verification at Etherscan.io on 2021-04-16 */ // Sources flattened with hardhat v2.1.1 https://hardhat.org // File @openzeppelin/contracts/math/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/access/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File contracts/v7/interfaces/IPoolAllowance.sol pragma solidity 0.7.4; interface IPoolAllowance is IERC20 { function mintAllowance(address _account, uint256 _amount) external; function burnAllowance(address _account, uint256 _amount) external; } // File contracts/v7/interfaces/IRewardsPool.sol pragma solidity 0.7.4; interface IRewardsPool is IERC20 { function updateReward(address _account) external; function withdraw() external; function depositReward(uint256 _reward) external; } // File contracts/v7/interfaces/IOwnersRewardsPool.sol pragma solidity 0.7.4; interface IOwnersRewardsPool is IRewardsPool { function withdraw(address _account) external; } // File contracts/v7/interfaces/IERC677.sol pragma solidity 0.7.4; interface IERC677 is IERC20 { function transferAndCall(address _to, uint256 _value, bytes calldata _data) external returns (bool success); } // File contracts/v7/PoolOwners.sol pragma solidity 0.7.4; /** * @title Pool Owners * @dev Handles owners token staking, allowance token distribution, & owners rewards assets */ contract PoolOwners is ReentrancyGuard, Ownable { using SafeMath for uint256; using SafeERC20 for IERC677; IERC677 public stakingToken; uint256 public totalStaked; mapping(address => uint256) private stakedBalances; uint16 public totalRewardTokens; mapping(uint16 => address) public rewardTokens; mapping(address => address) public rewardPools; mapping(address => address) public allowanceTokens; mapping(address => mapping(address => uint256)) private mintedAllowanceTokens; event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardsWithdrawn(address indexed user); event AllowanceMinted(address indexed user); event RewardTokenAdded(address indexed token, address allowanceToken, address rewardsPool); event RewardTokenRemoved(address indexed token); constructor(address _stakingToken) { stakingToken = IERC677(_stakingToken); } modifier updateRewards(address _account) { for (uint16 i = 0; i < totalRewardTokens; i++) { IOwnersRewardsPool(rewardPools[rewardTokens[i]]).updateReward(_account); } _; } /** * @dev returns a user's staked balance * @param _account user to return balance for * @return user's staked balance **/ function balanceOf(address _account) public view returns (uint256) { return stakedBalances[_account]; } /** * @dev returns how many allowance tokens have been minted for a user * @param _allowanceToken allowance token to return minted amount for * @param _account user to return minted amount for * @return total allowance tokens a user has minted **/ function mintedAllowance(address _allowanceToken, address _account) public view returns (uint256) { return mintedAllowanceTokens[_allowanceToken][_account]; } /** * @dev returns total amount staked * @return total amount staked **/ function totalSupply() public view returns (uint256) { return totalStaked; } /** * @dev ERC677 implementation that proxies staking * @param _sender of the token transfer * @param _value of the token transfer **/ function onTokenTransfer(address _sender, uint256 _value, bytes calldata) external nonReentrant { require(msg.sender == address(stakingToken), "Sender must be staking token"); require(_value > 0, "Cannot stake 0"); _stake(_sender, _value); } /** * @dev stakes owners tokens & mints staking allowance tokens in return * @param _amount amount to stake **/ function stake(uint256 _amount) external nonReentrant { require(_amount > 0, "Cannot stake 0"); stakingToken.safeTransferFrom(msg.sender, address(this), _amount); _stake(msg.sender, _amount); } /** * @dev burns staking allowance tokens and withdraws staked owners tokens * @param _amount amount to withdraw **/ function withdraw(uint256 _amount) public nonReentrant updateRewards(msg.sender) { require(_amount > 0, "Cannot withdraw 0"); stakedBalances[msg.sender] = stakedBalances[msg.sender].sub(_amount); totalStaked -= _amount; _burnAllowance(msg.sender); stakingToken.safeTransfer(msg.sender, _amount); emit Withdrawn(msg.sender, _amount); } /** * @dev withdraws user's earned rewards for a all assets **/ function withdrawAllRewards() public nonReentrant { for (uint16 i = 0; i < totalRewardTokens; i++) { _withdrawReward(rewardTokens[i], msg.sender); } emit RewardsWithdrawn(msg.sender); } /** * @dev withdraws users earned rewards for all assets and withdraws their owners tokens **/ function exit() external { withdraw(balanceOf(msg.sender)); withdrawAllRewards(); } /** * @dev mints a user's unclaimed allowance tokens (used if a new asset is added * after a user has already staked) **/ function mintAllowance() external nonReentrant { _mintAllowance(msg.sender); emit AllowanceMinted(msg.sender); } /** * @dev adds a new asset * @param _token asset to add * @param _allowanceToken asset pool allowance token to add * @param _rewardPool asset reward pool to add **/ function addRewardToken( address _token, address _allowanceToken, address _rewardPool ) external onlyOwner() { require(rewardPools[_token] == address(0), "Reward token already exists"); rewardTokens[totalRewardTokens] = _token; allowanceTokens[_token] = _allowanceToken; rewardPools[_token] = _rewardPool; totalRewardTokens++; emit RewardTokenAdded(_token, _allowanceToken, _rewardPool); } /** * @dev removes an existing asset * @param _index index of asset to remove **/ function removeRewardToken(uint16 _index) external onlyOwner() { require(_index < totalRewardTokens, "Reward token does not exist"); address token = rewardTokens[_index]; if (totalRewardTokens > 1) { rewardTokens[_index] = rewardTokens[totalRewardTokens - 1]; } delete rewardTokens[totalRewardTokens - 1]; delete allowanceTokens[token]; delete rewardPools[token]; totalRewardTokens--; emit RewardTokenRemoved(token); } /** * @dev stakes owners tokens & mints staking allowance tokens in return * @param _amount amount to stake **/ function _stake(address _sender, uint256 _amount) private updateRewards(_sender) { stakedBalances[_sender] = stakedBalances[_sender].add(_amount); totalStaked += _amount; _mintAllowance(_sender); emit Staked(_sender, _amount); } /** * @dev withdraws rewards for a specific asset & account * @param _token asset to withdraw * @param _account user to withdraw for **/ function _withdrawReward(address _token, address _account) private { require(rewardPools[_token] != address(0), "Reward token does not exist"); IOwnersRewardsPool(rewardPools[_token]).withdraw(_account); } /** * @dev mints allowance tokens based on a user's staked balance * @param _account user to mint tokens for **/ function _mintAllowance(address _account) private { uint256 stakedAmount = balanceOf(_account); for (uint16 i = 0; i < totalRewardTokens; i++) { address token = allowanceTokens[rewardTokens[i]]; uint256 minted = mintedAllowance(token, _account); if (minted < stakedAmount) { IPoolAllowance(token).mintAllowance(_account, stakedAmount.sub(minted)); mintedAllowanceTokens[token][_account] = stakedAmount; } } } /** * @dev burns allowance tokens based on a user's staked balance * @param _account user to burn tokens for **/ function _burnAllowance(address _account) private { uint256 stakedAmount = balanceOf(_account); for (uint16 i = 0; i < totalRewardTokens; i++) { address token = allowanceTokens[rewardTokens[i]]; uint256 minted = mintedAllowance(token, _account); if (minted > stakedAmount) { IPoolAllowance(token).burnAllowance(_account, minted.sub(stakedAmount)); mintedAllowanceTokens[token][_account] = stakedAmount; } } } }
stakes owners tokens & mints staking allowance tokens in return _amount amount to stake/
function stake(uint256 _amount) external nonReentrant { require(_amount > 0, "Cannot stake 0"); stakingToken.safeTransferFrom(msg.sender, address(this), _amount); _stake(msg.sender, _amount); }
7,811,858
pragma solidity 0.5.16; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./IStakingContract.sol"; import "./IStakeChangeNotifier.sol"; contract StakingContract is IStakingContract, IMigratableStakingContract { using SafeMath for uint256; struct Stake { uint256 amount; uint256 cooldownAmount; uint256 cooldownEndTime; } struct WithdrawResult { uint256 withdrawnAmount; uint256 stakedAmount; uint256 stakedAmountDiff; } // The version of the smart contract. uint256 public constant VERSION = 1; // The maximum number of approved staking contracts as migration destinations. uint256 public constant MAX_APPROVED_STAKING_CONTRACTS = 10; // The mapping between stake owners and their data. mapping(address => Stake) internal stakes; // Total amount of staked tokens (not including unstaked tokes in cooldown or pending withdrawal). uint256 internal totalStakedTokens; // The period (in seconds) between a stake owner's request to stop staking and being able to withdraw them. uint256 public cooldownPeriodInSec; // The address responsible for managing migration to a new staking contract. address public migrationManager; // The address responsible for emergency operations and graceful return of staked tokens back to their owners. address public emergencyManager; // The list of staking contracts that are approved by this contract. It would be only allowed to migrate a stake to // one of these contracts. IMigratableStakingContract[] public approvedStakingContracts; // The address of the contract responsible for publishing stake change notifications. IStakeChangeNotifier public notifier; // The address of the $EDI Token Contract IERC20 internal token; // Represents whether the contract accepts new staking requests. Please note, that even when it's turned off, // it'd be still possible to unstake or withdraw tokens. // // Note: This can be turned off only once by the emergency manager of the contract. bool public acceptingNewStakes = true; // Represents whether this staking contract allows releasing all unstaked tokens unconditionally. When it's turned // on, stake owners could release their staked tokens, without explicitly requesting to unstake them, and their // previously unstaked tokens, regardless of the cooldown period. This also stops the contract from accepting new // stakes. // // Note: This can be turned off only once by the emergency manager of the contract. bool public releasingAllStakes = false; event MigrationManagerUpdated(address indexed migrationManager); event MigrationDestinationAdded( IMigratableStakingContract indexed stakingContract ); event MigrationDestinationRemoved( IMigratableStakingContract indexed stakingContract ); event EmergencyManagerUpdated(address indexed emergencyManager); event StakeChangeNotifierUpdated(IStakeChangeNotifier indexed notifier); event StoppedAcceptingNewStake(); event ReleasedAllStakes(); modifier onlyMigrationManager() { require( msg.sender == migrationManager, "StakingContract: caller is not the migration manager" ); _; } modifier onlyEmergencyManager() { require( msg.sender == emergencyManager, "StakingContract: caller is not the emergency manager" ); _; } modifier onlyWhenAcceptingNewStakes() { require( acceptingNewStakes && !releasingAllStakes, "StakingContract: not accepting new stakes" ); _; } modifier onlyWhenStakesReleased() { require( releasingAllStakes, "StakingContract: not releasing all stakes" ); _; } modifier onlyWhenStakesNotReleased() { require(!releasingAllStakes, "StakingContract: releasing all stakes"); _; } /// @dev Initializes the staking contract. /// @param _cooldownPeriodInSec uint256 The period (in seconds) between a stake owner's request to stop staking and being /// able to withdraw them. /// @param _migrationManager address The address responsible for managing migration to a new staking contract. /// @param _emergencyManager address The address responsible for emergency operations and graceful return of staked /// tokens back to their owners. /// @param _token IERC20 The address of the $EDI Token constructor( uint256 _cooldownPeriodInSec, address _migrationManager, address _emergencyManager, IERC20 _token ) public { require( _cooldownPeriodInSec > 0, "StakingContract::ctor - cooldown period must be greater than 0" ); require( _migrationManager != address(0), "StakingContract::ctor - migration manager must not be 0" ); require( _emergencyManager != address(0), "StakingContract::ctor - emergency manager must not be 0" ); require( address(_token) != address(0), "StakingContract::ctor - $EDI token must not be 0" ); cooldownPeriodInSec = _cooldownPeriodInSec; migrationManager = _migrationManager; emergencyManager = _emergencyManager; token = _token; } /// @dev Sets the address of the migration manager. /// @param _newMigrationManager address The address of the new migration manager. function setMigrationManager(address _newMigrationManager) external onlyMigrationManager { require( _newMigrationManager != address(0), "StakingContract::setMigrationManager - address must not be 0" ); require( migrationManager != _newMigrationManager, "StakingContract::setMigrationManager - address must be different than the current address" ); migrationManager = _newMigrationManager; emit MigrationManagerUpdated(_newMigrationManager); } /// @dev Sets the address of the emergency manager. /// @param _newEmergencyManager address The address of the new emergency manager. function setEmergencyManager(address _newEmergencyManager) external onlyEmergencyManager { require( _newEmergencyManager != address(0), "StakingContract::setEmergencyManager - address must not be 0" ); require( emergencyManager != _newEmergencyManager, "StakingContract::setEmergencyManager - address must be different than the current address" ); emergencyManager = _newEmergencyManager; emit EmergencyManagerUpdated(_newEmergencyManager); } /// @dev Sets the address of the stake change notifier contract. /// @param _newNotifier IStakeChangeNotifier The address of the new stake change notifier contract. /// /// Note: it's allowed to reset the notifier to a zero address. function setStakeChangeNotifier(IStakeChangeNotifier _newNotifier) external onlyMigrationManager { require( notifier != _newNotifier, "StakingContract::setStakeChangeNotifier - address must be different than the current address" ); notifier = _newNotifier; emit StakeChangeNotifierUpdated(notifier); } /// @dev Adds a new contract to the list of approved staking contracts migration destinations. /// @param _newStakingContract IMigratableStakingContract The new contract to add. function addMigrationDestination( IMigratableStakingContract _newStakingContract ) external onlyMigrationManager { require( address(_newStakingContract) != address(0), "StakingContract::addMigrationDestination - address must not be 0" ); uint256 length = approvedStakingContracts.length; require( length + 1 <= MAX_APPROVED_STAKING_CONTRACTS, "StakingContract::addMigrationDestination - can't add more staking contracts" ); // Check for duplicates. for (uint256 i = 0; i < length; ++i) { require( approvedStakingContracts[i] != _newStakingContract, "StakingContract::addMigrationDestination - can't add a duplicate staking contract" ); } approvedStakingContracts.push(_newStakingContract); emit MigrationDestinationAdded(_newStakingContract); } /// @dev Removes a contract from the list of approved staking contracts migration destinations. /// @param _stakingContract IMigratableStakingContract The contract to remove. function removeMigrationDestination( IMigratableStakingContract _stakingContract ) external onlyMigrationManager { require( address(_stakingContract) != address(0), "StakingContract::removeMigrationDestination - address must not be 0" ); // Check for existence. (uint256 i, bool exists) = findApprovedStakingContractIndex( _stakingContract ); require( exists, "StakingContract::removeMigrationDestination - staking contract doesn't exist" ); // Swap the requested element with the last element and then delete it using pop/ approvedStakingContracts[i] = approvedStakingContracts[approvedStakingContracts .length - 1]; approvedStakingContracts.pop(); emit MigrationDestinationRemoved(_stakingContract); } /// @dev Stakes $EDI tokens on behalf of msg.sender. This method assumes that the user has already approved at least /// the required amount using ERC20 approve. /// @param _amount uint256 The amount of tokens to stake. function stake(uint256 _amount) external onlyWhenAcceptingNewStakes { address stakeOwner = msg.sender; uint256 totalStakedAmount = stake(stakeOwner, _amount); emit Staked(stakeOwner, _amount, totalStakedAmount); // Note: we aren't concerned with reentrancy since: // 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method. // 2. The notifier is set and managed by the migration manager. stakeChange(stakeOwner, _amount, true, totalStakedAmount); } /// @dev Unstakes $EDI tokens from msg.sender. If successful, this will start the cooldown period, after which /// msg.sender would be able to withdraw all of his tokens. /// @param _amount uint256 The amount of tokens to unstake. function unstake(uint256 _amount) external { require( _amount > 0, "StakingContract::unstake - amount must be greater than 0" ); address stakeOwner = msg.sender; Stake storage stakeData = stakes[stakeOwner]; uint256 stakedAmount = stakeData.amount; uint256 cooldownAmount = stakeData.cooldownAmount; uint256 cooldownEndTime = stakeData.cooldownEndTime; require( _amount <= stakedAmount, "StakingContract::unstake - can't unstake more than the current stake" ); // If any tokens in cooldown are ready for withdrawal - revert. Stake owner should withdraw their unstaked // tokens first. require( cooldownAmount == 0 || cooldownEndTime > now, "StakingContract::unstake - unable to unstake when there are tokens pending withdrawal" ); // Update the amount of tokens in cooldown. Please note that this will also restart the cooldown period of all // tokens in cooldown. stakeData.amount = stakedAmount.sub(_amount); stakeData.cooldownAmount = cooldownAmount.add(_amount); stakeData.cooldownEndTime = now.add(cooldownPeriodInSec); totalStakedTokens = totalStakedTokens.sub(_amount); uint256 totalStakedAmount = stakeData.amount; emit Unstaked(stakeOwner, _amount, totalStakedAmount); // Note: we aren't concerned with reentrancy since: // 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method. // 2. The notifier is set and managed by the migration manager. stakeChange(stakeOwner, _amount, false, totalStakedAmount); } /// @dev Requests to withdraw all of staked $EDI tokens back to msg.sender. Stake owners can withdraw their $EDI /// tokens only after previously unstaking them and after the cooldown period has passed (unless the contract was /// requested to release all stakes). function withdraw() external { address stakeOwner = msg.sender; WithdrawResult memory res = withdraw(stakeOwner); emit Withdrew(stakeOwner, res.withdrawnAmount, res.stakedAmount); // Trigger staking state change notifications only if the staking amount was changed. if (res.stakedAmountDiff == 0) { return; } // Note: we aren't concerned with reentrancy since: // 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method. // 2. The notifier is set and managed by the migration manager. stakeChange(stakeOwner, res.stakedAmountDiff, false, res.stakedAmount); } /// @dev Restakes unstaked $EDI tokens (in or after cooldown) for msg.sender. function restake() external onlyWhenAcceptingNewStakes { address stakeOwner = msg.sender; Stake storage stakeData = stakes[stakeOwner]; uint256 cooldownAmount = stakeData.cooldownAmount; require( cooldownAmount > 0, "StakingContract::restake - no unstaked tokens" ); stakeData.amount = stakeData.amount.add(cooldownAmount); stakeData.cooldownAmount = 0; stakeData.cooldownEndTime = 0; totalStakedTokens = totalStakedTokens.add(cooldownAmount); uint256 totalStakedAmount = stakeData.amount; emit Restaked(stakeOwner, cooldownAmount, totalStakedAmount); // Note: we aren't concerned with reentrancy since: // 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method. // 2. The notifier is set and managed by the migration manager. stakeChange(stakeOwner, cooldownAmount, true, totalStakedAmount); } /// @dev Stakes $EDI tokens on behalf of msg.sender. This method assumes that the user has already approved at least /// the required amount using ERC20 approve. /// @param _stakeOwner address The specified stake owner. /// @param _amount uint256 The amount of tokens to stake. function acceptMigration(address _stakeOwner, uint256 _amount) external onlyWhenAcceptingNewStakes { uint256 totalStakedAmount = stake(_stakeOwner, _amount); emit AcceptedMigration(_stakeOwner, _amount, totalStakedAmount); // Note: we aren't concerned with reentrancy since: // 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method. // 2. The notifier is set and managed by the migration manager. stakeChange(_stakeOwner, _amount, true, totalStakedAmount); } /// @dev Migrates the stake of msg.sender from this staking contract to a new approved staking contract. /// @param _newStakingContract IMigratableStakingContract The new staking contract which supports stake migration. /// @param _amount uint256 The amount of tokens to migrate. function migrateStakedTokens( IMigratableStakingContract _newStakingContract, uint256 _amount ) external onlyWhenStakesNotReleased { require( isApprovedStakingContract(_newStakingContract), "StakingContract::migrateStakedTokens - migration destination wasn't approved" ); require( _amount > 0, "StakingContract::migrateStakedTokens - amount must be greater than 0" ); address stakeOwner = msg.sender; Stake storage stakeData = stakes[stakeOwner]; uint256 stakedAmount = stakeData.amount; require( stakedAmount > 0, "StakingContract::migrateStakedTokens - no staked tokens" ); require( _amount <= stakedAmount, "StakingContract::migrateStakedTokens - amount exceeds staked token balance" ); stakeData.amount = stakedAmount.sub(_amount); totalStakedTokens = totalStakedTokens.sub(_amount); require( _newStakingContract.getToken() == token, "StakingContract::migrateStakedTokens - staked tokens must be the same" ); require( token.approve(address(_newStakingContract), _amount), "StakingContract::migrateStakedTokens - couldn't approve transfer" ); emit MigratedStake(stakeOwner, _amount, stakeData.amount); _newStakingContract.acceptMigration(stakeOwner, _amount); // Note: we aren't concerned with reentrancy since: // 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method. // 2. The notifier is set and managed by the migration manager. stakeMigration(stakeOwner, _amount); } /// @dev Distributes staking rewards to a list of addresses by directly adding rewards to their stakes. This method /// assumes that the user has already approved at least the required amount using ERC20 approve. Since this is a /// convenience method, we aren't concerned about reaching block gas limit by using large lists. We assume that /// callers will be able to batch/paginate their requests properly. /// @param _totalAmount uint256 The total amount of rewards to distributes. /// @param _stakeOwners address[] The addresses of the stake owners. /// @param _amounts uint256[] The amounts of the rewards. function distributeRewards( uint256 _totalAmount, address[] calldata _stakeOwners, uint256[] calldata _amounts ) external onlyWhenAcceptingNewStakes { require( _totalAmount > 0, "StakingContract::distributeRewards - total amount must be greater than 0" ); uint256 stakeOwnersLength = _stakeOwners.length; uint256 amountsLength = _amounts.length; require( stakeOwnersLength > 0 && amountsLength > 0, "StakingContract::distributeRewards - lists can't be empty" ); require( stakeOwnersLength == amountsLength, "StakingContract::distributeRewards - lists must be of the same size" ); // Transfer all the tokens to the smart contract and update the stake owners list accordingly. require( token.transferFrom(msg.sender, address(this), _totalAmount), "StakingContract::distributeRewards - insufficient allowance" ); bool[] memory signs = new bool[](amountsLength); uint256[] memory totalStakedAmounts = new uint256[](amountsLength); uint256 expectedTotalAmount = 0; for (uint256 i = 0; i < stakeOwnersLength; ++i) { address stakeOwner = _stakeOwners[i]; uint256 amount = _amounts[i]; require( stakeOwner != address(0), "StakingContract::distributeRewards - stake owner can't be 0" ); require( amount > 0, "StakingContract::distributeRewards - amount must be greater than 0" ); Stake storage stakeData = stakes[stakeOwner]; stakeData.amount = stakeData.amount.add(amount); expectedTotalAmount = expectedTotalAmount.add(amount); uint256 totalStakedAmount = stakeData.amount; signs[i] = true; totalStakedAmounts[i] = totalStakedAmount; emit Staked(stakeOwner, amount, totalStakedAmount); } require( _totalAmount == expectedTotalAmount, "StakingContract::distributeRewards - incorrect total amount" ); totalStakedTokens = totalStakedTokens.add(_totalAmount); // Note: we aren't concerned with reentrancy since: // 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method. // 2. The notifier is set and managed by the migration manager. stakeChangeBatch(_stakeOwners, _amounts, signs, totalStakedAmounts); } /// @dev Returns the stake of the specified stake owner (excluding unstaked tokens). /// @param _stakeOwner address The address to check. /// @return uint256 The stake of the stake owner. function getStakeBalanceOf(address _stakeOwner) external view returns (uint256) { return stakes[_stakeOwner].amount; } /// @dev Returns the total amount staked tokens (excluding unstaked tokens). /// @return uint256 The total staked tokens of all stake owners. function getTotalStakedTokens() external view returns (uint256) { return totalStakedTokens; } /// @dev Returns the time that the cooldown period ends (or ended) and the amount of tokens to be released. /// @param _stakeOwner address The address to check. /// @return cooldownAmount uint256 The total tokens in cooldown. /// @return cooldownEndTime uint256 The time when the cooldown period ends (in seconds). function getUnstakeStatus(address _stakeOwner) external view returns (uint256 cooldownAmount, uint256 cooldownEndTime) { Stake memory stakeData = stakes[_stakeOwner]; cooldownAmount = stakeData.cooldownAmount; cooldownEndTime = stakeData.cooldownEndTime; } /// @dev Returns the address of the underlying staked token. /// @return IERC20 The address of the token. function getToken() external view returns (IERC20) { return token; } /// @dev Requests the contract to stop accepting new staking requests. function stopAcceptingNewStakes() external onlyEmergencyManager onlyWhenAcceptingNewStakes { acceptingNewStakes = false; emit StoppedAcceptingNewStake(); } /// @dev Requests the contract to release all stakes. function releaseAllStakes() external onlyEmergencyManager onlyWhenStakesNotReleased { releasingAllStakes = true; emit ReleasedAllStakes(); } /// @dev Requests withdraw of released tokens for a list of addresses. /// @param _stakeOwners address[] The addresses of the stake owners. function withdrawReleasedStakes(address[] calldata _stakeOwners) external onlyWhenStakesReleased { uint256 stakeOwnersLength = _stakeOwners.length; uint256[] memory stakedAmountDiffs = new uint256[](stakeOwnersLength); bool[] memory signs = new bool[](stakeOwnersLength); uint256[] memory totalStakedAmounts = new uint256[](stakeOwnersLength); for (uint256 i = 0; i < stakeOwnersLength; ++i) { address stakeOwner = _stakeOwners[i]; WithdrawResult memory res = withdraw(stakeOwner); stakedAmountDiffs[i] = res.stakedAmountDiff; signs[i] = false; totalStakedAmounts[i] = res.stakedAmount; emit Withdrew(stakeOwner, res.withdrawnAmount, res.stakedAmount); } // Note: we aren't concerned with reentrancy since: // 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method. // 2. The notifier is set and managed by the migration manager. stakeChangeBatch( _stakeOwners, stakedAmountDiffs, signs, totalStakedAmounts ); } /// @dev Returns whether a specific staking contract was approved as a migration destination. /// @param _stakingContract IMigratableStakingContract The staking contract to look for. /// @return exists bool The approval status. function isApprovedStakingContract( IMigratableStakingContract _stakingContract ) public view returns (bool exists) { (, exists) = findApprovedStakingContractIndex(_stakingContract); } /// @dev Returns whether stake change notification is enabled. function shouldNotifyStakeChange() internal view returns (bool) { return address(notifier) != address(0); } /// @dev Notifies of stake change events. /// @param _stakeOwner address The address of the subject stake owner. /// @param _amount int256 The difference in the total staked amount. /// @param _sign bool The sign of the added (true) or subtracted (false) amount. /// @param _updatedStake uint256 The updated total staked amount. function stakeChange( address _stakeOwner, uint256 _amount, bool _sign, uint256 _updatedStake ) internal { if (!shouldNotifyStakeChange()) { return; } notifier.stakeChange(_stakeOwner, _amount, _sign, _updatedStake); } /// @dev Notifies of multiple stake change events. /// @param _stakeOwners address[] The addresses of subject stake owners. /// @param _amounts uint256[] The differences in total staked amounts. /// @param _signs bool[] The signs of the added (true) or subtracted (false) amounts. /// @param _updatedStakes uint256[] The updated total staked amounts. function stakeChangeBatch( address[] memory _stakeOwners, uint256[] memory _amounts, bool[] memory _signs, uint256[] memory _updatedStakes ) internal { if (!shouldNotifyStakeChange()) { return; } notifier.stakeChangeBatch( _stakeOwners, _amounts, _signs, _updatedStakes ); } /// @dev Notifies of stake migration event. /// @param _stakeOwner address The address of the subject stake owner. /// @param _amount uint256 The migrated amount. function stakeMigration(address _stakeOwner, uint256 _amount) internal { if (!shouldNotifyStakeChange()) { return; } notifier.stakeMigration(_stakeOwner, _amount); } /// @dev Stakes amount of $EDI tokens on behalf of the specified stake owner. /// @param _stakeOwner address The specified stake owner. /// @param _amount uint256 The amount of tokens to stake. /// @return totalStakedAmount uint256 The total stake of the stake owner. function stake(address _stakeOwner, uint256 _amount) private returns (uint256 totalStakedAmount) { require( _stakeOwner != address(0), "StakingContract::stake - stake owner can't be 0" ); require( _amount > 0, "StakingContract::stake - amount must be greater than 0" ); Stake storage stakeData = stakes[_stakeOwner]; stakeData.amount = stakeData.amount.add(_amount); totalStakedTokens = totalStakedTokens.add(_amount); totalStakedAmount = stakeData.amount; // Transfer the tokens to the smart contract and update the stake owners list accordingly. require( token.transferFrom(msg.sender, address(this), _amount), "StakingContract::stake - insufficient allowance" ); } /// @dev Requests to withdraw all of staked $EDI tokens back to the specified stake owner. Stake owners can withdraw /// their $EDI tokens only after previously unstaking them and after the cooldown period has passed (unless the /// contract was requested to release all stakes). /// @return res WithdrawResult The result of the withdraw operation. function withdraw(address _stakeOwner) private returns (WithdrawResult memory res) { require( _stakeOwner != address(0), "StakingContract::withdraw - stake owner can't be 0" ); Stake storage stakeData = stakes[_stakeOwner]; res.stakedAmount = stakeData.amount; res.withdrawnAmount = stakeData.cooldownAmount; res.stakedAmountDiff = 0; if (!releasingAllStakes) { require( res.withdrawnAmount > 0, "StakingContract::withdraw - no unstaked tokens" ); require( stakeData.cooldownEndTime <= now, "StakingContract::withdraw - tokens are still in cooldown" ); } else { // If the contract was requested to release all stakes - allow to withdraw all staked and unstaked tokens. res.withdrawnAmount = res.withdrawnAmount.add(res.stakedAmount); res.stakedAmountDiff = res.stakedAmount; require( res.withdrawnAmount > 0, "StakingContract::withdraw - no staked or unstaked tokens" ); stakeData.amount = 0; totalStakedTokens = totalStakedTokens.sub(res.stakedAmount); res.stakedAmount = 0; } stakeData.cooldownAmount = 0; stakeData.cooldownEndTime = 0; require( token.transfer(_stakeOwner, res.withdrawnAmount), "StakingContract::withdraw - couldn't transfer stake" ); } /// @dev Returns an index of an existing approved staking contract. /// @param _stakingContract IMigratableStakingContract The staking contract to look for. /// @return index uint The index of the located staking contract (in the case that it was found). /// @return exists bool The search result. function findApprovedStakingContractIndex( IMigratableStakingContract _stakingContract ) private view returns (uint256 index, bool exists) { uint256 length = approvedStakingContracts.length; for (index = 0; index < length; ++index) { if (approvedStakingContracts[index] == _stakingContract) { exists = true; return (index, exists); } } exists = false; } }
Migrates the stake of msg.sender from this staking contract to a new approved staking contract. _newStakingContract IMigratableStakingContract The new staking contract which supports stake migration. _amount uint256 The amount of tokens to migrate. Note: we aren't concerned with reentrancy since: 1. At this point, due to the CEI pattern, a reentrant notifier can't affect the effects of this method. 2. The notifier is set and managed by the migration manager.
function migrateStakedTokens( IMigratableStakingContract _newStakingContract, uint256 _amount ) external onlyWhenStakesNotReleased { require( isApprovedStakingContract(_newStakingContract), "StakingContract::migrateStakedTokens - migration destination wasn't approved" ); require( _amount > 0, "StakingContract::migrateStakedTokens - amount must be greater than 0" ); address stakeOwner = msg.sender; Stake storage stakeData = stakes[stakeOwner]; uint256 stakedAmount = stakeData.amount; require( stakedAmount > 0, "StakingContract::migrateStakedTokens - no staked tokens" ); require( _amount <= stakedAmount, "StakingContract::migrateStakedTokens - amount exceeds staked token balance" ); stakeData.amount = stakedAmount.sub(_amount); totalStakedTokens = totalStakedTokens.sub(_amount); require( _newStakingContract.getToken() == token, "StakingContract::migrateStakedTokens - staked tokens must be the same" ); require( token.approve(address(_newStakingContract), _amount), "StakingContract::migrateStakedTokens - couldn't approve transfer" ); emit MigratedStake(stakeOwner, _amount, stakeData.amount); _newStakingContract.acceptMigration(stakeOwner, _amount); stakeMigration(stakeOwner, _amount); }
1,815,885
./full_match/43114/0x17B4a4F3A21eF5318b1c485af92520a138E61A4B/sources/AbtRouterV8.sol
performs chained getAmountOut calculations on any number of pairsrequire(path.length >= 2, 'PancakeLibrary: INVALID_PATH');
function getAmountsOut2CustomFees(uint amountIn, address[] memory path, address[] memory lps, uint[] memory fees) internal view returns (uint[] memory amounts) { amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves2(lps[i], path[i], path[i + 1]); amounts[i + 1] = getAmountOut2CustomFee(amounts[i], reserveIn, reserveOut, fees[i]); } }
4,547,931
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; import "./EIP20Interface.sol"; import "./Joetroller.sol"; import "./JToken.sol"; contract RewardDistributorStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Active brains of Unitroller */ Joetroller public joetroller; struct RewardMarketState { /// @notice The market's last updated joeBorrowIndex or joeSupplyIndex uint224 index; /// @notice The timestamp number the index was last updated at uint32 timestamp; } /// @notice The portion of reward rate that each market currently receives mapping(uint8 => mapping(address => uint256)) public rewardSpeeds; /// @notice The JOE/AVAX market supply state for each market mapping(uint8 => mapping(address => RewardMarketState)) public rewardSupplyState; /// @notice The JOE/AVAX market borrow state for each market mapping(uint8 => mapping(address => RewardMarketState)) public rewardBorrowState; /// @notice The JOE/AVAX borrow index for each market for each supplier as of the last time they accrued reward mapping(uint8 => mapping(address => mapping(address => uint256))) public rewardSupplierIndex; /// @notice The JOE/AVAX borrow index for each market for each borrower as of the last time they accrued reward mapping(uint8 => mapping(address => mapping(address => uint256))) public rewardBorrowerIndex; /// @notice The JOE/AVAX accrued but not yet transferred to each user mapping(uint8 => mapping(address => uint256)) public rewardAccrued; /// @notice The initial reward index for a market uint224 public constant rewardInitialIndex = 1e36; /// @notice JOE token contract address address public joeAddress; } contract RewardDistributor is RewardDistributorStorage, Exponential { /// @notice Emitted when a new reward speed is calculated for a market event RewardSpeedUpdated(uint8 rewardType, JToken indexed jToken, uint256 newSpeed); /// @notice Emitted when JOE/AVAX is distributed to a supplier event DistributedSupplierReward( uint8 rewardType, JToken indexed jToken, address indexed supplier, uint256 rewardDelta, uint256 rewardSupplyIndex ); /// @notice Emitted when JOE/AVAX is distributed to a borrower event DistributedBorrowerReward( uint8 rewardType, JToken indexed jToken, address indexed borrower, uint256 rewardDelta, uint256 rewardBorrowIndex ); /// @notice Emitted when JOE is granted by admin event RewardGranted(uint8 rewardType, address recipient, uint256 amount); bool private initialized; constructor() public { admin = msg.sender; } function initialize() public { require(!initialized, "RewardDistributor already initialized"); joetroller = Joetroller(msg.sender); initialized = true; } /** * @notice Checks caller is admin, or this contract is becoming the new implementation */ function adminOrInitializing() internal view returns (bool) { return msg.sender == admin || msg.sender == address(joetroller); } /** * @notice Set JOE/AVAX speed for a single market * @param rewardType 0 = QI, 1 = AVAX * @param jToken The market whose reward speed to update * @param rewardSpeed New reward speed for market */ function _setRewardSpeed( uint8 rewardType, JToken jToken, uint256 rewardSpeed ) public { require(rewardType <= 1, "rewardType is invalid"); require(adminOrInitializing(), "only admin can set reward speed"); setRewardSpeedInternal(rewardType, jToken, rewardSpeed); } /** * @notice Set JOE/AVAX speed for a single market * @param rewardType 0: JOE, 1: AVAX * @param jToken The market whose speed to update * @param newSpeed New JOE or AVAX speed for market */ function setRewardSpeedInternal( uint8 rewardType, JToken jToken, uint256 newSpeed ) internal { uint256 currentRewardSpeed = rewardSpeeds[rewardType][address(jToken)]; if (currentRewardSpeed != 0) { // note that JOE speed could be set to 0 to halt liquidity rewards for a market Exp memory borrowIndex = Exp({mantissa: jToken.borrowIndex()}); updateRewardSupplyIndex(rewardType, address(jToken)); updateRewardBorrowIndex(rewardType, address(jToken), borrowIndex); } else if (newSpeed != 0) { // Add the JOE market require(joetroller.isMarketListed(address(jToken)), "reward market is not listed"); if ( rewardSupplyState[rewardType][address(jToken)].index == 0 && rewardSupplyState[rewardType][address(jToken)].timestamp == 0 ) { rewardSupplyState[rewardType][address(jToken)] = RewardMarketState({ index: rewardInitialIndex, timestamp: safe32(getBlockTimestamp(), "block timestamp exceeds 32 bits") }); } if ( rewardBorrowState[rewardType][address(jToken)].index == 0 && rewardBorrowState[rewardType][address(jToken)].timestamp == 0 ) { rewardBorrowState[rewardType][address(jToken)] = RewardMarketState({ index: rewardInitialIndex, timestamp: safe32(getBlockTimestamp(), "block timestamp exceeds 32 bits") }); } } if (currentRewardSpeed != newSpeed) { rewardSpeeds[rewardType][address(jToken)] = newSpeed; emit RewardSpeedUpdated(rewardType, jToken, newSpeed); } } /** * @notice Accrue JOE/AVAX to the market by updating the supply index * @param rewardType 0: JOE, 1: AVAX * @param jToken The market whose supply index to update */ function updateRewardSupplyIndex(uint8 rewardType, address jToken) public { require(rewardType <= 1, "rewardType is invalid"); RewardMarketState storage supplyState = rewardSupplyState[rewardType][jToken]; uint256 supplySpeed = rewardSpeeds[rewardType][jToken]; uint256 blockTimestamp = getBlockTimestamp(); uint256 deltaTimestamps = sub_(blockTimestamp, uint256(supplyState.timestamp)); if (deltaTimestamps > 0 && supplySpeed > 0) { uint256 supplyTokens = JToken(jToken).totalSupply(); uint256 rewardAccrued = mul_(deltaTimestamps, supplySpeed); Double memory ratio = supplyTokens > 0 ? fraction(rewardAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: supplyState.index}), ratio); rewardSupplyState[rewardType][jToken] = RewardMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), timestamp: safe32(blockTimestamp, "block timestamp exceeds 32 bits") }); } else if (deltaTimestamps > 0) { supplyState.timestamp = safe32(blockTimestamp, "block timestamp exceeds 32 bits"); } } /** * @notice Accrue JOE/AVAX to the market by updating the borrow index * @param rewardType 0: JOE, 1: AVAX * @param jToken The market whose borrow index to update */ function updateRewardBorrowIndex( uint8 rewardType, address jToken, Exp memory marketBorrowIndex ) internal { require(rewardType <= 1, "rewardType is invalid"); RewardMarketState storage borrowState = rewardBorrowState[rewardType][jToken]; uint256 borrowSpeed = rewardSpeeds[rewardType][jToken]; uint256 blockTimestamp = getBlockTimestamp(); uint256 deltaTimestamps = sub_(blockTimestamp, uint256(borrowState.timestamp)); if (deltaTimestamps > 0 && borrowSpeed > 0) { uint256 borrowAmount = div_(JToken(jToken).totalBorrows(), marketBorrowIndex); uint256 rewardAccrued = mul_(deltaTimestamps, borrowSpeed); Double memory ratio = borrowAmount > 0 ? fraction(rewardAccrued, borrowAmount) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: borrowState.index}), ratio); rewardBorrowState[rewardType][jToken] = RewardMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), timestamp: safe32(blockTimestamp, "block timestamp exceeds 32 bits") }); } else if (deltaTimestamps > 0) { borrowState.timestamp = safe32(blockTimestamp, "block timestamp exceeds 32 bits"); } } /** * @notice Calculate JOE/AVAX accrued by a supplier and possibly transfer it to them * @param rewardType 0: JOE, 1: AVAX * @param jToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute JOE/AVAX to */ function distributeSupplierReward( uint8 rewardType, address jToken, address supplier ) public { require(rewardType <= 1, "rewardType is invalid"); RewardMarketState storage supplyState = rewardSupplyState[rewardType][jToken]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({mantissa: rewardSupplierIndex[rewardType][jToken][supplier]}); rewardSupplierIndex[rewardType][jToken][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = rewardInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint256 supplierTokens = JToken(jToken).balanceOf(supplier); uint256 supplierDelta = mul_(supplierTokens, deltaIndex); uint256 supplierAccrued = add_(rewardAccrued[rewardType][supplier], supplierDelta); rewardAccrued[rewardType][supplier] = supplierAccrued; emit DistributedSupplierReward(rewardType, JToken(jToken), supplier, supplierDelta, supplyIndex.mantissa); } /** * @notice Calculate JOE/AVAX accrued by a borrower and possibly transfer it to them * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param rewardType 0: JOE, 1: AVAX * @param jToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute JOE/AVAX to */ function distributeBorrowerReward( uint8 rewardType, address jToken, address borrower, Exp memory marketBorrowIndex ) public { require(rewardType <= 1, "rewardType is invalid"); RewardMarketState storage borrowState = rewardBorrowState[rewardType][jToken]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({mantissa: rewardBorrowerIndex[rewardType][jToken][borrower]}); rewardBorrowerIndex[rewardType][jToken][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint256 borrowerAmount = div_(JToken(jToken).borrowBalanceStored(borrower), marketBorrowIndex); uint256 borrowerDelta = mul_(borrowerAmount, deltaIndex); uint256 borrowerAccrued = add_(rewardAccrued[rewardType][borrower], borrowerDelta); rewardAccrued[rewardType][borrower] = borrowerAccrued; emit DistributedBorrowerReward(rewardType, JToken(jToken), borrower, borrowerDelta, borrowIndex.mantissa); } } /** * @notice Refactored function to calc and rewards accounts supplier rewards * @param jToken The market to verify the mint against * @param supplier The supplier to be rewarded */ function updateAndDistributeSupplierRewardsForToken(address jToken, address supplier) external { require(adminOrInitializing(), "only admin can update and distribute supplier rewards"); for (uint8 rewardType = 0; rewardType <= 1; rewardType++) { updateRewardSupplyIndex(rewardType, jToken); distributeSupplierReward(rewardType, jToken, supplier); } } /** * @notice Refactored function to calc and rewards accounts supplier rewards * @param jToken The market to verify the mint against * @param borrower Borrower to be rewarded */ function updateAndDistributeBorrowerRewardsForToken( address jToken, address borrower, Exp calldata marketBorrowIndex ) external { require(adminOrInitializing(), "only admin can update and distribute borrower rewards"); for (uint8 rewardType = 0; rewardType <= 1; rewardType++) { updateRewardBorrowIndex(rewardType, jToken, marketBorrowIndex); distributeBorrowerReward(rewardType, jToken, borrower, marketBorrowIndex); } } /*** User functions ***/ /** * @notice Claim all the JOE/AVAX accrued by holder in all markets * @param holder The address to claim JOE/AVAX for */ function claimReward(uint8 rewardType, address payable holder) public { return claimReward(rewardType, holder, joetroller.getAllMarkets()); } /** * @notice Claim all the JOE/AVAX accrued by holder in the specified markets * @param holder The address to claim JOE/AVAX for * @param jTokens The list of markets to claim JOE/AVAX in */ function claimReward( uint8 rewardType, address payable holder, JToken[] memory jTokens ) public { address payable[] memory holders = new address payable[](1); holders[0] = holder; claimReward(rewardType, holders, jTokens, true, true); } /** * @notice Claim all JOE/AVAX accrued by the holders * @param rewardType 0 = JOE, 1 = AVAX * @param holders The addresses to claim JOE/AVAX for * @param jTokens The list of markets to claim JOE/AVAX in * @param borrowers Whether or not to claim JOE/AVAX earned by borrowing * @param suppliers Whether or not to claim JOE/AVAX earned by supplying */ function claimReward( uint8 rewardType, address payable[] memory holders, JToken[] memory jTokens, bool borrowers, bool suppliers ) public payable { require(rewardType <= 1, "rewardType is invalid"); for (uint256 i = 0; i < jTokens.length; i++) { JToken jToken = jTokens[i]; require(joetroller.isMarketListed(address(jToken)), "market must be listed"); if (borrowers == true) { Exp memory borrowIndex = Exp({mantissa: jToken.borrowIndex()}); updateRewardBorrowIndex(rewardType, address(jToken), borrowIndex); for (uint256 j = 0; j < holders.length; j++) { distributeBorrowerReward(rewardType, address(jToken), holders[j], borrowIndex); rewardAccrued[rewardType][holders[j]] = grantRewardInternal( rewardType, holders[j], rewardAccrued[rewardType][holders[j]] ); } } if (suppliers == true) { updateRewardSupplyIndex(rewardType, address(jToken)); for (uint256 j = 0; j < holders.length; j++) { distributeSupplierReward(rewardType, address(jToken), holders[j]); rewardAccrued[rewardType][holders[j]] = grantRewardInternal( rewardType, holders[j], rewardAccrued[rewardType][holders[j]] ); } } } } /** * @notice Transfer JOE/AVAX to the user * @dev Note: If there is not enough JOE/AVAX, we do not perform the transfer all. * @param user The address of the user to transfer JOE/AVAX to * @param amount The amount of JOE/AVAX to (possibly) transfer * @return The amount of JOE/AVAX which was NOT transferred to the user */ function grantRewardInternal( uint256 rewardType, address payable user, uint256 amount ) public returns (uint256) { if (rewardType == 0) { EIP20Interface joe = EIP20Interface(joeAddress); uint256 joeRemaining = joe.balanceOf(address(this)); if (amount > 0 && amount <= joeRemaining) { joe.transfer(user, amount); return 0; } } else if (rewardType == 1) { uint256 avaxRemaining = address(this).balance; if (amount > 0 && amount <= avaxRemaining) { user.transfer(amount); return 0; } } return amount; } /*** Joe Distribution Admin ***/ /** * @notice Transfer JOE to the recipient * @dev Note: If there is not enough JOE, we do not perform the transfer all. * @param recipient The address of the recipient to transfer JOE to * @param amount The amount of JOE to (possibly) transfer */ function _grantReward( uint8 rewardType, address payable recipient, uint256 amount ) public { require(adminOrInitializing(), "only admin can grant joe"); uint256 amountLeft = grantRewardInternal(rewardType, recipient, amount); require(amountLeft == 0, "insufficient joe for grant"); emit RewardGranted(rewardType, recipient, amount); } /** * @notice Set the JOE token address */ function setJoeAddress(address newJoeAddress) public { require(msg.sender == admin, "only admin can set JOE"); joeAddress = newJoeAddress; } /** * @notice Set the Joetroller address */ function setJoetroller(address _joetroller) public { require(msg.sender == admin, "only admin can set Joetroller"); joetroller = Joetroller(_joetroller); } /** * @notice Set the admin */ function setAdmin(address _newAdmin) public { require(msg.sender == admin, "only admin can set admin"); admin = _newAdmin; } /** * @notice payable function needed to receive AVAX */ function() external payable {} function getBlockTimestamp() public view returns (uint256) { return block.timestamp; } }
Calculate JOE/AVAX accrued by a borrower and possibly transfer it to them Borrowers will not begin to accrue until after the first interaction with the protocol. rewardType 0: JOE, 1: AVAX jToken The market in which the borrower is interacting borrower The address of the borrower to distribute JOE/AVAX to/
function distributeBorrowerReward( uint8 rewardType, address jToken, address borrower, Exp memory marketBorrowIndex ) public { require(rewardType <= 1, "rewardType is invalid"); RewardMarketState storage borrowState = rewardBorrowState[rewardType][jToken]; rewardBorrowerIndex[rewardType][jToken][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint256 borrowerAmount = div_(JToken(jToken).borrowBalanceStored(borrower), marketBorrowIndex); uint256 borrowerDelta = mul_(borrowerAmount, deltaIndex); uint256 borrowerAccrued = add_(rewardAccrued[rewardType][borrower], borrowerDelta); rewardAccrued[rewardType][borrower] = borrowerAccrued; emit DistributedBorrowerReward(rewardType, JToken(jToken), borrower, borrowerDelta, borrowIndex.mantissa); } }
1,821,355
./partial_match/56/0x5769dc4383D091fcA951b703F7E4f0d874c93BE8/sources/NotoriousFarming.sol
Safe big transfer function, just in case if rounding error causes pool to not have enough BIGs.
function safeBigTransfer(address _to, uint256 _amount) internal { uint256 bigBal = big.balanceOf(address(this)); if (_amount > bigBal) { big.transfer(_to, bigBal); big.transfer(_to, _amount); } }
11,246,239
pragma solidity 0.4.22; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } interface Token { function transfer(address _to, uint256 _amount) public returns (bool success); function balanceOf(address _owner) public view returns (uint256 balance); function decimals()public view returns (uint8); } /** * @title Vault * @dev This contract is used for storing funds while a crowdsale * is in progress. Funds will be transferred to owner once sale ends */ contract Vault is Ownable { using SafeMath for uint256; enum State { Active, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event withdrawn(address _wallet); function Vault(address _wallet) public { require(_wallet != 0x0); wallet = _wallet; state = State.Active; } function deposit(address investor) public onlyOwner payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() public onlyOwner { require(state == State.Active); state = State.Closed; Closed(); } function withdrawToWallet() onlyOwner public{ require(state == State.Closed); wallet.transfer(this.balance); withdrawn(wallet); } } contract MIOTCrowdsales is Ownable{ using SafeMath for uint256; //Token to be used for this sale Token public token; //All funds will go into this vault Vault public vault; //Total tokens which is on for sale uint256 public crowdSaleHardCap; //There can be 5 tiers and it will contain info about each tier struct TierInfo{ uint256 hardcap; uint256 startTime; uint256 endTime; uint256 rate; uint8 bonusPercentage; uint256 weiRaised; } //info of each tier TierInfo[] public tiers; //Total funding uint256 public totalFunding; uint8 public noOfTiers; uint256 public tokensSold; //Keep track whether sales is active or not bool public salesActive; //Keep track of whether the sale has ended or not bool public saleEnded; bool public unspentCreditsWithdrawn; //to make sure contract is poweredup only once bool contractPoweredUp = false; //Event to trigger Sale stop event SaleStopped(address _owner, uint256 time); //Event to trigger normal flow of sale end event Finalized(address _owner, uint256 time); /** * 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); //modifiers modifier _saleActive(){ require(salesActive); _; } modifier nonZeroAddress(address _to) { require(_to != 0x0); _; } modifier nonZeroEth() { require(msg.value > 0); _; } modifier _saleEnded() { require(saleEnded); _; } modifier tiersEmpty(){ require(noOfTiers==0); _; } function MIOTCrowdsales(address _tokenToBeUsed, address _wallet)public nonZeroAddress(_tokenToBeUsed) nonZeroAddress(_wallet){ token = Token(_tokenToBeUsed); vault = new Vault(_wallet); } /** * @dev Check if sale contract has enough tokens on its account balance * to reward all possible participations within sale period */ function powerUpContract() external onlyOwner { require(!contractPoweredUp); // Contract should not be powered up previously require(!salesActive); // Contract should have enough Parsec credits require(token.balanceOf(this) >= crowdSaleHardCap); //check whether tier information has been entered require(noOfTiers>0 && tiers.length==noOfTiers); //activate the sale process salesActive=true; contractPoweredUp = true; } //for Emergency stop of the sale function emergencyStop() public onlyOwner _saleActive{ salesActive = false; saleEnded = true; vault.close(); SaleStopped(msg.sender, now); } /** * @dev Must be called after sale ends, to do some extra finalization * work. Calls the contract&#39;s finalization function. */ function finalize()public onlyOwner _saleActive{ require(saleTimeOver()); salesActive = false; saleEnded = true; vault.close(); Finalized(msg.sender, now); } // @return true if all the tiers has been ended function saleTimeOver() public view returns (bool) { if(noOfTiers==0){ //since no tiers has been provided yet, hence sales has not started to end return false; } //If last tier has ended, it mean all tiers are finished return now > tiers[noOfTiers-1].endTime; } //if crowdsales is over, the money rasied should be transferred to the wallet address function withdrawFunds() public onlyOwner _saleEnded{ vault.withdrawToWallet(); } /** * @dev Can be called only once. The method to allow owner to set tier information * @param _noOfTiers The integer to set number of tiers * @param _startTimes The array containing start time of each tier * @param _endTimes The array containing end time of each tier * @param _hardCaps The array containing hard cap for each tier * @param _rates The array containing number of tokens per ether for each tier * @param _bonusPercentages The array containing bonus percentage for each tier * The arrays should be in sync with each other. For each index 0 for each of the array should contain info about Tier 1, similarly for Tier2, 3,4 and 5. * Sales hard cap will be the hard cap of last tier */ function setTiersInfo(uint8 _noOfTiers, uint256[] _startTimes, uint256[] _endTimes, uint256[] _hardCaps, uint256[] _rates, uint8[] _bonusPercentages)public onlyOwner tiersEmpty{ //Minimu number of tiers should be 1 and less than or equal to 5 require(_noOfTiers>=1 && _noOfTiers<=5); //Each array should contain info about each tier require(_startTimes.length == _noOfTiers); require(_endTimes.length==_noOfTiers); require(_hardCaps.length==_noOfTiers); require(_rates.length==_noOfTiers); require(_bonusPercentages.length==_noOfTiers); noOfTiers = _noOfTiers; for(uint8 i=0;i<noOfTiers;i++){ require(_hardCaps[i]>0); require(_endTimes[i]>_startTimes[i]); require(_rates[i]>0); require(_bonusPercentages[i]>0); if(i>0){ //check hard cap for this tier should be greater than the previous tier require(_hardCaps[i] > _hardCaps[i-1]); //start time of this tier should be greater than previous tier require(_startTimes[i]>_endTimes[i-1]); tiers.push(TierInfo({ hardcap:_hardCaps[i].mul( 10 ** uint256(token.decimals())), startTime:_startTimes[i], endTime:_endTimes[i], rate:_rates[i], bonusPercentage:_bonusPercentages[i], weiRaised:0 })); } else{ //start time of tier1 should be greater than current time require(_startTimes[i]>now); tiers.push(TierInfo({ hardcap:_hardCaps[i].mul( 10 ** uint256(token.decimals())), //multiplying with decimal places. So if hard cap is set to 1 it is actually set to 1 * 10^decimals startTime:_startTimes[i], endTime:_endTimes[i], rate:_rates[i], bonusPercentage:_bonusPercentages[i], weiRaised:0 })); } } crowdSaleHardCap = _hardCaps[noOfTiers-1].mul( 10 ** uint256(token.decimals())); } /** * @dev Allows owner to transfer unsold tokens to his/her address * This method should only be called once the sale has been stopped/ended */ function ownerWithdrawUnspentCredits()public onlyOwner _saleEnded{ require(!unspentCreditsWithdrawn); unspentCreditsWithdrawn = true; token.transfer(owner, token.balanceOf(this)); } //Fallback function used to buytokens function()public payable{ buyTokens(msg.sender); } /** * @dev Low level token purchase function * @param beneficiary The address who will receive the tokens for this transaction */ function buyTokens(address beneficiary)public _saleActive nonZeroEth nonZeroAddress(beneficiary) payable returns(bool){ int8 currentTierIndex = getCurrentlyRunningTier(); assert(currentTierIndex>=0); TierInfo storage currentlyRunningTier = tiers[uint256(currentTierIndex)]; //hard cap for this tier has not been reached require(tokensSold < currentlyRunningTier.hardcap); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(currentlyRunningTier.rate); uint256 bonusedTokens = applyBonus(tokens, currentlyRunningTier.bonusPercentage); //Total tokens sold including current sale should be less than hard cap of this tier assert(tokensSold.add(bonusedTokens) <= currentlyRunningTier.hardcap); tokensSold = tokensSold.add(bonusedTokens); totalFunding = totalFunding.add(weiAmount); currentlyRunningTier.weiRaised = currentlyRunningTier.weiRaised.add(weiAmount); vault.deposit.value(msg.value)(msg.sender); token.transfer(beneficiary, bonusedTokens); TokenPurchase(msg.sender, beneficiary, weiAmount, bonusedTokens); } function applyBonus(uint256 tokens, uint8 percent) internal pure returns (uint256 bonusedTokens) { uint256 tokensToAdd = tokens.mul(percent).div(100); return tokens.add(tokensToAdd); } /** * @dev returns the currently running tier index as per time * Return -1 if no tier is running currently * */ function getCurrentlyRunningTier()public view returns(int8){ for(uint8 i=0;i<noOfTiers;i++){ if(now>=tiers[i].startTime && now<tiers[i].endTime){ return int8(i); } } return -1; } /** * @dev Get functing info of user/address. It will return how much funding the user has made in terms of wei */ function getFundingInfoForUser(address _user)public view nonZeroAddress(_user) returns(uint256){ return vault.deposited(_user); } }
Low level token purchase function beneficiary The address who will receive the tokens for this transaction/hard cap for this tier has not been reachedTotal tokens sold including current sale should be less than hard cap of this tier
function buyTokens(address beneficiary)public _saleActive nonZeroEth nonZeroAddress(beneficiary) payable returns(bool){ int8 currentTierIndex = getCurrentlyRunningTier(); assert(currentTierIndex>=0); TierInfo storage currentlyRunningTier = tiers[uint256(currentTierIndex)]; require(tokensSold < currentlyRunningTier.hardcap); uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(currentlyRunningTier.rate); uint256 bonusedTokens = applyBonus(tokens, currentlyRunningTier.bonusPercentage); assert(tokensSold.add(bonusedTokens) <= currentlyRunningTier.hardcap); tokensSold = tokensSold.add(bonusedTokens); totalFunding = totalFunding.add(weiAmount); currentlyRunningTier.weiRaised = currentlyRunningTier.weiRaised.add(weiAmount); vault.deposit.value(msg.value)(msg.sender); token.transfer(beneficiary, bonusedTokens); TokenPurchase(msg.sender, beneficiary, weiAmount, bonusedTokens); }
6,499,183
pragma solidity ^0.4.4; import "./Owned.sol"; contract Bearchange is Owned { address owner; struct token { string symbol; address contract_address; } mapping(uint => token) tokens; uint numTokens; struct offer { uint amount; address who; } struct orderBook { uint higherPrice; uint lowerPrice; mapping (uint => offer) offers; uint offers_key; uint offers_length; } mapping(uint => orderBook) buyBook; mapping(uint => orderBook) sellBook; mapping(address => uint) balancesInEther; // address => ( tokenNum => balance) mapping(address => mapping (uint => uint)) balancesInTokens; function Bearchange() public { owner = msg.sender; } ////////////////////////////////// /// Ether /////////////////////////////////// /// Ether management functions function depositEther() payable public { // check for dodgy overflow stuff require (balancesInEther[msg.sender]+msg.value>=balancesInEther[msg.sender]); balancesInEther[msg.sender] += msg.value; } // amount in wei function withdrawEther(uint _amount) public { require(balancesInEther[msg.sender]-_amount >= 0); require(balancesInEther[msg.sender]-_amount <= balancesInEther[msg.sender]); balancesInEther[msg.sender] = balancesInEther[msg.sender]-_amount; msg.sender.transfer(_amount); } ////////////////////////////////// /// Tokens /////////////////////////////////// function withdrawToken(string _tokenSymbol, uint _amount) public { require(hasSymbol(_tokenSymbol)); uint tokenIndex = getTokenIndex(_tokenSymbol); require(balancesInTokens[msg.sender][_tokenIndex] - _amount >= 0); require(balancesInTokens[msg.sender][_tokenIndex] - _amount < balancesInTokens[msg.sender][_tokenIndex]); ERC20Interface token = ERC20Interface(tokens[tokenIndex].contract_address); require(token.transfer(msg.sender, amount) == true); } function depositToken(string _tokenSymbol, uint _amount) public { require(hasSymbol(_tokenSymbol)); require(amount>0); uint tokenIndex = getTokenIndex(_tokenSymbol); uint tokenContractAddress = tokens[tokenIndex].contract_address; ERC20Interface token = ERC20Interface(tokenContractAddress); require(token.transferFrom(msg.sender, address(this), amount) == true); require(balancesInTokens[msg.sender][tokenIndex] + amount >= balancesInTokens[msg.sender][tokenIndex]); balancesInTokens[msg.sender][tokenIndex] += amount; } function getBalanceToken(string _tokenSymbol) constant public returns (uint) { uint tokenIndex = getTokenIndex(_tokenSymbol); return balancesInTokens[msg.sender][tokenIndex]; } /// Add ERC20 Token function addToken(string _symbol, address _contract_address) onlyByOwner public returns (bool) { require(!hasSymbol(_symbol)); token memory t; t.contract_address = _contract_address; t.symbol = _symbol; tokens[numTokens] = t; numTokens++; return true; } /// Check if ERC20 token symbol exists function hasSymbol(string _symbol) public constant returns (bool) { if(numTokens == 0) { return false; } for(uint i=0; i<numTokens; i++) { if(keccak256(tokens[i].symbol) == keccak256(_symbol)) { return true; } } return false; } /// Get ERC20 token index function getTokenIndex(string _symbol) public constant returns (uint) { require(hasSymbol(_symbol)); for(uint i=0; i<numTokens; i++) { if(keccak256(tokens[i].symbol) == keccak256(_symbol)) { return i; } } } function getTokenAddress(uint _index) public constant returns (address) { return(tokens[_index].contract_address); } }
Check if ERC20 token symbol exists
function hasSymbol(string _symbol) public constant returns (bool) { if(numTokens == 0) { return false; } for(uint i=0; i<numTokens; i++) { if(keccak256(tokens[i].symbol) == keccak256(_symbol)) { return true; } } return false; }
5,444,905
// SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/token/ERC20/behaviours/ERC20Decimals.sol pragma solidity ^0.8.0; /** * @title ERC20Decimals * @dev Implementation of the ERC20Decimals. Extension of {ERC20} that adds decimals storage slot. */ abstract contract ERC20Decimals is ERC20 { uint8 immutable private _decimals; /** * @dev Sets the value of the `decimals`. This value is immutable, it can only be * set once during construction. */ constructor (uint8 decimals_) { _decimals = decimals_; } function decimals() public view virtual override returns (uint8) { return _decimals; } } // File: contracts/service/ServicePayer.sol pragma solidity ^0.8.0; interface IPayable { function pay(string memory serviceName) external payable; } /** * @title ServicePayer * @dev Implementation of the ServicePayer */ abstract contract ServicePayer { constructor (address payable receiver, string memory serviceName) payable { IPayable(receiver).pay{value: msg.value}(serviceName); } } // File: contracts/token/ERC20/StandardERC20.sol pragma solidity ^0.8.0; /** * @title StandardERC20 * @dev Implementation of the StandardERC20 */ contract StandardERC20 is ERC20Decimals, ServicePayer { constructor ( string memory name_, string memory symbol_, uint8 decimals_, uint256 initialBalance_, address payable feeReceiver_ ) ERC20(name_, symbol_) ERC20Decimals(decimals_) ServicePayer(feeReceiver_, "StandardERC20") payable { require(initialBalance_ > 0, "StandardERC20: supply cannot be zero"); _mint(_msgSender(), initialBalance_); } function decimals() public view virtual override returns (uint8) { return super.decimals(); } }
See {IERC20-allowance}./
function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; }
585
// Sources flattened with hardhat v2.6.4 https://hardhat.org // File openzeppelin-solidity/contracts/utils/Context.sol@v4.3.2 // 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 openzeppelin-solidity/contracts/access/Ownable.sol@v4.3.2 pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File openzeppelin-solidity/contracts/utils/introspection/IERC165.sol@v4.3.2 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/token/ERC721/IERC721.sol@v4.3.2 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/IERC721Receiver.sol@v4.3.2 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/token/ERC721/extensions/IERC721Metadata.sol@v4.3.2 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/utils/Address.sol@v4.3.2 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-solidity/contracts/utils/Strings.sol@v4.3.2 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-solidity/contracts/utils/introspection/ERC165.sol@v4.3.2 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/ERC721.sol@v4.3.2 pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File openzeppelin-solidity/contracts/utils/cryptography/ECDSA.sol@v4.3.2 pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { 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; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 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 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)); } } // File contracts/ArpeggiGenesisFinal.sol pragma solidity >=0.8.0 <0.9.0; // Arpeggi Studio Genesis is the first on-chain music creation platform. All data and instructions to recreate your Arpeggi song reside on the Ethereum blockchain. // // To recreate your song, you will need to retrieve two compressed files from the chain: "samples" and "scripts". // // STEPS TO RETRIEVE "samples": // - The mp3 samples to play your song have been packaged together as a single compressed file, split into pieces, and stored in transaction data on-chain. // - Make a new file on your local, 'samples.hex,' to piece together the samples hex data gathered from the contract. // - Query the contract for the sampleCount - this is the number of pieces of the samples file. You will need all of them. // - Pass in the sampleCount starting with 0 into the _samples read method of the ArpeggiStudioGenesis contract, this is will return a transaction hash. // - Use the transaction hash to find the sample transaction on Etherscan. // - Copy the "Input Data" field of this the transaction to the end of your local 'samples.hex' file, removing the leading 0x at the beggining of the input data. // - Repeat the last three steps, incrementing the sampleConut in the _samples read method and appending to the end of your local file data until you have copied all the sample data. // - Convert the local file from hex to binary using a command line tool. Example command: xxd -r -p samples.hex > samples.zip // - Follow the instructions to retrieve the scripts below. // // STEPS TO RETRIEVE "scripts": // - The song player script is written in JavaScript, split into pieces, and stored on chain. // - Make a new file on your local, 'scripts.hex' to piece together the script hex data gathered from the contract // - Query the contract for the scriptCount - this is the number of pieces of the player script. It's likely to be one transaction. // - Pass in the scriptCount starting with 0 into the _scripts read method of the ArpeggiStudioGenesis contract, this is will return a transaction hash. // - Use the transaction hash to find the script transaction on Etherscan // - Copy the "Input Data" field of this the transaction to your local 'scripts.hex' file, removing the leading 0x at the beggining of the input data. // - Repeat these last three steps, incrementing the scriptCount in the _scripts method and appending to the end of your local file data until you have copied all the script data. // - Convert the local file from hex to binary using a command line tool. Example command: xxd -r -p scripts.hex > scripts.zip // // PLAYING YOUR SONG: // - Extract the scripts and the samples files. This is all of the data required to play your song. // - Follow the instructions in the scripts/README file to play your song! contract ArpeggiStudioGenesis is ERC721, Ownable { ////////////////// STRUCT ////////////////// /** * @dev Struct for Pass and Song */ struct Pass { string title; string artist; bytes composition; uint mintTime; address artistAddress; } ////////////////// CONSTANTS ////////////////// uint256 public constant MAX_PASSES = 600; uint256 public constant PRESALE_MINT_PRICE = 0.25 ether; uint256 public constant GENERAL_MINT_PRICE = 0.3 ether; /** * @dev Max number of Passes that the contract owner can mint. */ uint256 public constant CREATORS_NUM_PASSES = 64; /** * @dev Max number of Passes that the contract owner can mint. */ uint256 public constant DEVELOPERS_NUM_PASSES = 24; ////////////////// STORAGE ////////////////// uint256 public _numMinted = 0; /** * @dev Custom pause functionality for Creator/Developer Reserve Mint */ bool private _paused = true; bool public _onlyEarlyAccess = true; address public immutable CREATORS_RESERVE; address public immutable DEVELOPERS_RESERVE; /** * @dev Base URL for external_url metadata field. */ string private _basePassExternalUrl = "http://www.arpeggi.io/metadata/pass/"; /** * @dev Base URL for external_url metadata field. */ string private _baseSongExternalUrl = "http://www.arpeggi.io/metadata/song/"; /** * @dev All existing Passes. */ mapping(uint256 => Pass) public _passes; /** * @dev Addresses with early minting access. */ mapping(address => bool) private _earlyAccess; /** * @dev For setting scripts. When locked it is irreversible. */ bool private _locked = false; /** * @dev The scripts used to render a composition from a token */ mapping (uint256 => string) public _scripts; uint256 public scriptCount = 0; /** * @dev The samples used to play a song */ mapping (uint256 => string) public _samples; uint256 public sampleCount = 0; ////////////////// CONSTRUCTOR ////////////////// constructor( address creatorsReserve, address developersReserve ) ERC721( "Arpeggi Genesis Studio Pass", "ARPEGGI" ) { CREATORS_RESERVE = creatorsReserve; DEVELOPERS_RESERVE = developersReserve; } ////////////////// MODIFIERS ////////////////// /** * @dev Modifier to make a function callable only when the contract is not paused. * Contract must not be paused */ modifier whenNotPaused() { require(!isPaused(), "Paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * Contract must be paused. */ modifier whenPaused() { require(isPaused(), "Paused"); _; } /** * @dev Lock functionality to lock scripts/samples after uploading */ modifier onlyUnlocked() { require(!_locked, "Contract is locked"); _; } ////////////////// EXTERNAL ONLY-OWNER FUNCTIONS ////////////////// /** * @dev Returns to unpaused state. The contract must be paused. */ function unpause() external onlyOwner whenPaused { _paused = false; } /** * @dev Function to lock on-chain scripts and samples */ function setLocked() external onlyOwner onlyUnlocked { _locked = true; } /** * @dev Add a new section of the script * @param script String value of script or pointer */ function addScript( string memory script ) external onlyOwner onlyUnlocked { _scripts[scriptCount] = script; scriptCount++; } /** * @dev Overwrite a script section at a particular index * @param script String value of script or pointer * @param index Index of the script to replace */ function updateScript( string memory script, uint256 index ) external onlyOwner onlyUnlocked { require(index < scriptCount, "Index out of bounds"); _scripts[index] = script; } /** * @dev Reset script index to zero, caller must be owner and the contract unlocked */ function resetScriptCount() external onlyOwner onlyUnlocked { scriptCount = 0; } /** * @dev Add a new section of the sample * @param sample String value of sample or pointer */ function addSample( string memory sample ) external onlyOwner onlyUnlocked { _samples[sampleCount] = sample; sampleCount++; } /** * @dev Reset sample index to zero, caller must be owner and the contract unlocked */ function resetSampleCount() external onlyOwner onlyUnlocked { sampleCount = 0; } /** * @dev Set the _onlyEarlyAccess flag. */ function setOnlyEarlyAccess( bool to ) external onlyOwner { _onlyEarlyAccess = to; } /** * @dev Set early-access granting or revocation for the addresses. eg. ["0x12345"] */ function setEarlyAccessGrants( address[] calldata addresses, bool hasAccess ) external onlyOwner { for (uint i = 0; i < addresses.length; i++) { _earlyAccess[addresses[i]] = hasAccess; } } /** * @dev Allocate passes to Arpeggi Creators Reserve wallet */ function mintCreatorsReserve() external onlyOwner whenPaused { for (uint i=0; i < CREATORS_NUM_PASSES; i++) { _mintToken(CREATORS_RESERVE); } } /** * @dev Allocate passes to Arpeggi Creators Reserve wallet */ function mintDevelopersReserve() external onlyOwner whenPaused { for (uint i=0; i < DEVELOPERS_NUM_PASSES; i++) { _mintToken(DEVELOPERS_RESERVE); } } /** * @dev Withdraw funds from contract to owner */ function withdraw() public onlyOwner { payable(owner()).transfer(address(this).balance); } ////////////////// EXTERNAL FUNCTIONS ////////////////// /** * @dev Mint a lab pass */ function mint() external payable whenNotPaused { require(_numMinted < MAX_PASSES, "No More Passes Left"); require( (_onlyEarlyAccess && PRESALE_MINT_PRICE == msg.value) || (!_onlyEarlyAccess && GENERAL_MINT_PRICE == msg.value), "Incorrect Ether value."); require(!_isContract(msg.sender), "Can't mint from a contract smh"); require( !_onlyEarlyAccess || _earlyAccess[msg.sender], "You are not approved for presale" ); _mintToken(msg.sender); if (_onlyEarlyAccess) { _earlyAccess[msg.sender] = false; } } function pressSong( uint256 _tokenId, bytes calldata _composition, string calldata _title, string calldata _artist ) external whenNotPaused { require(_isApprovedOrOwner(_msgSender(), _tokenId)); require(_passes[_tokenId].mintTime == 0, "Your Studio Pass has already been used"); _pressSongToken(msg.sender, _tokenId, _title, _artist, _composition); } ////////////////// PUBLIC ONLY-OWNER FUNCTIONS ////////////////// /** * @dev Set the base URL for external_url metadata field. */ function setBasePassExternalUrl( string memory url ) public onlyOwner { _basePassExternalUrl = url; } /** * @dev Set the base URL for external_url metadata field. */ function setBaseSongExternalUrl( string memory url ) public onlyOwner { _baseSongExternalUrl = url; } ////////////////// PUBLIC FUNCTIONS ////////////////// /** * @dev Returns data URI of token metadata. */ function tokenURI( uint256 _tokenId ) public override view returns (string memory) { if (_passes[_tokenId].mintTime == 0) { return string(abi.encodePacked(_basePassExternalUrl, Strings.toString(_tokenId))); } else { return string(abi.encodePacked(_baseSongExternalUrl, Strings.toString(_tokenId))); } } /** * @dev Checks an address to see if it has early access */ function hasEarlyAccess(address _address) public view returns (bool) { return _earlyAccess[_address] == true; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function isPaused() public view returns (bool) { return _paused; } ////////////////// INTERNAL FUNCTIONS ////////////////// function _mintToken( address _to ) internal { _numMinted++; _safeMint(_to, _numMinted); } function _pressSongToken( address _artistAddress, uint256 _tokenId, string calldata _title, string calldata _artist, bytes calldata _composition ) internal returns(uint256 _songToken) { _passes[_tokenId].title = _title; _passes[_tokenId].artist = _artist; _passes[_tokenId].composition = _composition; _passes[_tokenId].mintTime = block.timestamp; _passes[_tokenId].artistAddress = _artistAddress; return _tokenId; } /** * @dev Function to check if an address is a contract for minting */ function _isContract( address _addr ) internal view returns (bool) { uint32 _size; assembly { _size:= extcodesize(_addr) } return (_size > 0); } }
Function to check if an address is a contract for minting/
function _isContract( address _addr ) internal view returns (bool) { uint32 _size; assembly { _size:= extcodesize(_addr) } return (_size > 0); }
14,709,618
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. /** * @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(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "add: +"); return c; } /** * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint a, uint b) internal pure returns (uint) { return sub(a, b, "sub: -"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b <= a, errorMessage); uint 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(uint a, uint b) internal pure returns (uint) { // 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; } uint c = a * b; require(c / a == b, "mul: *"); return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // 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; } uint c = a * b; require(c / a == b, errorMessage); 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(uint a, uint b) internal pure returns (uint) { return div(a, b, "div: /"); } /** * @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(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint 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(uint a, uint b) internal pure returns (uint) { return mod(a, b, "mod: %"); } /** * @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(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b != 0, errorMessage); return a % b; } } /** * @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; } } /** * @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) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call{value:amount}(""); require(success, "Address: reverted"); } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: < 0"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: !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: !succeed"); } } } library Keep3rV1Library { function getReserve(address pair, address reserve) external view returns (uint) { (uint _r0, uint _r1,) = IUniswapV2Pair(pair).getReserves(); if (IUniswapV2Pair(pair).token0() == reserve) { return _r0; } else if (IUniswapV2Pair(pair).token1() == reserve) { return _r1; } else { return 0; } } } interface IUniswapV2Pair { function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); } interface IGovernance { function proposeJob(address job) external; } interface IKeep3rV1Helper { function getQuoteLimit(uint gasUsed) external view returns (uint); } // File: contracts/Keep3r.sol pragma solidity ^0.6.6; contract Relay3rV1 is ReentrancyGuard { using SafeMath for uint; using SafeERC20 for IERC20; /// @notice Keep3r Helper to set max prices for the ecosystem IKeep3rV1Helper public KPRH; /// @notice EIP-20 token name for this token string public constant name = "Relay3rV1"; /// @notice EIP-20 token symbol for this token string public constant symbol = "RL3R"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public totalSupply = 0; // Initial 0 /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @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; mapping (address => mapping (address => uint)) internal allowances; mapping (address => uint) internal balances; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint chainId,address verifyingContract)"); bytes32 public immutable DOMAINSEPARATOR; /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint nonce,uint expiry)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint value,uint nonce,uint deadline)"); /// @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 A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint votes; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { _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) public { 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), "delegateBySig: sig"); require(nonce == nonces[signatory]++, "delegateBySig: nonce"); require(now <= expiry, "delegateBySig: expired"); _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 (uint) { 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) public view returns (uint) { require(blockNumber < block.number, "getPriorVotes:"); 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]; uint delegatorBalance = votes[delegator].add(bonds[delegator][address(this)]); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint srcRepNew = srcRepOld.sub(amount, "_moveVotes: underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint oldVotes, uint newVotes) internal { uint32 blockNumber = safe32(block.number, "_writeCheckpoint: 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); } /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint amount); /// @notice Submit a job event SubmitJob(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit); /// @notice Apply credit to a job event ApplyCredit(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit); /// @notice Remove credit for a job event RemoveJob(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit); /// @notice Unbond credit for a job event UnbondJob(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit); /// @notice Added a Job event JobAdded(address indexed job, uint block, address governance); /// @notice Removed a job event JobRemoved(address indexed job, uint block, address governance); /// @notice Worked a job event KeeperWorked(address indexed credit, address indexed job, address indexed keeper, uint block); /// @notice Keeper bonding event KeeperBonding(address indexed keeper, uint block, uint active, uint bond); /// @notice Keeper bonded event KeeperBonded(address indexed keeper, uint block, uint activated, uint bond); /// @notice Keeper unbonding event KeeperUnbonding(address indexed keeper, uint block, uint deactive, uint bond); /// @notice Keeper unbound event KeeperUnbound(address indexed keeper, uint block, uint deactivated, uint bond); /// @notice Keeper slashed event KeeperSlashed(address indexed keeper, address indexed slasher, uint block, uint slash); /// @notice Keeper disputed event KeeperDispute(address indexed keeper, uint block); /// @notice Keeper resolved event KeeperResolved(address indexed keeper, uint block); event AddCredit(address indexed credit, address indexed job, address indexed creditor, uint block, uint amount); /// @notice Keeper rights approved to be spent by spender event KeeperRightApproval(address indexed owner, address indexed spender, bool allowed); /// @notice Keeper right transfered to a new address event KeeperRightTransfered(address indexed from, address indexed to, address indexed bond); /// @notice 3 days to bond to become a keeper uint public BOND = 3 days; /// @notice 14 days to unbond to remove funds from being a keeper uint public UNBOND = 14 days; /// @notice 3 days till liquidity can be bound uint public LIQUIDITYBOND = 3 days; /// @notice direct liquidity fee 0.3%,Can be modified by governance contract uint public FEE = 30; uint constant public BASE = 10000; /// @notice address used for ETH transfers address constant public ETH = address(0xE); /// @notice tracks all current bondings (time) mapping(address => mapping(address => uint)) public bondings; /// @notice tracks all current unbondings (time) mapping(address => mapping(address => uint)) public unbondings; /// @notice allows for partial unbonding mapping(address => mapping(address => uint)) public partialUnbonding; /// @notice tracks all current pending bonds (amount) mapping(address => mapping(address => uint)) public pendingbonds; /// @notice tracks how much a keeper has bonded mapping(address => mapping(address => uint)) public bonds; /// @notice tracks underlying votes (that don't have bond) mapping(address => uint) public votes; /// @notice total bonded (totalSupply for bonds) uint public totalBonded = 0; /// @notice tracks when a keeper was first registered mapping(address => uint) public firstSeen; /// @notice tracks if a keeper has a pending dispute mapping(address => bool) public disputes; /// @notice tracks last job performed for a keeper mapping(address => uint) public lastJob; /// @notice tracks the total job executions for a keeper mapping(address => uint) public workCompleted; /// @notice list of all jobs registered for the keeper system mapping(address => bool) public jobs; /// @notice the current credit available for a job mapping(address => mapping(address => uint)) public credits; /// @notice the balances for the liquidity providers mapping(address => mapping(address => mapping(address => uint))) public liquidityProvided; /// @notice liquidity unbonding days mapping(address => mapping(address => mapping(address => uint))) public liquidityUnbonding; /// @notice liquidity unbonding amounts mapping(address => mapping(address => mapping(address => uint))) public liquidityAmountsUnbonding; /// @dev job proposal delay mapping(address => uint) internal jobProposalDelayInternal; /// @notice liquidity apply date mapping(address => mapping(address => mapping(address => uint))) public liquidityApplied; /// @notice liquidity amount to apply mapping(address => mapping(address => mapping(address => uint))) public liquidityAmount; /// @notice list of all current keepers mapping(address => bool) public keepers; /// @notice blacklist of keepers not allowed to participate mapping(address => bool) public blacklist; mapping(address => mapping (address => bool)) internal KeeperAllowances; mapping(address => mapping (address => mapping(address => bool))) internal KeeperAllowancesPassed; /// @notice traversable array of keepers to make external management easier address[] public keeperList; /// @notice traversable array of jobs to make external management easier address[] public jobList; /// @notice governance address for the governance contract address public governance; address public pendingGovernance; /// @notice the liquidity token supplied by users paying for jobs mapping(address => bool) public liquidityAccepted; address[] public liquidityPairs; uint internal _gasUsed; constructor() public { // Set governance for this token governance = msg.sender; DOMAINSEPARATOR = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), _getChainId(), address(this))); } modifier onlyGovernance(){ require(msg.sender == governance); _; } /** * @notice Add ETH credit to a job to be paid out for work * @param job the job being credited */ function addCreditETH(address job) external payable { require(jobs[job], "addCreditETH: !job"); uint _fee = msg.value.mul(FEE).div(BASE); credits[job][ETH] = credits[job][ETH].add(msg.value.sub(_fee)); payable(governance).transfer(_fee); emit AddCredit(ETH, job, msg.sender, block.number, msg.value); } /** * @notice Add credit to a job to be paid out for work * @param credit the credit being assigned to the job * @param job the job being credited * @param amount the amount of credit being added to the job */ function addCredit(address credit, address job, uint amount) external nonReentrant { require(jobs[job], "addCreditETH: !job"); uint _before = IERC20(credit).balanceOf(address(this)); IERC20(credit).safeTransferFrom(msg.sender, address(this), amount); uint _received = IERC20(credit).balanceOf(address(this)).sub(_before); uint _fee = _received.mul(FEE).div(BASE); credits[job][credit] = credits[job][credit].add(_received.sub(_fee)); IERC20(credit).safeTransfer(governance, _fee); emit AddCredit(credit, job, msg.sender, block.number, _received); } /** * @notice Add non transferable votes for governance * @param voter to add the votes to * @param amount of votes to add */ function addVotes(address voter, uint amount) external onlyGovernance{ votes[voter] = votes[voter].add(amount); totalBonded = totalBonded.add(amount); _moveDelegates(address(0), delegates[voter], amount); } /** * @notice Remove non transferable votes for governance * @param voter to subtract the votes * @param amount of votes to remove */ function removeVotes(address voter, uint amount) external onlyGovernance{ votes[voter] = votes[voter].sub(amount); totalBonded = totalBonded.sub(amount); _moveDelegates(delegates[voter], address(0), amount); } /** * @notice Add credit to a job to be paid out for work * @param job the job being credited * @param amount the amount of credit being added to the job */ function addRLRCredit(address job, uint amount) external onlyGovernance{ require(jobs[job], "addRLRCredit: !job"); credits[job][address(this)] = credits[job][address(this)].add(amount); emit AddCredit(address(this), job, msg.sender, block.number, amount); } /** * @notice Approve a liquidity pair for being accepted in future * @param liquidity the liquidity no longer accepted */ function approveLiquidity(address liquidity) external onlyGovernance{ require(!liquidityAccepted[liquidity], "approveLiquidity: !pair"); liquidityAccepted[liquidity] = true; liquidityPairs.push(liquidity); } /** * @notice Revoke a liquidity pair from being accepted in future * @param liquidity the liquidity no longer accepted */ function revokeLiquidity(address liquidity) external onlyGovernance{ liquidityAccepted[liquidity] = false; } /** * @notice Set new liquidity fee from governance * @param newFee the new fee for further liquidity adds */ function setLiquidityFee(uint newFee) external onlyGovernance{ FEE = newFee; } /** * @notice Set bonding delay from governance * @param newBond the new bonding delay */ function setBondingDelay(uint newBond) external onlyGovernance{ BOND = newBond; } /** * @notice Set bonding delay from governance * @param newUnbond the new unbonding delay */ function setUnbondingDelay(uint newUnbond) external onlyGovernance{ UNBOND = newUnbond; } /** * @notice Set liquidity bonding delay from governance * @param newLiqBond the new liquidity bonding delay */ function setLiquidityBondingDelay(uint newLiqBond) external onlyGovernance{ LIQUIDITYBOND = newLiqBond; } /** * @notice Displays all accepted liquidity pairs */ function pairs() external view returns (address[] memory) { return liquidityPairs; } /** * @notice Gets the job proposal delay with the current unbound delay */ function jobProposalDelay(address job) public view returns (uint){ return jobProposalDelayInternal[job].add(UNBOND); } /** * @notice Allows liquidity providers to submit jobs * @param liquidity the liquidity being added * @param job the job to assign credit to * @param amount the amount of liquidity tokens to use */ function addLiquidityToJob(address liquidity, address job, uint amount) external nonReentrant { require(liquidityAccepted[liquidity], "addLiquidityToJob: !pair"); IERC20(liquidity).safeTransferFrom(msg.sender, address(this), amount); liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].add(amount); liquidityApplied[msg.sender][liquidity][job] = now; liquidityAmount[msg.sender][liquidity][job] = liquidityAmount[msg.sender][liquidity][job].add(amount); if (!jobs[job] && jobProposalDelay(job) < now) { IGovernance(governance).proposeJob(job); jobProposalDelayInternal[job] = now; } emit SubmitJob(job, liquidity, msg.sender, block.number, amount); } /** * @notice Applies the credit provided in addLiquidityToJob to the job * @param provider the liquidity provider * @param liquidity the pair being added as liquidity * @param job the job that is receiving the credit */ function applyCreditToJob(address provider, address liquidity, address job) external { require(liquidityAccepted[liquidity], "applyCreditToJob: !pair"); require(liquidityApplied[provider][liquidity][job] != 0, "credit: no bond"); require(block.timestamp.sub(liquidityApplied[provider][liquidity][job].add(LIQUIDITYBOND)) >= 0, "credit: bonding"); uint _liquidity = Keep3rV1Library.getReserve(liquidity, address(this)); uint _credit = _liquidity.mul(liquidityAmount[provider][liquidity][job]).div(IERC20(liquidity).totalSupply()); _mint(address(this), _credit); credits[job][address(this)] = credits[job][address(this)].add(_credit); liquidityAmount[provider][liquidity][job] = 0; emit ApplyCredit(job, liquidity, provider, block.number, _credit); } /** * @notice Unbond liquidity for a job * @param liquidity the pair being unbound * @param job the job being unbound from * @param amount the amount of liquidity being removed */ function unbondLiquidityFromJob(address liquidity, address job, uint amount) external { require(liquidityAmount[msg.sender][liquidity][job] == 0, "credit: pending credit"); liquidityUnbonding[msg.sender][liquidity][job] = now; liquidityAmountsUnbonding[msg.sender][liquidity][job] = liquidityAmountsUnbonding[msg.sender][liquidity][job].add(amount); require(liquidityAmountsUnbonding[msg.sender][liquidity][job] <= liquidityProvided[msg.sender][liquidity][job], "unbondLiquidityFromJob: insufficient funds"); uint _liquidity = Keep3rV1Library.getReserve(liquidity, address(this)); uint _credit = _liquidity.mul(amount).div(IERC20(liquidity).totalSupply()); if (_credit > credits[job][address(this)]) { _burn(address(this), credits[job][address(this)]); credits[job][address(this)] = 0; } else { _burn(address(this), _credit); credits[job][address(this)] = credits[job][address(this)].sub(_credit); } emit UnbondJob(job, liquidity, msg.sender, block.number, amount); } /** * @notice Allows liquidity providers to remove liquidity * @param liquidity the pair being unbound * @param job the job being unbound from */ function removeLiquidityFromJob(address liquidity, address job) external { require(liquidityUnbonding[msg.sender][liquidity][job] != 0, "removeJob: unbond"); require(block.timestamp.sub(liquidityUnbonding[msg.sender][liquidity][job].add(UNBOND)) >= 0, "removeJob: unbonding"); uint _amount = liquidityAmountsUnbonding[msg.sender][liquidity][job]; liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].sub(_amount); liquidityAmountsUnbonding[msg.sender][liquidity][job] = 0; IERC20(liquidity).safeTransfer(msg.sender, _amount); emit RemoveJob(job, liquidity, msg.sender, block.number, _amount); } /** * @notice Allows governance to mint new tokens to treasury * @param amount the amount of tokens to mint to treasury */ function mint(uint amount) external onlyGovernance{ _mint(governance, amount); } /** * @notice burn owned tokens * @param amount the amount of tokens to burn */ function burn(uint amount) external { _burn(msg.sender, amount); } function _mint(address dst, uint amount) internal { // mint the amount totalSupply = totalSupply.add(amount); // transfer the amount to the recipient balances[dst] = balances[dst].add(amount); emit Transfer(address(0), dst, amount); } function _burn(address dst, uint amount) internal { require(dst != address(0), "_burn: zero address"); balances[dst] = balances[dst].sub(amount, "_burn: exceeds balance"); totalSupply = totalSupply.sub(amount); emit Transfer(dst, address(0), amount); } /** * @notice Implemented by jobs to show that a keeper performed work * @param keeper address of the keeper that performed the work */ function worked(address keeper) external { workReceipt(keeper, KPRH.getQuoteLimit(_gasUsed.sub(gasleft()))); } /** * @notice Implemented by jobs to show that a keeper performed work and get paid in ETH * @param keeper address of the keeper that performed the work */ function workedETH(address keeper) external { receiptETH(keeper, KPRH.getQuoteLimit(_gasUsed.sub(gasleft()))); } /** * @notice Implemented by jobs to show that a keeper performed work * @param keeper address of the keeper that performed the work * @param amount the reward that should be allocated */ function workReceipt(address keeper, uint amount) public { require(jobs[msg.sender], "workReceipt: !job"); require(amount <= KPRH.getQuoteLimit(_gasUsed.sub(gasleft())), "workReceipt: max limit"); credits[msg.sender][address(this)] = credits[msg.sender][address(this)].sub(amount, "workReceipt: insuffcient funds"); lastJob[keeper] = now; _bond(address(this), keeper, amount); workCompleted[keeper] = workCompleted[keeper].add(amount); emit KeeperWorked(address(this), msg.sender, keeper, block.number); } /** * @notice Implemented by jobs to show that a keeper performed work * @param credit the asset being awarded to the keeper * @param keeper address of the keeper that performed the work * @param amount the reward that should be allocated */ function receipt(address credit, address keeper, uint amount) external { require(jobs[msg.sender], "receipt: !job"); credits[msg.sender][credit] = credits[msg.sender][credit].sub(amount, "workReceipt: insuffcient funds"); lastJob[keeper] = now; IERC20(credit).safeTransfer(keeper, amount); emit KeeperWorked(credit, msg.sender, keeper, block.number); } /** * @notice Implemented by jobs to show that a keeper performed work * @param keeper address of the keeper that performed the work * @param amount the amount of ETH sent to the keeper */ function receiptETH(address keeper, uint amount) public { require(jobs[msg.sender], "receipt: !job"); credits[msg.sender][ETH] = credits[msg.sender][ETH].sub(amount, "workReceipt: insuffcient funds"); lastJob[keeper] = now; payable(keeper).transfer(amount); emit KeeperWorked(ETH, msg.sender, keeper, block.number); } function _bond(address bonding, address _from, uint _amount) internal { bonds[_from][bonding] = bonds[_from][bonding].add(_amount); if (bonding == address(this)) { totalBonded = totalBonded.add(_amount); _moveDelegates(address(0), delegates[_from], _amount); } } function _unbond(address bonding, address _from, uint _amount) internal { bonds[_from][bonding] = bonds[_from][bonding].sub(_amount); if (bonding == address(this)) { totalBonded = totalBonded.sub(_amount); _moveDelegates(delegates[_from], address(0), _amount); } } /** * @notice Allows governance to add new job systems * @param job address of the contract for which work should be performed */ function addJob(address job) external onlyGovernance{ require(!jobs[job], "addJob: job known"); jobs[job] = true; jobList.push(job); emit JobAdded(job, block.number, msg.sender); } /** * @notice Full listing of all jobs ever added * @return array blob */ function getJobs() external view returns (address[] memory) { return jobList; } /** * @notice Allows governance to remove a job from the systems * @param job address of the contract for which work should be performed */ function removeJob(address job) external onlyGovernance{ jobs[job] = false; emit JobRemoved(job, block.number, msg.sender); } /** * @notice Allows governance to change the Keep3rHelper for max spend * @param _kprh new helper address to set */ function setKeep3rHelper(address _kprh) external onlyGovernance{ KPRH = IKeep3rV1Helper(_kprh); } /** * @notice Allows governance to change governance (for future upgradability) * @param _governance new governance address to set */ function setGovernance(address _governance) external onlyGovernance{ pendingGovernance = _governance; } /** * @notice Allows pendingGovernance to accept their role as governance (protection pattern) */ function acceptGovernance() external { require(msg.sender == pendingGovernance, "acceptGovernance: !pendingGov"); governance = pendingGovernance; } /** * @notice confirms if the current keeper is registered, can be used for general (non critical) functions * @param keeper the keeper being investigated * @return true/false if the address is a keeper */ function isKeeper(address keeper) public returns (bool) { _gasUsed = gasleft(); return keepers[keeper]; } /** * @notice confirms if the current keeper is registered and has a minimum bond, should be used for protected functions * @param keeper the keeper being investigated * @param minBond the minimum requirement for the asset provided in bond * @param earned the total funds earned in the keepers lifetime * @param age the age of the keeper in the system * @return true/false if the address is a keeper and has more than the bond */ function isMinKeeper(address keeper, uint minBond, uint earned, uint age) external returns (bool) { _gasUsed = gasleft(); return keepers[keeper] && bonds[keeper][address(this)].add(votes[keeper]) >= minBond && workCompleted[keeper] >= earned && now.sub(firstSeen[keeper]) >= age; } /** * @notice confirms if the current keeper is registered and has a minimum bond, should be used for protected functions * @param keeper the keeper being investigated * @param bond the bound asset being evaluated * @param minBond the minimum requirement for the asset provided in bond * @param earned the total funds earned in the keepers lifetime * @param age the age of the keeper in the system * @return true/false if the address is a keeper and has more than the bond */ function isBondedKeeper(address keeper, address bond, uint minBond, uint earned, uint age) external returns (bool) { _gasUsed = gasleft(); return keepers[keeper] && bonds[keeper][bond] >= minBond && workCompleted[keeper] >= earned && now.sub(firstSeen[keeper]) >= age; } /** * @notice begin the bonding process for a new keeper * @param bonding the asset being bound * @param amount the amount of bonding asset being bound */ function bond(address bonding, uint amount) external nonReentrant { require(!blacklist[msg.sender], "bond: blacklisted"); //In this part we changed the addition of current time + bond time to the time bond was called bondings[msg.sender][bonding] = now; if (bonding == address(this)) { _transferTokens(msg.sender, address(this), amount); } else { uint _before = IERC20(bonding).balanceOf(address(this)); IERC20(bonding).safeTransferFrom(msg.sender, address(this), amount); amount = IERC20(bonding).balanceOf(address(this)).sub(_before); } pendingbonds[msg.sender][bonding] = pendingbonds[msg.sender][bonding].add(amount); emit KeeperBonding(msg.sender, block.number, bondings[msg.sender][bonding], amount); } /** * @notice get full list of keepers in the system */ function getKeepers() external view returns (address[] memory) { return keeperList; } /** * @notice Does initial data initialization of keeper entry * @param sender the address to init data for */ function doDataInit(address sender) internal { if (firstSeen[sender] == 0) { firstSeen[sender] = now; keeperList.push(sender); lastJob[sender] = now; } } /** * @notice allows a keeper to activate/register themselves after bonding * @param bonding the asset being activated as bond collateral */ function activate(address bonding) external { require(!blacklist[msg.sender], "activate: blacklisted"); //In this part we changed the check of bonding time being lesser than now to check if current time is > bonding time require(bondings[msg.sender][bonding] != 0 && block.timestamp.sub(bondings[msg.sender][bonding].add(BOND)) >= 0, "activate: bonding"); //Setup initial data doDataInit(msg.sender); keepers[msg.sender] = true; _bond(bonding, msg.sender, pendingbonds[msg.sender][bonding]); pendingbonds[msg.sender][bonding] = 0; emit KeeperBonded(msg.sender, block.number, block.timestamp, bonds[msg.sender][bonding]); } function doKeeperrightChecks(address from,address to,address bonding) internal returns (bool){ require(!blacklist[from], "transferKeeperRight: blacklisted"); require(isKeeper(from), "transferKeeperRight: not keeper"); require(msg.sender == from || KeeperAllowances[msg.sender][from],"transferKeeperRight: Unauthorized transfer call"); require(bondings[from][bonding] != 0 && block.timestamp.sub(bondings[from][bonding].add(BOND)) >= 0, "transferKeeperRight: bonding"); KeeperAllowancesPassed[from][to][bonding] = true; return true; } /** * @notice allows a keeper to transfer their keeper rights and bonds to another address * @param bonding the asset being transfered to new address as bond collateral * @param from the address keeper rights and bonding amount is transfered from * @param to the address keeper rights and bonding amount is transfered to */ function transferKeeperRight(address bonding,address from,address to) public { require(KeeperAllowancesPassed[from][to][bonding],"pass doKeeperrightChecks first"); doDataInit(to); //Set the user calling keeper stat to false keepers[from] = false; //Set the to addr keeper stat to true keepers[to] = true; //Unbond from sender uint currentbond = bonds[from][bonding]; _unbond(bonding,from,currentbond); //Bond to receiver _bond(bonding,to,currentbond); //Remove allowance passed after transfer KeeperAllowancesPassed[from][to][bonding] = false; //remove rights for this address after transfer is done from caller KeeperAllowances[from][msg.sender] = false; emit KeeperRightTransfered(from,to,bonding); } /** * @notice begin the unbonding process to stop being a keeper * @param bonding the asset being unbound * @param amount allows for partial unbonding */ function unbond(address bonding, uint amount) external { unbondings[msg.sender][bonding] = now; _unbond(bonding, msg.sender, amount); partialUnbonding[msg.sender][bonding] = partialUnbonding[msg.sender][bonding].add(amount); emit KeeperUnbonding(msg.sender, block.number, unbondings[msg.sender][bonding], amount); } // function getUnbondTime(address user,address bonding) public view returns (uint256){ // return unbondings[user][bonding].add(UNBOND); // } /** * @notice withdraw funds after unbonding has finished * @param bonding the asset to withdraw from the bonding pool */ function withdraw(address bonding) external nonReentrant { //Same changes as on bonding check is done here require(unbondings[msg.sender][bonding] != 0 && block.timestamp.sub(unbondings[msg.sender][bonding].add(UNBOND)) >= 0, "withdraw: unbonding"); require(!disputes[msg.sender], "withdraw: disputes"); if (bonding == address(this)) { _transferTokens(address(this), msg.sender, partialUnbonding[msg.sender][bonding]); } else { IERC20(bonding).safeTransfer(msg.sender, partialUnbonding[msg.sender][bonding]); } emit KeeperUnbound(msg.sender, block.number, block.timestamp, partialUnbonding[msg.sender][bonding]); partialUnbonding[msg.sender][bonding] = 0; } /** * @notice allows governance to create a dispute for a given keeper * @param keeper the address in dispute */ function dispute(address keeper) external onlyGovernance{ disputes[keeper] = true; emit KeeperDispute(keeper, block.number); } /** * @notice allows governance to slash a keeper based on a dispute * @param bonded the asset being slashed * @param keeper the address being slashed * @param amount the amount being slashed */ function slash(address bonded, address keeper, uint amount) public nonReentrant onlyGovernance{ if (bonded == address(this)) { _transferTokens(address(this), governance, amount); } else { IERC20(bonded).safeTransfer(governance, amount); } _unbond(bonded, keeper, amount); disputes[keeper] = false; emit KeeperSlashed(keeper, msg.sender, block.number, amount); } /** * @notice blacklists a keeper from participating in the network * @param keeper the address being slashed */ function revoke(address keeper) external onlyGovernance{ keepers[keeper] = false; blacklist[keeper] = true; slash(address(this), keeper, bonds[keeper][address(this)]); } /** * @notice allows governance to resolve a dispute on a keeper * @param keeper the address cleared */ function resolve(address keeper) external onlyGovernance{ disputes[keeper] = false; emit KeeperResolved(keeper, block.number); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint amount) public returns (bool) { allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Approve `spender` to transfer Keeper rights * @param spender The address of the account which may transfer keeper rights * @param fAllow whether this spender should be able to transfer rights * @return Whether or not the approval succeeded */ function keeperrightapprove(address spender,bool fAllow) public returns (bool) { KeeperAllowances[msg.sender][spender] = fAllow; emit KeeperRightApproval(msg.sender, spender, fAllow); return true; } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param amount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit(address owner, address spender, uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAINSEPARATOR, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "permit: signature"); require(signatory == owner, "permit: unauthorized"); require(now <= deadline, "permit: expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint amount) public returns (bool) { _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint amount) external returns (bool) { address spender = msg.sender; uint spenderAllowance = allowances[src][spender]; if (spender != src && spenderAllowance != uint(-1)) { uint newAllowance = spenderAllowance.sub(amount, "transferFrom: exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } function _transferTokens(address src, address dst, uint amount) internal { require(src != address(0), "_transferTokens: zero address"); require(dst != address(0), "_transferTokens: zero address"); balances[src] = balances[src].sub(amount); balances[dst] = balances[dst].add(amount); emit Transfer(src, dst, amount); } function _getChainId() internal pure returns (uint) { uint chainId; assembly { chainId := chainid() } return chainId; } }
Add credit to a job to be paid out for work job the job being credited amount the amount of credit being added to the job/
function addRLRCredit(address job, uint amount) external onlyGovernance{ require(jobs[job], "addRLRCredit: !job"); credits[job][address(this)] = credits[job][address(this)].add(amount); emit AddCredit(address(this), job, msg.sender, block.number, amount); }
1,429,880
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./utils/EnumerableSet.sol"; import "./interfaces/IAssetAllocation.sol"; import "./interfaces/ITVLManager.sol"; import "./interfaces/IOracleAdapter.sol"; import "./interfaces/IAddressRegistryV2.sol"; /// @title TVL Manager /// @author APY.Finance /// @notice Deployed assets can exist across various platforms within the /// defi ecosystem: pools, accounts, defi protocols, etc. This contract /// tracks deployed capital by registering the look up functions so that /// the TVL can be properly computed. /// @dev It is imperative that this manager has the most up to date asset /// allocations registered. Any assets in the system that have been deployed, /// but are not registered can have devastating and catastrophic effects on the TVL. contract TVLManager is Ownable, ReentrancyGuard, ITVLManager, IAssetAllocation { using EnumerableSet for EnumerableSet.Bytes32Set; using Address for address; IAddressRegistryV2 public addressRegistry; // all registered allocation ids EnumerableSet.Bytes32Set private _allocationIds; // ids mapped to data mapping(bytes32 => Data) private _allocationData; // ids mapped to symbol mapping(bytes32 => string) private _allocationSymbols; // ids mapped to decimals mapping(bytes32 => uint256) private _allocationDecimals; /// @notice Constructor TVLManager /// @param _addressRegistry the address registry to initialize with constructor(address _addressRegistry) public { setAddressRegistry(_addressRegistry); } /// @dev Reverts if non-permissed account calls. /// Permissioned accounts are: owner, pool manager, and account manager modifier onlyPermissioned() { require( msg.sender == owner() || msg.sender == addressRegistry.poolManagerAddress() || msg.sender == addressRegistry.lpSafeAddress(), "PERMISSIONED_ONLY" ); _; } function lockOracleAdapter() internal { IOracleAdapter oracleAdapter = IOracleAdapter(addressRegistry.oracleAdapterAddress()); oracleAdapter.lock(); } /// @notice Registers a new asset allocation /// @dev only permissed accounts can call. /// New ids are uniquely determined by the provided data struct; no duplicates are allowed /// @param data the data struct containing the target address and the bytes lookup data that will be registered /// @param symbol the token symbol to register for the asset allocation /// @param decimals the decimals to register for the new asset allocation function addAssetAllocation( Data memory data, string calldata symbol, uint256 decimals ) external override nonReentrant onlyPermissioned { require(!isAssetAllocationRegistered(data), "DUPLICATE_DATA_DETECTED"); bytes32 dataHash = generateDataHash(data); _allocationIds.add(dataHash); _allocationData[dataHash] = data; _allocationSymbols[dataHash] = symbol; _allocationDecimals[dataHash] = decimals; lockOracleAdapter(); } /// @notice Removes an existing asset allocation /// @dev only permissed accounts can call. /// @param data the data struct containing the target address and bytes lookup data that will be removed function removeAssetAllocation(Data memory data) external override nonReentrant onlyPermissioned { require(isAssetAllocationRegistered(data), "ALLOCATION_DOES_NOT_EXIST"); bytes32 dataHash = generateDataHash(data); _allocationIds.remove(dataHash); delete _allocationData[dataHash]; delete _allocationSymbols[dataHash]; delete _allocationDecimals[dataHash]; lockOracleAdapter(); } /// @notice Generates a data hash used for uniquely identifying asset allocations /// @param data the data hash containing the target address and the bytes lookup data /// @return returns the resulting bytes32 hash of the abi encode packed target address and bytes look up data function generateDataHash(Data memory data) public pure override returns (bytes32) { return keccak256(abi.encodePacked(data.target, data.data)); } /// @notice determines if a target address and bytes lookup data has already been registered /// @param data the data hash containing the target address and the bytes lookup data /// @return returns true if the asset allocation is currently registered, otherwise false function isAssetAllocationRegistered(Data memory data) public view override returns (bool) { return _isAssetAllocationRegistered(generateDataHash(data)); } /// @notice helper function for isAssetallocationRegistered function /// @param data the bytes32 hash /// @return returns true if the asset allocation is currently registered, otherwise false function _isAssetAllocationRegistered(bytes32 data) public view returns (bool) { return _allocationIds.contains(data); } /// @notice Returns a list of all identifiers where asset allocations have been registered /// @dev the list contains no duplicate identifiers /// @return list of all the registered identifiers function getAssetAllocationIds() external view override returns (bytes32[] memory) { uint256 length = _allocationIds.length(); bytes32[] memory allocationIds = new bytes32[](length); for (uint256 i = 0; i < length; i++) { allocationIds[i] = _allocationIds.at(i); } return allocationIds; } /// @notice Executes the bytes lookup data registered under an id /// @dev The balance of an id may be aggregated from multiple contracts /// @param allocationId the id to fetch the balance for /// @return returns the result of the executed lookup data registered for the provided id function balanceOf(bytes32 allocationId) external view override returns (uint256) { require( _isAssetAllocationRegistered(allocationId), "INVALID_ALLOCATION_ID" ); Data memory data = _allocationData[allocationId]; bytes memory returnData = executeView(data); uint256 _balance; assembly { _balance := mload(add(returnData, 0x20)) } return _balance; } /// @notice Returns the token symbol registered under an id /// @param allocationId the id to fetch the token for /// @return returns the result of the token symbol registered for the provided id function symbolOf(bytes32 allocationId) external view override returns (string memory) { return _allocationSymbols[allocationId]; } /// @notice Returns the decimals registered under an id /// @param allocationId the id to fetch the decimals for /// @return returns the result of the decimal value registered for the provided id function decimalsOf(bytes32 allocationId) external view override returns (uint256) { return _allocationDecimals[allocationId]; } /// @notice Executes data's bytes look up data against data's target address /// @dev execution is a static call /// @param data the data hash containing the target address and the bytes lookup data to execute /// @return returnData returns return data from the executed contract function executeView(Data memory data) public view returns (bytes memory returnData) { returnData = data.target.functionStaticCall(data.data); } /** * @notice Sets the address registry * @dev only callable by owner * @param _addressRegistry the address of the registry */ function setAddressRegistry(address _addressRegistry) public onlyOwner { require(Address.isContract(_addressRegistry), "INVALID_ADDRESS"); addressRegistry = IAddressRegistryV2(_addressRegistry); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; /** * @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. */ /* solhint-disable */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.11; /// @title Interface to Access APY.Finance's Asset Allocations /// @author APY.Finance /// @notice Enables 3rd Parties (ie. Chainlink) to pull relevant asset allocations /// in order to compute the TVL across the entire APY.Finance system. interface IAssetAllocation { /// @notice Returns a list of all identifiers where asset allocations have been registered /// @dev the list contains no duplicate identifiers /// @return list of all the registered identifiers function getAssetAllocationIds() external view returns (bytes32[] memory); /// @notice Executes the bytes lookup data registered under an id /// @dev The balance of an id may be aggregated from multiple contracts /// @param allocationId the id to fetch the balance for /// @return returns the result of the executed lookup data registered for the provided id function balanceOf(bytes32 allocationId) external view returns (uint256); /// @notice Returns the token symbol registered under an id /// @param allocationId the id to fetch the token for /// @return returns the result of the token symbol registered for the provided id function symbolOf(bytes32 allocationId) external view returns (string memory); /// @notice Returns the decimals registered under an id /// @param allocationId the id to fetch the decimals for /// @return returns the result of the decimal value registered for the provided id function decimalsOf(bytes32 allocationId) external view returns (uint256); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.11; pragma experimental ABIEncoderV2; /** * @title Interface for addition and removal of asset allocations for account deployments * @author APY.Finance * @notice These functions enable external systems to pull necessary info * to compute the TVL of the APY.Finance system. */ interface ITVLManager { // struct representing a view call execution against a target contract given bytes // target is the target contract to execute view calls against // bytes data represents the encoded function signature + parameters struct Data { address target; bytes data; } // struct representing the relevant pieces of data that need to be provided when registering an asset allocation // symbol is the symbol of the token that the resulting view call execution will need to be evaluated as // decimals is the number of decimals that the resulting view call execution will need to be evaluated as // data is the struct representing the view call execution struct AssetAllocation { string symbol; uint256 decimals; Data data; } function addAssetAllocation( Data calldata data, string calldata symbol, uint256 decimals ) external; function removeAssetAllocation(Data calldata data) external; function generateDataHash(Data calldata data) external pure returns (bytes32); function isAssetAllocationRegistered(Data calldata data) external view returns (bool); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.11; interface IOracleAdapter { struct Value { uint256 value; uint256 periodEnd; } function setTvl(uint256 value, uint256 period) external; function setAssetValue( address asset, uint256 value, uint256 period ) external; function lock() external; function defaultLockPeriod() external returns (uint256 period); function setDefaultLockPeriod(uint256 period) external; function lockFor(uint256 period) external; function unlock() external; function getAssetPrice(address asset) external view returns (uint256); function getTvl() external view returns (uint256); function isLocked() external view returns (bool); } // SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.11; /** * @title Interface to access APY.Finance's address registry * @author APY.Finance * @notice The address registry has two important purposes, one which * is fairly concrete and another abstract. * * 1. The registry enables components of the APY.Finance system * and external systems to retrieve core addresses reliably * even when the functionality may move to a different * address. * * 2. The registry also makes explicit which contracts serve * as primary entrypoints for interacting with different * components. Not every contract is registered here, only * the ones properly deserving of an identifier. This helps * define explicit boundaries between groups of contracts, * each of which is logically cohesive. */ interface IAddressRegistryV2 { /** * @notice Returns the list of identifiers for core components of * the APY.Finance system. * @return List of identifiers */ function getIds() external view returns (bytes32[] memory); /** * @notice Returns the current address represented by an identifier * for a core component. * @param id Component identifier * @return The current address represented by an identifier */ function getAddress(bytes32 id) external view returns (address); function poolManagerAddress() external view returns (address); function tvlManagerAddress() external view returns (address); function chainlinkRegistryAddress() external view returns (address); function daiPoolAddress() external view returns (address); function usdcPoolAddress() external view returns (address); function usdtPoolAddress() external view returns (address); function mAptAddress() external view returns (address); function lpSafeAddress() external view returns (address); function oracleAdapterAddress() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } }
Interface to Access APY.Finance's Asset Allocations APY.Finance Enables 3rd Parties (ie. Chainlink) to pull relevant asset allocations in order to compute the TVL across the entire APY.Finance system.
interface IAssetAllocation { function getAssetAllocationIds() external view returns (bytes32[] memory); function balanceOf(bytes32 allocationId) external view returns (uint256); function symbolOf(bytes32 allocationId) external view returns (string memory); function decimalsOf(bytes32 allocationId) external view returns (uint256); pragma solidity 0.6.11; }
195,619
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "./Ownable.sol"; import "./SafeMath.sol"; /** * @notice Stakeable is a contract who is ment to be inherited by other contract that wants Staking capabilities */ contract Stakeable is Ownable{ // we don't want to have any security issues using SafeMath for uint256; /** * @notice Constructor since this contract is not ment to be used without inheritance * push once to stakeholders for it to work proplerly */ constructor() { // This push is needed so we avoid index 0 causing bug of index-1 stakeholders.push(); // populate rewards _rewards.push(uint(200)); // 2.00% per month _rewards.push(uint(300)); // 3.00% per month _rewards.push(uint(500)); // 5.00% per month _rewards.push(uint(700)); // 7.00% per month _rewards.push(uint(900)); // 8.00%s per month // populate periods with monts _periods.push(uint(1)); _periods.push(uint(3)); _periods.push(uint(6)); _periods.push(uint(12)); } /** * @notice * A stake struct is used to represent the way we store stakes, * A Stake will contain the users address, the amount staked and a timestamp, * Since which is when the stake was made */ struct Stake{ address user; uint256 amount; uint256 since; uint8 period; // this represent the stake interval // values 0 - 1 month, 1 - 3 months, 2 - 6 months, 3 - 12 months // This claimable field is new and used to tell how big of a reward is currently available uint256 claimable; } /** * @notice Stakeholder is a staker that has active stakes */ struct Stakeholder{ address user; Stake[] address_stakes; } /* * StakingSummary is a struct that is used to contain all stakes performed by a certain account */ struct StakingSummary{ uint256 total_amount; Stake[] stakes; } uint[] private _rewards; uint[] private _periods; /** * @notice * This is a array where we store all Stakes that are performed on the Contract * The stakes for each address are stored at a certain index, the index can be found using the stakes mapping */ Stakeholder[] internal stakeholders; /** * @notice * stakes is used to keep track of the INDEX for the stakers in the stakes array */ mapping(address => uint256) internal stakes; /** * @notice Staked event is triggered whenever a user stakes tokens, address is indexed to make it filterable */ event Staked(address indexed user, uint256 amount, uint256 index, uint256 timestamp); /** * @notice getReward will get the reward value for a specific period */ function getReward(uint8 index) public view returns (uint) { return _rewards[index]; } /** * @notice setReward will set a specific value for index */ function setReward(uint8 index, uint value) external onlyOwner{ _rewards[index] = value; } /** * @notice getRewards will get the reward value for a specific period */ function getRewards() public view returns (uint[] memory) { return _rewards; } /** * @notice getPeriod will get the period in months for a specific index */ function getPeriod(uint8 index) public view returns (uint) { return _periods[index]; } /** * @notice setPeriod will get the period in months for a specific index */ function setPeriod(uint8 index, uint value) external onlyOwner{ _periods[index] = value; } /** * @notice getPeriods willreturn all periods */ function getPeriods() public view returns (uint[] memory) { return _periods; } /** * @notice _addStakeholder takes care of adding a stakeholder to the stakeholders array */ function _addStakeholder(address staker) internal returns (uint256){ // Push a empty item to the Array to make space for our new stakeholder stakeholders.push(); // Calculate the index of the last item in the array by Len-1 uint256 userIndex = stakeholders.length - 1; // Assign the address to the new index stakeholders[userIndex].user = staker; // Add index to the stakeHolders stakes[staker] = userIndex; return userIndex; } /** * @notice * _Stake is used to make a stake for an sender. It will remove the amount staked from the stakers account and place those tokens inside a stake container * StakeID */ function _stake(uint256 _amount, uint8 _period) internal{ // Simple check so that user does not stake 0 require(_amount > 0, "Cannot stake nothing"); // Mappings in solidity creates all values, but empty, so we can just check the address uint256 index = stakes[msg.sender]; // block.timestamp = timestamp of the current block in seconds since the epoch uint256 timestamp = block.timestamp; // See if the staker already has a staked index or if its the first time if(index == 0){ // This stakeholder stakes for the first time // We need to add him to the stakeHolders and also map it into the Index of the stakes // The index returned will be the index of the stakeholder in the stakeholders array index = _addStakeholder(msg.sender); } // Use the index to push a new Stake // push a newly created Stake with the current block timestamp. stakeholders[index].address_stakes.push(Stake(msg.sender, _amount, timestamp, _period, 0)); // Emit an event that the stake has occured emit Staked(msg.sender, _amount, index,timestamp); } /** * @notice * calculateStakeReward is used to calculate how much a user should be rewarded for their stakes * for the duration of the stake */ function calculateStakeReward(Stake memory _current_stake) internal view returns(uint256){ // first we check if we have the right to withdraw the stake by period uint8 periodIndex = _current_stake.period; uint reward = getReward(periodIndex); uint period = getPeriod(periodIndex); require (period>0, "We cannot stake for a 0 period"); require (reward>0, "We cannot stake for 0 reward"); uint256 divStake = _current_stake.amount.div(100); uint256 divReward = reward.div(100); uint256 stakeReward = divStake.mul(divReward).mul(period); require (stakeReward>0, "The reward is 0 (not ok)"); return stakeReward; } /** * @notice * withdrawStake takes in an amount and a index of the stake and will remove tokens from that stake * Notice index of the stake is the users stake counter, starting at 0 for the first stake * Will return the amount to MINT onto the acount * Will also calculateStakeReward and reset timer */ function _withdrawStake(uint256 amount, uint256 index) internal returns(uint256){ // Grab user_index which is the index to use to grab the Stake[] uint256 user_index = stakes[msg.sender]; Stake memory current_stake = stakeholders[user_index].address_stakes[index]; require(current_stake.amount >= amount, "Staking: Cannot withdraw more than you have staked"); // check to see if the stake is locked uint stakeAge = (block.timestamp - current_stake.since)/(3600*24*30); // number of months uint period = getPeriod(current_stake.period); require (stakeAge >= period, "Stake is locked for the initial defined period"); // Calculate available Reward first before we start modifying data uint256 reward = calculateStakeReward(current_stake); // Remove by subtracting the money unstaked current_stake.amount = current_stake.amount - amount; // If stake is empty, 0, then remove it from the array of stakes if (current_stake.amount == 0){ delete stakeholders[user_index].address_stakes[index]; } else { // If not empty then replace the value of it stakeholders[user_index].address_stakes[index].amount = current_stake.amount; // Reset timer of stake stakeholders[user_index].address_stakes[index].since = block.timestamp; } return amount+reward; } /** * @notice * hasStake is used to check if a account has stakes and the total amount along with all the seperate stakes */ function hasStake(address _staker) public view returns(StakingSummary memory){ // totalStakeAmount is used to count total staked amount of the address uint256 totalStakeAmount; // Keep a summary in memory since we need to calculate this StakingSummary memory summary = StakingSummary(0, stakeholders[stakes[_staker]].address_stakes); // Itterate all stakes and grab amount of stakes for (uint256 s = 0; s < summary.stakes.length; s += 1){ uint256 availableReward = calculateStakeReward(summary.stakes[s]); summary.stakes[s].claimable = availableReward; totalStakeAmount = totalStakeAmount+summary.stakes[s].amount; } // Assign calculate amount to summary summary.total_amount = totalStakeAmount; return summary; } }
getReward will get the reward value for a specific period/
function getReward(uint8 index) public view returns (uint) { return _rewards[index]; }
14,084,103
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.6; import "@yield-protocol/utils-v2/contracts/token/IERC20.sol"; import "@yield-protocol/utils-v2/contracts/token/IERC20Metadata.sol"; import "@yield-protocol/utils-v2/contracts/token/ERC20Permit.sol"; import "@yield-protocol/utils-v2/contracts/token/SafeERC20Namer.sol"; import "@yield-protocol/utils-v2/contracts/token/MinimalTransferHelper.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU256U128.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU256U112.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU256I256.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU128U112.sol"; import "@yield-protocol/utils-v2/contracts/cast/CastU128I128.sol"; import "@yield-protocol/yieldspace-interfaces/IPool.sol"; import "@yield-protocol/yieldspace-interfaces/IPoolFactory.sol"; import "@yield-protocol/vault-interfaces/IFYToken.sol"; import "./YieldMath.sol"; /// @dev The Pool contract exchanges base for fyToken at a price defined by a specific formula. contract Pool is IPool, ERC20Permit { using CastU256U128 for uint256; using CastU256U112 for uint256; using CastU256I256 for uint256; using CastU128U112 for uint128; using CastU128I128 for uint128; using MinimalTransferHelper for IERC20; event Trade(uint32 maturity, address indexed from, address indexed to, int256 bases, int256 fyTokens); event Liquidity(uint32 maturity, address indexed from, address indexed to, address indexed fyTokenTo, int256 bases, int256 fyTokens, int256 poolTokens); event Sync(uint112 baseCached, uint112 fyTokenCached, uint256 cumulativeBalancesRatio); int128 public immutable override ts; // 1 / Seconds in 10 years, in 64.64 int128 public immutable override g1; // To be used when selling base to the pool int128 public immutable override g2; // To be used when selling fyToken to the pool uint32 public immutable override maturity; uint96 public immutable override scaleFactor; // Scale up to 18 low decimal tokens to get the right precision in YieldMath IERC20 public immutable override base; IFYToken public immutable override fyToken; uint112 private baseCached; // uses single storage slot, accessible via getCache uint112 private fyTokenCached; // uses single storage slot, accessible via getCache uint32 private blockTimestampLast; // uses single storage slot, accessible via getCache uint256 public cumulativeBalancesRatio; // Fixed point factor with 27 decimals (ray) constructor() ERC20Permit( string(abi.encodePacked("Yield ", SafeERC20Namer.tokenName(IPoolFactory(msg.sender).nextFYToken()), " LP Token")), string(abi.encodePacked(SafeERC20Namer.tokenSymbol(IPoolFactory(msg.sender).nextFYToken()), "LP")), SafeERC20Namer.tokenDecimals(IPoolFactory(msg.sender).nextBase()) ) { IPoolFactory _factory = IPoolFactory(msg.sender); IFYToken _fyToken = IFYToken(_factory.nextFYToken()); IERC20 _base = IERC20(_factory.nextBase()); fyToken = _fyToken; base = _base; uint256 _maturity = _fyToken.maturity(); require (_maturity <= type(uint32).max, "Pool: Maturity too far in the future"); maturity = uint32(_maturity); ts = _factory.ts(); g1 = _factory.g1(); g2 = _factory.g2(); scaleFactor = uint96(10 ** (18 - SafeERC20Namer.tokenDecimals(address(_base)))); } /// @dev Trading can only be done before maturity modifier beforeMaturity() { require( block.timestamp < maturity, "Pool: Too late" ); _; } // ---- Balances management ---- /// @dev Updates the cache to match the actual balances. function sync() external { _update(_getBaseBalance(), _getFYTokenBalance(), baseCached, fyTokenCached); } /// @dev Returns the cached balances & last updated timestamp. /// @return Cached base token balance. /// @return Cached virtual FY token balance. /// @return Timestamp that balances were last cached. function getCache() external view override returns (uint112, uint112, uint32) { return (baseCached, fyTokenCached, blockTimestampLast); } /// @dev Returns the "virtual" fyToken balance, which is the real balance plus the pool token supply. function getFYTokenBalance() public view override returns(uint112) { return _getFYTokenBalance(); } /// @dev Returns the base balance function getBaseBalance() public view override returns(uint112) { return _getBaseBalance(); } /// @dev Returns the "virtual" fyToken balance, which is the real balance plus the pool token supply. function _getFYTokenBalance() internal view returns(uint112) { return (fyToken.balanceOf(address(this)) + _totalSupply).u112(); } /// @dev Returns the base balance function _getBaseBalance() internal view returns(uint112) { return base.balanceOf(address(this)).u112(); } /// @dev Retrieve any base tokens not accounted for in the cache function retrieveBase(address to) external override returns(uint128 retrieved) { retrieved = _getBaseBalance() - baseCached; // Cache can never be above balances base.safeTransfer(to, retrieved); // Now the current balances match the cache, so no need to update the TWAR } /// @dev Retrieve any fyTokens not accounted for in the cache function retrieveFYToken(address to) external override returns(uint128 retrieved) { retrieved = _getFYTokenBalance() - fyTokenCached; // Cache can never be above balances IERC20(address(fyToken)).safeTransfer(to, retrieved); // Now the balances match the cache, so no need to update the TWAR } /// @dev Update cache and, on the first call per block, ratio accumulators function _update(uint128 baseBalance, uint128 fyBalance, uint112 _baseCached, uint112 _fyTokenCached) private { uint32 blockTimestamp = uint32(block.timestamp); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired if (timeElapsed > 0 && _baseCached != 0 && _fyTokenCached != 0) { // We multiply by 1e27 here so that r = t * y/x is a fixed point factor with 27 decimals uint256 scaledFYTokenCached = uint256(_fyTokenCached) * 1e27; cumulativeBalancesRatio += scaledFYTokenCached * timeElapsed / _baseCached; } baseCached = baseBalance.u112(); fyTokenCached = fyBalance.u112(); blockTimestampLast = blockTimestamp; emit Sync(baseCached, fyTokenCached, cumulativeBalancesRatio); } // ---- Liquidity ---- /// @dev Mint liquidity tokens in exchange for adding base and fyToken /// The amount of liquidity tokens to mint is calculated from the amount of unaccounted for fyToken in this contract. /// A proportional amount of base tokens need to be present in this contract, also unaccounted for. /// @param to Wallet receiving the minted liquidity tokens. /// @param remainder Wallet receiving any surplus base. /// @param minRatio Minimum ratio of base to fyToken in the pool. /// @param maxRatio Maximum ratio of base to fyToken in the pool. /// @return The amount of liquidity tokens minted. function mint(address to, address remainder, uint256 minRatio, uint256 maxRatio) external override returns (uint256, uint256, uint256) { return _mintInternal(to, remainder, 0, minRatio, maxRatio); } /// @dev Mint liquidity tokens in exchange for adding only base /// The amount of liquidity tokens is calculated from the amount of fyToken to buy from the pool, /// plus the amount of unaccounted for fyToken in this contract. /// The base tokens need to be present in this contract, unaccounted for. /// @param to Wallet receiving the minted liquidity tokens. /// @param remainder Wallet receiving any surplus base. /// @param fyTokenToBuy Amount of `fyToken` being bought in the Pool, from this we calculate how much base it will be taken in. /// @param minRatio Minimum ratio of base to fyToken in the pool. /// @param maxRatio Maximum ratio of base to fyToken in the pool. /// @return The amount of liquidity tokens minted. function mintWithBase(address to, address remainder, uint256 fyTokenToBuy, uint256 minRatio, uint256 maxRatio) external override returns (uint256, uint256, uint256) { return _mintInternal(to, remainder, fyTokenToBuy, minRatio, maxRatio); } /// @dev Mint liquidity tokens, with an optional internal trade to buy fyToken beforehand. /// The amount of liquidity tokens is calculated from the amount of fyToken to buy from the pool, /// plus the amount of unaccounted for fyToken in this contract. /// The base tokens need to be present in this contract, unaccounted for. /// @param to Wallet receiving the minted liquidity tokens. /// @param remainder Wallet receiving any surplus base. /// @param fyTokenToBuy Amount of `fyToken` being bought in the Pool, from this we calculate how much base it will be taken in. /// @param minRatio Minimum ratio of base to fyToken in the pool. /// @param maxRatio Minimum ratio of base to fyToken in the pool. function _mintInternal(address to, address remainder, uint256 fyTokenToBuy, uint256 minRatio, uint256 maxRatio) internal returns (uint256 baseIn, uint256 fyTokenIn, uint256 tokensMinted) { // Gather data uint256 supply = _totalSupply; (uint112 _baseCached, uint112 _fyTokenCached) = (baseCached, fyTokenCached); uint256 _realFYTokenCached = _fyTokenCached - supply; // The fyToken cache includes the virtual fyToken, equal to the supply uint256 baseBalance = base.balanceOf(address(this)); uint256 fyTokenBalance = fyToken.balanceOf(address(this)); uint256 baseAvailable = baseBalance - _baseCached; // Check the burn wasn't sandwiched require ( _realFYTokenCached == 0 || ( uint256(_baseCached) * 1e18 / _realFYTokenCached >= minRatio && uint256(_baseCached) * 1e18 / _realFYTokenCached <= maxRatio ), "Pool: Reserves ratio changed" ); // Calculate token amounts if (supply == 0) { // Initialize at 1 pool token minted per base token supplied baseIn = baseAvailable; tokensMinted = baseIn; } else if (_realFYTokenCached == 0) { // Edge case, no fyToken in the Pool after initialization baseIn = baseAvailable; tokensMinted = supply * baseIn / _baseCached; } else { // There is an optional virtual trade before the mint uint256 baseToSell; if (fyTokenToBuy > 0) { baseToSell = _buyFYTokenPreview( fyTokenToBuy.u128(), _baseCached, _fyTokenCached ); } // We use all the available fyTokens, plus a virtual trade if it happened, surplus is in base tokens fyTokenIn = fyTokenBalance - _realFYTokenCached; tokensMinted = (supply * (fyTokenToBuy + fyTokenIn)) / (_realFYTokenCached - fyTokenToBuy); baseIn = baseToSell + ((_baseCached + baseToSell) * tokensMinted) / supply; require(baseAvailable >= baseIn, "Pool: Not enough base token in"); } // Update TWAR _update( (_baseCached + baseIn).u128(), (_fyTokenCached + fyTokenIn + tokensMinted).u128(), // Account for the "virtual" fyToken from the new minted LP tokens _baseCached, _fyTokenCached ); // Execute mint _mint(to, tokensMinted); // Return any unused base if (baseAvailable - baseIn > 0) base.safeTransfer(remainder, baseAvailable - baseIn); emit Liquidity(maturity, msg.sender, to, address(0), -(baseIn.i256()), -(fyTokenIn.i256()), tokensMinted.i256()); } /// @dev Burn liquidity tokens in exchange for base and fyToken. /// The liquidity tokens need to be in this contract. /// @param baseTo Wallet receiving the base. /// @param fyTokenTo Wallet receiving the fyToken. /// @param minRatio Minimum ratio of base to fyToken in the pool. /// @param maxRatio Maximum ratio of base to fyToken in the pool. /// @return The amount of tokens burned and returned (tokensBurned, bases, fyTokens). function burn(address baseTo, address fyTokenTo, uint256 minRatio, uint256 maxRatio) external override returns (uint256, uint256, uint256) { return _burnInternal(baseTo, fyTokenTo, false, minRatio, maxRatio); } /// @dev Burn liquidity tokens in exchange for base. /// The liquidity provider needs to have called `pool.approve`. /// @param to Wallet receiving the base and fyToken. /// @param minRatio Minimum ratio of base to fyToken in the pool. /// @param maxRatio Minimum ratio of base to fyToken in the pool. /// @return tokensBurned The amount of lp tokens burned. /// @return baseOut The amount of base tokens returned. function burnForBase(address to, uint256 minRatio, uint256 maxRatio) external override returns (uint256 tokensBurned, uint256 baseOut) { (tokensBurned, baseOut, ) = _burnInternal(to, address(0), true, minRatio, maxRatio); } /// @dev Burn liquidity tokens in exchange for base. /// The liquidity provider needs to have called `pool.approve`. /// @param baseTo Wallet receiving the base. /// @param fyTokenTo Wallet receiving the fyToken. /// @param tradeToBase Whether the resulting fyToken should be traded for base tokens. /// @param minRatio Minimum ratio of base to fyToken in the pool. /// @param maxRatio Minimum ratio of base to fyToken in the pool. /// @return tokensBurned The amount of pool tokens burned. /// @return tokenOut The amount of base tokens returned. /// @return fyTokenOut The amount of fyTokens returned. function _burnInternal(address baseTo, address fyTokenTo, bool tradeToBase, uint256 minRatio, uint256 maxRatio) internal returns (uint256 tokensBurned, uint256 tokenOut, uint256 fyTokenOut) { // Gather data tokensBurned = _balanceOf[address(this)]; uint256 supply = _totalSupply; (uint112 _baseCached, uint112 _fyTokenCached) = (baseCached, fyTokenCached); uint256 _realFYTokenCached = _fyTokenCached - supply; // The fyToken cache includes the virtual fyToken, equal to the supply // Check the burn wasn't sandwiched require ( _realFYTokenCached == 0 || ( uint256(_baseCached) * 1e18 / _realFYTokenCached >= minRatio && uint256(_baseCached) * 1e18 / _realFYTokenCached <= maxRatio ), "Pool: Reserves ratio changed" ); // Calculate trade tokenOut = (tokensBurned * _baseCached) / supply; fyTokenOut = (tokensBurned * _realFYTokenCached) / supply; if (tradeToBase) { tokenOut += YieldMath.baseOutForFYTokenIn( // This is a virtual sell (_baseCached - tokenOut.u128()) * scaleFactor, // Cache, minus virtual burn (_fyTokenCached - fyTokenOut.u128()) * scaleFactor, // Cache, minus virtual burn fyTokenOut.u128() * scaleFactor, // Sell the virtual fyToken obtained maturity - uint32(block.timestamp), // This can't be called after maturity ts, g2 ) / scaleFactor; fyTokenOut = 0; } // Update TWAR _update( (_baseCached - tokenOut).u128(), (_fyTokenCached - fyTokenOut - tokensBurned).u128(), _baseCached, _fyTokenCached ); // Transfer assets _burn(address(this), tokensBurned); base.safeTransfer(baseTo, tokenOut); if (fyTokenOut > 0) IERC20(address(fyToken)).safeTransfer(fyTokenTo, fyTokenOut); emit Liquidity(maturity, msg.sender, baseTo, fyTokenTo, tokenOut.i256(), fyTokenOut.i256(), -(tokensBurned.i256())); } // ---- Trading ---- /// @dev Sell base for fyToken. /// The trader needs to have transferred the amount of base to sell to the pool before in the same transaction. /// @param to Wallet receiving the fyToken being bought /// @param min Minimm accepted amount of fyToken /// @return Amount of fyToken that will be deposited on `to` wallet function sellBase(address to, uint128 min) external override returns(uint128) { // Calculate trade (uint112 _baseCached, uint112 _fyTokenCached) = (baseCached, fyTokenCached); uint112 _baseBalance = _getBaseBalance(); uint112 _fyTokenBalance = _getFYTokenBalance(); uint128 baseIn = _baseBalance - _baseCached; uint128 fyTokenOut = _sellBasePreview( baseIn, _baseCached, _fyTokenBalance ); // Slippage check require( fyTokenOut >= min, "Pool: Not enough fyToken obtained" ); // Update TWAR _update( _baseBalance, _fyTokenBalance - fyTokenOut, _baseCached, _fyTokenCached ); // Transfer assets IERC20(address(fyToken)).safeTransfer(to, fyTokenOut); emit Trade(maturity, msg.sender, to, -(baseIn.i128()), fyTokenOut.i128()); return fyTokenOut; } /// @dev Returns how much fyToken would be obtained by selling `baseIn` base /// @param baseIn Amount of base hypothetically sold. /// @return Amount of fyToken hypothetically bought. function sellBasePreview(uint128 baseIn) external view override returns(uint128) { (uint112 _baseCached, uint112 _fyTokenCached) = (baseCached, fyTokenCached); return _sellBasePreview(baseIn, _baseCached, _fyTokenCached); } /// @dev Returns how much fyToken would be obtained by selling `baseIn` base function _sellBasePreview( uint128 baseIn, uint112 baseBalance, uint112 fyTokenBalance ) private view beforeMaturity returns(uint128) { uint128 fyTokenOut = YieldMath.fyTokenOutForBaseIn( baseBalance * scaleFactor, fyTokenBalance * scaleFactor, baseIn * scaleFactor, maturity - uint32(block.timestamp), // This can't be called after maturity ts, g1 ) / scaleFactor; require( fyTokenBalance - fyTokenOut >= baseBalance + baseIn, "Pool: fyToken balance too low" ); return fyTokenOut; } /// @dev Buy base for fyToken /// The trader needs to have called `fyToken.approve` /// @param to Wallet receiving the base being bought /// @param tokenOut Amount of base being bought that will be deposited in `to` wallet /// @param max Maximum amount of fyToken that will be paid for the trade /// @return Amount of fyToken that will be taken from caller function buyBase(address to, uint128 tokenOut, uint128 max) external override returns(uint128) { // Calculate trade uint128 fyTokenBalance = _getFYTokenBalance(); (uint112 _baseCached, uint112 _fyTokenCached) = (baseCached, fyTokenCached); uint128 fyTokenIn = _buyBasePreview( tokenOut, _baseCached, _fyTokenCached ); require( fyTokenBalance - _fyTokenCached >= fyTokenIn, "Pool: Not enough fyToken in" ); // Slippage check require( fyTokenIn <= max, "Pool: Too much fyToken in" ); // Update TWAR _update( _baseCached - tokenOut, _fyTokenCached + fyTokenIn, _baseCached, _fyTokenCached ); // Transfer assets base.safeTransfer(to, tokenOut); emit Trade(maturity, msg.sender, to, tokenOut.i128(), -(fyTokenIn.i128())); return fyTokenIn; } /// @dev Returns how much fyToken would be required to buy `tokenOut` base. /// @param tokenOut Amount of base hypothetically desired. /// @return Amount of fyToken hypothetically required. function buyBasePreview(uint128 tokenOut) external view override returns(uint128) { (uint112 _baseCached, uint112 _fyTokenCached) = (baseCached, fyTokenCached); return _buyBasePreview(tokenOut, _baseCached, _fyTokenCached); } /// @dev Returns how much fyToken would be required to buy `tokenOut` base. function _buyBasePreview( uint128 tokenOut, uint112 baseBalance, uint112 fyTokenBalance ) private view beforeMaturity returns(uint128) { return YieldMath.fyTokenInForBaseOut( baseBalance * scaleFactor, fyTokenBalance * scaleFactor, tokenOut * scaleFactor, maturity - uint32(block.timestamp), // This can't be called after maturity ts, g2 ) / scaleFactor; } /// @dev Sell fyToken for base /// The trader needs to have transferred the amount of fyToken to sell to the pool before in the same transaction. /// @param to Wallet receiving the base being bought /// @param min Minimm accepted amount of base /// @return Amount of base that will be deposited on `to` wallet function sellFYToken(address to, uint128 min) external override returns(uint128) { // Calculate trade (uint112 _baseCached, uint112 _fyTokenCached) = (baseCached, fyTokenCached); uint112 _fyTokenBalance = _getFYTokenBalance(); uint112 _baseBalance = _getBaseBalance(); uint128 fyTokenIn = _fyTokenBalance - _fyTokenCached; uint128 baseOut = _sellFYTokenPreview( fyTokenIn, _baseCached, _fyTokenCached ); // Slippage check require( baseOut >= min, "Pool: Not enough base obtained" ); // Update TWAR _update( _baseBalance - baseOut, _fyTokenBalance, _baseCached, _fyTokenCached ); // Transfer assets base.safeTransfer(to, baseOut); emit Trade(maturity, msg.sender, to, baseOut.i128(), -(fyTokenIn.i128())); return baseOut; } /// @dev Returns how much base would be obtained by selling `fyTokenIn` fyToken. /// @param fyTokenIn Amount of fyToken hypothetically sold. /// @return Amount of base hypothetically bought. function sellFYTokenPreview(uint128 fyTokenIn) external view override returns(uint128) { (uint112 _baseCached, uint112 _fyTokenCached) = (baseCached, fyTokenCached); return _sellFYTokenPreview(fyTokenIn, _baseCached, _fyTokenCached); } /// @dev Returns how much base would be obtained by selling `fyTokenIn` fyToken. function _sellFYTokenPreview( uint128 fyTokenIn, uint112 baseBalance, uint112 fyTokenBalance ) private view beforeMaturity returns(uint128) { return YieldMath.baseOutForFYTokenIn( baseBalance * scaleFactor, fyTokenBalance * scaleFactor, fyTokenIn * scaleFactor, maturity - uint32(block.timestamp), // This can't be called after maturity ts, g2 ) / scaleFactor; } /// @dev Buy fyToken for base /// The trader needs to have called `base.approve` /// @param to Wallet receiving the fyToken being bought /// @param fyTokenOut Amount of fyToken being bought that will be deposited in `to` wallet /// @param max Maximum amount of base token that will be paid for the trade /// @return Amount of base that will be taken from caller's wallet function buyFYToken(address to, uint128 fyTokenOut, uint128 max) external override returns(uint128) { // Calculate trade uint128 baseBalance = _getBaseBalance(); (uint112 _baseCached, uint112 _fyTokenCached) = (baseCached, fyTokenCached); uint128 baseIn = _buyFYTokenPreview( fyTokenOut, _baseCached, _fyTokenCached ); require( baseBalance - _baseCached >= baseIn, "Pool: Not enough base token in" ); // Slippage check require( baseIn <= max, "Pool: Too much base token in" ); // Update TWAR _update( _baseCached + baseIn, _fyTokenCached - fyTokenOut, _baseCached, _fyTokenCached ); // Transfer assets IERC20(address(fyToken)).safeTransfer(to, fyTokenOut); emit Trade(maturity, msg.sender, to, -(baseIn.i128()), fyTokenOut.i128()); return baseIn; } /// @dev Returns how much base would be required to buy `fyTokenOut` fyToken. /// @param fyTokenOut Amount of fyToken hypothetically desired. /// @return Amount of base hypothetically required. function buyFYTokenPreview(uint128 fyTokenOut) external view override returns(uint128) { (uint112 _baseCached, uint112 _fyTokenCached) = (baseCached, fyTokenCached); return _buyFYTokenPreview(fyTokenOut, _baseCached, _fyTokenCached); } /// @dev Returns how much base would be required to buy `fyTokenOut` fyToken. function _buyFYTokenPreview( uint128 fyTokenOut, uint128 baseBalance, uint128 fyTokenBalance ) private view beforeMaturity returns(uint128) { uint128 baseIn = YieldMath.baseInForFYTokenOut( baseBalance * scaleFactor, fyTokenBalance * scaleFactor, fyTokenOut * scaleFactor, maturity - uint32(block.timestamp), // This can't be called after maturity ts, g1 ) / scaleFactor; require( fyTokenBalance - fyTokenOut >= baseBalance + baseIn, "Pool: fyToken balance too low" ); return baseIn; } } // 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 // Taken from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/extensions/IERC20Metadata.sol pragma solidity ^0.8.0; import "./IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // Adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/53516bc555a454862470e7860a9b5254db4d00f5/contracts/token/ERC20/ERC20Permit.sol pragma solidity ^0.8.0; import "./ERC20.sol"; import "./IERC2612.sol"; /** * @dev Extension of {ERC20} that allows token holders to use their tokens * without sending any transactions by setting {IERC20-allowance} with a * signature using the {permit} method, and then spend them via * {IERC20-transferFrom}. * * The {permit} signature mechanism conforms to the {IERC2612} interface. */ abstract contract ERC20Permit is ERC20, IERC2612 { mapping (address => uint256) public override nonces; bytes32 public immutable PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 private immutable _DOMAIN_SEPARATOR; uint256 public immutable deploymentChainId; constructor(string memory name_, string memory symbol_, uint8 decimals_) ERC20(name_, symbol_, decimals_) { deploymentChainId = block.chainid; _DOMAIN_SEPARATOR = _calculateDomainSeparator(block.chainid); } /// @dev Calculate the DOMAIN_SEPARATOR. function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32) { return keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes(version())), chainId, address(this) ) ); } /// @dev Return the DOMAIN_SEPARATOR. function DOMAIN_SEPARATOR() external view returns (bytes32) { return block.chainid == deploymentChainId ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(block.chainid); } /// @dev Setting the version as a function so that it can be overriden function version() public pure virtual returns(string memory) { return "1"; } /** * @dev See {IERC2612-permit}. * * In cases where the free option is not a concern, deadline can simply be * set to uint(-1), so it should be seen as an optional parameter */ function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external virtual override { require(deadline >= block.timestamp, "ERC20Permit: expired deadline"); bytes32 hashStruct = keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline ) ); bytes32 hash = keccak256( abi.encodePacked( "\x19\x01", block.chainid == deploymentChainId ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(block.chainid), hashStruct ) ); address signer = ecrecover(hash, v, r, s); require( signer != address(0) && signer == owner, "ERC20Permit: invalid signature" ); _setAllowance(owner, spender, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "../token/IERC20Metadata.sol"; import "../utils/AddressStringUtil.sol"; // produces token descriptors from inconsistent or absent ERC20 symbol implementations that can return string or bytes32 // this library will always produce a string symbol to represent the token library SafeERC20Namer { function bytes32ToString(bytes32 x) private pure returns (string memory) { bytes memory bytesString = new bytes(32); uint256 charCount = 0; for (uint256 j = 0; j < 32; j++) { bytes1 char = x[j]; if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (uint256 j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } // assumes the data is in position 2 function parseStringData(bytes memory b) private pure returns (string memory) { uint256 charCount = 0; // first parse the charCount out of the data for (uint256 i = 32; i < 64; i++) { charCount <<= 8; charCount += uint8(b[i]); } bytes memory bytesStringTrimmed = new bytes(charCount); for (uint256 i = 0; i < charCount; i++) { bytesStringTrimmed[i] = b[i + 64]; } return string(bytesStringTrimmed); } // uses a heuristic to produce a token name from the address // the heuristic returns the full hex of the address string in upper case function addressToName(address token) private pure returns (string memory) { return AddressStringUtil.toAsciiString(token, 40); } // uses a heuristic to produce a token symbol from the address // the heuristic returns the first 6 hex of the address string in upper case function addressToSymbol(address token) private pure returns (string memory) { return AddressStringUtil.toAsciiString(token, 6); } // calls an external view token contract method that returns a symbol or name, and parses the output into a string function callAndParseStringReturn(address token, bytes4 selector) private view returns (string memory) { (bool success, bytes memory data) = token.staticcall(abi.encodeWithSelector(selector)); // if not implemented, or returns empty data, return empty string if (!success || data.length == 0) { return ""; } // bytes32 data always has length 32 if (data.length == 32) { bytes32 decoded = abi.decode(data, (bytes32)); return bytes32ToString(decoded); } else if (data.length > 64) { return abi.decode(data, (string)); } return ""; } // attempts to extract the token symbol. if it does not implement symbol, returns a symbol derived from the address function tokenSymbol(address token) public view returns (string memory) { string memory symbol = callAndParseStringReturn(token, IERC20Metadata.symbol.selector); if (bytes(symbol).length == 0) { // fallback to 6 uppercase hex of address return addressToSymbol(token); } return symbol; } // attempts to extract the token name. if it does not implement name, returns a name derived from the address function tokenName(address token) public view returns (string memory) { string memory name = callAndParseStringReturn(token, IERC20Metadata.name.selector); if (bytes(name).length == 0) { // fallback to full hex of address return addressToName(token); } return name; } /// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value. /// @param token The address of the ERC-20 token contract. /// @return (uint8) Token decimals. function tokenDecimals(address token) public view returns (uint8) { (bool success, bytes memory data) = token.staticcall(abi.encodeWithSelector(IERC20Metadata.decimals.selector)); return success && data.length == 32 ? abi.decode(data, (uint8)) : 18; } } // SPDX-License-Identifier: MIT // Taken from https://github.com/Uniswap/uniswap-lib/blob/master/contracts/libraries/TransferHelper.sol pragma solidity >=0.6.0; import "./IERC20.sol"; import "../utils/RevertMsgExtractor.sol"; // helper methods for transferring ERC20 tokens that do not consistently return true/false library MinimalTransferHelper { /// @notice Transfers tokens from msg.sender to a recipient /// @dev Errors with the underlying revert message 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( IERC20 token, address to, uint256 value ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); if (!(success && (data.length == 0 || abi.decode(data, (bool))))) revert(RevertMsgExtractor.getRevertMsg(data)); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library CastU256U128 { /// @dev Safely cast an uint256 to an uint128 function u128(uint256 x) internal pure returns (uint128 y) { require (x <= type(uint128).max, "Cast overflow"); y = uint128(x); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library CastU256U112 { /// @dev Safely cast an uint256 to an uint112 function u112(uint256 x) internal pure returns (uint112 y) { require (x <= type(uint112).max, "Cast overflow"); y = uint112(x); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library CastU256I256 { /// @dev Safely cast an uint256 to an int256 function i256(uint256 x) internal pure returns (int256 y) { require (x <= uint256(type(int256).max), "Cast overflow"); y = int256(x); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library CastU128U112 { /// @dev Safely cast an uint128 to an uint112 function u112(uint128 x) internal pure returns (uint112 y) { require (x <= uint128(type(uint112).max), "Cast overflow"); y = uint112(x); } } // SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; library CastU128I128 { /// @dev Safely cast an uint128 to an int128 function i128(uint128 x) internal pure returns (int128 y) { require (x <= uint128(type(int128).max), "Cast overflow"); y = int128(x); } } // SPDX-License-Identifier: MIT pragma solidity >= 0.8.0; import "@yield-protocol/utils-v2/contracts/token/IERC20.sol"; import "@yield-protocol/utils-v2/contracts/token/IERC2612.sol"; import "@yield-protocol/vault-interfaces/IFYToken.sol"; interface IPool is IERC20, IERC2612 { function ts() external view returns(int128); function g1() external view returns(int128); function g2() external view returns(int128); function maturity() external view returns(uint32); function scaleFactor() external view returns(uint96); function getCache() external view returns (uint112, uint112, uint32); function base() external view returns(IERC20); function fyToken() external view returns(IFYToken); function getBaseBalance() external view returns(uint112); function getFYTokenBalance() external view returns(uint112); function retrieveBase(address to) external returns(uint128 retrieved); function retrieveFYToken(address to) external returns(uint128 retrieved); function sellBase(address to, uint128 min) external returns(uint128); function buyBase(address to, uint128 baseOut, uint128 max) external returns(uint128); function sellFYToken(address to, uint128 min) external returns(uint128); function buyFYToken(address to, uint128 fyTokenOut, uint128 max) external returns(uint128); function sellBasePreview(uint128 baseIn) external view returns(uint128); function buyBasePreview(uint128 baseOut) external view returns(uint128); function sellFYTokenPreview(uint128 fyTokenIn) external view returns(uint128); function buyFYTokenPreview(uint128 fyTokenOut) external view returns(uint128); function mint(address to, address remainder, uint256 minRatio, uint256 maxRatio) external returns (uint256, uint256, uint256); function mintWithBase(address to, address remainder, uint256 fyTokenToBuy, uint256 minRatio, uint256 maxRatio) external returns (uint256, uint256, uint256); function burn(address baseTo, address fyTokenTo, uint256 minRatio, uint256 maxRatio) external returns (uint256, uint256, uint256); function burnForBase(address to, uint256 minRatio, uint256 maxRatio) external returns (uint256, uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IPoolFactory { event PoolCreated(address indexed base, address indexed fyToken, address pool); function POOL_BYTECODE_HASH() external pure returns (bytes32); function calculatePoolAddress(address base, address fyToken) external view returns (address); function getPool(address base, address fyToken) external view returns (address); function createPool(address base, address fyToken) external returns (address); function nextBase() external view returns (address); function nextFYToken() external view returns (address); function ts() external view returns (int128); function g1() external view returns (int128); function g2() external view returns (int128); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@yield-protocol/utils-v2/contracts/token/IERC20.sol"; interface IFYToken is IERC20 { /// @dev Asset that is returned on redemption. function underlying() external view returns (address); /// @dev Unix time at which redemption of fyToken for underlying are possible function maturity() external view returns (uint256); /// @dev Record price data at maturity function mature() external; /// @dev Mint fyToken providing an equal amount of underlying to the protocol function mintWithUnderlying(address to, uint256 amount) external; /// @dev Burn fyToken after maturity for an amount of underlying. function redeem(address to, uint256 amount) external returns (uint256); /// @dev Mint fyToken. /// This function can only be called by other Yield contracts, not users directly. /// @param to Wallet to mint the fyToken in. /// @param fyTokenAmount Amount of fyToken to mint. function mint(address to, uint256 fyTokenAmount) external; /// @dev Burn fyToken. /// This function can only be called by other Yield contracts, not users directly. /// @param from Wallet to burn the fyToken from. /// @param fyTokenAmount Amount of fyToken to burn. function burn(address from, uint256 fyTokenAmount) external; } // SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.6; import "./Math64x64.sol"; library Exp64x64 { /** * Raise given number x into power specified as a simple fraction y/z and then * multiply the result by the normalization factor 2^(128 * (1 - y/z)). * Revert if z is zero, or if both x and y are zeros. * * @param x number to raise into given power y/z * @param y numerator of the power to raise x into * @param z denominator of the power to raise x into * @return x raised into power y/z and then multiplied by 2^(128 * (1 - y/z)) */ function pow(uint128 x, uint128 y, uint128 z) internal pure returns(uint128) { unchecked { require(z != 0); if(x == 0) { require(y != 0); return 0; } else { uint256 l = uint256(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - log_2(x)) * y / z; if(l > 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) return 0; else return pow_2(uint128(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - l)); } } } /** * Calculate base 2 logarithm of an unsigned 128-bit integer number. Revert * in case x is zero. * * @param x number to calculate base 2 logarithm of * @return base 2 logarithm of x, multiplied by 2^121 */ function log_2(uint128 x) internal pure returns(uint128) { unchecked { require(x != 0); uint b = x; uint l = 0xFE000000000000000000000000000000; if(b < 0x10000000000000000) {l -= 0x80000000000000000000000000000000; b <<= 64;} if(b < 0x1000000000000000000000000) {l -= 0x40000000000000000000000000000000; b <<= 32;} if(b < 0x10000000000000000000000000000) {l -= 0x20000000000000000000000000000000; b <<= 16;} if(b < 0x1000000000000000000000000000000) {l -= 0x10000000000000000000000000000000; b <<= 8;} if(b < 0x10000000000000000000000000000000) {l -= 0x8000000000000000000000000000000; b <<= 4;} if(b < 0x40000000000000000000000000000000) {l -= 0x4000000000000000000000000000000; b <<= 2;} if(b < 0x80000000000000000000000000000000) {l -= 0x2000000000000000000000000000000; b <<= 1;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000000;} /* b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x1000;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x800;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x400;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x200;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x100;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x80;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x40;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x20;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x10;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x8;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x4;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) {b >>= 1; l |= 0x2;} b = b * b >> 127; if(b >= 0x100000000000000000000000000000000) l |= 0x1; */ return uint128(l); } } /** * Calculate 2 raised into given power. * * @param x power to raise 2 into, multiplied by 2^121 * @return 2 raised into given power */ function pow_2(uint128 x) internal pure returns(uint128) { unchecked { uint r = 0x80000000000000000000000000000000; if(x & 0x1000000000000000000000000000000 > 0) r = r * 0xb504f333f9de6484597d89b3754abe9f >> 127; if(x & 0x800000000000000000000000000000 > 0) r = r * 0x9837f0518db8a96f46ad23182e42f6f6 >> 127; if(x & 0x400000000000000000000000000000 > 0) r = r * 0x8b95c1e3ea8bd6e6fbe4628758a53c90 >> 127; if(x & 0x200000000000000000000000000000 > 0) r = r * 0x85aac367cc487b14c5c95b8c2154c1b2 >> 127; if(x & 0x100000000000000000000000000000 > 0) r = r * 0x82cd8698ac2ba1d73e2a475b46520bff >> 127; if(x & 0x80000000000000000000000000000 > 0) r = r * 0x8164d1f3bc0307737be56527bd14def4 >> 127; if(x & 0x40000000000000000000000000000 > 0) r = r * 0x80b1ed4fd999ab6c25335719b6e6fd20 >> 127; if(x & 0x20000000000000000000000000000 > 0) r = r * 0x8058d7d2d5e5f6b094d589f608ee4aa2 >> 127; if(x & 0x10000000000000000000000000000 > 0) r = r * 0x802c6436d0e04f50ff8ce94a6797b3ce >> 127; if(x & 0x8000000000000000000000000000 > 0) r = r * 0x8016302f174676283690dfe44d11d008 >> 127; if(x & 0x4000000000000000000000000000 > 0) r = r * 0x800b179c82028fd0945e54e2ae18f2f0 >> 127; if(x & 0x2000000000000000000000000000 > 0) r = r * 0x80058baf7fee3b5d1c718b38e549cb93 >> 127; if(x & 0x1000000000000000000000000000 > 0) r = r * 0x8002c5d00fdcfcb6b6566a58c048be1f >> 127; if(x & 0x800000000000000000000000000 > 0) r = r * 0x800162e61bed4a48e84c2e1a463473d9 >> 127; if(x & 0x400000000000000000000000000 > 0) r = r * 0x8000b17292f702a3aa22beacca949013 >> 127; if(x & 0x200000000000000000000000000 > 0) r = r * 0x800058b92abbae02030c5fa5256f41fe >> 127; if(x & 0x100000000000000000000000000 > 0) r = r * 0x80002c5c8dade4d71776c0f4dbea67d6 >> 127; if(x & 0x80000000000000000000000000 > 0) r = r * 0x8000162e44eaf636526be456600bdbe4 >> 127; if(x & 0x40000000000000000000000000 > 0) r = r * 0x80000b1721fa7c188307016c1cd4e8b6 >> 127; if(x & 0x20000000000000000000000000 > 0) r = r * 0x8000058b90de7e4cecfc487503488bb1 >> 127; if(x & 0x10000000000000000000000000 > 0) r = r * 0x800002c5c8678f36cbfce50a6de60b14 >> 127; if(x & 0x8000000000000000000000000 > 0) r = r * 0x80000162e431db9f80b2347b5d62e516 >> 127; if(x & 0x4000000000000000000000000 > 0) r = r * 0x800000b1721872d0c7b08cf1e0114152 >> 127; if(x & 0x2000000000000000000000000 > 0) r = r * 0x80000058b90c1aa8a5c3736cb77e8dff >> 127; if(x & 0x1000000000000000000000000 > 0) r = r * 0x8000002c5c8605a4635f2efc2362d978 >> 127; if(x & 0x800000000000000000000000 > 0) r = r * 0x800000162e4300e635cf4a109e3939bd >> 127; if(x & 0x400000000000000000000000 > 0) r = r * 0x8000000b17217ff81bef9c551590cf83 >> 127; if(x & 0x200000000000000000000000 > 0) r = r * 0x800000058b90bfdd4e39cd52c0cfa27c >> 127; if(x & 0x100000000000000000000000 > 0) r = r * 0x80000002c5c85fe6f72d669e0e76e411 >> 127; if(x & 0x80000000000000000000000 > 0) r = r * 0x8000000162e42ff18f9ad35186d0df28 >> 127; if(x & 0x40000000000000000000000 > 0) r = r * 0x80000000b17217f84cce71aa0dcfffe7 >> 127; if(x & 0x20000000000000000000000 > 0) r = r * 0x8000000058b90bfc07a77ad56ed22aaa >> 127; if(x & 0x10000000000000000000000 > 0) r = r * 0x800000002c5c85fdfc23cdead40da8d6 >> 127; if(x & 0x8000000000000000000000 > 0) r = r * 0x80000000162e42fefc25eb1571853a66 >> 127; if(x & 0x4000000000000000000000 > 0) r = r * 0x800000000b17217f7d97f692baacded5 >> 127; if(x & 0x2000000000000000000000 > 0) r = r * 0x80000000058b90bfbead3b8b5dd254d7 >> 127; if(x & 0x1000000000000000000000 > 0) r = r * 0x8000000002c5c85fdf4eedd62f084e67 >> 127; if(x & 0x800000000000000000000 > 0) r = r * 0x800000000162e42fefa58aef378bf586 >> 127; if(x & 0x400000000000000000000 > 0) r = r * 0x8000000000b17217f7d24a78a3c7ef02 >> 127; if(x & 0x200000000000000000000 > 0) r = r * 0x800000000058b90bfbe9067c93e474a6 >> 127; if(x & 0x100000000000000000000 > 0) r = r * 0x80000000002c5c85fdf47b8e5a72599f >> 127; if(x & 0x80000000000000000000 > 0) r = r * 0x8000000000162e42fefa3bdb315934a2 >> 127; if(x & 0x40000000000000000000 > 0) r = r * 0x80000000000b17217f7d1d7299b49c46 >> 127; if(x & 0x20000000000000000000 > 0) r = r * 0x8000000000058b90bfbe8e9a8d1c4ea0 >> 127; if(x & 0x10000000000000000000 > 0) r = r * 0x800000000002c5c85fdf4745969ea76f >> 127; if(x & 0x8000000000000000000 > 0) r = r * 0x80000000000162e42fefa3a0df5373bf >> 127; if(x & 0x4000000000000000000 > 0) r = r * 0x800000000000b17217f7d1cff4aac1e1 >> 127; if(x & 0x2000000000000000000 > 0) r = r * 0x80000000000058b90bfbe8e7db95a2f1 >> 127; if(x & 0x1000000000000000000 > 0) r = r * 0x8000000000002c5c85fdf473e61ae1f8 >> 127; if(x & 0x800000000000000000 > 0) r = r * 0x800000000000162e42fefa39f121751c >> 127; if(x & 0x400000000000000000 > 0) r = r * 0x8000000000000b17217f7d1cf815bb96 >> 127; if(x & 0x200000000000000000 > 0) r = r * 0x800000000000058b90bfbe8e7bec1e0d >> 127; if(x & 0x100000000000000000 > 0) r = r * 0x80000000000002c5c85fdf473dee5f17 >> 127; if(x & 0x80000000000000000 > 0) r = r * 0x8000000000000162e42fefa39ef5438f >> 127; if(x & 0x40000000000000000 > 0) r = r * 0x80000000000000b17217f7d1cf7a26c8 >> 127; if(x & 0x20000000000000000 > 0) r = r * 0x8000000000000058b90bfbe8e7bcf4a4 >> 127; if(x & 0x10000000000000000 > 0) r = r * 0x800000000000002c5c85fdf473de72a2 >> 127; /* if(x & 0x8000000000000000 > 0) r = r * 0x80000000000000162e42fefa39ef3765 >> 127; if(x & 0x4000000000000000 > 0) r = r * 0x800000000000000b17217f7d1cf79b37 >> 127; if(x & 0x2000000000000000 > 0) r = r * 0x80000000000000058b90bfbe8e7bcd7d >> 127; if(x & 0x1000000000000000 > 0) r = r * 0x8000000000000002c5c85fdf473de6b6 >> 127; if(x & 0x800000000000000 > 0) r = r * 0x800000000000000162e42fefa39ef359 >> 127; if(x & 0x400000000000000 > 0) r = r * 0x8000000000000000b17217f7d1cf79ac >> 127; if(x & 0x200000000000000 > 0) r = r * 0x800000000000000058b90bfbe8e7bcd6 >> 127; if(x & 0x100000000000000 > 0) r = r * 0x80000000000000002c5c85fdf473de6a >> 127; if(x & 0x80000000000000 > 0) r = r * 0x8000000000000000162e42fefa39ef35 >> 127; if(x & 0x40000000000000 > 0) r = r * 0x80000000000000000b17217f7d1cf79a >> 127; if(x & 0x20000000000000 > 0) r = r * 0x8000000000000000058b90bfbe8e7bcd >> 127; if(x & 0x10000000000000 > 0) r = r * 0x800000000000000002c5c85fdf473de6 >> 127; if(x & 0x8000000000000 > 0) r = r * 0x80000000000000000162e42fefa39ef3 >> 127; if(x & 0x4000000000000 > 0) r = r * 0x800000000000000000b17217f7d1cf79 >> 127; if(x & 0x2000000000000 > 0) r = r * 0x80000000000000000058b90bfbe8e7bc >> 127; if(x & 0x1000000000000 > 0) r = r * 0x8000000000000000002c5c85fdf473de >> 127; if(x & 0x800000000000 > 0) r = r * 0x800000000000000000162e42fefa39ef >> 127; if(x & 0x400000000000 > 0) r = r * 0x8000000000000000000b17217f7d1cf7 >> 127; if(x & 0x200000000000 > 0) r = r * 0x800000000000000000058b90bfbe8e7b >> 127; if(x & 0x100000000000 > 0) r = r * 0x80000000000000000002c5c85fdf473d >> 127; if(x & 0x80000000000 > 0) r = r * 0x8000000000000000000162e42fefa39e >> 127; if(x & 0x40000000000 > 0) r = r * 0x80000000000000000000b17217f7d1cf >> 127; if(x & 0x20000000000 > 0) r = r * 0x8000000000000000000058b90bfbe8e7 >> 127; if(x & 0x10000000000 > 0) r = r * 0x800000000000000000002c5c85fdf473 >> 127; if(x & 0x8000000000 > 0) r = r * 0x80000000000000000000162e42fefa39 >> 127; if(x & 0x4000000000 > 0) r = r * 0x800000000000000000000b17217f7d1c >> 127; if(x & 0x2000000000 > 0) r = r * 0x80000000000000000000058b90bfbe8e >> 127; if(x & 0x1000000000 > 0) r = r * 0x8000000000000000000002c5c85fdf47 >> 127; if(x & 0x800000000 > 0) r = r * 0x800000000000000000000162e42fefa3 >> 127; if(x & 0x400000000 > 0) r = r * 0x8000000000000000000000b17217f7d1 >> 127; if(x & 0x200000000 > 0) r = r * 0x800000000000000000000058b90bfbe8 >> 127; if(x & 0x100000000 > 0) r = r * 0x80000000000000000000002c5c85fdf4 >> 127; if(x & 0x80000000 > 0) r = r * 0x8000000000000000000000162e42fefa >> 127; if(x & 0x40000000 > 0) r = r * 0x80000000000000000000000b17217f7d >> 127; if(x & 0x20000000 > 0) r = r * 0x8000000000000000000000058b90bfbe >> 127; if(x & 0x10000000 > 0) r = r * 0x800000000000000000000002c5c85fdf >> 127; if(x & 0x8000000 > 0) r = r * 0x80000000000000000000000162e42fef >> 127; if(x & 0x4000000 > 0) r = r * 0x800000000000000000000000b17217f7 >> 127; if(x & 0x2000000 > 0) r = r * 0x80000000000000000000000058b90bfb >> 127; if(x & 0x1000000 > 0) r = r * 0x8000000000000000000000002c5c85fd >> 127; if(x & 0x800000 > 0) r = r * 0x800000000000000000000000162e42fe >> 127; if(x & 0x400000 > 0) r = r * 0x8000000000000000000000000b17217f >> 127; if(x & 0x200000 > 0) r = r * 0x800000000000000000000000058b90bf >> 127; if(x & 0x100000 > 0) r = r * 0x80000000000000000000000002c5c85f >> 127; if(x & 0x80000 > 0) r = r * 0x8000000000000000000000000162e42f >> 127; if(x & 0x40000 > 0) r = r * 0x80000000000000000000000000b17217 >> 127; if(x & 0x20000 > 0) r = r * 0x8000000000000000000000000058b90b >> 127; if(x & 0x10000 > 0) r = r * 0x800000000000000000000000002c5c85 >> 127; if(x & 0x8000 > 0) r = r * 0x80000000000000000000000000162e42 >> 127; if(x & 0x4000 > 0) r = r * 0x800000000000000000000000000b1721 >> 127; if(x & 0x2000 > 0) r = r * 0x80000000000000000000000000058b90 >> 127; if(x & 0x1000 > 0) r = r * 0x8000000000000000000000000002c5c8 >> 127; if(x & 0x800 > 0) r = r * 0x800000000000000000000000000162e4 >> 127; if(x & 0x400 > 0) r = r * 0x8000000000000000000000000000b172 >> 127; if(x & 0x200 > 0) r = r * 0x800000000000000000000000000058b9 >> 127; if(x & 0x100 > 0) r = r * 0x80000000000000000000000000002c5c >> 127; if(x & 0x80 > 0) r = r * 0x8000000000000000000000000000162e >> 127; if(x & 0x40 > 0) r = r * 0x80000000000000000000000000000b17 >> 127; if(x & 0x20 > 0) r = r * 0x8000000000000000000000000000058b >> 127; if(x & 0x10 > 0) r = r * 0x800000000000000000000000000002c5 >> 127; if(x & 0x8 > 0) r = r * 0x80000000000000000000000000000162 >> 127; if(x & 0x4 > 0) r = r * 0x800000000000000000000000000000b1 >> 127; if(x & 0x2 > 0) r = r * 0x80000000000000000000000000000058 >> 127; if(x & 0x1 > 0) r = r * 0x8000000000000000000000000000002c >> 127; */ r >>= 127 -(x >> 121); return uint128(r); } } } /** * Ethereum smart contract library implementing Yield Math model. */ library YieldMath { using Math64x64 for int128; using Math64x64 for uint128; using Math64x64 for int256; using Math64x64 for uint256; using Exp64x64 for uint128; uint128 public constant ONE = 0x10000000000000000; // In 64.64 uint128 public constant TWO = 0x20000000000000000; // In 64.64 uint256 public constant MAX = type(uint128).max; // Used for overflow checks uint256 public constant VAR = 1e12; // The logarithm math used is not precise to the wei, but can deviate up to 1e12 from the real value. /** * Calculate a YieldSpace pool invariant according to the whitepaper */ function invariant(uint128 baseReserves, uint128 fyTokenReserves, uint256 totalSupply, uint128 timeTillMaturity, int128 ts) public pure returns(uint128) { if (totalSupply == 0) return 0; unchecked { // a = (1 - ts * timeTillMaturity) int128 a = int128(ONE).sub(ts.mul(timeTillMaturity.fromUInt())); require (a > 0, "YieldMath: Too far from maturity"); uint256 sum = uint256(baseReserves.pow(uint128 (a), ONE)) + uint256(fyTokenReserves.pow(uint128 (a), ONE)) >> 1; require(sum < MAX, "YieldMath: Sum overflow"); uint256 result = uint256(uint128(sum).pow(ONE, uint128(a))) / totalSupply; require (result < MAX, "YieldMath: Result overflow"); return uint128(result); } } /** * Calculate the amount of fyToken a user would get for given amount of Base. * https://www.desmos.com/calculator/5nf2xuy6yb * @param baseReserves base reserves amount * @param fyTokenReserves fyToken reserves amount * @param baseAmount base amount to be traded * @param timeTillMaturity time till maturity in seconds * @param ts time till maturity coefficient, multiplied by 2^64 * @param g fee coefficient, multiplied by 2^64 * @return the amount of fyToken a user would get for given amount of Base */ function fyTokenOutForBaseIn( uint128 baseReserves, uint128 fyTokenReserves, uint128 baseAmount, uint128 timeTillMaturity, int128 ts, int128 g) public pure returns(uint128) { unchecked { uint128 a = _computeA(timeTillMaturity, ts, g); // za = baseReserves ** a uint256 za = baseReserves.pow(a, ONE); // ya = fyTokenReserves ** a uint256 ya = fyTokenReserves.pow(a, ONE); // zx = baseReserves + baseAmount uint256 zx = uint256(baseReserves) + uint256(baseAmount); require(zx <= MAX, "YieldMath: Too much base in"); // zxa = zx ** a uint256 zxa = uint128(zx).pow(a, ONE); // sum = za + ya - zxa uint256 sum = za + ya - zxa; // z < MAX, y < MAX, a < 1. It can only underflow, not overflow. require(sum <= MAX, "YieldMath: Insufficient fyToken reserves"); // result = fyTokenReserves - (sum ** (1/a)) uint256 result = uint256(fyTokenReserves) - uint256(uint128(sum).pow(ONE, a)); require(result <= MAX, "YieldMath: Rounding induced error"); result = result > VAR ? result - VAR : 0; // Subtract error guard, flooring the result at zero return uint128(result); } } /** * Calculate the amount of base a user would get for certain amount of fyToken. * https://www.desmos.com/calculator/6jlrre7ybt * @param baseReserves base reserves amount * @param fyTokenReserves fyToken reserves amount * @param fyTokenAmount fyToken amount to be traded * @param timeTillMaturity time till maturity in seconds * @param ts time till maturity coefficient, multiplied by 2^64 * @param g fee coefficient, multiplied by 2^64 * @return the amount of Base a user would get for given amount of fyToken */ function baseOutForFYTokenIn( uint128 baseReserves, uint128 fyTokenReserves, uint128 fyTokenAmount, uint128 timeTillMaturity, int128 ts, int128 g) public pure returns(uint128) { unchecked { uint128 a = _computeA(timeTillMaturity, ts, g); // za = baseReserves ** a uint256 za = baseReserves.pow(a, ONE); // ya = fyTokenReserves ** a uint256 ya = fyTokenReserves.pow(a, ONE); // yx = fyDayReserves + fyTokenAmount uint256 yx = uint256(fyTokenReserves) + uint256(fyTokenAmount); require(yx <= MAX, "YieldMath: Too much fyToken in"); // yxa = yx ** a uint256 yxa = uint128(yx).pow(a, ONE); // sum = za + ya - yxa uint256 sum = za + ya - yxa; // z < MAX, y < MAX, a < 1. It can only underflow, not overflow. require(sum <= MAX, "YieldMath: Insufficient base reserves"); // result = baseReserves - (sum ** (1/a)) uint256 result = uint256(baseReserves) - uint256(uint128(sum).pow(ONE, a)); require(result <= MAX, "YieldMath: Rounding induced error"); result = result > VAR ? result - VAR : 0; // Subtract error guard, flooring the result at zero return uint128(result); } } /** * Calculate the amount of fyToken a user could sell for given amount of Base. * https://www.desmos.com/calculator/0rgnmtckvy * @param baseReserves base reserves amount * @param fyTokenReserves fyToken reserves amount * @param baseAmount Base amount to be traded * @param timeTillMaturity time till maturity in seconds * @param ts time till maturity coefficient, multiplied by 2^64 * @param g fee coefficient, multiplied by 2^64 * @return the amount of fyToken a user could sell for given amount of Base */ function fyTokenInForBaseOut( uint128 baseReserves, uint128 fyTokenReserves, uint128 baseAmount, uint128 timeTillMaturity, int128 ts, int128 g) public pure returns(uint128) { unchecked { uint128 a = _computeA(timeTillMaturity, ts, g); // za = baseReserves ** a uint256 za = baseReserves.pow(a, ONE); // ya = fyTokenReserves ** a uint256 ya = fyTokenReserves.pow(a, ONE); // zx = baseReserves - baseAmount uint256 zx = uint256(baseReserves) - uint256(baseAmount); require(zx <= MAX, "YieldMath: Too much base out"); // zxa = zx ** a uint256 zxa = uint128(zx).pow(a, ONE); // sum = za + ya - zxa uint256 sum = za + ya - zxa; // z < MAX, y < MAX, a < 1. It can only underflow, not overflow. require(sum <= MAX, "YieldMath: Resulting fyToken reserves too high"); // result = (sum ** (1/a)) - fyTokenReserves uint256 result = uint256(uint128(sum).pow(ONE, a)) - uint256(fyTokenReserves); require(result <= MAX, "YieldMath: Rounding induced error"); result = result < MAX - VAR ? result + VAR : MAX; // Add error guard, ceiling the result at max return uint128(result); } } /** * Calculate the amount of base a user would have to pay for certain amount of fyToken. * https://www.desmos.com/calculator/ws5oqj8x5i * @param baseReserves Base reserves amount * @param fyTokenReserves fyToken reserves amount * @param fyTokenAmount fyToken amount to be traded * @param timeTillMaturity time till maturity in seconds * @param ts time till maturity coefficient, multiplied by 2^64 * @param g fee coefficient, multiplied by 2^64 * @return the amount of base a user would have to pay for given amount of * fyToken */ function baseInForFYTokenOut( uint128 baseReserves, uint128 fyTokenReserves, uint128 fyTokenAmount, uint128 timeTillMaturity, int128 ts, int128 g) public pure returns(uint128) { unchecked { uint128 a = _computeA(timeTillMaturity, ts, g); // za = baseReserves ** a uint256 za = baseReserves.pow(a, ONE); // ya = fyTokenReserves ** a uint256 ya = fyTokenReserves.pow(a, ONE); // yx = baseReserves - baseAmount uint256 yx = uint256(fyTokenReserves) - uint256(fyTokenAmount); require(yx <= MAX, "YieldMath: Too much fyToken out"); // yxa = yx ** a uint256 yxa = uint128(yx).pow(a, ONE); // sum = za + ya - yxa uint256 sum = za + ya - yxa; // z < MAX, y < MAX, a < 1. It can only underflow, not overflow. require(sum <= MAX, "YieldMath: Resulting base reserves too high"); // result = (sum ** (1/a)) - baseReserves uint256 result = uint256(uint128(sum).pow(ONE, a)) - uint256(baseReserves); require(result <= MAX, "YieldMath: Rounding induced error"); result = result < MAX - VAR ? result + VAR : MAX; // Add error guard, ceiling the result at max return uint128(result); } } /** * Calculate the max amount of fyTokens that can be bought from the pool without making the interest rate negative. * See section 6.3 of the YieldSpace White paper * @param baseReserves Base reserves amount * @param fyTokenReserves fyToken reserves amount * @param timeTillMaturity time till maturity in seconds * @param ts time till maturity coefficient, multiplied by 2^64 * @param g fee coefficient, multiplied by 2^64 * @return max amount of fyTokens that can be bought from the pool */ function maxFYTokenOut( uint128 baseReserves, uint128 fyTokenReserves, uint128 timeTillMaturity, int128 ts, int128 g) public pure returns(uint128) { if (baseReserves == fyTokenReserves) return 0; unchecked { uint128 a = _computeA(timeTillMaturity, ts, g); // xa = baseReserves ** a uint128 xa = baseReserves.pow(a, ONE); // ya = fyTokenReserves ** a uint128 ya = fyTokenReserves.pow(a, ONE); int128 xy2 = (xa + ya).divu(TWO); uint inaccessible = uint256(uint128(xy2).pow(ONE, a)); require(inaccessible <= MAX, "YieldMath: Rounding induced error"); inaccessible = inaccessible < MAX - VAR ? inaccessible + VAR : MAX; // Add error guard, ceiling the result at max return uint128(inaccessible) > fyTokenReserves ? 0 : fyTokenReserves - uint128(inaccessible); } } /** * Calculate the max amount of fyTokens that can be sold to into the pool. * @param baseReserves Base reserves amount * @param fyTokenReserves fyToken reserves amount * @param timeTillMaturity time till maturity in seconds * @param ts time till maturity coefficient, multiplied by 2^64 * @param g fee coefficient, multiplied by 2^64 * @return max amount of fyTokens that can be sold to into the pool */ function maxFYTokenIn( uint128 baseReserves, uint128 fyTokenReserves, uint128 timeTillMaturity, int128 ts, int128 g) public pure returns(uint128) { unchecked { uint128 b = _computeB(timeTillMaturity, ts, g); // xa = baseReserves ** a uint128 xa = baseReserves.pow(b, ONE); // ya = fyTokenReserves ** a uint128 ya = fyTokenReserves.pow(b, ONE); uint result = (xa + ya).pow(ONE, b) - fyTokenReserves; require(result <= MAX, "YieldMath: Rounding induced error"); result = result > VAR ? result - VAR : 0; // Subtract error guard, flooring the result at zero return uint128(result); } } /** * Calculate the max amount of base that can be sold to into the pool without making the interest rate negative. * @param baseReserves Base reserves amount * @param fyTokenReserves fyToken reserves amount * @param timeTillMaturity time till maturity in seconds * @param ts time till maturity coefficient, multiplied by 2^64 * @param g fee coefficient, multiplied by 2^64 * @return max amount of base that can be sold to into the pool */ function maxBaseIn( uint128 baseReserves, uint128 fyTokenReserves, uint128 timeTillMaturity, int128 ts, int128 g) public pure returns (uint128) { uint128 _maxFYTokenOut = maxFYTokenOut(baseReserves, fyTokenReserves, timeTillMaturity, ts, g); if (_maxFYTokenOut > 0) return baseInForFYTokenOut(baseReserves, fyTokenReserves, _maxFYTokenOut, timeTillMaturity, ts, g); return 0; } /** * Calculate the max amount of base that can be bought from the pool. * @param baseReserves Base reserves amount * @param fyTokenReserves fyToken reserves amount * @param timeTillMaturity time till maturity in seconds * @param ts time till maturity coefficient, multiplied by 2^64 * @param g fee coefficient, multiplied by 2^64 * @return max amount of base that can be bought from the pool */ function maxBaseOut( uint128 baseReserves, uint128 fyTokenReserves, uint128 timeTillMaturity, int128 ts, int128 g) public pure returns (uint128) { uint128 _maxFYTokenIn = maxFYTokenIn(baseReserves, fyTokenReserves, timeTillMaturity, ts, g); return baseOutForFYTokenIn(baseReserves, fyTokenReserves, _maxFYTokenIn, timeTillMaturity, ts, g); } function _computeA(uint128 timeTillMaturity, int128 ts, int128 g) private pure returns (uint128) { unchecked { // t = ts * timeTillMaturity int128 t = ts.mul(timeTillMaturity.fromUInt()); require(t >= 0, "YieldMath: t must be positive"); // Meaning neither T or ts can be negative // a = (1 - gt) int128 a = int128(ONE).sub(g.mul(t)); require(a > 0, "YieldMath: Too far from maturity"); require(a <= int128(ONE), "YieldMath: g must be positive"); return uint128(a); } } function _computeB(uint128 timeTillMaturity, int128 ts, int128 g) private pure returns (uint128) { unchecked { // t = ts * timeTillMaturity int128 t = ts.mul(timeTillMaturity.fromUInt()); require(t >= 0, "YieldMath: t must be positive"); // Meaning neither T or ts can be negative // b = (1 - t/g) int128 b = int128(ONE).sub(t.div(g)); require(b > 0, "YieldMath: Too far from maturity"); require(b <= int128(ONE), "YieldMath: g must be positive"); return uint128(b); } } } // SPDX-License-Identifier: MIT // Inspired on token.sol from DappHub. Natspec adpated from OpenZeppelin. pragma solidity ^0.8.0; import "./IERC20Metadata.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}. * * 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. * * Calls to {transferFrom} do not check for allowance if the caller is the owner * of the funds. This allows to reduce the number of approvals that are necessary. * * Finally, {transferFrom} does not decrease the allowance if it is set to * type(uint256).max. This reduces the gas costs without any likely impact. */ contract ERC20 is IERC20Metadata { uint256 internal _totalSupply; mapping (address => uint256) internal _balanceOf; mapping (address => mapping (address => uint256)) internal _allowance; string public override name = "???"; string public override symbol = "???"; uint8 public override decimals = 18; /** * @dev Sets the values for {name}, {symbol} and {decimals}. */ constructor(string memory name_, string memory symbol_, uint8 decimals_) { name = name_; symbol = symbol_; decimals = decimals_; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() external view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address guy) external view virtual override returns (uint256) { return _balanceOf[guy]; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) external view virtual override returns (uint256) { return _allowance[owner][spender]; } /** * @dev See {IERC20-approve}. */ function approve(address spender, uint wad) external virtual override returns (bool) { return _setAllowance(msg.sender, spender, wad); } /** * @dev See {IERC20-transfer}. * * Requirements: * * - the caller must have a balance of at least `wad`. */ function transfer(address dst, uint wad) external virtual override returns (bool) { return _transfer(msg.sender, dst, wad); } /** * @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: * * - `src` must have a balance of at least `wad`. * - the caller is not `src`, it must have allowance for ``src``'s tokens of at least * `wad`. */ /// if_succeeds {:msg "TransferFrom - decrease allowance"} msg.sender != src ==> old(_allowance[src][msg.sender]) >= wad; function transferFrom(address src, address dst, uint wad) external virtual override returns (bool) { _decreaseAllowance(src, wad); return _transfer(src, dst, wad); } /** * @dev Moves tokens `wad` from `src` to `dst`. * * Emits a {Transfer} event. * * Requirements: * * - `src` must have a balance of at least `amount`. */ /// if_succeeds {:msg "Transfer - src decrease"} old(_balanceOf[src]) >= _balanceOf[src]; /// if_succeeds {:msg "Transfer - dst increase"} _balanceOf[dst] >= old(_balanceOf[dst]); /// if_succeeds {:msg "Transfer - supply"} old(_balanceOf[src]) + old(_balanceOf[dst]) == _balanceOf[src] + _balanceOf[dst]; function _transfer(address src, address dst, uint wad) internal virtual returns (bool) { require(_balanceOf[src] >= wad, "ERC20: Insufficient balance"); unchecked { _balanceOf[src] = _balanceOf[src] - wad; } _balanceOf[dst] = _balanceOf[dst] + wad; emit Transfer(src, dst, wad); return true; } /** * @dev Sets the allowance granted to `spender` by `owner`. * * Emits an {Approval} event indicating the updated allowance. */ function _setAllowance(address owner, address spender, uint wad) internal virtual returns (bool) { _allowance[owner][spender] = wad; emit Approval(owner, spender, wad); return true; } /** * @dev Decreases the allowance granted to the caller by `src`, unless src == msg.sender or _allowance[src][msg.sender] == MAX * * Emits an {Approval} event indicating the updated allowance, if the allowance is updated. * * Requirements: * * - `spender` must have allowance for the caller of at least * `wad`, unless src == msg.sender */ /// if_succeeds {:msg "Decrease allowance - underflow"} old(_allowance[src][msg.sender]) <= _allowance[src][msg.sender]; function _decreaseAllowance(address src, uint wad) internal virtual returns (bool) { if (src != msg.sender) { uint256 allowed = _allowance[src][msg.sender]; if (allowed != type(uint).max) { require(allowed >= wad, "ERC20: Insufficient approval"); unchecked { _setAllowance(src, msg.sender, allowed - wad); } } } return true; } /** @dev Creates `wad` tokens and assigns them to `dst`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. */ /// if_succeeds {:msg "Mint - balance overflow"} old(_balanceOf[dst]) >= _balanceOf[dst]; /// if_succeeds {:msg "Mint - supply overflow"} old(_totalSupply) >= _totalSupply; function _mint(address dst, uint wad) internal virtual returns (bool) { _balanceOf[dst] = _balanceOf[dst] + wad; _totalSupply = _totalSupply + wad; emit Transfer(address(0), dst, wad); return true; } /** * @dev Destroys `wad` tokens from `src`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `src` must have at least `wad` tokens. */ /// if_succeeds {:msg "Burn - balance underflow"} old(_balanceOf[src]) <= _balanceOf[src]; /// if_succeeds {:msg "Burn - supply underflow"} old(_totalSupply) <= _totalSupply; function _burn(address src, uint wad) internal virtual returns (bool) { unchecked { require(_balanceOf[src] >= wad, "ERC20: Insufficient balance"); _balanceOf[src] = _balanceOf[src] - wad; _totalSupply = _totalSupply - wad; emit Transfer(src, address(0), wad); } return true; } } // SPDX-License-Identifier: MIT // Code adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237/ pragma solidity ^0.8.0; /** * @dev Interface of the ERC2612 standard as defined in the EIP. * * Adds the {permit} method, which can be used to change one's * {IERC20-allowance} without having to send a transaction, by signing a * message. This allows users to spend tokens without having to hold Ether. * * See https://eips.ethereum.org/EIPS/eip-2612. */ interface IERC2612 { /** * @dev Sets `amount` 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: * * - `owner` cannot be the zero address. * - `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 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current ERC2612 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); } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; library AddressStringUtil { // converts an address to the uppercase hex string, extracting only len bytes (up to 20, multiple of 2) function toAsciiString(address addr, uint256 len) internal pure returns (string memory) { require(len % 2 == 0 && len > 0 && len <= 40, "AddressStringUtil: INVALID_LEN"); bytes memory s = new bytes(len); uint256 addrNum = uint256(uint160(addr)); for (uint256 ii = 0; ii < len ; ii +=2) { uint8 b = uint8(addrNum >> (4 * (38 - ii))); s[ii] = char(b >> 4); s[ii + 1] = char(b & 0x0f); } return string(s); } // hi and lo are only 4 bits and between 0 and 16 // this method converts those values to the unicode/ascii code point for the hex representation // uses upper case for the characters function char(uint8 b) private pure returns (bytes1 c) { if (b < 10) { return bytes1(b + 0x30); } else { return bytes1(b + 0x37); } } } // SPDX-License-Identifier: MIT // Taken from https://github.com/sushiswap/BoringSolidity/blob/441e51c0544cf2451e6116fe00515e71d7c42e2c/contracts/BoringBatchable.sol pragma solidity >=0.6.0; library RevertMsgExtractor { /// @dev Helper function to extract a useful revert message from a failed call. /// If the returned data is malformed or not correctly abi encoded then this call can fail itself. function getRevertMsg(bytes memory returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. returnData := add(returnData, 0x04) } return abi.decode(returnData, (string)); // All that remains is the revert string } } // SPDX-License-Identifier: BUSL-1.1 /* * Math 64.64 Smart Contract Library. Copyright © 2019 by Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity 0.8.6; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library Math64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { unchecked { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { unchecked { return int64 (x >> 64); } } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { unchecked { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (int256 (x << 64)); } } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { unchecked { require (x >= 0); return uint64 (uint128 (x >> 64)); } } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { unchecked { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { unchecked { return int256 (x) << 64; } } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { unchecked { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { unchecked { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (int256 (x)) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { unchecked { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { unchecked { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { unchecked { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return -x; } } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return x < 0 ? -x : x; } } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { unchecked { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { unchecked { return int128 ((int256 (x) + int256 (y)) >> 1); } } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { unchecked { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128 (x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x2 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x4 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x8 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require (absXShift < 64); if (y & 0x1 != 0) { absResult = absResult * absX >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = absX * absX >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require (resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256 (absResult) : int256 (absResult); require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { unchecked { require (x >= 0); return int128 (sqrtu (uint256 (int256 (x)) << 64)); } } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { unchecked { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { unchecked { require (x > 0); return int128 (int256 ( uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128)); } } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (int256 (63 - (x >> 64))); require (result <= uint256 (int256 (MAX_64x64))); return int128 (int256 (result)); } } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { unchecked { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x) private pure returns (uint128) { unchecked { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128 (r < r1 ? r : r1); } } } }
Returns the "virtual" fyToken balance, which is the real balance plus the pool token supply.
function getFYTokenBalance() public view override returns(uint112) { return _getFYTokenBalance(); }
223,864
./full_match/97/0xb0b2dD90491Bc9091604793321b98aC863dE8C0C/sources/project_/contracts/piMarket.sol
executes a sale with a specified bid. _saleId The Id of the sale. _bidId The Id of the bid./
function withdrawBidMoney(uint256 _saleId, uint256 _bidId) external nonReentrant { LibMarket.withdrawBid(_tokenMeta[_saleId], Bids[_saleId][_bidId]); emit BidWithdrawn(_saleId, _bidId); }
3,282,927
./full_match/11155111/0x41B80fC08eCaAbDC58b2dd5cAf7E8E33519BC0F0/sources/project_/contracts/PaymentProcessor.sol
uint256 adjustedPrice = uint256(price) 10 10; uint256 _minimumUSD = (minimumUSD 10 18) / adjustedPrice; return _minimumUSD;
function getLatestPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return int(price * 1000000000); }
3,803,461
pragma solidity ^0.6.3; import "./ERC20Interface.sol"; import "./BlackCaspianUpgradeable.sol"; contract ERC20Proxy is ERC20Interface, BlackCaspianUpgradeable { // MEMBERS /// @notice Returns the name of the token. string public name; /// @notice Returns the symbol of the token. string public symbol; /// @notice Returns the number of decimals the token uses. uint8 public decimals; // CONSTRUCTOR function ERC20Proxy( string _name, string _symbol, uint8 _decimals, address _custodian ) BlackCaspianUpgradeable(_custodian) public { name = _name; symbol = _symbol; decimals = _decimals; } // PUBLIC FUNCTIONS // (ERC20Interface) /** @notice Returns the total token supply. * * @return the total token supply. */ function totalSupply() public view returns (uint256) { return BlackCaspian.totalSupply(); } /** @notice Returns the account balance of another account with address * `_owner`. * * @return balance the balance of account with address `_owner`. */ function balanceOf(address _owner) public view returns (uint256 balance) { return BlackCaspian.balanceOf(_owner); } /** @dev Internal use only. */ function emitTransfer(address _from, address _to, uint256 _value) public onlyImpl { emit Transfer(_from, _to, _value); } /** @notice Transfers `_value` amount of tokens to address `_to`. * * @dev Will fire the `Transfer` event. Will revert if the `_from` * account balance does not have enough tokens to spend. * * @return success true if transfer completes. */ function transfer(address _to, uint256 _value) public returns (bool success) { return BlackCaspian.transferWithSender(msg.sender, _to, _value); } /** @notice Transfers `_value` amount of tokens from address `_from` * to address `_to`. * * @dev Will fire the `Transfer` event. Will revert unless the `_from` * account has deliberately authorized the sender of the message * via some mechanism. * * @return success true if transfer completes. */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { return BlackCaspian.transferFromWithSender(msg.sender, _from, _to, _value); } /** @dev Internal use only. */ function emitApproval(address _owner, address _spender, uint256 _value) public onlyImpl { emit Approval(_owner, _spender, _value); } /** @notice Allows `_spender` to withdraw from your account multiple times, * up to the `_value` amount. If this function is called again it * overwrites the current allowance with _value. * * @dev Will fire the `Approval` event. * * @return success true if approval completes. */ function approve(address _spender, uint256 _value) public returns (bool success) { return BlackCaspian.approveWithSender(msg.sender, _spender, _value); } /** @notice Increases the amount `_spender` is allowed to withdraw from * your account. * This function is implemented to avoid the race condition in standard * ERC20 contracts surrounding the `approve` method. * * @dev Will fire the `Approval` event. This function should be used instead of * `approve`. * * @return success true if approval completes. */ function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) { return BlackCaspian.increaseApprovalWithSender(msg.sender, _spender, _addedValue); } /** @notice Decreases the amount `_spender` is allowed to withdraw from * your account. This function is implemented to avoid the race * condition in standard ERC20 contracts surrounding the `approve` method. * * @dev Will fire the `Approval` event. This function should be used * instead of `approve`. * * @return success true if approval completes. */ function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) { return BlackCaspian.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue); } /** @notice Returns how much `_spender` is currently allowed to spend from * `_owner`'s balance. * * @return remaining the remaining allowance. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return BlackCaspian.allowance(_owner, _spender); } }
Transfers `_value` amount of tokens to address `_to`. Will fire the `Transfer` event. Will revert if the `_from` account balance does not have enough tokens to spend. return success true if transfer completes./
function transfer(address _to, uint256 _value) public returns (bool success) { return BlackCaspian.transferWithSender(msg.sender, _to, _value); }
5,369,289
./full_match/3/0x6d977069Dadef5A30789C38c33645de3f4e391A3/sources/browser/ILUS.sol
Function for withdrawing staked tokens stakingId stake id for the stake/
function withdrawStakedTokens(uint256 stakingId) public failSafe returns(bool){ require(_stakerAddress[stakingId] == msg.sender,"No staked token found on this address and ID"); require(_TokenTransactionstatus[stakingId] != true,"Either tokens are already withdrawn or blocked by admin"); require(balanceOf(_tokenPoolAddress) > _usersTokens[stakingId], "Pool is dry, can not perform transaction"); _TokenTransactionstatus[stakingId] = true; _finalWithdrawlStake[stakingId] = _usersTokens[stakingId] +getRewardsDetailsOfUserById(stakingId); _mint(getRewardsDetailsOfUserById(stakingId), _tokenPoolAddress); _transfer(_tokenPoolAddress,msg.sender,_usersTokens[stakingId] +getRewardsDetailsOfUserById(stakingId)); return true; } mapping (address => bool) public isBlocked; mapping (uint => uint256) private votesNeeded; uint proposalIDcount = 0;
8,230,516
pragma solidity 0.4.21; /** * @title Array64 Library * @author Modular Inc, https://modular.network * * version 1.2.0 * Copyright (c) 2017 Modular, Inc * The MIT License (MIT) * https://github.com/Modular-Network/ethereum-libraries/blob/master/LICENSE * * The Array64 Library provides a few utility functions to work with * storage uint64[] types in place. Modular provides smart contract services * and security reviews for contract deployments in addition to working on open * source projects in the Ethereum community. Our purpose is to test, document, * and deploy reusable code onto the blockchain and improve both security and * usability. We also educate non-profits, schools, and other community members * about the application of blockchain technology. * For further information: Modular.network * * 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. */ library Array64Lib { /// @dev Sum vector /// @param self Storage array containing uint256 type variables /// @return sum The sum of all elements, does not check for overflow function sumElements(uint64[] storage self) public view returns(uint256 sum) { uint256 term; uint8 remainder; assembly { mstore(0x60,self_slot) for { let i := 0 } lt(i, sload(self_slot)) { i := add(i, 1) } { term := sload(add(sha3(0x60,0x20),div(i,4))) remainder := mod(i,4) for { let j := 0 } lt(j, mul(remainder, 2)) { j := add(j, 1) } { term := div(term,4294967296) } term := and(0x000000000000000000000000000000000000000000000000ffffffffffffffff,term) sum := add(term,sum) } } } /// @dev Returns the max value in an array. /// @param self Storage array containing uint256 type variables /// @return maxValue The highest value in the array function getMax(uint64[] storage self) public view returns(uint64 maxValue) { uint256 term; uint8 remainder; assembly { mstore(0x60,self_slot) maxValue := 0 for { let i := 0 } lt(i, sload(self_slot)) { i := add(i, 1) } { term := sload(add(sha3(0x60,0x20),div(i,4))) remainder := mod(i,4) for { let j := 0 } lt(j, mul(remainder, 2)) { j := add(j, 1) } { term := div(term,4294967296) } term := and(0x000000000000000000000000000000000000000000000000ffffffffffffffff,term) switch lt(maxValue, term) case 1 { maxValue := term } } } } /// @dev Returns the minimum value in an array. /// @param self Storage array containing uint256 type variables /// @return minValue The highest value in the array function getMin(uint64[] storage self) public view returns(uint64 minValue) { uint256 term; uint8 remainder; assembly { mstore(0x60,self_slot) for { let i := 0 } lt(i, sload(self_slot)) { i := add(i, 1) } { term := sload(add(sha3(0x60,0x20),div(i,4))) remainder := mod(i,4) for { let j := 0 } lt(j, mul(remainder, 2)) { j := add(j, 1) } { term := div(term,4294967296) } term := and(0x000000000000000000000000000000000000000000000000ffffffffffffffff,term) switch eq(i,0) case 1 { minValue := term } switch gt(minValue, term) case 1 { minValue := term } } } } /// @dev Finds the index of a given value in an array /// @param self Storage array containing uint256 type variables /// @param value The value to search for /// @param isSorted True if the array is sorted, false otherwise /// @return found True if the value was found, false otherwise /// @return index The index of the given value, returns 0 if found is false function indexOf(uint64[] storage self, uint64 value, bool isSorted) public view returns(bool found, uint256 index) { if (isSorted) { uint256 high = self.length - 1; uint256 mid = 0; uint256 low = 0; while (low <= high) { mid = (low+high)/2; if (self[mid] == value) { found = true; index = mid; low = high + 1; } else if (self[mid] < value) { low = mid + 1; } else { high = mid - 1; } } } else { for (uint256 i = 0; i<self.length; i++) { if (self[i] == value) { found = true; index = i; i = self.length; } } } } /// @dev Utility function for heapSort /// @param index The index of child node /// @return pI The parent node index function getParentI(uint256 index) private pure returns (uint256 pI) { uint256 i = index - 1; pI = i/2; } /// @dev Utility function for heapSort /// @param index The index of parent node /// @return lcI The index of left child function getLeftChildI(uint256 index) private pure returns (uint256 lcI) { uint256 i = index * 2; lcI = i + 1; } /// @dev Sorts given array in place /// @param self Storage array containing uint256 type variables function heapSort(uint64[] storage self) public { if(self.length > 1){ uint256 end = self.length - 1; uint256 start = getParentI(end); uint256 root = start; uint256 lChild; uint256 rChild; uint256 swap; uint64 temp; while(start >= 0){ root = start; lChild = getLeftChildI(start); while(lChild <= end){ rChild = lChild + 1; swap = root; if(self[swap] < self[lChild]) swap = lChild; if((rChild <= end) && (self[swap]<self[rChild])) swap = rChild; if(swap == root) lChild = end+1; else { temp = self[swap]; self[swap] = self[root]; self[root] = temp; root = swap; lChild = getLeftChildI(root); } } if(start == 0) break; else start = start - 1; } while(end > 0){ temp = self[end]; self[end] = self[0]; self[0] = temp; end = end - 1; root = 0; lChild = getLeftChildI(0); while(lChild <= end){ rChild = lChild + 1; swap = root; if(self[swap] < self[lChild]) swap = lChild; if((rChild <= end) && (self[swap]<self[rChild])) swap = rChild; if(swap == root) lChild = end + 1; else { temp = self[swap]; self[swap] = self[root]; self[root] = temp; root = swap; lChild = getLeftChildI(root); } } } } } /// @dev Removes duplicates from a given array. /// @param self Storage array containing uint256 type variables function uniq(uint64[] storage self) public returns (uint256 length) { bool contains; uint256 index; for (uint256 i = 0; i < self.length; i++) { (contains, index) = indexOf(self, self[i], false); if (i > index) { for (uint256 j = i; j < self.length - 1; j++){ self[j] = self[j + 1]; } delete self[self.length - 1]; self.length--; i--; } } length = self.length; } }
Returns the minimum value in an array. self Storage array containing uint256 type variables return minValue The highest value in the array
function getMin(uint64[] storage self) public view returns(uint64 minValue) { uint256 term; uint8 remainder; assembly { mstore(0x60,self_slot) term := sload(add(sha3(0x60,0x20),div(i,4))) remainder := mod(i,4) term := div(term,4294967296) } term := and(0x000000000000000000000000000000000000000000000000ffffffffffffffff,term) switch eq(i,0) for { let i := 0 } lt(i, sload(self_slot)) { i := add(i, 1) } { for { let j := 0 } lt(j, mul(remainder, 2)) { j := add(j, 1) } { case 1 { minValue := term } switch gt(minValue, term) case 1 { minValue := term } }
7,807,201
/* * source https://github.com/blockbitsio/ * @name Funding Contract * @package BlockBitsIO * @author Micky Socaci <micky@nowlive.ro> Contains the Funding Contract code deployed and linked to the Application Entity */ pragma solidity ^0.4.17; import "./../ApplicationAsset.sol"; import "./../abis/ABITokenManager.sol"; import "./../abis/ABIProposals.sol"; import "./../abis/ABIMilestones.sol"; import "./../abis/ABIFunding.sol"; import "./../abis/ABIToken.sol"; import "./../abis/ABITokenSCADAVariable.sol"; import "./FundingVault.sol"; contract FundingManager is ApplicationAsset { ABIFunding FundingEntity; ABITokenManager TokenManagerEntity; ABIToken TokenEntity; ABITokenSCADAVariable TokenSCADAEntity; ABIProposals ProposalsEntity; ABIMilestones MilestonesEntity; uint256 public LockedVotingTokens = 0; event EventFundingManagerReceivedPayment(address indexed _vault, uint8 indexed _payment_method, uint256 indexed _amount ); event EventFundingManagerProcessedVault(address _vault, uint256 id ); mapping (address => address) public vaultList; mapping (uint256 => address) public vaultById; uint256 public vaultNum = 0; function setAssetStates() internal { // Asset States EntityStates["__IGNORED__"] = 0; EntityStates["NEW"] = 1; EntityStates["WAITING"] = 2; EntityStates["FUNDING_FAILED_START"] = 10; EntityStates["FUNDING_FAILED_PROGRESS"] = 11; EntityStates["FUNDING_FAILED_DONE"] = 12; EntityStates["FUNDING_SUCCESSFUL_START"] = 20; EntityStates["FUNDING_SUCCESSFUL_PROGRESS"] = 21; EntityStates["FUNDING_SUCCESSFUL_DONE"] = 22; EntityStates["FUNDING_SUCCESSFUL_ALLOCATE"] = 25; EntityStates["MILESTONE_PROCESS_START"] = 30; EntityStates["MILESTONE_PROCESS_PROGRESS"] = 31; EntityStates["MILESTONE_PROCESS_DONE"] = 32; EntityStates["EMERGENCY_PROCESS_START"] = 40; EntityStates["EMERGENCY_PROCESS_PROGRESS"] = 41; EntityStates["EMERGENCY_PROCESS_DONE"] = 42; EntityStates["COMPLETE_PROCESS_START"] = 100; EntityStates["COMPLETE_PROCESS_PROGRESS"] = 101; EntityStates["COMPLETE_PROCESS_DONE"] = 102; // Funding Stage States RecordStates["__IGNORED__"] = 0; } function runBeforeApplyingSettings() internal requireInitialised requireSettingsNotApplied { address FundingAddress = getApplicationAssetAddressByName('Funding'); FundingEntity = ABIFunding(FundingAddress); EventRunBeforeApplyingSettings(assetName); address TokenManagerAddress = getApplicationAssetAddressByName('TokenManager'); TokenManagerEntity = ABITokenManager(TokenManagerAddress); TokenEntity = ABIToken(TokenManagerEntity.TokenEntity()); address TokenSCADAAddress = TokenManagerEntity.TokenSCADAEntity(); TokenSCADAEntity = ABITokenSCADAVariable(TokenSCADAAddress) ; address MilestonesAddress = getApplicationAssetAddressByName('Milestones'); MilestonesEntity = ABIMilestones(MilestonesAddress) ; address ProposalsAddress = getApplicationAssetAddressByName('Proposals'); ProposalsEntity = ABIProposals(ProposalsAddress) ; } function receivePayment(address _sender, uint8 _payment_method, uint8 _funding_stage) payable public requireInitialised onlyAsset('Funding') returns(bool) { // check that msg.value is higher than 0, don't really want to have to deal with minus in case the network breaks this somehow if(msg.value > 0) { FundingVault vault; // no vault present if(!hasVault(_sender)) { // create and initialize a new one vault = new FundingVault(); if(vault.initialize( _sender, FundingEntity.multiSigOutputAddress(), address(FundingEntity), address(getApplicationAssetAddressByName('Milestones')), address(getApplicationAssetAddressByName('Proposals')) )) { // store new vault address. vaultList[_sender] = vault; // increase internal vault number vaultNum++; // assign vault to by int registry vaultById[vaultNum] = vault; } else { revert(); } } else { // use existing vault vault = FundingVault(vaultList[_sender]); } EventFundingManagerReceivedPayment(vault, _payment_method, msg.value); if( vault.addPayment.value(msg.value)( _payment_method, _funding_stage ) ) { // if payment is received in the vault then mint tokens based on the received value! TokenManagerEntity.mint( vault, TokenSCADAEntity.getTokensForValueInCurrentStage(msg.value) ); return true; } else { revert(); } } else { revert(); } } function getMyVaultAddress(address _sender) public view returns (address) { return vaultList[_sender]; } function hasVault(address _sender) internal view returns(bool) { if(vaultList[_sender] != address(0x0)) { return true; } else { return false; } } bool public fundingProcessed = false; uint256 public lastProcessedVaultId = 0; uint8 public VaultCountPerProcess = 10; bytes32 public currentTask = ""; mapping (bytes32 => bool) public taskByHash; function setVaultCountPerProcess(uint8 _perProcess) external onlyDeployer { if(_perProcess > 0) { VaultCountPerProcess = _perProcess; } else { revert(); } } function getHash(bytes32 actionType, bytes32 arg1) public pure returns ( bytes32 ) { return keccak256(actionType, arg1); } function getCurrentMilestoneProcessed() public view returns (bool) { return taskByHash[ getHash("MILESTONE_PROCESS_START", getCurrentMilestoneIdHash() ) ]; } function ProcessVaultList(uint8 length) internal { if(taskByHash[currentTask] == false) { if( CurrentEntityState == getEntityState("FUNDING_FAILED_PROGRESS") || CurrentEntityState == getEntityState("FUNDING_SUCCESSFUL_PROGRESS") || CurrentEntityState == getEntityState("MILESTONE_PROCESS_PROGRESS") || CurrentEntityState == getEntityState("EMERGENCY_PROCESS_PROGRESS") || CurrentEntityState == getEntityState("COMPLETE_PROCESS_PROGRESS") ) { uint256 start = lastProcessedVaultId + 1; uint256 end = start + length - 1; if(end > vaultNum) { end = vaultNum; } // first run if(start == 1) { // reset LockedVotingTokens, as we reindex them LockedVotingTokens = 0; } for(uint256 i = start; i <= end; i++) { address currentVault = vaultById[i]; EventFundingManagerProcessedVault(currentVault, i); ProcessFundingVault(currentVault); lastProcessedVaultId++; } if(lastProcessedVaultId >= vaultNum ) { // reset iterator and set task state to true so we can't call it again. lastProcessedVaultId = 0; taskByHash[currentTask] = true; } } else { revert(); } } else { revert(); } } function processFundingFailedFinished() public view returns (bool) { bytes32 thisHash = getHash("FUNDING_FAILED_START", ""); return taskByHash[thisHash]; } function processFundingSuccessfulFinished() public view returns (bool) { bytes32 thisHash = getHash("FUNDING_SUCCESSFUL_START", ""); return taskByHash[thisHash]; } function getCurrentMilestoneIdHash() internal view returns (bytes32) { return bytes32(MilestonesEntity.currentRecord()); } function processMilestoneFinished() public view returns (bool) { bytes32 thisHash = getHash("MILESTONE_PROCESS_START", getCurrentMilestoneIdHash()); return taskByHash[thisHash]; } function processEmergencyFundReleaseFinished() public view returns (bool) { bytes32 thisHash = getHash("EMERGENCY_PROCESS_START", bytes32(0)); return taskByHash[thisHash]; } function ProcessFundingVault(address vaultAddress ) internal { FundingVault vault = FundingVault(vaultAddress); if(vault.allFundingProcessed() == false) { if(CurrentEntityState == getEntityState("FUNDING_SUCCESSFUL_PROGRESS")) { // tokens are minted and allocated to this vault when it receives payments. // vault should now hold as many tokens as the investor bought using direct and milestone funding, // as well as the ether they sent // "direct funding" release -> funds to owner / tokens to investor if(!vault.ReleaseFundsAndTokens()) { revert(); } } else if(CurrentEntityState == getEntityState("MILESTONE_PROCESS_PROGRESS")) { // release funds to owner / tokens to investor if(!vault.ReleaseFundsAndTokens()) { revert(); } } else if(CurrentEntityState == getEntityState("EMERGENCY_PROCESS_PROGRESS")) { // release emergency funds to owner / tokens to investor if(!vault.releaseTokensAndEtherForEmergencyFund()) { revert(); } } // For proposal voting, we need to know how many investor locked tokens remain. LockedVotingTokens+= getAfterTransferLockedTokenBalances(vaultAddress, true); } } function getAfterTransferLockedTokenBalances(address vaultAddress, bool excludeCurrent) public view returns (uint256) { FundingVault vault = FundingVault(vaultAddress); uint8 currentMilestone = MilestonesEntity.currentRecord(); uint256 LockedBalance = 0; // handle emergency funding first if(vault.emergencyFundReleased() == false) { LockedBalance+=vault.tokenBalances(0); } // get token balances starting from current uint8 start = currentMilestone; if(CurrentEntityState != getEntityState("FUNDING_SUCCESSFUL_PROGRESS")) { if(excludeCurrent == true) { start++; } } for(uint8 i = start; i < vault.BalanceNum() ; i++) { LockedBalance+=vault.tokenBalances(i); } return LockedBalance; } function VaultRequestedUpdateForLockedVotingTokens(address owner) public { // validate sender address vaultAddress = vaultList[owner]; if(msg.sender == vaultAddress){ // get token balances starting from current LockedVotingTokens-= getAfterTransferLockedTokenBalances(vaultAddress, false); } } bool FundingPoolBalancesAllocated = false; function AllocateAfterFundingBalances() internal { // allocate owner, advisor, bounty pools if(FundingPoolBalancesAllocated == false) { // mint em! uint256 mintedSupply = TokenEntity.totalSupply(); uint256 salePercent = getAppBylawUint256("token_sale_percentage"); // find one percent uint256 onePercent = (mintedSupply * 1 / salePercent * 100) / 100; // bounty tokens uint256 bountyPercent = getAppBylawUint256("token_bounty_percentage"); uint256 bountyValue = onePercent * bountyPercent; address BountyManagerAddress = getApplicationAssetAddressByName("BountyManager"); TokenManagerEntity.mint( BountyManagerAddress, bountyValue ); // project tokens // should be 40 uint256 projectPercent = 100 - salePercent - bountyPercent; uint256 projectValue = onePercent * projectPercent; // project tokens get minted to Token Manager's address, and are locked there TokenManagerEntity.mint( TokenManagerEntity, projectValue ); TokenManagerEntity.finishMinting(); FundingPoolBalancesAllocated = true; } } function doStateChanges() public { var (returnedCurrentEntityState, EntityStateRequired) = getRequiredStateChanges(); bool callAgain = false; DebugEntityRequiredChanges( assetName, returnedCurrentEntityState, EntityStateRequired ); if(EntityStateRequired != getEntityState("__IGNORED__") ) { EntityProcessor(EntityStateRequired); callAgain = true; } } function hasRequiredStateChanges() public view returns (bool) { bool hasChanges = false; var (returnedCurrentEntityState, EntityStateRequired) = getRequiredStateChanges(); // suppress unused local variable warning returnedCurrentEntityState = 0; if(EntityStateRequired != getEntityState("__IGNORED__") ) { hasChanges = true; } return hasChanges; } function EntityProcessor(uint8 EntityStateRequired) internal { EventEntityProcessor( assetName, CurrentEntityState, EntityStateRequired ); // Update our Entity State CurrentEntityState = EntityStateRequired; // Do State Specific Updates // Funding Failed if ( EntityStateRequired == getEntityState("FUNDING_FAILED_START") ) { // set ProcessVaultList Task currentTask = getHash("FUNDING_FAILED_START", ""); CurrentEntityState = getEntityState("FUNDING_FAILED_PROGRESS"); } else if ( EntityStateRequired == getEntityState("FUNDING_FAILED_PROGRESS") ) { ProcessVaultList(VaultCountPerProcess); // Funding Successful } else if ( EntityStateRequired == getEntityState("FUNDING_SUCCESSFUL_START") ) { // init SCADA variable cache. //if(TokenSCADAEntity.initCacheForVariables()) { // start processing vaults currentTask = getHash("FUNDING_SUCCESSFUL_START", ""); CurrentEntityState = getEntityState("FUNDING_SUCCESSFUL_PROGRESS"); } else if ( EntityStateRequired == getEntityState("FUNDING_SUCCESSFUL_PROGRESS") ) { ProcessVaultList(VaultCountPerProcess); } else if ( EntityStateRequired == getEntityState("FUNDING_SUCCESSFUL_ALLOCATE") ) { AllocateAfterFundingBalances(); // Milestones } else if ( EntityStateRequired == getEntityState("MILESTONE_PROCESS_START") ) { currentTask = getHash("MILESTONE_PROCESS_START", getCurrentMilestoneIdHash() ); CurrentEntityState = getEntityState("MILESTONE_PROCESS_PROGRESS"); } else if ( EntityStateRequired == getEntityState("MILESTONE_PROCESS_PROGRESS") ) { ProcessVaultList(VaultCountPerProcess); // Emergency funding release } else if ( EntityStateRequired == getEntityState("EMERGENCY_PROCESS_START") ) { currentTask = getHash("EMERGENCY_PROCESS_START", bytes32(0) ); CurrentEntityState = getEntityState("EMERGENCY_PROCESS_PROGRESS"); } else if ( EntityStateRequired == getEntityState("EMERGENCY_PROCESS_PROGRESS") ) { ProcessVaultList(VaultCountPerProcess); // Completion } else if ( EntityStateRequired == getEntityState("COMPLETE_PROCESS_START") ) { currentTask = getHash("COMPLETE_PROCESS_START", ""); CurrentEntityState = getEntityState("COMPLETE_PROCESS_PROGRESS"); } else if ( EntityStateRequired == getEntityState("COMPLETE_PROCESS_PROGRESS") ) { // release platform owner tokens from token manager TokenManagerEntity.ReleaseOwnersLockedTokens( FundingEntity.multiSigOutputAddress() ); CurrentEntityState = getEntityState("COMPLETE_PROCESS_DONE"); } } /* * Method: Get Entity Required State Changes * * @access public * @type method * * @return ( uint8 CurrentEntityState, uint8 EntityStateRequired ) */ function getRequiredStateChanges() public view returns (uint8, uint8) { uint8 EntityStateRequired = getEntityState("__IGNORED__"); if(ApplicationInFundingOrDevelopment()) { if ( CurrentEntityState == getEntityState("WAITING") ) { /* This is where we decide if we should process something */ // For funding if(FundingEntity.CurrentEntityState() == FundingEntity.getEntityState("FAILED")) { EntityStateRequired = getEntityState("FUNDING_FAILED_START"); } else if(FundingEntity.CurrentEntityState() == FundingEntity.getEntityState("SUCCESSFUL")) { // make sure we haven't processed this yet if(taskByHash[ getHash("FUNDING_SUCCESSFUL_START", "") ] == false) { EntityStateRequired = getEntityState("FUNDING_SUCCESSFUL_START"); } } else if(FundingEntity.CurrentEntityState() == FundingEntity.getEntityState("SUCCESSFUL_FINAL")) { if ( processMilestoneFinished() == false) { if( MilestonesEntity.CurrentEntityState() == MilestonesEntity.getEntityState("VOTING_ENDED_YES") || MilestonesEntity.CurrentEntityState() == MilestonesEntity.getEntityState("VOTING_ENDED_NO_FINAL") ) { EntityStateRequired = getEntityState("MILESTONE_PROCESS_START"); } } if(processEmergencyFundReleaseFinished() == false) { if(ProposalsEntity.EmergencyFundingReleaseApproved() == true) { EntityStateRequired = getEntityState("EMERGENCY_PROCESS_START"); } } // else, check if all milestones have been processed and try finalising development process // EntityStateRequired = getEntityState("COMPLETE_PROCESS_START"); } } else if ( CurrentEntityState == getEntityState("FUNDING_SUCCESSFUL_PROGRESS") ) { // still in progress? check if we should move to done if ( processFundingSuccessfulFinished() ) { EntityStateRequired = getEntityState("FUNDING_SUCCESSFUL_ALLOCATE"); } else { EntityStateRequired = getEntityState("FUNDING_SUCCESSFUL_PROGRESS"); } } else if ( CurrentEntityState == getEntityState("FUNDING_SUCCESSFUL_ALLOCATE") ) { if(FundingPoolBalancesAllocated) { EntityStateRequired = getEntityState("FUNDING_SUCCESSFUL_DONE"); } } else if ( CurrentEntityState == getEntityState("FUNDING_SUCCESSFUL_DONE") ) { EntityStateRequired = getEntityState("WAITING"); // Funding Failed } else if ( CurrentEntityState == getEntityState("FUNDING_FAILED_PROGRESS") ) { // still in progress? check if we should move to done if ( processFundingFailedFinished() ) { EntityStateRequired = getEntityState("FUNDING_FAILED_DONE"); } else { EntityStateRequired = getEntityState("FUNDING_FAILED_PROGRESS"); } // Milestone process } else if ( CurrentEntityState == getEntityState("MILESTONE_PROCESS_PROGRESS") ) { // still in progress? check if we should move to done if ( processMilestoneFinished() ) { EntityStateRequired = getEntityState("MILESTONE_PROCESS_DONE"); } else { EntityStateRequired = getEntityState("MILESTONE_PROCESS_PROGRESS"); } } else if ( CurrentEntityState == getEntityState("MILESTONE_PROCESS_DONE") ) { if(processMilestoneFinished() == false) { EntityStateRequired = getEntityState("WAITING"); } else if(MilestonesEntity.currentRecord() == MilestonesEntity.RecordNum()) { EntityStateRequired = getEntityState("COMPLETE_PROCESS_START"); } // Emergency funding release } else if ( CurrentEntityState == getEntityState("EMERGENCY_PROCESS_PROGRESS") ) { // still in progress? check if we should move to done if ( processEmergencyFundReleaseFinished() ) { EntityStateRequired = getEntityState("EMERGENCY_PROCESS_DONE"); } else { EntityStateRequired = getEntityState("EMERGENCY_PROCESS_PROGRESS"); } } else if ( CurrentEntityState == getEntityState("EMERGENCY_PROCESS_DONE") ) { EntityStateRequired = getEntityState("WAITING"); // Completion } else if ( CurrentEntityState == getEntityState("COMPLETE_PROCESS_PROGRESS") ) { EntityStateRequired = getEntityState("COMPLETE_PROCESS_PROGRESS"); } } else { if( CurrentEntityState == getEntityState("NEW") ) { // general so we know we initialized EntityStateRequired = getEntityState("WAITING"); } } return (CurrentEntityState, EntityStateRequired); } function ApplicationInFundingOrDevelopment() public view returns(bool) { uint8 AppState = getApplicationState(); if( AppState == getApplicationEntityState("IN_FUNDING") || AppState == getApplicationEntityState("IN_DEVELOPMENT") ) { return true; } return false; } }
Asset States Funding Stage States
function setAssetStates() internal { EntityStates["__IGNORED__"] = 0; EntityStates["NEW"] = 1; EntityStates["WAITING"] = 2; EntityStates["FUNDING_FAILED_START"] = 10; EntityStates["FUNDING_FAILED_PROGRESS"] = 11; EntityStates["FUNDING_FAILED_DONE"] = 12; EntityStates["FUNDING_SUCCESSFUL_START"] = 20; EntityStates["FUNDING_SUCCESSFUL_PROGRESS"] = 21; EntityStates["FUNDING_SUCCESSFUL_DONE"] = 22; EntityStates["FUNDING_SUCCESSFUL_ALLOCATE"] = 25; EntityStates["MILESTONE_PROCESS_START"] = 30; EntityStates["MILESTONE_PROCESS_PROGRESS"] = 31; EntityStates["MILESTONE_PROCESS_DONE"] = 32; EntityStates["EMERGENCY_PROCESS_START"] = 40; EntityStates["EMERGENCY_PROCESS_PROGRESS"] = 41; EntityStates["EMERGENCY_PROCESS_DONE"] = 42; EntityStates["COMPLETE_PROCESS_START"] = 100; EntityStates["COMPLETE_PROCESS_PROGRESS"] = 101; EntityStates["COMPLETE_PROCESS_DONE"] = 102; RecordStates["__IGNORED__"] = 0; }
919,760
pragma solidity ^0.4.24; library SafeMath { 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; } function div(uint256 a, uint256 b) internal pure returns (uint256) {return a / b;} 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 c) { c = a + b; assert(c >= a); return c; } } contract BlackChain { using SafeMath for uint256; uint256 public costPerTicket = 7500000000000000; // Init with 0.0075 ETH per bet uint256 public maxCost = 25000000000000000; // Price increase every 7 days until 0.025 ETH uint256 constant public expireDate = 1543622400; // Contract refused to get any more bets after Dec 1, 2018 bool public confirmed; bool public announced; bool public gameOver; bool public locked; bool private developmentPaid; uint private i; uint256 public startDate; address public owner; address public leader; address public leader_2; address public leader_3; uint256 public announcedTimeStamp; uint256 public rewardPool; uint256 public confirmreward; // Help us confirm when the man die and get a total of 5% ETH reward uint256 public init_fund; uint256 public countConfirmed = 0; uint256 public countPlayer = 0; uint256 public countBet = 0 ; uint256 public countWinners = 0; uint256 public countSecondWinners = 0; uint256 public averageTimestamp; uint256 public numOfConfirmationNeeded; uint256 private share = 0; uint256 public winnerTimestamp = 0; uint256 public secondWinnerTimestamp =0; uint256 countWeek; constructor() payable public { owner = 0xD29C684C272ca7BEb3B54Ed876acF8C784a84fD1; leader = 0xD29C684C272ca7BEb3B54Ed876acF8C784a84fD1; leader_2 = msg.sender; leader_3 = 0xF06A984d59E64687a7Fd508554eB8763899366EE; countWeek = 1; numOfConfirmationNeeded =100; startDate = now; rewardPool = msg.value; init_fund = msg.value; announced = false; confirmed = false; gameOver = false; locked = false; } mapping(uint256 => address[]) mirrors ; uint256[] public timestampList; mapping(address => bool) public isPlayer; mapping(address => bool) public hasConfirmed; mapping(address => uint256[]) public betHistory; mapping(address => uint256) public playerBets; mapping(address => address) public referral; mapping(address => uint256) public countReferral; event Bet(uint256 bets, address indexed player); event Confirm(address player); event Payreward(address indexed player, uint256 reward); function bet(uint256[] _timestamps, address _referral) payable public{ require(msg.value>=costPerTicket.mul(_timestamps.length)); require(!announced); if(now < expireDate){ for(i=0; i<_timestamps.length;i++){ timestampList.push(_timestamps[i]); mirrors[_timestamps[i]].push(msg.sender); betHistory[msg.sender].push(_timestamps[i]); averageTimestamp = averageTimestamp.mul(countBet) + _timestamps[i]; averageTimestamp = averageTimestamp.div(countBet+1); countBet ++; playerBets[msg.sender]++; } if(isPlayer[msg.sender]!=true){ countPlayer++; isPlayer[msg.sender]=true; referral[msg.sender]=_referral; countReferral[_referral]+=1; } if(playerBets[msg.sender]>playerBets[leader] && msg.sender!=leader){ if(msg.sender!=leader_2){ leader_3 = leader_2; } leader_2 = leader; leader = msg.sender; }else if(playerBets[msg.sender]>playerBets[leader_2] && msg.sender !=leader_2 && msg.sender != leader){ leader_3 = leader_2; leader_2 = msg.sender; }else if(playerBets[msg.sender]>playerBets[leader_3] && msg.sender !=leader_2 && msg.sender != leader && msg.sender != leader_3){ leader_3 = msg.sender; } rewardPool=rewardPool.add(msg.value); owner.transfer(msg.value.mul(12).div(100)); // Developement Team get 12% on every transfer emit Bet(_timestamps.length, msg.sender); }else{ if(!locked){ locked=true; } owner.transfer(msg.value); } // Increase Ticket Price every week if(startDate.add(countWeek.mul(604800)) < now ){ countWeek++; if(costPerTicket < maxCost){ costPerTicket=costPerTicket.add(2500000000000000); } } } function payLeaderAndDev() public { require(locked || announced); require(!developmentPaid); // Send 12% of the original fund back to owner owner.transfer(init_fund.mul(12).div(100)); // Send 8% of all rewardPool to Leaderboard winners leader.transfer(rewardPool.mul(4).div(100)); leader_2.transfer(rewardPool.mul(25).div(1000)); leader_3.transfer(rewardPool.mul(15).div(1000)); developmentPaid = true; } function getBetsOnTimestamp(uint256 _timestamp)public view returns (uint256){ return mirrors[_timestamp].length; } function announce(uint256 _timestamp, uint256 _winnerTimestamp_1, uint256 _winnerTimestamp_2) public { require(msg.sender == owner); announced = true; announcedTimeStamp = _timestamp; // Announce winners winnerTimestamp = _winnerTimestamp_1; secondWinnerTimestamp = _winnerTimestamp_2; countWinners = mirrors[winnerTimestamp].length; countSecondWinners = mirrors[secondWinnerTimestamp].length; //5% of total rewardPool goes as confirmreward confirmreward = rewardPool.mul(5).div(100).div(numOfConfirmationNeeded); } function confirm() public{ require(announced==true); require(confirmed==false); require(isPlayer[msg.sender]==true); require(hasConfirmed[msg.sender]!=true); countConfirmed += 1; hasConfirmed[msg.sender] = true; msg.sender.transfer(confirmreward); emit Confirm(msg.sender); emit Payreward(msg.sender, confirmreward); if(countConfirmed>=numOfConfirmationNeeded){ confirmed=true; } } function payWinners() public{ require(confirmed); require(!gameOver); // Send ETH(50%) to first prize winners share = rewardPool.div(2); share = share.div(countWinners); for(i=0; i<countWinners; i++){ mirrors[winnerTimestamp][i].transfer(share.mul(9).div(10)); referral[mirrors[winnerTimestamp][i]].transfer(share.mul(1).div(10)); emit Payreward(mirrors[winnerTimestamp][i], share); } // Send ETH(25%) to second Winners share = rewardPool.div(4); share = share.div(countSecondWinners); for(i=0; i<countSecondWinners; i++){ mirrors[secondWinnerTimestamp][i].transfer(share.mul(9).div(10)); referral[mirrors[secondWinnerTimestamp][i]].transfer(share.mul(1).div(10)); emit Payreward(mirrors[secondWinnerTimestamp][i], share); } // Bye Guys gameOver = true; } function getBalance() public view returns (uint256){ return address(this).balance; } function () public payable { owner.transfer(msg.value); } }
Increase Ticket Price every week
function bet(uint256[] _timestamps, address _referral) payable public{ require(msg.value>=costPerTicket.mul(_timestamps.length)); require(!announced); if(now < expireDate){ for(i=0; i<_timestamps.length;i++){ timestampList.push(_timestamps[i]); mirrors[_timestamps[i]].push(msg.sender); betHistory[msg.sender].push(_timestamps[i]); averageTimestamp = averageTimestamp.mul(countBet) + _timestamps[i]; averageTimestamp = averageTimestamp.div(countBet+1); countBet ++; playerBets[msg.sender]++; } if(isPlayer[msg.sender]!=true){ countPlayer++; isPlayer[msg.sender]=true; referral[msg.sender]=_referral; countReferral[_referral]+=1; } if(playerBets[msg.sender]>playerBets[leader] && msg.sender!=leader){ if(msg.sender!=leader_2){ leader_3 = leader_2; } leader_2 = leader; leader = msg.sender; leader_3 = leader_2; leader_2 = msg.sender; leader_3 = msg.sender; } rewardPool=rewardPool.add(msg.value); emit Bet(_timestamps.length, msg.sender); if(!locked){ locked=true; } owner.transfer(msg.value); } if(startDate.add(countWeek.mul(604800)) < now ){ countWeek++; if(costPerTicket < maxCost){ costPerTicket=costPerTicket.add(2500000000000000); } } }
5,471,582
pragma solidity ^0.4.18; contract ERC721 { // ERC20 compatible functions // use variable getter // function name() constant returns (string name); // function symbol() constant returns (string symbol); function totalSupply() public constant returns (uint256); function balanceOf(address _owner) public constant returns (uint balance); function ownerOf(uint256 _tokenId) public constant returns (address owner); function approve(address _to, uint256 _tokenId) public ; function allowance(address _owner, address _spender) public constant returns (uint256 tokenId); function transfer(address _to, uint256 _tokenId) external ; function transferFrom(address _from, address _to, uint256 _tokenId) external; // Optional // function takeOwnership(uint256 _tokenId) public ; // function tokenOfOwnerByIndex(address _owner, uint256 _index) external constant returns (uint tokenId); // function tokenMetadata(uint256 _tokenId) public constant returns (string infoUrl); // Events event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); } contract ERC20 { // Get the total token supply function totalSupply() public constant returns (uint256 _totalSupply); // Get the account balance of another account with address _owner function balanceOf(address _owner) public constant returns (uint256 balance); // Send _value amount of tokens to address _to function transfer(address _to, uint256 _value) public returns (bool success); // transfer _value amount of token approved by address _from function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); // approve an address with _value amount of tokens function approve(address _spender, uint256 _value) public returns (bool success); // get remaining token approved by _owner to _spender function allowance(address _owner, address _spender) public constant returns (uint256 remaining); // Triggered when tokens are transferred. event Transfer(address indexed _from, address indexed _to, uint256 _value); // Triggered whenever approve(address _spender, uint256 _value) is called. event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract VirtualGift is ERC721 { // load GTO to Virtual Gift contract, to interact with GTO ERC20 GTO = ERC20(0x00C5bBaE50781Be1669306b9e001EFF57a2957b09d); // Gift data struct Gift { // gift price uint256 price; // gift description string description; } address public owner; event Transfer(address indexed _from, address indexed _to, uint256 _GiftId); event Approval(address indexed _owner, address indexed _approved, uint256 _GiftId); event Creation(address indexed _owner, uint256 indexed GiftId); string public constant name = "VirtualGift"; string public constant symbol = "VTG"; // Gift object storage in array Gift[] giftStorage; // total Gift of an address mapping(address => uint256) private balances; // index of Gift array to Owner mapping(uint256 => address) private GiftIndexToOwners; // Gift exist or not mapping(uint256 => bool) private GiftExists; // mapping from owner and approved address to GiftId mapping(address => mapping (address => uint256)) private allowed; // mapping from owner and index Gift of owner to GiftId mapping(address => mapping(uint256 => uint256)) private ownerIndexToGifts; // Gift metadata mapping(uint256 => string) GiftLinks; modifier onlyOwner(){ require(msg.sender == owner); _; } modifier onlyGiftOwner(uint256 GiftId){ require(msg.sender == GiftIndexToOwners[GiftId]); _; } modifier validGift(uint256 GiftId){ require(GiftExists[GiftId]); _; } /// @dev constructor function VirtualGift() public{ owner = msg.sender; // save temporaryly new Gift Gift memory newGift = Gift({ price: 0, description: "MYTHICAL" }); // push to array and return the length is the id of new Gift uint256 mythicalGift = giftStorage.push(newGift) - 1; // id = 0 // mythical Gift is not exist GiftExists[mythicalGift] = false; // assign url for Gift GiftLinks[mythicalGift] = "mythicalGift"; // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(0, msg.sender, mythicalGift); // event create new Gift for msg.sender Creation(msg.sender, mythicalGift); } /// @dev this function change GTO address, this mean you can use many token to buy gift /// by change GTO address to BNB address /// @param newAddress is new address of GTO or another Gift like BNB function changeGTOAddress(address newAddress) public onlyOwner{ GTO = ERC20(newAddress); } /// @dev return current GTO address function getGTOAddress() public constant returns (address) { return address(GTO); } /// @dev return total supply of Gift /// @return length of Gift storage array, except Gift Zero function totalSupply() public constant returns (uint256){ // exclusive Gift Zero return giftStorage.length - 1; } /// @dev allow people to buy Gift /// @param GiftId : id of gift user want to buy function buy(uint256 GiftId) validGift(GiftId) public { // get old owner of Gift address oldowner = ownerOf(GiftId); // tell gifto transfer GTO from new owner to oldowner // NOTE: new owner MUST approve for Virtual Gift contract to take his balance require(GTO.transferFrom(msg.sender, oldowner, giftStorage[GiftId].price) == true); // assign new owner for GiftId // TODO: old owner should have something to confirm that he want to sell this Gift _transfer(oldowner, msg.sender, GiftId); } /// @dev owner send gift to recipient when VG was approved /// @param recipient : received gift /// @param GiftId : id of gift which recipient want to buy function sendGift(address recipient, uint256 GiftId) onlyGiftOwner(GiftId) validGift(GiftId) public { // transfer GTO to owner // require(GTO.transfer(msg.sender, giftStorage[GiftId].price) == true); // transfer gift to recipient _transfer(msg.sender, recipient, GiftId); } /// @dev get total Gift of an address /// @param _owner to get balance /// @return balance of an address function balanceOf(address _owner) public constant returns (uint256 balance){ return balances[_owner]; } function isExist(uint256 GiftId) public constant returns(bool){ return GiftExists[GiftId]; } /// @dev get owner of an Gift id /// @param _GiftId : id of Gift to get owner /// @return owner : owner of an Gift id function ownerOf(uint256 _GiftId) public constant returns (address _owner) { require(GiftExists[_GiftId]); return GiftIndexToOwners[_GiftId]; } /// @dev approve Gift id from msg.sender to an address /// @param _to : address is approved /// @param _GiftId : id of Gift in array function approve(address _to, uint256 _GiftId) validGift(_GiftId) public { require(msg.sender == ownerOf(_GiftId)); require(msg.sender != _to); allowed[msg.sender][_to] = _GiftId; Approval(msg.sender, _to, _GiftId); } /// @dev get id of Gift was approved from owner to spender /// @param _owner : address owner of Gift /// @param _spender : spender was approved /// @return GiftId function allowance(address _owner, address _spender) public constant returns (uint256 GiftId) { return allowed[_owner][_spender]; } /// @dev a spender take owner ship of Gift id, when he was approved /// @param _GiftId : id of Gift has being takeOwnership function takeOwnership(uint256 _GiftId) validGift(_GiftId) public { // get oldowner of Giftid address oldOwner = ownerOf(_GiftId); // new owner is msg sender address newOwner = msg.sender; require(newOwner != oldOwner); // newOwner must be approved by oldOwner require(allowed[oldOwner][newOwner] == _GiftId); // transfer Gift for new owner _transfer(oldOwner, newOwner, _GiftId); // delete approve when being done take owner ship delete allowed[oldOwner][newOwner]; Transfer(oldOwner, newOwner, _GiftId); } /// @dev transfer ownership of a specific Gift to an address. /// @param _from : address owner of Giftid /// @param _to : address's received /// @param _GiftId : Gift id function _transfer(address _from, address _to, uint256 _GiftId) internal { // Since the number of Gift is capped to 2^32 we can't overflow this balances[_to]++; // transfer ownership GiftIndexToOwners[_GiftId] = _to; // When creating new Gift _from is 0x0, but we can't account that address. if (_from != address(0)) { balances[_from]--; } // Emit the transfer event. Transfer(_from, _to, _GiftId); } /// @dev transfer ownership of Giftid from msg sender to an address /// @param _to : address's received /// @param _GiftId : Gift id function transfer(address _to, uint256 _GiftId) validGift(_GiftId) external { // not transfer to zero require(_to != 0x0); // address received different from sender require(msg.sender != _to); // sender must be owner of Giftid require(msg.sender == ownerOf(_GiftId)); // do not send to Gift contract require(_to != address(this)); _transfer(msg.sender, _to, _GiftId); } /// @dev transfer Giftid was approved by _from to _to /// @param _from : address owner of Giftid /// @param _to : address is received /// @param _GiftId : Gift id function transferFrom(address _from, address _to, uint256 _GiftId) validGift(_GiftId) external { require(_from == ownerOf(_GiftId)); // Check for approval and valid ownership require(allowance(_from, msg.sender) == _GiftId); // address received different from _owner require(_from != _to); // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any Gift require(_to != address(this)); // Reassign ownership (also clears pending approvals and emits Transfer event). _transfer(_from, _to, _GiftId); } /// @dev Returns a list of all Gift IDs assigned to an address. /// @param _owner The owner whose Gift we are interested in. /// @notice This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire Gift array looking for Gift belonging to owner), /// @return ownerGifts : list Gift of owner function GiftsOfOwner(address _owner) public view returns(uint256[] ownerGifts) { uint256 GiftCount = balanceOf(_owner); if (GiftCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](GiftCount); uint256 total = totalSupply(); uint256 resultIndex = 0; // We count on the fact that all Gift have IDs starting at 1 and increasing // sequentially up to the totalCat count. uint256 GiftId; // scan array and filter Gift of owner for (GiftId = 0; GiftId <= total; GiftId++) { if (GiftIndexToOwners[GiftId] == _owner) { result[resultIndex] = GiftId; resultIndex++; } } return result; } } /// @dev Returns a Gift IDs assigned to an address. /// @param _owner The owner whose Gift we are interested in. /// @param _index to owner Gift list /// @notice This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire Gift array looking for Gift belonging to owner), /// it is only supported for web3 calls, and /// not contract-to-contract calls. function giftOwnerByIndex(address _owner, uint256 _index) external constant returns (uint256 GiftId) { uint256[] memory ownerGifts = GiftsOfOwner(_owner); return ownerGifts[_index]; } /// @dev get Gift metadata (url) from GiftLinks /// @param _GiftId : Gift id /// @return infoUrl : url of Gift function GiftMetadata(uint256 _GiftId) public constant returns (string infoUrl) { return GiftLinks[_GiftId]; } /// @dev function create new Gift /// @param _price : Gift property /// @param _description : Gift property /// @return GiftId function createGift(uint256 _price, string _description, string _url) public onlyOwner returns (uint256) { // save temporarily new Gift Gift memory newGift = Gift({ price: _price, description: _description }); // push to array and return the length is the id of new Gift uint256 newGiftId = giftStorage.push(newGift) - 1; // turn on existen GiftExists[newGiftId] = true; // assin gift url GiftLinks[newGiftId] = _url; // event create new Gift for msg.sender Creation(msg.sender, newGiftId); // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(0, msg.sender, newGiftId); return newGiftId; } /// @dev get Gift property /// @param GiftId : id of Gift /// @return properties of Gift function getGift(uint256 GiftId) public constant returns (uint256, string){ if(GiftId > giftStorage.length){ return (0, ""); } Gift memory newGift = giftStorage[GiftId]; return (newGift.price, newGift.description); } /// @dev change gift properties /// @param GiftId : to change /// @param _price : new price of gift /// @param _description : new description /// @param _giftUrl : new url function updateGift(uint256 GiftId, uint256 _price, string _description, string _giftUrl) public onlyOwner { // check Gift exist First require(GiftExists[GiftId]); // setting new properties giftStorage[GiftId].price = _price; giftStorage[GiftId].description = _description; GiftLinks[GiftId] = _giftUrl; } /// @dev remove gift /// @param GiftId : gift id to remove function removeGift(uint256 GiftId) public onlyOwner { // just setting GiftExists equal to false GiftExists[GiftId] = false; } /// @dev withdraw GTO in this contract function withdrawGTO() onlyOwner public { GTO.transfer(owner, GTO.balanceOf(address(this))); } }
transfer ownership of Giftid from msg sender to an address _to : address's received _GiftId : Gift id not transfer to zero address received different from sender sender must be owner of Giftid do not send to Gift contract
function transfer(address _to, uint256 _GiftId) validGift(_GiftId) external { require(_to != 0x0); require(msg.sender != _to); require(msg.sender == ownerOf(_GiftId)); require(_to != address(this)); _transfer(msg.sender, _to, _GiftId); }
15,884,082
./partial_match/42/0xb2A9c9cB4796dFc137a3EbBF312d73A7837CF708/sources/PobTokenPresale.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,460,823
pragma solidity ^0.4.18; import 'zeppelin-solidity/contracts/math/SafeMath.sol'; import 'zeppelin-solidity/contracts/token/ERC20/MintableToken.sol'; import './Whitelist.sol'; /** * @title Payout * @dev Payout capacity: eth sent to this contract (by Tokenestate) will be distributed to their token holders */ contract Payout is MintableToken, Whitelist { using SafeMath for uint256; // Not every year equals 365 days, because of leap year, and not even every day has 24 hours, because of leap seconds // We don't need strong precision here because we want the token holders should claim his // payout during min 5 years. uint256 public payoutTimeout = 5 years + 2 days; //Payout not accounted yet to make system rounding error proof uint256 public rounding = 0; struct Beneficiary { uint256 nbTokens; bool isNbSharesInitialized; bool hasClaimed; } struct PayoutObject { string addr; //Uri of payout document bytes32 hash; //Hash of the uri content for checking uint256 startTime; uint256 endTime; uint256 totalWei; uint256 nbWeiPerToken; uint256 totalWeiPayed; mapping(address => Beneficiary) beneficiaries; } PayoutObject[] public payoutObjects; event PayoutAvailable(string addr, bytes32 hash, uint256 startTime, uint256 endTime, uint256 totalWei, uint256 nbWeiPerToken, uint256 payoutId); event PayoutClaimed(address addr, uint256 nbTokens, uint256 nbWeiPerToken, uint256 amount, uint256 payoutId); /** * @dev Submit a payout Object * @param _addr Uri of payout document. * @param _hash Hash of the uri content. */ function payoutObject(string _addr, bytes32 _hash) onlyOwner public payable { //require(!shouldRemovePayoutObject(0)); // Remove expired payout first require(_hash != bytes32(0)); require(bytes(_addr).length > 0); require(msg.value > 0); uint256 _totalWei = msg.value; uint256 _nbWeiPerToken = nbWeiPerToken(_totalWei); _totalWei = _nbWeiPerToken.mul(totalSupply_); // After rounding uint256 _endTime = now.add(payoutTimeout); payoutObjects.push(PayoutObject({ addr: _addr, hash: _hash, startTime: now, endTime: _endTime, totalWei: _totalWei, nbWeiPerToken: _nbWeiPerToken, totalWeiPayed: 0 })); PayoutAvailable(_addr, _hash, now, _endTime, _totalWei, _nbWeiPerToken, payoutObjects.length-1); } /** * @dev Returns the number of Wei available per token and update rounding accordingly * @param valueWei Number of Wei available for all tokens. */ // TODO: separate concerns and improve method name function nbWeiPerToken(uint256 valueWei) internal returns (uint256) { uint256 totalWei = valueWei.add(rounding); // add old rounding rounding = totalWei % totalSupply_; // ensure no rounding error return totalWei.sub(rounding).div(totalSupply_); // weiPerToken } /** * @dev Returns true if the payout has expired * @param payoutId Id of payout to check. */ function isPayoutExpired(uint8 payoutId) public view returns (bool) { return payoutObjects[payoutId].endTime < now; } /** * @dev No payment to the contract should be possible with fallback method */ function() public payable { revert(); } /** * @dev Initialize the number of shares for payout for a beneficiary if needed * @param addr The address to initialize. * @param balance The number of shares. */ function initNbSharesForPayoutIfNeeded(address addr, uint256 balance) internal { for (uint8 payoutId = 0; payoutId < payoutObjects.length; payoutId++) { Beneficiary memory beneficiary = payoutObjects[payoutId].beneficiaries[addr]; if(!beneficiary.isNbSharesInitialized) { initNbSharesForPayout(addr, balance, payoutId); } } } /** * @dev Initialize the number of shares for payout for a beneficiary * @param addr The address to initialize. * @param balance The number of shares. * @param payoutId Id of payout to update. */ function initNbSharesForPayout(address addr, uint256 balance, uint8 payoutId) internal { Beneficiary storage beneficiary = payoutObjects[payoutId].beneficiaries[addr]; beneficiary.isNbSharesInitialized = true; beneficiary.nbTokens = balance; } /** * @dev Returns false if no payout Object, true otherwise */ function hasPayout() public view returns (bool) { return payoutObjects.length > 0; } /** * @dev Returns the number of shares available for an account * @param addr The address to enquire. * @param payoutId Id of payout to update. */ function showNbShares(address addr, uint8 payoutId) public constant returns (uint256) { PayoutObject memory payout = payoutObjects[payoutId]; if (now < payout.endTime) { Beneficiary memory beneficiary = payoutObjects[payoutId].beneficiaries[addr]; if (beneficiary.hasClaimed) { return 0; } if(beneficiary.isNbSharesInitialized) { return beneficiary.nbTokens; } return balances[addr]; } return 0; } /** * @dev Send payout amount on caller address * @param payoutId Id of claimed payout. */ function claimPayout(uint8 payoutId) payoutExist(payoutId) isWhitelisted(msg.sender) public { require(!isPayoutExpired(payoutId)); uint256 nbTokens = showNbShares(msg.sender, payoutId); require(nbTokens > 0); PayoutObject storage payout = payoutObjects[payoutId]; Beneficiary storage beneficiary = payout.beneficiaries[msg.sender]; require(!beneficiary.hasClaimed); beneficiary.hasClaimed = true; uint256 payoutAmount = payout.nbWeiPerToken.mul(nbTokens); payout.totalWeiPayed += payoutAmount; require(payout.totalWeiPayed <= payout.totalWei); PayoutClaimed(msg.sender, nbTokens, payout.nbWeiPerToken, payoutAmount, payoutId); assert(msg.sender.send(payoutAmount)); } /** * @dev Throws if paout doesn't exist * @param payoutId Id of claimed payout. */ modifier payoutExist(uint8 payoutId) { require(payoutObjects.length > payoutId); _; } /** * @dev Send non claimed payout amount to the contract owner address * @param payoutId Id of expired payout. */ function withdrawExpiredPayout(uint8 payoutId) onlyOwner payoutExist(payoutId) public { require(isPayoutExpired(payoutId)); PayoutObject storage payout = payoutObjects[payoutId]; uint256 withdrawAmount = payout.totalWei - payout.totalWeiPayed; require(withdrawAmount > 0); payout.totalWeiPayed += withdrawAmount; assert(owner.send(withdrawAmount)); } /** * @dev Set timeout for payout * @param _payoutTimeout Timeout for expired payout. */ function setPayoutTimeout(uint256 _payoutTimeout) onlyOwner public { require(_payoutTimeout > 1 years); payoutTimeout = _payoutTimeout; } }
Initialize the number of shares for payout for a beneficiary if needed addr The address to initialize. balance The number of shares./
function initNbSharesForPayoutIfNeeded(address addr, uint256 balance) internal { for (uint8 payoutId = 0; payoutId < payoutObjects.length; payoutId++) { Beneficiary memory beneficiary = payoutObjects[payoutId].beneficiaries[addr]; if(!beneficiary.isNbSharesInitialized) { initNbSharesForPayout(addr, balance, payoutId); } } }
12,664,947
pragma solidity ^0.4.11; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal 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 returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value); function approve(address spender, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) { require ( balances[msg.sender] >= _value); // Check if the sender has enough require (balances[_to] + _value >= balances[_to]); // Check for overflows balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); } // burn tokens from sender balance function burn(uint256 _value) { require ( balances[msg.sender] >= _value); // Check if the sender has enough balances[msg.sender] = balances[msg.sender].sub(_value); Burn(msg.sender, _value); } /** * @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) constant returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); } /** * @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) { // 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); } /** * @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]; } } contract Ownable { address public owner; /** * @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 { if (newOwner != address(0)) { owner = newOwner; } } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); string public name = "Crystal Clear Token"; string public symbol = "CCT"; uint256 public decimals = 18; bool public mintingFinished = false; modifier canMint() { require(!mintingFinished) ; _; } function MintableToken(){ mint(msg.sender,10000000000000000000000000); finishMinting(); } /** * @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) onlyOwner canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } }
burn tokens from sender balance
function burn(uint256 _value) { balances[msg.sender] = balances[msg.sender].sub(_value); Burn(msg.sender, _value); }
7,759,730
pragma solidity ^0.5.4; /** * ERC20 contract interface. */ contract ERC20 { function totalSupply() public view returns (uint); function decimals() 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); } /** * @title Module * @dev Interface for a module. * A module MUST implement the addModule() method to ensure that a wallet with at least one module * can never end up in a "frozen" state. * @author Julien Niset - <julien@argent.xyz> */ interface Module { function init(BaseWallet _wallet) external; function addModule(BaseWallet _wallet, Module _module) external; function recoverToken(address _token) external; } /** * @title BaseWallet * @dev Simple modular wallet that authorises modules to call its invoke() method. * Based on https://gist.github.com/Arachnid/a619d31f6d32757a4328a428286da186 by * @author Julien Niset - <julien@argent.xyz> */ contract BaseWallet { address public implementation; address public owner; mapping (address => bool) public authorised; mapping (bytes4 => address) public enabled; uint public modules; function init(address _owner, address[] calldata _modules) external; function authoriseModule(address _module, bool _value) external; function enableStaticCall(address _module, bytes4 _method) external; function setOwner(address _newOwner) external; function invoke(address _target, uint _value, bytes calldata _data) external; function() external payable; } /** * @title ModuleRegistry * @dev Registry of authorised modules. * Modules must be registered before they can be authorised on a wallet. * @author Julien Niset - <julien@argent.xyz> */ contract ModuleRegistry { function registerModule(address _module, bytes32 _name) external; function deregisterModule(address _module) external; function registerUpgrader(address _upgrader, bytes32 _name) external; function deregisterUpgrader(address _upgrader) external; function recoverToken(address _token) external; function moduleInfo(address _module) external view returns (bytes32); function upgraderInfo(address _upgrader) external view returns (bytes32); function isRegisteredModule(address _module) external view returns (bool); function isRegisteredModule(address[] calldata _modules) external view returns (bool); function isRegisteredUpgrader(address _upgrader) external view returns (bool); } /** * @title GuardianStorage * @dev Contract storing the state of wallets related to guardians and lock. * The contract only defines basic setters and getters with no logic. Only modules authorised * for a wallet can modify its state. * @author Julien Niset - <julien@argent.xyz> * @author Olivier Van Den Biggelaar - <olivier@argent.xyz> */ contract GuardianStorage { function addGuardian(BaseWallet _wallet, address _guardian) external; function revokeGuardian(BaseWallet _wallet, address _guardian) external; function guardianCount(BaseWallet _wallet) external view returns (uint256); function getGuardians(BaseWallet _wallet) external view returns (address[] memory); function isGuardian(BaseWallet _wallet, address _guardian) external view returns (bool); function setLock(BaseWallet _wallet, uint256 _releaseAfter) external; function isLocked(BaseWallet _wallet) external view returns (bool); function getLock(BaseWallet _wallet) external view returns (uint256); function getLocker(BaseWallet _wallet) external view returns (address); } /** * @title BaseModule * @dev Basic module that contains some methods common to all modules. * @author Julien Niset - <julien@argent.im> */ contract BaseModule is Module { // The adddress of the module registry. ModuleRegistry internal registry; event ModuleCreated(bytes32 name); event ModuleInitialised(address wallet); constructor(ModuleRegistry _registry, bytes32 _name) public { registry = _registry; emit ModuleCreated(_name); } /** * @dev Throws if the sender is not the target wallet of the call. */ modifier onlyWallet(BaseWallet _wallet) { require(msg.sender == address(_wallet), "BM: caller must be wallet"); _; } /** * @dev Throws if the sender is not the owner of the target wallet or the module itself. */ modifier onlyWalletOwner(BaseWallet _wallet) { require(msg.sender == address(this) || isOwner(_wallet, msg.sender), "BM: must be an owner for the wallet"); _; } /** * @dev Throws if the sender is not the owner of the target wallet. */ modifier strictOnlyWalletOwner(BaseWallet _wallet) { require(isOwner(_wallet, msg.sender), "BM: msg.sender must be an owner for the wallet"); _; } /** * @dev Inits the module for a wallet by logging an event. * The method can only be called by the wallet itself. * @param _wallet The wallet. */ function init(BaseWallet _wallet) external onlyWallet(_wallet) { emit ModuleInitialised(address(_wallet)); } /** * @dev Adds a module to a wallet. First checks that the module is registered. * @param _wallet The target wallet. * @param _module The modules to authorise. */ function addModule(BaseWallet _wallet, Module _module) external strictOnlyWalletOwner(_wallet) { require(registry.isRegisteredModule(address(_module)), "BM: module is not registered"); _wallet.authoriseModule(address(_module), true); } /** * @dev Utility method enbaling anyone to recover ERC20 token sent to the * module by mistake and transfer them to the Module Registry. * @param _token The token to recover. */ function recoverToken(address _token) external { uint total = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(address(registry), total); } /** * @dev Helper method to check if an address is the owner of a target wallet. * @param _wallet The target wallet. * @param _addr The address. */ function isOwner(BaseWallet _wallet, address _addr) internal view returns (bool) { return _wallet.owner() == _addr; } } /** * @title RelayerModule * @dev Base module containing logic to execute transactions signed by eth-less accounts and sent by a relayer. * @author Julien Niset - <julien@argent.im> */ contract RelayerModule is Module { uint256 constant internal BLOCKBOUND = 10000; mapping (address => RelayerConfig) public relayer; struct RelayerConfig { uint256 nonce; mapping (bytes32 => bool) executedTx; } event TransactionExecuted(address indexed wallet, bool indexed success, bytes32 signedHash); /** * @dev Throws if the call did not go through the execute() method. */ modifier onlyExecute { require(msg.sender == address(this), "RM: must be called via execute()"); _; } /* ***************** Abstract method ************************* */ /** * @dev Gets the number of valid signatures that must be provided to execute a * specific relayed transaction. * @param _wallet The target wallet. * @param _data The data of the relayed transaction. * @return The number of required signatures. */ function getRequiredSignatures(BaseWallet _wallet, bytes memory _data) internal view returns (uint256); /** * @dev Validates the signatures provided with a relayed transaction. * The method MUST throw if one or more signatures are not valid. * @param _wallet The target wallet. * @param _data The data of the relayed transaction. * @param _signHash The signed hash representing the relayed transaction. * @param _signatures The signatures as a concatenated byte array. */ function validateSignatures(BaseWallet _wallet, bytes memory _data, bytes32 _signHash, bytes memory _signatures) internal view returns (bool); /* ************************************************************ */ /** * @dev Executes a relayed transaction. * @param _wallet The target wallet. * @param _data The data for the relayed transaction * @param _nonce The nonce used to prevent replay attacks. * @param _signatures The signatures as a concatenated byte array. * @param _gasPrice The gas price to use for the gas refund. * @param _gasLimit The gas limit to use for the gas refund. */ function execute( BaseWallet _wallet, bytes calldata _data, uint256 _nonce, bytes calldata _signatures, uint256 _gasPrice, uint256 _gasLimit ) external returns (bool success) { uint startGas = gasleft(); bytes32 signHash = getSignHash(address(this), address(_wallet), 0, _data, _nonce, _gasPrice, _gasLimit); require(checkAndUpdateUniqueness(_wallet, _nonce, signHash), "RM: Duplicate request"); require(verifyData(address(_wallet), _data), "RM: the wallet authorized is different then the target of the relayed data"); uint256 requiredSignatures = getRequiredSignatures(_wallet, _data); if((requiredSignatures * 65) == _signatures.length) { if(verifyRefund(_wallet, _gasLimit, _gasPrice, requiredSignatures)) { if(requiredSignatures == 0 || validateSignatures(_wallet, _data, signHash, _signatures)) { // solium-disable-next-line security/no-call-value (success,) = address(this).call(_data); refund(_wallet, startGas - gasleft(), _gasPrice, _gasLimit, requiredSignatures, msg.sender); } } } emit TransactionExecuted(address(_wallet), success, signHash); } /** * @dev Gets the current nonce for a wallet. * @param _wallet The target wallet. */ function getNonce(BaseWallet _wallet) external view returns (uint256 nonce) { return relayer[address(_wallet)].nonce; } /** * @dev Generates the signed hash of a relayed transaction according to ERC 1077. * @param _from The starting address for the relayed transaction (should be the module) * @param _to The destination address for the relayed transaction (should be the wallet) * @param _value The value for the relayed transaction * @param _data The data for the relayed transaction * @param _nonce The nonce used to prevent replay attacks. * @param _gasPrice The gas price to use for the gas refund. * @param _gasLimit The gas limit to use for the gas refund. */ function getSignHash( address _from, address _to, uint256 _value, bytes memory _data, uint256 _nonce, uint256 _gasPrice, uint256 _gasLimit ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked(byte(0x19), byte(0), _from, _to, _value, _data, _nonce, _gasPrice, _gasLimit)) )); } /** * @dev Checks if the relayed transaction is unique. * @param _wallet The target wallet. * @param _nonce The nonce * @param _signHash The signed hash of the transaction */ function checkAndUpdateUniqueness(BaseWallet _wallet, uint256 _nonce, bytes32 _signHash) internal returns (bool) { if(relayer[address(_wallet)].executedTx[_signHash] == true) { return false; } relayer[address(_wallet)].executedTx[_signHash] = true; return true; } /** * @dev Checks that a nonce has the correct format and is valid. * It must be constructed as nonce = {block number}{timestamp} where each component is 16 bytes. * @param _wallet The target wallet. * @param _nonce The nonce */ function checkAndUpdateNonce(BaseWallet _wallet, uint256 _nonce) internal returns (bool) { if(_nonce <= relayer[address(_wallet)].nonce) { return false; } uint256 nonceBlock = (_nonce & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000) >> 128; if(nonceBlock > block.number + BLOCKBOUND) { return false; } relayer[address(_wallet)].nonce = _nonce; return true; } /** * @dev Recovers the signer at a given position from a list of concatenated signatures. * @param _signedHash The signed hash * @param _signatures The concatenated signatures. * @param _index The index of the signature to recover. */ function recoverSigner(bytes32 _signedHash, bytes memory _signatures, uint _index) internal pure returns (address) { uint8 v; bytes32 r; bytes32 s; // we jump 32 (0x20) as the first slot of bytes contains the length // we jump 65 (0x41) per signature // for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(_signatures, add(0x20,mul(0x41,_index)))) s := mload(add(_signatures, add(0x40,mul(0x41,_index)))) v := and(mload(add(_signatures, add(0x41,mul(0x41,_index)))), 0xff) } require(v == 27 || v == 28); return ecrecover(_signedHash, v, r, s); } /** * @dev Refunds the gas used to the Relayer. * For security reasons the default behavior is to not refund calls with 0 or 1 signatures. * @param _wallet The target wallet. * @param _gasUsed The gas used. * @param _gasPrice The gas price for the refund. * @param _gasLimit The gas limit for the refund. * @param _signatures The number of signatures used in the call. * @param _relayer The address of the Relayer. */ function refund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _gasLimit, uint _signatures, address _relayer) internal { uint256 amount = 29292 + _gasUsed; // 21000 (transaction) + 7620 (execution of refund) + 672 to log the event + _gasUsed // only refund if gas price not null, more than 1 signatures, gas less than gasLimit if(_gasPrice > 0 && _signatures > 1 && amount <= _gasLimit) { if(_gasPrice > tx.gasprice) { amount = amount * tx.gasprice; } else { amount = amount * _gasPrice; } _wallet.invoke(_relayer, amount, ""); } } /** * @dev Returns false if the refund is expected to fail. * @param _wallet The target wallet. * @param _gasUsed The expected gas used. * @param _gasPrice The expected gas price for the refund. */ function verifyRefund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _signatures) internal view returns (bool) { if(_gasPrice > 0 && _signatures > 1 && (address(_wallet).balance < _gasUsed * _gasPrice || _wallet.authorised(address(this)) == false)) { return false; } return true; } /** * @dev Checks that the wallet address provided as the first parameter of the relayed data is the same * as the wallet passed as the input of the execute() method. @return false if the addresses are different. */ function verifyData(address _wallet, bytes memory _data) private pure returns (bool) { require(_data.length >= 36, "RM: Invalid dataWallet"); address dataWallet; // solium-disable-next-line security/no-inline-assembly assembly { //_data = {length:32}{sig:4}{_wallet:32}{...} dataWallet := mload(add(_data, 0x24)) } return dataWallet == _wallet; } /** * @dev Parses the data to extract the method signature. */ function functionPrefix(bytes memory _data) internal pure returns (bytes4 prefix) { require(_data.length >= 4, "RM: Invalid functionPrefix"); // solium-disable-next-line security/no-inline-assembly assembly { prefix := mload(add(_data, 0x20)) } } } /** * @title OnlyOwnerModule * @dev Module that extends BaseModule and RelayerModule for modules where the execute() method * must be called with one signature frm the owner. * @author Julien Niset - <julien@argent.im> */ contract OnlyOwnerModule is BaseModule, RelayerModule { // *************** Implementation of RelayerModule methods ********************* // // Overrides to use the incremental nonce and save some gas function checkAndUpdateUniqueness(BaseWallet _wallet, uint256 _nonce, bytes32 _signHash) internal returns (bool) { return checkAndUpdateNonce(_wallet, _nonce); } function validateSignatures(BaseWallet _wallet, bytes memory _data, bytes32 _signHash, bytes memory _signatures) internal view returns (bool) { address signer = recoverSigner(_signHash, _signatures, 0); return isOwner(_wallet, signer); // "OOM: signer must be owner" } function getRequiredSignatures(BaseWallet _wallet, bytes memory _data) internal view returns (uint256) { return 1; } } /** * @title NftTransfer * @dev Module to transfer NFTs (ERC721), * @author Olivier VDB - <olivier@argent.xyz> */ contract NftTransfer is BaseModule, RelayerModule, OnlyOwnerModule { bytes32 constant NAME = "NftTransfer"; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` bytes4 private constant ERC721_RECEIVED = 0x150b7a02; // The Guardian storage GuardianStorage public guardianStorage; // The address of the CryptoKitties contract address public ckAddress; // *************** Events *************************** // event NonFungibleTransfer(address indexed wallet, address indexed nftContract, uint256 indexed tokenId, address to, bytes data); // *************** Modifiers *************************** // /** * @dev Throws if the wallet is locked. */ modifier onlyWhenUnlocked(BaseWallet _wallet) { // solium-disable-next-line security/no-block-members require(!guardianStorage.isLocked(_wallet), "NT: wallet must be unlocked"); _; } // *************** Constructor ********************** // constructor( ModuleRegistry _registry, GuardianStorage _guardianStorage, address _ckAddress ) BaseModule(_registry, NAME) public { guardianStorage = _guardianStorage; ckAddress = _ckAddress; } // *************** External/Public Functions ********************* // /** * @dev Inits the module for a wallet by setting up the onERC721Received * static call redirection from the wallet to the module. * @param _wallet The target wallet. */ function init(BaseWallet _wallet) external onlyWallet(_wallet) { _wallet.enableStaticCall(address(this), ERC721_RECEIVED); } /** * @notice Handle the receipt of an NFT * @dev An ERC721 smart contract calls this function on the recipient contract * after a `safeTransfer`. If the recipient is a BaseWallet, the call to onERC721Received * will be forwarded to the method onERC721Received of the present module. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4) { return ERC721_RECEIVED; } /** * @dev lets the owner transfer NFTs from a wallet. * @param _wallet The target wallet. * @param _nftContract The ERC721 address. * @param _to The recipient. * @param _tokenId The NFT id * @param _safe Whether to execute a safe transfer or not * @param _data The data to pass with the transfer. */ function transferNFT( BaseWallet _wallet, address _nftContract, address _to, uint256 _tokenId, bool _safe, bytes calldata _data ) external onlyWalletOwner(_wallet) onlyWhenUnlocked(_wallet) { bytes memory methodData; if(_nftContract == ckAddress) { methodData = abi.encodeWithSignature("transfer(address,uint256)", _to, _tokenId); } else { if(_safe) { methodData = abi.encodeWithSignature( "safeTransferFrom(address,address,uint256,bytes)", address(_wallet), _to, _tokenId, _data); } else { require(isERC721(_nftContract, _tokenId), "NT: Non-compliant NFT contract"); methodData = abi.encodeWithSignature( "transferFrom(address,address,uint256)", address(_wallet), _to, _tokenId); } } _wallet.invoke(_nftContract, 0, methodData); emit NonFungibleTransfer(address(_wallet), _nftContract, _tokenId, _to, _data); } // *************** Internal Functions ********************* // /** * @dev Check whether a given contract complies with ERC721. * @param _nftContract The contract to check. * @param _tokenId The tokenId to use for the check. * @return true if the contract is an ERC721, false otherwise. */ function isERC721(address _nftContract, uint256 _tokenId) internal returns (bool) { // solium-disable-next-line security/no-low-level-calls (bool success, bytes memory result) = _nftContract.call(abi.encodeWithSignature('supportsInterface(bytes4)', 0x80ac58cd)); if(success && result[0] != 0x0) return true; // solium-disable-next-line security/no-low-level-calls (success, result) = _nftContract.call(abi.encodeWithSignature('supportsInterface(bytes4)', 0x6466353c)); if(success && result[0] != 0x0) return true; // solium-disable-next-line security/no-low-level-calls (success,) = _nftContract.call(abi.encodeWithSignature('ownerOf(uint256)', _tokenId)); return success; } }
Handle the receipt of an NFT An ERC721 smart contract calls this function on the recipient contract after a `safeTransfer`. If the recipient is a BaseWallet, the call to onERC721Received will be forwarded to the method onERC721Received of the present module. operator The address which called `safeTransferFrom` function from The address which previously owned the token tokenId The NFT identifier which is being transferred data Additional data with no specified format return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4) { return ERC721_RECEIVED; }
5,543,215
./full_match/4/0x0b08f24c0346337837C7B4031c531F4E2E4087Fa/sources/mynft.sol
ERC-721 Non-Fungible Token Standard, optional metadata extension/
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); } }
720,661
./full_match/42/0x857BbFEDEb123107F0Bb9990be49ebE88960Aac0/sources/uniswap-solidity-example/flatten/Flattened.sol
number / 100 is amount in ether require(wethToken.balanceOf(address(this)) > 0, "Weth amount is zero"); require(newAmount > 0, "Weth amount is zero");
function test(uint256 _amount) external onlyAdmin { uint256 newAmount = _amount * 1000000000000000; address UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; uniswapRouter = IUniswapV2Router02(UNISWAP_ROUTER_ADDRESS); uniswapRouterAddress = UNISWAP_ROUTER_ADDRESS; address multiDaiKovan = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa; address _wethAddress = 0xd0A1E359811322d97991E03f863a0C30C2cF029C; wethToken = IERC20(_wethAddress); wethAddress = _wethAddress; wethToken.approve(uniswapRouterAddress, newAmount *2); uint256 aAmount = wethToken.balanceOf(address(this)); uniswapRouter.swapExactTokensForTokens( newAmount, 1000000, getPathForWethtoDAI(), address(this), block.timestamp + 15 ); }
16,285,460
./full_match/5/0xa987Be2cE29A4EE51745604c0B83041c04a75FbB/sources/contracts/SBTnft.sol
uint256 amountToken = calculatePoint(_mintAmount);
function mintNFT(uint256 _mintAmountA , uint256 _mintAmountB ,uint256 _mintAmountC) public payable checkbalance(){ Auction memory currentAuction = auction; require(lock,"Wait for public sale"); require(block.timestamp >= currentAuction.firstStat, "Auction not started"); require(pointBalances[msg.sender] >= _mintAmountA + _mintAmountB + _mintAmountC, "Buy call option first"); uint256 amountETH = _mintAmountA * 3 * getAuctionPrice() + _mintAmountB * 2 * getAuctionPrice() + _mintAmountC * getAuctionPrice(); require( balanceOf(msg.sender) + _mintAmountA + _mintAmountB + _mintAmountC <= maxPerWallet, "exceed max wallet limit" ); require(msg.value == amountETH, "Must send the correct amount of ETH"); if (block.timestamp < currentAuction.secondStat){ require(nowSupplyA + _mintAmountA <= maxSupplyA && nowSupplyB + _mintAmountB <= maxSupplyB && nowSupplyC + _mintAmountC <= maxSupplyC, "sold out"); useCallOption(_mintAmountA + _mintAmountB + _mintAmountC); for (uint256 i = 0; i < _mintAmountA; i++) { uint256 newTokenId = nowSupplyA + 1; nowSupplyA++; _safeMint(msg.sender, newTokenId); addressNFTs[msg.sender].push(newTokenId); emit firstMint(newTokenId,msg.sender,block.timestamp); } for (uint256 i = 0; i < _mintAmountB; i++) { uint256 newTokenId = nowSupplyB + maxSupplyA + 1; nowSupplyB++; _safeMint(msg.sender, newTokenId); addressNFTs[msg.sender].push(newTokenId); emit firstMint(newTokenId,msg.sender,block.timestamp); } for (uint256 i = 0; i < _mintAmountC; i++) { uint256 newTokenId = nowSupplyC + maxSupplyA + maxSupplyB + 1; nowSupplyC++; _safeMint(msg.sender, newTokenId); addressNFTs[msg.sender].push(newTokenId); emit firstMint(newTokenId,msg.sender,block.timestamp); } } else{ require(nowSupplyA + _mintAmountA <= maxSupplyA + nextSaleNumberA && nowSupplyB + _mintAmountB <= maxSupplyB + nextSaleNumberB && nowSupplyC + _mintAmountC <= maxSupplyC + nextSaleNumberC, "sold out"); useCallOption(_mintAmountA + _mintAmountB + _mintAmountC); uint256 newTokenIdA = maxSupplyA + maxSupplyB + maxSupplyC + secSupplyA ; uint256 newTokenIdB = maxSupplyA + newTokenIdA ; uint256 newTokenIdC = maxSupplyB + newTokenIdB ; for (uint256 i = 0; i < _mintAmountA; i++) { secSupplyA++; _safeMint(msg.sender, newTokenIdA); emit secondMint(newTokenIdA,msg.sender,block.timestamp); } for (uint256 i = 0; i < _mintAmountB; i++) { secSupplyB++; _safeMint(msg.sender, newTokenIdB); emit secondMint(newTokenIdB,msg.sender,block.timestamp); } for (uint256 i = 0; i < _mintAmountC; i++) { secSupplyC++; _safeMint(msg.sender, newTokenIdC); emit secondMint(newTokenIdC,msg.sender,block.timestamp); } } }
11,621,460
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "../../openzeppelin-upgradeable/token/ERC1155/ERC1155Upgradeable.sol"; import "../libraries-solidity/access/AdminControlUpgradeable.sol"; import "./core/ERC1155CreatorCore.sol"; /** * @dev ERC1155Creator implementation */ contract ERC1155CreatorImplementation is AdminControlUpgradeable, ERC1155Upgradeable, ERC1155CreatorCore { mapping(uint256 => uint256) private _totalSupply; /** * Initializer */ function initialize() public initializer { __ERC1155_init(""); __Ownable_init(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override( ERC1155Upgradeable, ERC1155CreatorCore, AdminControlUpgradeable ) returns (bool) { return ERC1155CreatorCore.supportsInterface(interfaceId) || ERC1155Upgradeable.supportsInterface(interfaceId) || AdminControlUpgradeable.supportsInterface(interfaceId); } function _beforeTokenTransfer( address, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory ) internal virtual override { _approveTransfer(from, to, ids, amounts); } /** * @dev See {ICreatorCore-registerExtension}. */ function registerExtension(address extension, string calldata baseURI) external override adminRequired nonBlacklistRequired(extension) { _registerExtension(extension, baseURI, false); } /** * @dev See {ICreatorCore-registerExtension}. */ function registerExtension( address extension, string calldata baseURI, bool baseURIIdentical ) external override adminRequired nonBlacklistRequired(extension) { _registerExtension(extension, baseURI, baseURIIdentical); } /** * @dev See {ICreatorCore-unregisterExtension}. */ function unregisterExtension(address extension) external override adminRequired { _unregisterExtension(extension); } /** * @dev See {ICreatorCore-blacklistExtension}. */ function blacklistExtension(address extension) external override adminRequired { _blacklistExtension(extension); } /** * @dev See {ICreatorCore-setBaseTokenURIExtension}. */ function setBaseTokenURIExtension(string calldata uri_) external override extensionRequired { _setBaseTokenURIExtension(uri_, false); } /** * @dev See {ICreatorCore-setBaseTokenURIExtension}. */ function setBaseTokenURIExtension(string calldata uri_, bool identical) external override extensionRequired { _setBaseTokenURIExtension(uri_, identical); } /** * @dev See {ICreatorCore-setTokenURIPrefixExtension}. */ function setTokenURIPrefixExtension(string calldata prefix) external override extensionRequired { _setTokenURIPrefixExtension(prefix); } /** * @dev See {ICreatorCore-setTokenURIExtension}. */ function setTokenURIExtension(uint256 tokenId, string calldata uri_) external override extensionRequired { _setTokenURIExtension(tokenId, uri_); } /** * @dev See {ICreatorCore-setTokenURIExtension}. */ function setTokenURIExtension( uint256[] memory tokenIds, string[] calldata uris ) external override extensionRequired { require(tokenIds.length == uris.length, "Invalid input"); for (uint256 i = 0; i < tokenIds.length; i++) { _setTokenURIExtension(tokenIds[i], uris[i]); } } /** * @dev See {ICreatorCore-setBaseTokenURI}. */ function setBaseTokenURI(string calldata uri_) external override adminRequired { _setBaseTokenURI(uri_); } /** * @dev See {ICreatorCore-setTokenURIPrefix}. */ function setTokenURIPrefix(string calldata prefix) external override adminRequired { _setTokenURIPrefix(prefix); } /** * @dev See {ICreatorCore-setTokenURI}. */ function setTokenURI(uint256 tokenId, string calldata uri_) external override adminRequired { _setTokenURI(tokenId, uri_); } /** * @dev See {ICreatorCore-setTokenURI}. */ function setTokenURI(uint256[] memory tokenIds, string[] calldata uris) external override adminRequired { require(tokenIds.length == uris.length, "Invalid input"); for (uint256 i = 0; i < tokenIds.length; i++) { _setTokenURI(tokenIds[i], uris[i]); } } /** * @dev See {ICreatorCore-setMintPermissions}. */ function setMintPermissions(address extension, address permissions) external override adminRequired { _setMintPermissions(extension, permissions); } /** * @dev See {IERC1155CreatorCore-mintBaseNew}. */ function mintBaseNew( address[] calldata to, uint256[] calldata amounts, string[] calldata uris ) public virtual override nonReentrant adminRequired returns (uint256[] memory) { return _mintNew(address(this), to, amounts, uris); } /** * @dev See {IERC1155CreatorCore-mintBaseExisting}. */ function mintBaseExisting( address[] calldata to, uint256[] calldata tokenIds, uint256[] calldata amounts ) public virtual override nonReentrant adminRequired { for (uint256 i = 0; i < tokenIds.length; i++) { require( _tokensExtension[tokenIds[i]] == address(this), "A token was created by an extension" ); } _mintExisting(address(this), to, tokenIds, amounts); } /** * @dev See {IERC1155CreatorCore-mintExtensionNew}. */ function mintExtensionNew( address[] calldata to, uint256[] calldata amounts, string[] calldata uris ) public virtual override nonReentrant extensionRequired returns (uint256[] memory tokenIds) { return _mintNew(msg.sender, to, amounts, uris); } /** * @dev See {IERC1155CreatorCore-mintExtensionExisting}. */ function mintExtensionExisting( address[] calldata to, uint256[] calldata tokenIds, uint256[] calldata amounts ) public virtual override nonReentrant extensionRequired { for (uint256 i = 0; i < tokenIds.length; i++) { require( _tokensExtension[tokenIds[i]] == address(msg.sender), "A token was not created by this extension" ); } _mintExisting(msg.sender, to, tokenIds, amounts); } /** * @dev Mint new tokens */ function _mintNew( address extension, address[] memory to, uint256[] memory amounts, string[] memory uris ) internal returns (uint256[] memory tokenIds) { if (to.length > 1) { // Multiple receiver. Give every receiver the same new token tokenIds = new uint256[](1); require( uris.length <= 1 && (amounts.length == 1 || to.length == amounts.length), "Invalid input" ); } else { // Single receiver. Generating multiple tokens tokenIds = new uint256[](amounts.length); require( uris.length == 0 || amounts.length == uris.length, "Invalid input" ); } // Assign tokenIds for (uint256 i = 0; i < tokenIds.length; i++) { _tokenCount++; tokenIds[i] = _tokenCount; // Track the extension that minted the token _tokensExtension[_tokenCount] = extension; } if (extension != address(this)) { _checkMintPermissions(to, tokenIds, amounts); } if (to.length == 1 && tokenIds.length == 1) { // Single mint _mint(to[0], tokenIds[0], amounts[0], new bytes(0)); } else if (to.length > 1) { // Multiple receivers. Receiving the same token if (amounts.length == 1) { // Everyone receiving the same amount for (uint256 i = 0; i < to.length; i++) { _mint(to[i], tokenIds[0], amounts[0], new bytes(0)); } } else { // Everyone receiving different amounts for (uint256 i = 0; i < to.length; i++) { _mint(to[i], tokenIds[0], amounts[i], new bytes(0)); } } } else { _mintBatch(to[0], tokenIds, amounts, new bytes(0)); } for (uint256 i = 0; i < tokenIds.length; i++) { if (i < uris.length && bytes(uris[i]).length > 0) { _tokenURIs[tokenIds[i]] = uris[i]; } } return tokenIds; } /** * @dev Mint existing tokens */ function _mintExisting( address extension, address[] memory to, uint256[] memory tokenIds, uint256[] memory amounts ) internal { if (extension != address(this)) { _checkMintPermissions(to, tokenIds, amounts); } if (to.length == 1 && tokenIds.length == 1 && amounts.length == 1) { // Single mint _mint(to[0], tokenIds[0], amounts[0], new bytes(0)); } else if (to.length == 1 && tokenIds.length == amounts.length) { // Batch mint to same receiver _mintBatch(to[0], tokenIds, amounts, new bytes(0)); } else if (tokenIds.length == 1 && amounts.length == 1) { // Mint of the same token/token amounts to various receivers for (uint256 i = 0; i < to.length; i++) { _mint(to[i], tokenIds[0], amounts[0], new bytes(0)); } } else if (tokenIds.length == 1 && to.length == amounts.length) { // Mint of the same token with different amounts to different receivers for (uint256 i = 0; i < to.length; i++) { _mint(to[i], tokenIds[0], amounts[i], new bytes(0)); } } else if ( to.length == tokenIds.length && to.length == amounts.length ) { // Mint of different tokens and different amounts to different receivers for (uint256 i = 0; i < to.length; i++) { _mint(to[i], tokenIds[i], amounts[i], new bytes(0)); } } else { revert("Invalid input"); } } /** * @dev See {IERC1155CreatorCore-tokenExtension}. */ function tokenExtension(uint256 tokenId) public view virtual override returns (address) { return _tokenExtension(tokenId); } /** * @dev See {IERC1155CreatorCore-burn}. */ function burn( address account, uint256[] memory tokenIds, uint256[] memory amounts ) public virtual override nonReentrant { require( account == msg.sender || isApprovedForAll(account, msg.sender), "Caller is not owner nor approved" ); require(tokenIds.length == amounts.length, "Invalid input"); if (tokenIds.length == 1) { _burn(account, tokenIds[0], amounts[0]); } else { _burnBatch(account, tokenIds, amounts); } _postBurn(account, tokenIds, amounts); } /** * @dev See {ICreatorCore-setRoyalties}. */ function setRoyalties( address payable[] calldata receivers, uint256[] calldata basisPoints ) external override adminRequired { _setRoyaltiesExtension(address(this), receivers, basisPoints); } /** * @dev See {ICreatorCore-setRoyalties}. */ function setRoyalties( uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints ) external override adminRequired { _setRoyalties(tokenId, receivers, basisPoints); } /** * @dev See {ICreatorCore-setRoyaltiesExtension}. */ function setRoyaltiesExtension( address extension, address payable[] calldata receivers, uint256[] calldata basisPoints ) external override adminRequired { _setRoyaltiesExtension(extension, receivers, basisPoints); } /** * @dev {See ICreatorCore-getRoyalties}. */ function getRoyalties(uint256 tokenId) external view virtual override returns (address payable[] memory, uint256[] memory) { return _getRoyalties(tokenId); } /** * @dev {See ICreatorCore-getFees}. */ function getFees(uint256 tokenId) external view virtual override returns (address payable[] memory, uint256[] memory) { return _getRoyalties(tokenId); } /** * @dev {See ICreatorCore-getFeeRecipients}. */ function getFeeRecipients(uint256 tokenId) external view virtual override returns (address payable[] memory) { return _getRoyaltyReceivers(tokenId); } /** * @dev {See ICreatorCore-getFeeBps}. */ function getFeeBps(uint256 tokenId) external view virtual override returns (uint256[] memory) { return _getRoyaltyBPS(tokenId); } /** * @dev {See ICreatorCore-royaltyInfo}. */ function royaltyInfo(uint256 tokenId, uint256 value) external view virtual override returns (address, uint256) { return _getRoyaltyInfo(tokenId, value); } /** * @dev See {IERC721Metadata-tokenURI}. */ function uri(uint256 tokenId) public view virtual override returns (string memory) { return _tokenURI(tokenId); } /** * @dev Total amount of tokens in with a given id. */ function totalSupply(uint256 tokenId) external view virtual override returns (uint256) { return _totalSupply[tokenId]; } /** * @dev See {ERC1155-_mint}. */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual override { super._mint(account, id, amount, data); _totalSupply[id] += amount; } /** * @dev See {ERC1155-_mintBatch}. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._mintBatch(to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] += amounts[i]; } } /** * @dev See {ERC1155-_burn}. */ function _burn( address account, uint256 id, uint256 amount ) internal virtual override { super._burn(account, id, amount); _totalSupply[id] -= amount; } /** * @dev See {ERC1155-_burnBatch}. */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual override { super._burnBatch(account, ids, amounts); for (uint256 i = 0; i < ids.length; ++i) { _totalSupply[ids[i]] -= amounts[i]; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; import "./IERC1155Upgradeable.sol"; import "./IERC1155ReceiverUpgradeable.sol"; import "./extensions/IERC1155MetadataURIUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155Upgradeable, IERC1155MetadataURIUpgradeable { using AddressUpgradeable for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ function __ERC1155_init(string memory uri_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC1155_init_unchained(uri_); } function __ERC1155_init_unchained(string memory uri_) internal initializer { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC1155Upgradeable).interfaceId || interfaceId == type(IERC1155MetadataURIUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155ReceiverUpgradeable.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155ReceiverUpgradeable.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } uint256[47] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "../../../openzeppelin/utils/structs/EnumerableSet.sol"; import "../../../openzeppelin/utils/introspection/ERC165.sol"; import "../../../openzeppelin-upgradeable/access/OwnableUpgradeable.sol"; import "./IAdminControl.sol"; abstract contract AdminControlUpgradeable is OwnableUpgradeable, IAdminControl, ERC165 { using EnumerableSet for EnumerableSet.AddressSet; // Track registered admins EnumerableSet.AddressSet private _admins; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IAdminControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Only allows approved admins to call the specified function */ modifier adminRequired() { require( owner() == msg.sender || _admins.contains(msg.sender), "AdminControl: Must be owner or admin" ); _; } /** * @dev See {IAdminControl-getAdmins}. */ function getAdmins() external view override returns (address[] memory admins) { admins = new address[](_admins.length()); for (uint256 i = 0; i < _admins.length(); i++) { admins[i] = _admins.at(i); } return admins; } /** * @dev See {IAdminControl-approveAdmin}. */ function approveAdmin(address admin) external override onlyOwner { if (!_admins.contains(admin)) { emit AdminApproved(admin, msg.sender); _admins.add(admin); } } /** * @dev See {IAdminControl-revokeAdmin}. */ function revokeAdmin(address admin) external override onlyOwner { if (_admins.contains(admin)) { emit AdminRevoked(admin, msg.sender); _admins.remove(admin); } } /** * @dev See {IAdminControl-isAdmin}. */ function isAdmin(address admin) public view override returns (bool) { return (owner() == admin || _admins.contains(admin)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "../../../openzeppelin/utils/structs/EnumerableSet.sol"; import "../extensions/ERC1155/IERC1155CreatorExtensionApproveTransfer.sol"; import "../extensions/ERC1155/IERC1155CreatorExtensionBurnable.sol"; import "../permissions/ERC1155/IERC1155CreatorMintPermissions.sol"; import "./IERC1155CreatorCore.sol"; import "./CreatorCore.sol"; /** * @dev Core ERC1155 creator implementation */ abstract contract ERC1155CreatorCore is CreatorCore, IERC1155CreatorCore { using EnumerableSet for EnumerableSet.AddressSet; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(CreatorCore, IERC165) returns (bool) { return interfaceId == type(IERC1155CreatorCore).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {ICreatorCore-setApproveTransferExtension}. */ function setApproveTransferExtension(bool enabled) external override extensionRequired { require( !enabled || ERC165Checker.supportsInterface( msg.sender, type(IERC1155CreatorExtensionApproveTransfer).interfaceId ), "Extension must implement IERC1155CreatorExtensionApproveTransfer" ); if (_extensionApproveTransfers[msg.sender] != enabled) { _extensionApproveTransfers[msg.sender] = enabled; emit ExtensionApproveTransferUpdated(msg.sender, enabled); } } /** * @dev Set mint permissions for an extension */ function _setMintPermissions(address extension, address permissions) internal { require(_extensions.contains(extension), "Invalid extension"); require( permissions == address(0x0) || ERC165Checker.supportsInterface( permissions, type(IERC1155CreatorMintPermissions).interfaceId ), "Invalid address" ); if (_extensionPermissions[extension] != permissions) { _extensionPermissions[extension] = permissions; emit MintPermissionsUpdated(extension, permissions, msg.sender); } } /** * Check if an extension can mint */ function _checkMintPermissions( address[] memory to, uint256[] memory tokenIds, uint256[] memory amounts ) internal { if (_extensionPermissions[msg.sender] != address(0x0)) { IERC1155CreatorMintPermissions(_extensionPermissions[msg.sender]) .approveMint(msg.sender, to, tokenIds, amounts); } } /** * Post burn actions */ function _postBurn( address owner, uint256[] memory tokenIds, uint256[] memory amounts ) internal virtual { require(tokenIds.length > 0, "Invalid input"); address extension = _tokensExtension[tokenIds[0]]; for (uint256 i = 0; i < tokenIds.length; i++) { require( _tokensExtension[tokenIds[i]] == extension, "Mismatched token originators" ); } // Callback to originating extension if needed if (extension != address(this)) { if ( ERC165Checker.supportsInterface( extension, type(IERC1155CreatorExtensionBurnable).interfaceId ) ) { IERC1155CreatorExtensionBurnable(extension).onBurn( owner, tokenIds, amounts ); } } } /** * Approve a transfer */ function _approveTransfer( address from, address to, uint256[] memory tokenIds, uint256[] memory amounts ) internal { require(tokenIds.length > 0, "Invalid input"); address extension = _tokensExtension[tokenIds[0]]; for (uint256 i = 0; i < tokenIds.length; i++) { require( _tokensExtension[tokenIds[i]] == extension, "Mismatched token originators" ); } if (_extensionApproveTransfers[extension]) { require( IERC1155CreatorExtensionApproveTransfer(extension) .approveTransfer(from, to, tokenIds, amounts), "Extension approval failure" ); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @param operator The address which initiated the transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param id The ID of the token being transferred * @param value The amount of tokens being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155Upgradeable.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURIUpgradeable is IERC1155Upgradeable { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (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 initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since 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() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) 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 // OpenZeppelin Contracts v4.4.0 (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 initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _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); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "../../../openzeppelin/utils/introspection/IERC165.sol"; /** * @dev Interface for admin control */ interface IAdminControl is IERC165 { event AdminApproved(address indexed account, address indexed sender); event AdminRevoked(address indexed account, address indexed sender); /** * @dev gets address of all admins */ function getAdmins() external view returns (address[] memory); /** * @dev add an admin. Can only be called by contract owner. */ function approveAdmin(address admin) external; /** * @dev remove an admin. Can only be called by contract owner. */ function revokeAdmin(address admin) external; /** * @dev checks whether or not given address is an admin * Returns True if they are */ function isAdmin(address admin) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "../../../../openzeppelin/utils/introspection/IERC165.sol"; /** * Implement this if you want your extension to approve a transfer */ interface IERC1155CreatorExtensionApproveTransfer is IERC165 { /** * @dev Set whether or not the creator contract will check the extension for approval of token transfer */ function setApproveTransfer(address creator, bool enabled) external; /** * @dev Called by creator contract to approve a transfer */ function approveTransfer( address from, address to, uint256[] calldata tokenIds, uint256[] calldata amounts ) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "../../../../openzeppelin/utils/introspection/IERC165.sol"; /** * @dev Your extension is required to implement this interface if it wishes * to receive the onBurn callback whenever a token the extension created is * burned */ interface IERC1155CreatorExtensionBurnable is IERC165 { /** * @dev callback handler for burn events */ function onBurn( address owner, uint256[] calldata tokenIds, uint256[] calldata amounts ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "../../../../openzeppelin/utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155Creator compliant extension contracts. */ interface IERC1155CreatorMintPermissions is IERC165 { /** * @dev get approval to mint */ function approveMint( address extension, address[] calldata to, uint256[] calldata tokenIds, uint256[] calldata amounts ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "./CreatorCore.sol"; /** * @dev Core ERC1155 creator interface */ interface IERC1155CreatorCore is ICreatorCore { /** * @dev mint a token with no extension. Can only be called by an admin. * * @param to - Can be a single element array (all tokens go to same address) or multi-element array (single token to many recipients) * @param amounts - Can be a single element array (all recipients get the same amount) or a multi-element array * @param uris - If no elements, all tokens use the default uri. * If any element is an empty string, the corresponding token uses the default uri. * * * Requirements: If to is a multi-element array, then uris must be empty or single element array * If to is a multi-element array, then amounts must be a single element array or a multi-element array of the same size * If to is a single element array, uris must be empty or the same length as amounts * * Examples: * mintBaseNew(['0x....1', '0x....2'], [1], []) * Mints a single new token, and gives 1 each to '0x....1' and '0x....2'. Token uses default uri. * * mintBaseNew(['0x....1', '0x....2'], [1, 2], []) * Mints a single new token, and gives 1 to '0x....1' and 2 to '0x....2'. Token uses default uri. * * mintBaseNew(['0x....1'], [1, 2], ["", "http://token2.com"]) * Mints two new tokens to '0x....1'. 1 of the first token, 2 of the second. 1st token uses default uri, second uses "http://token2.com". * * @return Returns list of tokenIds minted */ function mintBaseNew(address[] calldata to, uint256[] calldata amounts, string[] calldata uris) external returns (uint256[] memory); /** * @dev batch mint existing token with no extension. Can only be called by an admin. * * @param to - Can be a single element array (all tokens go to same address) or multi-element array (single token to many recipients) * @param tokenIds - Can be a single element array (all recipients get the same token) or a multi-element array * @param amounts - Can be a single element array (all recipients get the same amount) or a multi-element array * * Requirements: If any of the parameters are multi-element arrays, they need to be the same length as other multi-element arrays * * Examples: * mintBaseExisting(['0x....1', '0x....2'], [1], [10]) * Mints 10 of tokenId 1 to each of '0x....1' and '0x....2'. * * mintBaseExisting(['0x....1', '0x....2'], [1, 2], [10, 20]) * Mints 10 of tokenId 1 to '0x....1' and 20 of tokenId 2 to '0x....2'. * * mintBaseExisting(['0x....1'], [1, 2], [10, 20]) * Mints 10 of tokenId 1 and 20 of tokenId 2 to '0x....1'. * * mintBaseExisting(['0x....1', '0x....2'], [1], [10, 20]) * Mints 10 of tokenId 1 to '0x....1' and 20 of tokenId 1 to '0x....2'. * */ function mintBaseExisting(address[] calldata to, uint256[] calldata tokenIds, uint256[] calldata amounts) external; /** * @dev mint a token from an extension. Can only be called by a registered extension. * * @param to - Can be a single element array (all tokens go to same address) or multi-element array (single token to many recipients) * @param amounts - Can be a single element array (all recipients get the same amount) or a multi-element array * @param uris - If no elements, all tokens use the default uri. * If any element is an empty string, the corresponding token uses the default uri. * * * Requirements: If to is a multi-element array, then uris must be empty or single element array * If to is a multi-element array, then amounts must be a single element array or a multi-element array of the same size * If to is a single element array, uris must be empty or the same length as amounts * * Examples: * mintExtensionNew(['0x....1', '0x....2'], [1], []) * Mints a single new token, and gives 1 each to '0x....1' and '0x....2'. Token uses default uri. * * mintExtensionNew(['0x....1', '0x....2'], [1, 2], []) * Mints a single new token, and gives 1 to '0x....1' and 2 to '0x....2'. Token uses default uri. * * mintExtensionNew(['0x....1'], [1, 2], ["", "http://token2.com"]) * Mints two new tokens to '0x....1'. 1 of the first token, 2 of the second. 1st token uses default uri, second uses "http://token2.com". * * @return Returns list of tokenIds minted */ function mintExtensionNew(address[] calldata to, uint256[] calldata amounts, string[] calldata uris) external returns (uint256[] memory); /** * @dev batch mint existing token from extension. Can only be called by a registered extension. * * @param to - Can be a single element array (all tokens go to same address) or multi-element array (single token to many recipients) * @param tokenIds - Can be a single element array (all recipients get the same token) or a multi-element array * @param amounts - Can be a single element array (all recipients get the same amount) or a multi-element array * * Requirements: If any of the parameters are multi-element arrays, they need to be the same length as other multi-element arrays * * Examples: * mintExtensionExisting(['0x....1', '0x....2'], [1], [10]) * Mints 10 of tokenId 1 to each of '0x....1' and '0x....2'. * * mintExtensionExisting(['0x....1', '0x....2'], [1, 2], [10, 20]) * Mints 10 of tokenId 1 to '0x....1' and 20 of tokenId 2 to '0x....2'. * * mintExtensionExisting(['0x....1'], [1, 2], [10, 20]) * Mints 10 of tokenId 1 and 20 of tokenId 2 to '0x....1'. * * mintExtensionExisting(['0x....1', '0x....2'], [1], [10, 20]) * Mints 10 of tokenId 1 to '0x....1' and 20 of tokenId 1 to '0x....2'. * */ function mintExtensionExisting(address[] calldata to, uint256[] calldata tokenIds, uint256[] calldata amounts) external; /** * @dev burn tokens. Can only be called by token owner or approved address. * On burn, calls back to the registered extension's onBurn method */ function burn(address account, uint256[] calldata tokenIds, uint256[] calldata amounts) external; /** * @dev Total amount of tokens in with a given tokenId. */ function totalSupply(uint256 tokenId) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "../../../openzeppelin/security/ReentrancyGuard.sol"; import "../../../openzeppelin/utils/Strings.sol"; import "../../../openzeppelin/utils/introspection/ERC165.sol"; import "../../../openzeppelin/utils/introspection/ERC165Checker.sol"; import "../../../openzeppelin/utils/structs/EnumerableSet.sol"; import "../../../openzeppelin-upgradeable/utils/AddressUpgradeable.sol"; import "../extensions/ICreatorExtensionTokenURI.sol"; import "./ICreatorCore.sol"; /** * @dev Core creator implementation */ abstract contract CreatorCore is ReentrancyGuard, ICreatorCore, ERC165 { using Strings for uint256; using EnumerableSet for EnumerableSet.AddressSet; using AddressUpgradeable for address; uint256 _tokenCount = 0; // Track registered extensions data EnumerableSet.AddressSet internal _extensions; EnumerableSet.AddressSet internal _blacklistedExtensions; mapping(address => address) internal _extensionPermissions; mapping(address => bool) internal _extensionApproveTransfers; // For tracking which extension a token was minted by mapping(uint256 => address) internal _tokensExtension; // The baseURI for a given extension mapping(address => string) private _extensionBaseURI; mapping(address => bool) private _extensionBaseURIIdentical; // The prefix for any tokens with a uri configured mapping(address => string) private _extensionURIPrefix; // Mapping for individual token URIs mapping(uint256 => string) internal _tokenURIs; // Royalty configurations mapping(address => address payable[]) internal _extensionRoyaltyReceivers; mapping(address => uint256[]) internal _extensionRoyaltyBPS; mapping(uint256 => address payable[]) internal _tokenRoyaltyReceivers; mapping(uint256 => uint256[]) internal _tokenRoyaltyBPS; /** * External interface identifiers for royalties */ /** * @dev CreatorCore * * bytes4(keccak256('getRoyalties(uint256)')) == 0xbb3bafd6 * * => 0xbb3bafd6 = 0xbb3bafd6 */ bytes4 private constant _INTERFACE_ID_ROYALTIES_CREATORCORE = 0xbb3bafd6; /** * @dev Rarible: RoyaltiesV1 * * bytes4(keccak256('getFeeRecipients(uint256)')) == 0xb9c4d9fb * bytes4(keccak256('getFeeBps(uint256)')) == 0x0ebd4c7f * * => 0xb9c4d9fb ^ 0x0ebd4c7f = 0xb7799584 */ bytes4 private constant _INTERFACE_ID_ROYALTIES_RARIBLE = 0xb7799584; /** * @dev Foundation * * bytes4(keccak256('getFees(uint256)')) == 0xd5a06d4c * * => 0xd5a06d4c = 0xd5a06d4c */ bytes4 private constant _INTERFACE_ID_ROYALTIES_FOUNDATION = 0xd5a06d4c; /** * @dev EIP-2981 * * bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a * * => 0x2a55205a = 0x2a55205a */ bytes4 private constant _INTERFACE_ID_ROYALTIES_EIP2981 = 0x2a55205a; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(ICreatorCore).interfaceId || super.supportsInterface(interfaceId) || interfaceId == _INTERFACE_ID_ROYALTIES_CREATORCORE || interfaceId == _INTERFACE_ID_ROYALTIES_RARIBLE || interfaceId == _INTERFACE_ID_ROYALTIES_FOUNDATION || interfaceId == _INTERFACE_ID_ROYALTIES_EIP2981; } /** * @dev Only allows registered extensions to call the specified function */ modifier extensionRequired() { require( _extensions.contains(msg.sender), "Must be registered extension" ); _; } /** * @dev Only allows non-blacklisted extensions */ modifier nonBlacklistRequired(address extension) { require( !_blacklistedExtensions.contains(extension), "Extension blacklisted" ); _; } /** * @dev See {ICreatorCore-getExtensions}. */ function getExtensions() external view override returns (address[] memory extensions) { extensions = new address[](_extensions.length()); for (uint256 i = 0; i < _extensions.length(); i++) { extensions[i] = _extensions.at(i); } return extensions; } /** * @dev Register an extension */ function _registerExtension( address extension, string calldata baseURI, bool baseURIIdentical ) internal { require(extension != address(this), "Creator: Invalid"); require( extension.isContract(), "Creator: Extension must be a contract" ); if (!_extensions.contains(extension)) { _extensionBaseURI[extension] = baseURI; _extensionBaseURIIdentical[extension] = baseURIIdentical; emit ExtensionRegistered(extension, msg.sender); _extensions.add(extension); } } /** * @dev Unregister an extension */ function _unregisterExtension(address extension) internal { if (_extensions.contains(extension)) { emit ExtensionUnregistered(extension, msg.sender); _extensions.remove(extension); } } /** * @dev Blacklist an extension */ function _blacklistExtension(address extension) internal { require(extension != address(this), "Cannot blacklist yourself"); if (_extensions.contains(extension)) { emit ExtensionUnregistered(extension, msg.sender); _extensions.remove(extension); } if (!_blacklistedExtensions.contains(extension)) { emit ExtensionBlacklisted(extension, msg.sender); _blacklistedExtensions.add(extension); } } /** * @dev Set base token uri for an extension */ function _setBaseTokenURIExtension(string calldata uri, bool identical) internal { _extensionBaseURI[msg.sender] = uri; _extensionBaseURIIdentical[msg.sender] = identical; } /** * @dev Set token uri prefix for an extension */ function _setTokenURIPrefixExtension(string calldata prefix) internal { _extensionURIPrefix[msg.sender] = prefix; } /** * @dev Set token uri for a token of an extension */ function _setTokenURIExtension(uint256 tokenId, string calldata uri) internal { require(_tokensExtension[tokenId] == msg.sender, "Invalid token"); _tokenURIs[tokenId] = uri; } /** * @dev Set base token uri for tokens with no extension */ function _setBaseTokenURI(string memory uri) internal { _extensionBaseURI[address(this)] = uri; } /** * @dev Set token uri prefix for tokens with no extension */ function _setTokenURIPrefix(string calldata prefix) internal { _extensionURIPrefix[address(this)] = prefix; } /** * @dev Set token uri for a token with no extension */ function _setTokenURI(uint256 tokenId, string calldata uri) internal { require(_tokensExtension[tokenId] == address(this), "Invalid token"); _tokenURIs[tokenId] = uri; } /** * @dev Retrieve a token's URI */ function _tokenURI(uint256 tokenId) internal view returns (string memory) { address extension = _tokensExtension[tokenId]; require( !_blacklistedExtensions.contains(extension), "Extension blacklisted" ); if (bytes(_tokenURIs[tokenId]).length != 0) { if (bytes(_extensionURIPrefix[extension]).length != 0) { return string( abi.encodePacked( _extensionURIPrefix[extension], _tokenURIs[tokenId] ) ); } return _tokenURIs[tokenId]; } if ( ERC165Checker.supportsInterface( extension, type(ICreatorExtensionTokenURI).interfaceId ) ) { return ICreatorExtensionTokenURI(extension).tokenURI( address(this), tokenId ); } if (!_extensionBaseURIIdentical[extension]) { return string( abi.encodePacked( _extensionBaseURI[extension], tokenId.toString() ) ); } else { return _extensionBaseURI[extension]; } } /** * Get token extension */ function _tokenExtension(uint256 tokenId) internal view returns (address extension) { extension = _tokensExtension[tokenId]; require(extension != address(this), "No extension for token"); require( !_blacklistedExtensions.contains(extension), "Extension blacklisted" ); return extension; } /** * Helper to get royalties for a token */ function _getRoyalties(uint256 tokenId) internal view returns (address payable[] storage, uint256[] storage) { return (_getRoyaltyReceivers(tokenId), _getRoyaltyBPS(tokenId)); } /** * Helper to get royalty receivers for a token */ function _getRoyaltyReceivers(uint256 tokenId) internal view returns (address payable[] storage) { if (_tokenRoyaltyReceivers[tokenId].length > 0) { return _tokenRoyaltyReceivers[tokenId]; } else if ( _extensionRoyaltyReceivers[_tokensExtension[tokenId]].length > 0 ) { return _extensionRoyaltyReceivers[_tokensExtension[tokenId]]; } return _extensionRoyaltyReceivers[address(this)]; } /** * Helper to get royalty basis points for a token */ function _getRoyaltyBPS(uint256 tokenId) internal view returns (uint256[] storage) { if (_tokenRoyaltyBPS[tokenId].length > 0) { return _tokenRoyaltyBPS[tokenId]; } else if (_extensionRoyaltyBPS[_tokensExtension[tokenId]].length > 0) { return _extensionRoyaltyBPS[_tokensExtension[tokenId]]; } return _extensionRoyaltyBPS[address(this)]; } function _getRoyaltyInfo(uint256 tokenId, uint256 value) internal view returns (address receiver, uint256 amount) { address payable[] storage receivers = _getRoyaltyReceivers(tokenId); require(receivers.length <= 1, "More than 1 royalty receiver"); if (receivers.length == 0) { return (address(this), 0); } return (receivers[0], (_getRoyaltyBPS(tokenId)[0] * value) / 10000); } /** * Set royalties for a token */ function _setRoyalties( uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints ) internal { require(receivers.length == basisPoints.length, "Invalid input"); uint256 totalBasisPoints; for (uint256 i = 0; i < basisPoints.length; i++) { totalBasisPoints += basisPoints[i]; } require(totalBasisPoints < 10000, "Invalid total royalties"); _tokenRoyaltyReceivers[tokenId] = receivers; _tokenRoyaltyBPS[tokenId] = basisPoints; emit RoyaltiesUpdated(tokenId, receivers, basisPoints); } /** * Set royalties for all tokens of an extension */ function _setRoyaltiesExtension( address extension, address payable[] calldata receivers, uint256[] calldata basisPoints ) internal { require(receivers.length == basisPoints.length, "Invalid input"); uint256 totalBasisPoints; for (uint256 i = 0; i < basisPoints.length; i++) { totalBasisPoints += basisPoints[i]; } require(totalBasisPoints < 10000, "Invalid total royalties"); _extensionRoyaltyReceivers[extension] = receivers; _extensionRoyaltyBPS[extension] = basisPoints; if (extension == address(this)) { emit DefaultRoyaltiesUpdated(receivers, basisPoints); } else { emit ExtensionRoyaltiesUpdated(extension, receivers, basisPoints); } } } // 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 // OpenZeppelin Contracts v4.4.0 (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 v4.4.0 (utils/introspection/ERC165Checker.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, type(IERC165).interfaceId) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Available since v3.4._ */ function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { bytes memory encodedParams = abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId); (bool success, bytes memory result) = account.staticcall{gas: 30000}(encodedParams); if (result.length < 32) return false; return success && abi.decode(result, (bool)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "../../../openzeppelin/utils/introspection/IERC165.sol"; /** * @dev Implement this if you want your extension to have overloadable URI's */ interface ICreatorExtensionTokenURI is IERC165 { /** * Get the uri for a given creator/tokenId */ function tokenURI(address creator, uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "../../../openzeppelin/utils/introspection/IERC165.sol"; /** * @dev Core creator interface */ interface ICreatorCore is IERC165 { event ExtensionRegistered( address indexed extension, address indexed sender ); event ExtensionUnregistered( address indexed extension, address indexed sender ); event ExtensionBlacklisted( address indexed extension, address indexed sender ); event MintPermissionsUpdated( address indexed extension, address indexed permissions, address indexed sender ); event RoyaltiesUpdated( uint256 indexed tokenId, address payable[] receivers, uint256[] basisPoints ); event DefaultRoyaltiesUpdated( address payable[] receivers, uint256[] basisPoints ); event ExtensionRoyaltiesUpdated( address indexed extension, address payable[] receivers, uint256[] basisPoints ); event ExtensionApproveTransferUpdated( address indexed extension, bool enabled ); /** * @dev gets address of all extensions */ function getExtensions() external view returns (address[] memory); /** * @dev add an extension. Can only be called by contract owner or admin. * extension address must point to a contract implementing ICreatorExtension. * Returns True if newly added, False if already added. */ function registerExtension(address extension, string calldata baseURI) external; /** * @dev add an extension. Can only be called by contract owner or admin. * extension address must point to a contract implementing ICreatorExtension. * Returns True if newly added, False if already added. */ function registerExtension( address extension, string calldata baseURI, bool baseURIIdentical ) external; /** * @dev add an extension. Can only be called by contract owner or admin. * Returns True if removed, False if already removed. */ function unregisterExtension(address extension) external; /** * @dev blacklist an extension. Can only be called by contract owner or admin. * This function will destroy all ability to reference the metadata of any tokens created * by the specified extension. It will also unregister the extension if needed. * Returns True if removed, False if already removed. */ function blacklistExtension(address extension) external; /** * @dev set the baseTokenURI of an extension. Can only be called by extension. */ function setBaseTokenURIExtension(string calldata uri) external; /** * @dev set the baseTokenURI of an extension. Can only be called by extension. * For tokens with no uri configured, tokenURI will return "uri+tokenId" */ function setBaseTokenURIExtension(string calldata uri, bool identical) external; /** * @dev set the common prefix of an extension. Can only be called by extension. * If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI" * Useful if you want to use ipfs/arweave */ function setTokenURIPrefixExtension(string calldata prefix) external; /** * @dev set the tokenURI of a token extension. Can only be called by extension that minted token. */ function setTokenURIExtension(uint256 tokenId, string calldata uri) external; /** * @dev set the tokenURI of a token extension for multiple tokens. Can only be called by extension that minted token. */ function setTokenURIExtension( uint256[] memory tokenId, string[] calldata uri ) external; /** * @dev set the baseTokenURI for tokens with no extension. Can only be called by owner/admin. * For tokens with no uri configured, tokenURI will return "uri+tokenId" */ function setBaseTokenURI(string calldata uri) external; /** * @dev set the common prefix for tokens with no extension. Can only be called by owner/admin. * If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI" * Useful if you want to use ipfs/arweave */ function setTokenURIPrefix(string calldata prefix) external; /** * @dev set the tokenURI of a token with no extension. Can only be called by owner/admin. */ function setTokenURI(uint256 tokenId, string calldata uri) external; /** * @dev set the tokenURI of multiple tokens with no extension. Can only be called by owner/admin. */ function setTokenURI(uint256[] memory tokenIds, string[] calldata uris) external; /** * @dev set a permissions contract for an extension. Used to control minting. */ function setMintPermissions(address extension, address permissions) external; /** * @dev Configure so transfers of tokens created by the caller (must be extension) gets approval * from the extension before transferring */ function setApproveTransferExtension(bool enabled) external; /** * @dev get the extension of a given token */ function tokenExtension(uint256 tokenId) external view returns (address); /** * @dev Set default royalties */ function setRoyalties( address payable[] calldata receivers, uint256[] calldata basisPoints ) external; /** * @dev Set royalties of a token */ function setRoyalties( uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints ) external; /** * @dev Set royalties of an extension */ function setRoyaltiesExtension( address extension, address payable[] calldata receivers, uint256[] calldata basisPoints ) external; /** * @dev Get royalites of a token. Returns list of receivers and basisPoints */ function getRoyalties(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); // Royalty support for various other standards function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory); function getFeeBps(uint256 tokenId) external view returns (uint256[] memory); function getFees(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); function royaltyInfo(uint256 tokenId, uint256 value) external view returns (address, uint256); }
See {IERC1155CreatorCore-mintExtensionNew}./
function mintExtensionNew( address[] calldata to, uint256[] calldata amounts, string[] calldata uris ) public virtual override nonReentrant extensionRequired returns (uint256[] memory tokenIds) { return _mintNew(msg.sender, to, amounts, uris); }
11,819,365
./full_match/1/0xA1f35Da94D3C25c1c130092122Db690FF10d47c4/sources/contracts/PresaleV2.sol
Helper funtion to get USDT price for given amount amount No of tokens to buy/
function usdtBuyHelper( uint256 amount ) external view returns (uint256 usdPrice) { usdPrice = amount * tokenPrice; usdPrice = usdPrice / (10 ** 12); }
9,813,394
./full_match/43113/0x01dACB86c63dD654093781d6Ed177D52532c23C2/sources/contracts/AG.sol
string memory _name, string memory _descr, uint duration, uint _ballotType 0=perAPA 1=perAddressBallotType _ballotType proposals[nextPropId].id = nextPropId; proposals[nextPropId].name = _name; proposals[nextPropId].description = _descr; proposals[nextPropId].end = block.timestamp + duration; proposals[nextPropId].ballotType = _ballotType;
function createProposal( string[] memory _options ) external verifyNumApas(proposerApas) returns(uint) { for(uint i=0; i < _options.length; i++) { Option memory tempStruct; tempStruct.id = i; tempStruct.name = _options[i]; tempStruct.numVotes = 0; proposals[nextPropId].options.push(tempStruct); } nextPropId += 1; return _options.length; }
7,191,519
pragma solidity 0.5.10; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /** * @title Commit-Reveal Voting logic for use/adaptation in commit-reveal voting contracts * @author TruSet * @dev The functions that change state are all internal, so to make use of this logic * this contract must be subclassed and have some functions that change state exposed publically. It is anticipated * that the public functions will need to be restricted in some way (e.g. whitelisting), which is out of the scope * of this base contract. */ // Initial implementaiton adapted from "Partial-Lock-Commit-Reveal Voting scheme with ERC20 tokens" by Aspyn Palatnick, Cem Ozer, Yorke Rhodes contract CommitRevealVoting { using SafeMath for uint; // ============ // EVENTS: // ============ event VoteCommitted(bytes32 indexed pollID, address indexed voter, bytes32 indexed secretHash); event VoteRevealed(bytes32 indexed pollID, bytes32 indexed secretHash, uint indexed choice, address voter, address revealer, uint votesFor, uint votesAgainst, uint votesCommittedButNotRevealed); event PollCreated(bytes32 indexed pollID, address creator, uint commitDuration, uint revealDuration); event CommitPeriodHalted(bytes32 indexed pollID, address haltedBy, uint timestamp); event RevealPeriodHalted(bytes32 indexed pollID, address haltedBy, uint timestamp); // ============ // DATA STRUCTURES: // ============ struct Poll { uint commitPeriodStartedAt; // the poll was opened and the commit period started at this time uint commitDuration; // the maxiumum amount of time (in seconds) to allow for vote commitments following the start of the commit period, or zero to have no maximum uint commitsHaltedAt; // the time that the commit period ended, if different from the value returned by commitDeadline() uint revealDuration; // the maxiumum amount of time (in seconds) to allow for vote revelation following the end of the commit period, or zero to have no maximum uint revealsHaltedAt; // the time that the reveal period ended, if different from the value returned by revealDeadline() uint votesFor; // tally of votes supporting proposal uint votesAgainst; // tally of votes countering proposal uint votesCommittedButNotRevealed; // tally of votes that have been committed but not revealed mapping(address => bool) didReveal; // voter -> whether the voter's vote has been revealed mapping(address => bytes32) commitHashes; // voter -> voter's commitment to a vote mapping(address => uint) revealedVotes; // voter -> voter's revealed vote (0=Against; 1=For) address[] voters; // a list of the addresses who have committed (not necess revealed) a vote in this poll } // ============ // STATE VARIABLES: // ============ mapping(bytes32 => Poll) public pollMap; // maps pollID to Poll struct uint public constant MAX_COMMIT_DURATION_IN_SECONDS = 365 days; uint public constant MAX_REVEAL_DURATION_IN_SECONDS = 365 days; uint public constant VOTE_FOR = 1; uint public constant VOTE_AGAINST = 0; // ================= // VOTING INTERFACE: // ================= /** * @notice Commits vote using hash of choice and secret salt to conceal vote until reveal * @param _pollID Identifer associated with target poll * @param _secretHash Commit keccak256 hash of voter's choice and salt (tightly packed in this order) */ function _commitVote(bytes32 _pollID, bytes32 _secretHash) internal { // prevent user from committing to a non-existent poll or one in the wrong state require(_pollID != 0, "Not a valid pollID"); require(commitPeriodActive(_pollID), "Commit period must be active"); // prevent user from committing a secretHash of 0 require(_secretHash != 0, "Invalid commitment hash"); Poll storage p = pollMap[_pollID]; if (p.commitHashes[msg.sender] == bytes32(0)) { // This commitment has not already been counted p.votesCommittedButNotRevealed = p.votesCommittedButNotRevealed.add(1); p.voters.push(msg.sender); } p.commitHashes[msg.sender] = _secretHash; emit VoteCommitted(_pollID, msg.sender, _secretHash); } /** * @notice Commits votes using hashes of choices and secret salts to conceal votes until reveal * @param _pollIDs Array of identifers associated with target polls * @param _secretHashes Array of commit keccak256 hashes of voter's choices and salts (tightly packed in this order) */ function _commitVotes(bytes32[] memory _pollIDs, bytes32[] memory _secretHashes) internal { // make sure the array lengths are all the same require(_pollIDs.length == _secretHashes.length, "Expected as many secretHashes as pollIDs"); // loop through arrays, committing each individual vote values for (uint i = 0; i < _pollIDs.length; i++) { _commitVote(_pollIDs[i], _secretHashes[i]); } } /** * @notice Reveals a vote. The vote choice and secret salt must correspond to a prior commitment. * @param _pollID Identifer associated with target poll * @param _voter The user who committed the vote * @param _voteOption Vote choice (0 or 1) * @param _salt Secret number that was used to generate the vote commitment */ function _revealVote(bytes32 _pollID, address _voter, uint _voteOption, uint _salt) internal { // Make sure the reveal period is active require(revealPeriodActive(_pollID), "Reveal period must be active"); require(_voteOption == VOTE_AGAINST || _voteOption == VOTE_FOR, "voteOption must be 0 or 1"); require(didCommit(_pollID, _voter), "no commitment found"); // make sure user has committed a vote for this poll require(!didReveal(_pollID, _voter), "already revealed"); // prevent user from revealing multiple times Poll storage p = pollMap[_pollID]; bytes32 commitHash = p.commitHashes[_voter]; require(keccak256(abi.encodePacked(_voteOption, _salt)) == commitHash, "The hash of the vote and salt (tightly packed in that order) does not match the commitment"); // compare resultant hash from inputs to original commitHash require(p.votesCommittedButNotRevealed > 0, "No votes left to reveal"); if (_voteOption == VOTE_FOR) { p.votesFor = p.votesFor.add(1); } else { p.votesAgainst = p.votesAgainst.add(1); } p.revealedVotes[_voter] = _voteOption; p.didReveal[_voter] = true; p.votesCommittedButNotRevealed = p.votesCommittedButNotRevealed.sub(1); emit VoteRevealed(_pollID, commitHash, _voteOption, _voter, msg.sender, p.votesFor, p.votesAgainst, p.votesCommittedButNotRevealed); } /** * @notice Reveals multiple votes. All input arrays must be the same length, and the four values at any given * array index constitute the information required to reveal a single vote (see `_revealVote` params) * @param _pollIDs Array of identifers associated with target polls * @param _voters Array of voter addresses * @param _voteOptions Array of vote choices (each 0 or 1) * @param _salts Array of secret numbers that were used to generate the vote commitment */ function _revealVotes(bytes32[] memory _pollIDs, address[] memory _voters, uint[] memory _voteOptions, uint[] memory _salts) internal { // Make sure the array lengths are all the same uint l = _pollIDs.length; require(l == _voteOptions.length, "Expected as many voteOptions as pollIDs"); require(l == _salts.length, "Expected as many salts as pollIDs"); require(l == _voters.length, "Expected as many voters as pollIDs"); // Loop through arrays, revealing each individual vote values for (uint i = 0; i < l; i++) { _revealVote(_pollIDs[i], _voters[i], _voteOptions[i], _salts[i]); } } // ================== // ADMIN INTERFACE: // ================== /** * @dev Initiates a poll with canonical configured parameters at pollID emitted by PollCreated event * @param _commitDuration Duration after which the commit period will end, in seconds. * Or zero to have no fixed duration, relying only on _haltCommitPeriod * @param _revealDuration Duration after which the reveal period will end, in seconds. * Or zero to have no fixed duration, relying only on _haltRevealPeriod */ function _startPoll(bytes32 _pollID, uint _commitDuration, uint _revealDuration) internal returns (bytes32 pollID) { require(!pollExists(_pollID), "no such poll"); require(_commitDuration <= MAX_COMMIT_DURATION_IN_SECONDS, "commitDuration <= 365 days"); require(_revealDuration <= MAX_REVEAL_DURATION_IN_SECONDS, "revealDuration <= 365 days"); pollMap[_pollID] = Poll({ commitPeriodStartedAt: block.timestamp, // Invariant: all existing (active or inactive) Polls have a non-zero commitPeriodStartedAt commitDuration: _commitDuration, commitsHaltedAt: 0, revealDuration: _revealDuration, revealsHaltedAt: 0, votesFor: 0, votesAgainst: 0, votesCommittedButNotRevealed: 0, voters: new address[](0) }); emit PollCreated(_pollID, msg.sender, _commitDuration, _revealDuration); return _pollID; } /** * @dev Closes the commit period, or reverts if it is not currently open. * @param _pollID Bytes32 identifier associated with target poll */ function _haltCommitPeriod(bytes32 _pollID) internal { require(commitPeriodActive(_pollID), "Commit period must be active"); Poll storage p = pollMap[_pollID]; p.commitsHaltedAt = block.timestamp; emit CommitPeriodHalted(_pollID, msg.sender, block.timestamp); } /** * @dev Closes the reveal period, or reverts if it is not currently open * @param _pollID Bytes32 identifier associated with target poll */ function _haltRevealPeriod(bytes32 _pollID) internal { require(revealPeriodActive(_pollID), "Reveal period must be active"); pollMap[_pollID].revealsHaltedAt = block.timestamp; emit RevealPeriodHalted(_pollID, msg.sender, block.timestamp); } // ---------------- // POLLING HELPERS: // ---------------- /** * @dev Gets the vote counts for a poll * N.B. Ensure that the reveal period is over before assuming that these results are final. * @param _pollID Bytes32 identifier associated with target poll * @return Total number of 'For' votes, 'Against' votes, and committed votes that were not revealed. (3 integers, in that order.) */ function getVoteCounts(bytes32 _pollID) view public returns ( uint numForVotes, uint numAgainstVotes, uint numCommittedButNotRevealedVotes) { Poll memory p = pollMap[_pollID]; return (p.votesFor, p.votesAgainst, p.votesCommittedButNotRevealed); } /** * @dev Gets the addresses that voted in a poll * Unless restrictions are added to the implementing contract, * the length of this list is unbounded and therefore unsuitable for examination on-chain. * Ensure that the commit period is over before assuming that this list is final. * @param _pollID Bytes32 identifier associated with target poll * @return The list of addresses that voted in the poll, regardless of whether or not they * revealed their vote. */ function getVoters(bytes32 _pollID) view public returns (address[] memory voters) { return pollMap[_pollID].voters; } /** * @notice Determines if poll is over * @dev If neither the commit period nor the reveal period is active then we assume the poll is over * @return Boolean indication of whether polling period is over */ function pollEnded(bytes32 _pollID) view public returns (bool ended) { return !commitPeriodActive(_pollID) && !revealPeriodActive(_pollID); } /** * @notice Returns the deadline for commits to a given poll. * The commit period may be halted earlier by calls to _haltCommitPeriod(). * @param _pollID Identifer associated with target poll * @return Returns the deadline at which the commit period is/was scheduled to end, or 0 if no such deadline * exists/existed. */ function commitDeadline(bytes32 _pollID) view public returns (uint timestamp) { require(pollExists(_pollID), "Poll does not exist"); Poll memory p = pollMap[_pollID]; if (p.commitDuration == 0) { return 0; } else { return p.commitPeriodStartedAt.add(p.commitDuration); } } /** * @notice Checks if the commit period is still active for the specified poll * @dev Checks the specified poll's commitDeadline(), and for earlier manual halting of commits * @param _pollID Identifer associated with target poll * @return Boolean indication of isCommitPeriodActive for target poll */ function commitPeriodActive(bytes32 _pollID) view public returns (bool active) { require(pollExists(_pollID), "Poll does not exist"); Poll memory p = pollMap[_pollID]; bool endedEarly = (p.commitsHaltedAt != 0); return !endedEarly && !isExpired(commitDeadline(_pollID)); } /** * @notice Returns the time at which a commit period started * @param _pollID Identifer associated with target poll * @return The timestamp at which the commit period started for the given poll */ function commitPeriodStartedTimestamp(bytes32 _pollID) view public returns (uint timestamp) { require(pollExists(_pollID), "Poll does not exist"); return pollMap[_pollID].commitPeriodStartedAt; } /** * @notice Returns the deadline for reveals to a given poll. This is subject to change (the reveal period * may be brought forward by calls to _haltCommitPeriod()) and reveals may be halted earlier * by calls to _haltRevealPeriod(). * @param _pollID Identifer associated with target poll * @return Returns the deadline at which the reveal period is currently or was scheduled to end, or 0 if no * such deadline exists/existed. */ function revealDeadline(bytes32 _pollID) view public returns (uint timestamp) { require(pollExists(_pollID), "Poll does not exist"); uint revealDuration = pollMap[_pollID].revealDuration; uint revealPeriodStarted = revealPeriodStartedTimestamp(_pollID); if ((revealDuration == 0) || (revealPeriodStarted == 0)) { return 0; } else { return revealPeriodStarted.add(revealDuration); // Both non-zero } } /** * @notice Checks if the reveal period is still active for the specified poll * @dev Checks the specified poll's revealDeadline, and for earlier manual halting of reveals * @param _pollID Identifer associated with target poll */ function revealPeriodActive(bytes32 _pollID) view public returns (bool active) { require(pollExists(_pollID), "Poll does not exist"); Poll memory p = pollMap[_pollID]; bool endedEarly = (p.revealsHaltedAt != 0); return !endedEarly && !isExpired(revealDeadline(_pollID)) && !commitPeriodActive(_pollID); } /** * @notice Returns the time at which a reveal period started * @param _pollID Identifer associated with target poll * @return The timestamp at which the reveal period started for the given poll, or zero if it has not yet started */ function revealPeriodStartedTimestamp(bytes32 _pollID) view public returns (uint timestamp) { require(pollExists(_pollID), "Poll does not exist"); Poll memory p = pollMap[_pollID]; if (p.commitsHaltedAt != 0) { timestamp = p.commitsHaltedAt; } else if (commitPeriodActive(_pollID)) { timestamp = 0; } else { timestamp = commitDeadline(_pollID); // Commit period has ended and was not halted, so this is non-zero } return timestamp; } /** * @dev Checks if user has committed for specified poll * @param _pollID Identifier associated with target poll * @param _voter Address of user to check * @return Boolean indication of whether user has committed */ function didCommit(bytes32 _pollID, address _voter) view public returns (bool committed) { require(pollExists(_pollID), "Poll does not exist"); return pollMap[_pollID].commitHashes[_voter] != bytes32(0); } /** @dev Checks if user has already committed and revealed for specified poll. @param _pollID Identifier associated with target poll @param _voter Address of user to check @return Boolean indication of whether user has revealed */ function didReveal(bytes32 _pollID, address _voter) view public returns (bool revealed) { require(pollExists(_pollID), "Poll does not exist"); return pollMap[_pollID].didReveal[_voter]; } /** * @dev Returns user's revealed vote value in a specified poll. Reverts if they did not * commit a vote or if they failed to reveal it. * @param _pollID Identifier associated with target poll * @param _voter Address of user to check * @return Whether the user has voted, whether the user's vote has been revealed, and (if revealed) the vote itself */ function getVote(bytes32 _pollID, address _voter) view public returns ( bool hasVoted, bool hasRevealed, uint vote ) { hasVoted = didCommit(_pollID, _voter); hasRevealed = didReveal(_pollID, _voter); if (hasVoted && hasRevealed) { vote = pollMap[_pollID].revealedVotes[_voter]; } return ( hasVoted, hasRevealed, vote ); } /** * @dev Checks if a poll exists * @param _pollID The pollID whose existance is to be evaluated. * @return Boolean Indicates whether a poll exists for the provided pollID */ function pollExists(bytes32 _pollID) view public returns (bool exists) { return (_pollID != 0) && (pollMap[_pollID].commitPeriodStartedAt > 0); } /** * @dev Gets the bytes32 commitHash property of target poll * @param _voter Address of user to check against * @param _pollID Identifer associated with target poll * @return Bytes32 hash property attached to target poll */ function getCommitHash(bytes32 _pollID, address _voter) view public returns (bytes32 commitHash) { return pollMap[_pollID].commitHashes[_voter]; } // ---------------- // GENERAL HELPERS: // ---------------- /** * @dev Checks if an expiration date has been reached. An expiration date of 0 will always return false. * @param _terminationDate Integer timestamp of date to compare current timestamp with * @return expired Boolean indication of whether the terminationDate has passed */ function isExpired(uint _terminationDate) view public returns (bool expired) { return (_terminationDate > 0 && block.timestamp > _terminationDate); } }
Gets the vote counts for a poll N.B. Ensure that the reveal period is over before assuming that these results are final. _pollID Bytes32 identifier associated with target poll return Total number of 'For' votes, 'Against' votes, and committed votes that were not revealed. (3 integers, in that order.)/
function getVoteCounts(bytes32 _pollID) view public returns ( uint numForVotes, uint numAgainstVotes, uint numCommittedButNotRevealedVotes) { Poll memory p = pollMap[_pollID]; return (p.votesFor, p.votesAgainst, p.votesCommittedButNotRevealed); }
1,798,975
/** *Submitted for verification at Etherscan.io on 2020-01-30 */ // File: contracts/math/SafeMath.sol pragma solidity 0.5.12; /// @title SafeMath /// @dev Math operations with safety checks that throw on error library SafeMath { /// @dev Add two integers function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; //assert(c >= a); return c; } /// @dev Subtract two integers function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } /// @dev Multiply tow integers function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; assert(c / a == b); return c; } /// @dev Floor divide two integers function div(uint a, uint b) internal pure returns (uint) { return a / b; } } // File: contracts/ownership/Ownable.sol pragma solidity 0.5.12; /// @title Ownable /// @dev Provide a simple access control with a single authority: the owner contract Ownable { // Ethereum address of current owner address public owner; // Ethereum address of the next owner // (has to claim ownership first to become effective owner) address public newOwner; // @dev Log event on ownership transferred // @param previousOwner Ethereum address of previous owner // @param newOwner Ethereum address of new owner event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /// @dev Forbid call by anyone but owner modifier onlyOwner() { require(msg.sender == owner, "Restricted to owner"); _; } /// @dev Deployer account becomes initial owner constructor() public { owner = msg.sender; } /// @dev Transfer ownership to a new Ethereum account (safe method) /// Note: the new owner has to claim his ownership to become effective owner. /// @param _newOwner Ethereum address to transfer ownership to function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0x0), "New owner is zero"); newOwner = _newOwner; } /// @dev Transfer ownership to a new Ethereum account (unsafe method) /// Note: It's strongly recommended to use the safe variant via transferOwnership /// and claimOwnership, to prevent accidental transfers to a wrong address. /// @param _newOwner Ethereum address to transfer ownership to function transferOwnershipUnsafe(address _newOwner) public onlyOwner { require(_newOwner != address(0x0), "New owner is zero"); _transferOwnership(_newOwner); } /// @dev Become effective owner (if dedicated so by previous owner) function claimOwnership() public { require(msg.sender == newOwner, "Restricted to new owner"); _transferOwnership(msg.sender); } /// @dev Transfer ownership (internal method) /// @param _newOwner Ethereum address to transfer ownership to function _transferOwnership(address _newOwner) private { if (_newOwner != owner) { emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } newOwner = address(0x0); } } // File: contracts/whitelist/Whitelist.sol pragma solidity 0.5.12; /// @title Whitelist /// @author STOKR contract Whitelist is Ownable { // Set of admins mapping(address => bool) public admins; // Set of Whitelisted addresses mapping(address => bool) public isWhitelisted; /// @dev Log entry on admin added to set /// @param admin An Ethereum address event AdminAdded(address indexed admin); /// @dev Log entry on admin removed from set /// @param admin An Ethereum address event AdminRemoved(address indexed admin); /// @dev Log entry on investor added set /// @param admin An Ethereum address /// @param investor An Ethereum address event InvestorAdded(address indexed admin, address indexed investor); /// @dev Log entry on investor removed from set /// @param admin An Ethereum address /// @param investor An Ethereum address event InvestorRemoved(address indexed admin, address indexed investor); /// @dev Only admin modifier onlyAdmin() { require(admins[msg.sender], "Restricted to whitelist admin"); _; } /// @dev Add admin to set /// @param _admin An Ethereum address function addAdmin(address _admin) public onlyOwner { require(_admin != address(0x0), "Whitelist admin is zero"); if (!admins[_admin]) { admins[_admin] = true; emit AdminAdded(_admin); } } /// @dev Remove admin from set /// @param _admin An Ethereum address function removeAdmin(address _admin) public onlyOwner { require(_admin != address(0x0), "Whitelist admin is zero"); // Necessary? if (admins[_admin]) { admins[_admin] = false; emit AdminRemoved(_admin); } } /// @dev Add investor to set of whitelisted addresses /// @param _investors A list where each entry is an Ethereum address function addToWhitelist(address[] calldata _investors) external onlyAdmin { for (uint256 i = 0; i < _investors.length; i++) { if (!isWhitelisted[_investors[i]]) { isWhitelisted[_investors[i]] = true; emit InvestorAdded(msg.sender, _investors[i]); } } } /// @dev Remove investor from set of whitelisted addresses /// @param _investors A list where each entry is an Ethereum address function removeFromWhitelist(address[] calldata _investors) external onlyAdmin { for (uint256 i = 0; i < _investors.length; i++) { if (isWhitelisted[_investors[i]]) { isWhitelisted[_investors[i]] = false; emit InvestorRemoved(msg.sender, _investors[i]); } } } } // File: contracts/whitelist/Whitelisted.sol pragma solidity 0.5.12; /// @title Whitelisted /// @author STOKR contract Whitelisted is Ownable { Whitelist public whitelist; /// @dev Log entry on change of whitelist contract instance /// @param previous Ethereum address of previous whitelist /// @param current Ethereum address of new whitelist event WhitelistChange(address indexed previous, address indexed current); /// @dev Ensure only whitelisted addresses can call modifier onlyWhitelisted(address _address) { require(whitelist.isWhitelisted(_address), "Address is not whitelisted"); _; } /// @dev Constructor /// @param _whitelist address of whitelist contract constructor(Whitelist _whitelist) public { setWhitelist(_whitelist); } /// @dev Set the address of whitelist /// @param _newWhitelist An Ethereum address function setWhitelist(Whitelist _newWhitelist) public onlyOwner { require(address(_newWhitelist) != address(0x0), "Whitelist address is zero"); if (address(_newWhitelist) != address(whitelist)) { emit WhitelistChange(address(whitelist), address(_newWhitelist)); whitelist = Whitelist(_newWhitelist); } } } // File: contracts/token/ERC20.sol pragma solidity 0.5.12; /// @title ERC20 interface /// @dev see https://github.com/ethereum/EIPs/issues/20 interface ERC20 { event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); function totalSupply() external view returns (uint); function balanceOf(address _owner) external view returns (uint); function allowance(address _owner, address _spender) external view returns (uint); function approve(address _spender, uint _value) external returns (bool); function transfer(address _to, uint _value) external returns (bool); function transferFrom(address _from, address _to, uint _value) external returns (bool); } // File: contracts/token/ProfitSharing.sol pragma solidity 0.5.12; /// @title ProfitSharing /// @author STOKR contract ProfitSharing is Ownable { using SafeMath for uint; // An InvestorAccount object keeps track of the investor's // - balance: amount of tokens he/she holds (always up-to-date) // - profitShare: amount of wei this token owed him/her at the last update // - lastTotalProfits: determines when his/her profitShare was updated // Note, this construction requires: // - totalProfits to never decrease // - totalSupply to be fixed // - profitShare of all involved parties to get updated prior to any token transfer // - lastTotalProfits to be set to current totalProfits upon profitShare update struct InvestorAccount { uint balance; // token balance uint lastTotalProfits; // totalProfits [wei] at the time of last profit share update uint profitShare; // profit share [wei] of last update } // Investor account database mapping(address => InvestorAccount) public accounts; // Authority who is allowed to deposit profits [wei] on this address public profitDepositor; // Authority who is allowed to distribute profit shares [wei] to investors // (so, that they don't need to withdraw it by themselves) address public profitDistributor; // Amount of total profits [wei] stored to this token // In contrast to the wei balance (which may be reduced due to profit share withdrawal) // this value will never decrease uint public totalProfits; // As long as the total supply isn't fixed, i.e. new tokens can appear out of thin air, // the investors' profit shares aren't determined bool public totalSupplyIsFixed; // Total amount of tokens uint internal totalSupply_; /// @dev Log entry on change of profit deposit authority /// @param previous Ethereum address of previous profit depositor /// @param current Ethereum address of new profit depositor event ProfitDepositorChange( address indexed previous, address indexed current ); /// @dev Log entry on change of profit distribution authority /// @param previous Ethereum address of previous profit distributor /// @param current Ethereum address of new profit distributor event ProfitDistributorChange( address indexed previous, address indexed current ); /// @dev Log entry on profit deposit /// @param depositor Profit depositor's address /// @param amount Deposited profits in wei event ProfitDeposit( address indexed depositor, uint amount ); /// @dev Log entry on profit share update /// @param investor Investor's address /// @param amount New wei amount the token owes the investor event ProfitShareUpdate( address indexed investor, uint amount ); /// @dev Log entry on profit withdrawal /// @param investor Investor's address /// @param amount Wei amount the investor withdrew from this token event ProfitShareWithdrawal( address indexed investor, address indexed beneficiary, uint amount ); /// @dev Restrict operation to profit deposit authority only modifier onlyProfitDepositor() { require(msg.sender == profitDepositor, "Restricted to profit depositor"); _; } /// @dev Restrict operation to profit distribution authority only modifier onlyProfitDistributor() { require(msg.sender == profitDistributor, "Restricted to profit distributor"); _; } /// @dev Restrict operation to when total supply doesn't change anymore modifier onlyWhenTotalSupplyIsFixed() { require(totalSupplyIsFixed, "Total supply may change"); _; } /// @dev Constructor /// @param _profitDepositor Profit deposit authority constructor(address _profitDepositor, address _profitDistributor) public { setProfitDepositor(_profitDepositor); setProfitDistributor(_profitDistributor); } /// @dev Profit deposit if possible via fallback function function () external payable { require(msg.data.length == 0, "Fallback call with data"); depositProfit(); } /// @dev Change profit depositor /// @param _newProfitDepositor An Ethereum address function setProfitDepositor(address _newProfitDepositor) public onlyOwner { require(_newProfitDepositor != address(0x0), "New profit depositor is zero"); if (_newProfitDepositor != profitDepositor) { emit ProfitDepositorChange(profitDepositor, _newProfitDepositor); profitDepositor = _newProfitDepositor; } } /// @dev Change profit distributor /// @param _newProfitDistributor An Ethereum address function setProfitDistributor(address _newProfitDistributor) public onlyOwner { require(_newProfitDistributor != address(0x0), "New profit distributor is zero"); if (_newProfitDistributor != profitDistributor) { emit ProfitDistributorChange(profitDistributor, _newProfitDistributor); profitDistributor = _newProfitDistributor; } } /// @dev Deposit profit function depositProfit() public payable onlyProfitDepositor onlyWhenTotalSupplyIsFixed { require(totalSupply_ > 0, "Total supply is zero"); totalProfits = totalProfits.add(msg.value); emit ProfitDeposit(msg.sender, msg.value); } /// @dev Profit share owing /// @param _investor An Ethereum address /// @return A positive number function profitShareOwing(address _investor) public view returns (uint) { if (!totalSupplyIsFixed || totalSupply_ == 0) { return 0; } InvestorAccount memory account = accounts[_investor]; return totalProfits.sub(account.lastTotalProfits) .mul(account.balance) .div(totalSupply_) .add(account.profitShare); } /// @dev Update profit share /// @param _investor An Ethereum address function updateProfitShare(address _investor) public onlyWhenTotalSupplyIsFixed { uint newProfitShare = profitShareOwing(_investor); accounts[_investor].lastTotalProfits = totalProfits; accounts[_investor].profitShare = newProfitShare; emit ProfitShareUpdate(_investor, newProfitShare); } /// @dev Withdraw profit share function withdrawProfitShare() public { _withdrawProfitShare(msg.sender, msg.sender); } function withdrawProfitShareTo(address payable _beneficiary) public { _withdrawProfitShare(msg.sender, _beneficiary); } /// @dev Withdraw profit share function withdrawProfitShares(address payable[] calldata _investors) external onlyProfitDistributor { for (uint i = 0; i < _investors.length; ++i) { _withdrawProfitShare(_investors[i], _investors[i]); } } /// @dev Withdraw profit share function _withdrawProfitShare(address _investor, address payable _beneficiary) internal { updateProfitShare(_investor); uint withdrawnProfitShare = accounts[_investor].profitShare; accounts[_investor].profitShare = 0; _beneficiary.transfer(withdrawnProfitShare); emit ProfitShareWithdrawal(_investor, _beneficiary, withdrawnProfitShare); } } // File: contracts/token/MintableToken.sol pragma solidity 0.5.12; /// @title MintableToken /// @author STOKR /// @dev Extension of the ERC20 compliant ProfitSharing Token /// that allows the creation of tokens via minting for a /// limited time period (until minting gets finished). contract MintableToken is ERC20, ProfitSharing, Whitelisted { address public minter; uint public numberOfInvestors = 0; /// @dev Log entry on mint /// @param to Beneficiary who received the newly minted tokens /// @param amount The amount of minted token units event Minted(address indexed to, uint amount); /// @dev Log entry on mint finished event MintFinished(); /// @dev Restrict an operation to be callable only by the minter modifier onlyMinter() { require(msg.sender == minter, "Restricted to minter"); _; } /// @dev Restrict an operation to be executable only while minting was not finished modifier canMint() { require(!totalSupplyIsFixed, "Total supply has been fixed"); _; } /// @dev Set minter authority /// @param _minter Ethereum address of minter authority function setMinter(address _minter) public onlyOwner { require(minter == address(0x0), "Minter has already been set"); require(_minter != address(0x0), "Minter is zero"); minter = _minter; } /// @dev Mint tokens, i.e. create tokens out of thin air /// @param _to Beneficiary who will receive the newly minted tokens /// @param _amount The amount of minted token units function mint(address _to, uint _amount) public onlyMinter canMint onlyWhitelisted(_to) { if (accounts[_to].balance == 0) { numberOfInvestors++; } totalSupply_ = totalSupply_.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW accounts[_to].balance = accounts[_to].balance.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW emit Minted(_to, _amount); emit Transfer(address(0x0), _to, _amount); } /// @dev Finish minting -- this should be irreversible function finishMinting() public onlyMinter canMint { totalSupplyIsFixed = true; emit MintFinished(); } } // File: contracts/crowdsale/RateSourceInterface.sol pragma solidity 0.5.12; /// @title RateSource /// @author STOKR interface RateSource { /// @dev The current price of an Ether in EUR cents /// @return Current ether rate function etherRate() external view returns (uint); } // File: contracts/crowdsale/MintingCrowdsale.sol pragma solidity 0.5.12; /// @title MintingCrowdsale /// @author STOKR contract MintingCrowdsale is Ownable { using SafeMath for uint; // Maximum Time of offering period after extension uint constant MAXOFFERINGPERIOD = 80 days; // Ether rate oracle contract providing the price of an Ether in EUR cents RateSource public rateSource; // The token to be sold // In the following, the term "token unit" always refers to the smallest // and non-divisible quantum. Thus, token unit amounts are always integers. // One token is expected to consist of 10^18 token units. MintableToken public token; // Token amounts in token units // The public and the private sale are both capped (i.e. two distinct token pools) // The tokenRemaining variables keep track of how many token units are available // for the respective type of sale uint public tokenCapOfPublicSale; uint public tokenCapOfPrivateSale; uint public tokenRemainingForPublicSale; uint public tokenRemainingForPrivateSale; // Prices are in Euro cents (i.e. 1/100 EUR) uint public tokenPrice; // The minimum amount of tokens a purchaser has to buy via one transaction uint public tokenPurchaseMinimum; // The maximum total amount of tokens a purchaser may buy during start phase uint public tokenPurchaseLimit; // Total token purchased by investor (while purchase amount is limited) mapping(address => uint) public tokenPurchased; // Public sale period uint public openingTime; uint public closingTime; uint public limitEndTime; // Ethereum address where invested funds will be transferred to address payable public companyWallet; // Amount and receiver of reserved tokens uint public tokenReservePerMill; address public reserveAccount; // Wether this crowdsale was finalized or not bool public isFinalized = false; /// @dev Log entry upon token distribution event /// @param beneficiary Ethereum address of token recipient /// @param amount Number of token units /// @param isPublicSale Whether the distribution was via public sale event TokenDistribution(address indexed beneficiary, uint amount, bool isPublicSale); /// @dev Log entry upon token purchase event /// @param buyer Ethereum address of token purchaser /// @param value Worth in wei of purchased token amount /// @param amount Number of token units event TokenPurchase(address indexed buyer, uint value, uint amount); /// @dev Log entry upon rate change event /// @param previous Previous closing time of sale /// @param current Current closing time of sale event ClosingTimeChange(uint previous, uint current); /// @dev Log entry upon finalization event event Finalization(); /// @dev Constructor /// @param _rateSource Ether rate oracle contract /// @param _token The token to be sold /// @param _tokenCapOfPublicSale Maximum number of token units to mint in public sale /// @param _tokenCapOfPrivateSale Maximum number of token units to mint in private sale /// @param _tokenPurchaseMinimum Minimum amount of tokens an investor has to buy at once /// @param _tokenPurchaseLimit Maximum total token amounts individually buyable in limit phase /// @param _tokenPrice Price of a token in EUR cent /// @param _openingTime Block (Unix) timestamp of sale opening time /// @param _closingTime Block (Unix) timestamp of sale closing time /// @param _limitEndTime Block (Unix) timestamp until token purchases are limited /// @param _companyWallet Ethereum account who will receive sent ether /// @param _tokenReservePerMill Per mill amount of sold tokens to mint for reserve account /// @param _reserveAccount Ethereum address of reserve tokens recipient constructor( RateSource _rateSource, MintableToken _token, uint _tokenCapOfPublicSale, uint _tokenCapOfPrivateSale, uint _tokenPurchaseMinimum, uint _tokenPurchaseLimit, uint _tokenReservePerMill, uint _tokenPrice, uint _openingTime, uint _closingTime, uint _limitEndTime, address payable _companyWallet, address _reserveAccount ) public { require(address(_rateSource) != address(0x0), "Rate source is zero"); require(address(_token) != address(0x0), "Token address is zero"); require(_token.minter() == address(0x0), "Token has another minter"); require(_tokenCapOfPublicSale > 0, "Cap of public sale is zero"); require(_tokenCapOfPrivateSale > 0, "Cap of private sale is zero"); require(_tokenPurchaseMinimum <= _tokenCapOfPublicSale && _tokenPurchaseMinimum <= _tokenCapOfPrivateSale, "Purchase minimum exceeds cap"); require(_tokenPrice > 0, "Token price is zero"); require(_openingTime >= now, "Opening lies in the past"); require(_closingTime >= _openingTime, "Closing lies before opening"); require(_companyWallet != address(0x0), "Company wallet is zero"); require(_reserveAccount != address(0x0), "Reserve account is zero"); // Note: There are no time related requirements regarding limitEndTime. // If it's below openingTime, token purchases will never be limited. // If it's above closingTime, token purchases will always be limited. if (_limitEndTime > _openingTime) { // But, if there's a purchase limitation phase, the limit must be at // least the purchase minimum or above to make purchases possible. require(_tokenPurchaseLimit >= _tokenPurchaseMinimum, "Purchase limit is below minimum"); } // Utilize safe math to ensure the sum of three token pools does't overflow _tokenCapOfPublicSale.add(_tokenCapOfPrivateSale).mul(_tokenReservePerMill); rateSource = _rateSource; token = _token; tokenCapOfPublicSale = _tokenCapOfPublicSale; tokenCapOfPrivateSale = _tokenCapOfPrivateSale; tokenPurchaseMinimum = _tokenPurchaseMinimum; tokenPurchaseLimit= _tokenPurchaseLimit; tokenReservePerMill = _tokenReservePerMill; tokenPrice = _tokenPrice; openingTime = _openingTime; closingTime = _closingTime; limitEndTime = _limitEndTime; companyWallet = _companyWallet; reserveAccount = _reserveAccount; tokenRemainingForPublicSale = _tokenCapOfPublicSale; tokenRemainingForPrivateSale = _tokenCapOfPrivateSale; } /// @dev Fallback function: buys tokens function () external payable { require(msg.data.length == 0, "Fallback call with data"); buyTokens(); } /// @dev Distribute tokens purchased off-chain via public sale /// Note: additional requirements are enforced in internal function. /// @param beneficiaries List of recipients' Ethereum addresses /// @param amounts List of token units each recipient will receive function distributeTokensViaPublicSale( address[] memory beneficiaries, uint[] memory amounts ) public { tokenRemainingForPublicSale = distributeTokens(tokenRemainingForPublicSale, beneficiaries, amounts, true); } /// @dev Distribute tokens purchased off-chain via private sale /// Note: additional requirements are enforced in internal function. /// @param beneficiaries List of recipients' Ethereum addresses /// @param amounts List of token units each recipient will receive function distributeTokensViaPrivateSale( address[] memory beneficiaries, uint[] memory amounts ) public { tokenRemainingForPrivateSale = distributeTokens(tokenRemainingForPrivateSale, beneficiaries, amounts, false); } /// @dev Check whether the sale has closed /// @return True iff sale closing time has passed function hasClosed() public view returns (bool) { return now >= closingTime; } /// @dev Check wether the sale is open /// @return True iff sale opening time has passed and sale is not closed yet function isOpen() public view returns (bool) { return now >= openingTime && !hasClosed(); } /// @dev Determine the remaining open time of sale /// @return Time in seconds until sale gets closed, or 0 if sale was closed function timeRemaining() public view returns (uint) { if (hasClosed()) { return 0; } return closingTime - now; } /// @dev Determine the amount of sold tokens (off-chain and on-chain) /// @return Token units amount function tokenSold() public view returns (uint) { return (tokenCapOfPublicSale - tokenRemainingForPublicSale) + (tokenCapOfPrivateSale - tokenRemainingForPrivateSale); } /// @dev Purchase tokens function buyTokens() public payable { require(isOpen(), "Sale is not open"); uint etherRate = rateSource.etherRate(); require(etherRate > 0, "Ether rate is zero"); // Units: [1e-18*ether] * [cent/ether] / [cent/token] => [1e-18*token] uint amount = msg.value.mul(etherRate).div(tokenPrice); require(amount <= tokenRemainingForPublicSale, "Not enough tokens available"); require(amount >= tokenPurchaseMinimum, "Investment is too low"); // Is the total amount an investor can purchase with Ether limited? if (now < limitEndTime) { uint purchased = tokenPurchased[msg.sender].add(amount); require(purchased <= tokenPurchaseLimit, "Purchase limit reached"); tokenPurchased[msg.sender] = purchased; } tokenRemainingForPublicSale = tokenRemainingForPublicSale.sub(amount); token.mint(msg.sender, amount); forwardFunds(); emit TokenPurchase(msg.sender, msg.value, amount); } /// @dev Extend the offering period of the crowd sale. /// @param _newClosingTime new closingTime of the crowdsale function changeClosingTime(uint _newClosingTime) public onlyOwner { require(!hasClosed(), "Sale has already ended"); require(_newClosingTime > now, "ClosingTime not in the future"); require(_newClosingTime > openingTime, "New offering is zero"); require(_newClosingTime - openingTime <= MAXOFFERINGPERIOD, "New offering too long"); emit ClosingTimeChange(closingTime, _newClosingTime); closingTime = _newClosingTime; } /// @dev Finalize, i.e. end token minting phase and enable token transfers function finalize() public onlyOwner { require(!isFinalized, "Sale has already been finalized"); require(hasClosed(), "Sale has not closed"); if (tokenReservePerMill > 0) { token.mint(reserveAccount, tokenSold().mul(tokenReservePerMill).div(1000)); } token.finishMinting(); isFinalized = true; emit Finalization(); } /// @dev Distribute tokens purchased off-chain (in Euro) to investors /// @param tokenRemaining Token units available for sale /// @param beneficiaries Ethereum addresses of purchasers /// @param amounts Token unit amounts to deliver to each investor /// @return Token units available for sale after distribution function distributeTokens( uint tokenRemaining, address[] memory beneficiaries, uint[] memory amounts, bool isPublicSale ) internal onlyOwner returns (uint) { require(!isFinalized, "Sale has been finalized"); require(beneficiaries.length == amounts.length, "Lengths are different"); for (uint i = 0; i < beneficiaries.length; ++i) { address beneficiary = beneficiaries[i]; uint amount = amounts[i]; require(amount <= tokenRemaining, "Not enough tokens available"); tokenRemaining = tokenRemaining.sub(amount); token.mint(beneficiary, amount); emit TokenDistribution(beneficiary, amount, isPublicSale); } return tokenRemaining; } /// @dev Forward invested ether to company wallet function forwardFunds() internal { companyWallet.transfer(address(this).balance); } } // File: contracts/token/TokenRecoverable.sol pragma solidity 0.5.12; /// @title TokenRecoverable /// @author STOKR contract TokenRecoverable is Ownable { // Address that can do the TokenRecovery address public tokenRecoverer; /// @dev Event emitted when the TokenRecoverer changes /// @param previous Ethereum address of previous token recoverer /// @param current Ethereum address of new token recoverer event TokenRecovererChange(address indexed previous, address indexed current); /// @dev Event emitted in case of a TokenRecovery /// @param oldAddress Ethereum address of old account /// @param newAddress Ethereum address of new account event TokenRecovery(address indexed oldAddress, address indexed newAddress); /// @dev Restrict operation to token recoverer modifier onlyTokenRecoverer() { require(msg.sender == tokenRecoverer, "Restricted to token recoverer"); _; } /// @dev Constructor /// @param _tokenRecoverer Ethereum address of token recoverer constructor(address _tokenRecoverer) public { setTokenRecoverer(_tokenRecoverer); } /// @dev Set token recoverer /// @param _newTokenRecoverer Ethereum address of new token recoverer function setTokenRecoverer(address _newTokenRecoverer) public onlyOwner { require(_newTokenRecoverer != address(0x0), "New token recoverer is zero"); if (_newTokenRecoverer != tokenRecoverer) { emit TokenRecovererChange(tokenRecoverer, _newTokenRecoverer); tokenRecoverer = _newTokenRecoverer; } } /// @dev Recover token /// @param _oldAddress address /// @param _newAddress address function recoverToken(address _oldAddress, address _newAddress) public; } // File: contracts/token/StokrToken.sol pragma solidity 0.5.12; /// @title StokrToken /// @author Stokr contract StokrToken is MintableToken, TokenRecoverable { string public name; string public symbol; uint8 public constant decimals = 18; mapping(address => mapping(address => uint)) internal allowance_; /// @dev Log entry on self destruction of the token event TokenDestroyed(); /// @dev Constructor /// @param _whitelist Ethereum address of whitelist contract /// @param _tokenRecoverer Ethereum address of token recoverer constructor( string memory _name, string memory _symbol, Whitelist _whitelist, address _profitDepositor, address _profitDistributor, address _tokenRecoverer ) public Whitelisted(_whitelist) ProfitSharing(_profitDepositor, _profitDistributor) TokenRecoverable(_tokenRecoverer) { name = _name; symbol = _symbol; } /// @dev Self destruct can only be called by crowdsale contract in case the goal wasn't reached function destruct() public onlyMinter { emit TokenDestroyed(); selfdestruct(address(uint160(owner))); } /// @dev Recover token /// @param _oldAddress address of old account /// @param _newAddress address of new account function recoverToken(address _oldAddress, address _newAddress) public onlyTokenRecoverer onlyWhitelisted(_newAddress) { // Ensure that new address is *not* an existing account. // Check for account.profitShare is not needed because of following implication: // (account.lastTotalProfits == 0) ==> (account.profitShare == 0) require(accounts[_newAddress].balance == 0 && accounts[_newAddress].lastTotalProfits == 0, "New address exists already"); updateProfitShare(_oldAddress); accounts[_newAddress] = accounts[_oldAddress]; delete accounts[_oldAddress]; emit TokenRecovery(_oldAddress, _newAddress); emit Transfer(_oldAddress, _newAddress, accounts[_newAddress].balance); } /// @dev Total supply of this token /// @return Token amount function totalSupply() public view returns (uint) { return totalSupply_; } /// @dev Token balance /// @param _investor Ethereum address of token holder /// @return Token amount function balanceOf(address _investor) public view returns (uint) { return accounts[_investor].balance; } /// @dev Allowed token amount a third party trustee may transfer /// @param _investor Ethereum address of token holder /// @param _spender Ethereum address of third party /// @return Allowed token amount function allowance(address _investor, address _spender) public view returns (uint) { return allowance_[_investor][_spender]; } /// @dev Approve a third party trustee to transfer tokens /// Note: additional requirements are enforced within internal function. /// @param _spender Ethereum address of third party /// @param _value Maximum token amount that is allowed to get transferred /// @return Always true function approve(address _spender, uint _value) public returns (bool) { return _approve(msg.sender, _spender, _value); } /// @dev Increase the amount of tokens a third party trustee may transfer /// Note: additional requirements are enforces within internal function. /// @param _spender Ethereum address of third party /// @param _amount Additional token amount that is allowed to get transferred /// @return Always true function increaseAllowance(address _spender, uint _amount) public returns (bool) { require(allowance_[msg.sender][_spender] + _amount >= _amount, "Allowance overflow"); return _approve(msg.sender, _spender, allowance_[msg.sender][_spender].add(_amount)); } /// @dev Decrease the amount of tokens a third party trustee may transfer /// Note: additional requirements are enforces within internal function. /// @param _spender Ethereum address of third party /// @param _amount Reduced token amount that is allowed to get transferred /// @return Always true function decreaseAllowance(address _spender, uint _amount) public returns (bool) { require(_amount <= allowance_[msg.sender][_spender], "Amount exceeds allowance"); return _approve(msg.sender, _spender, allowance_[msg.sender][_spender].sub(_amount)); } /// @dev Check if a token transfer is possible /// @param _from Ethereum address of token sender /// @param _to Ethereum address of token recipient /// @param _value Token amount to transfer /// @return True iff a transfer with given pramaters would succeed function canTransfer(address _from, address _to, uint _value) public view returns (bool) { return totalSupplyIsFixed && _from != address(0x0) && _to != address(0x0) && _value <= accounts[_from].balance && whitelist.isWhitelisted(_from) && whitelist.isWhitelisted(_to); } /// @dev Check if a token transfer by third party is possible /// @param _spender Ethereum address of third party trustee /// @param _from Ethereum address of token holder /// @param _to Ethereum address of token recipient /// @param _value Token amount to transfer /// @return True iff a transfer with given pramaters would succeed function canTransferFrom(address _spender, address _from, address _to, uint _value) public view returns (bool) { return canTransfer(_from, _to, _value) && _value <= allowance_[_from][_spender]; } /// @dev Token transfer /// Note: additional requirements are enforces within internal function. /// @param _to Ethereum address of token recipient /// @param _value Token amount to transfer /// @return Always true function transfer(address _to, uint _value) public returns (bool) { return _transfer(msg.sender, _to, _value); } /// @dev Token transfer by a third party /// Note: additional requirements are enforces within internal function. /// @param _from Ethereum address of token holder /// @param _to Ethereum address of token recipient /// @param _value Token amount to transfer /// @return Always true function transferFrom(address _from, address _to, uint _value) public returns (bool) { require(_value <= allowance_[_from][msg.sender], "Amount exceeds allowance"); return _approve(_from, msg.sender, allowance_[_from][msg.sender].sub(_value)) && _transfer(_from, _to, _value); } /// @dev Approve a third party trustee to transfer tokens (internal implementation) /// @param _from Ethereum address of token holder /// @param _spender Ethereum address of third party /// @param _value Maximum token amount the trustee is allowed to transfer /// @return Always true function _approve(address _from, address _spender, uint _value) internal onlyWhitelisted(_from) onlyWhenTotalSupplyIsFixed returns (bool) { allowance_[_from][_spender] = _value; emit Approval(_from, _spender, _value); return true; } /// @dev Token transfer (internal implementation) /// @param _from Ethereum address of token sender /// @param _to Ethereum address of token recipient /// @param _value Token amount to transfer /// @return Always true function _transfer(address _from, address _to, uint _value) internal onlyWhitelisted(_from) onlyWhitelisted(_to) onlyWhenTotalSupplyIsFixed returns (bool) { require(_to != address(0x0), "Recipient is zero"); require(_value <= accounts[_from].balance, "Amount exceeds balance"); updateProfitShare(_from); updateProfitShare(_to); accounts[_from].balance = accounts[_from].balance.sub(_value); accounts[_to].balance = accounts[_to].balance.add(_value); emit Transfer(_from, _to, _value); return true; } } // File: contracts/crowdsale/StokrCrowdsale.sol pragma solidity 0.5.12; /// @title StokrCrowdsale /// @author STOKR contract StokrCrowdsale is MintingCrowdsale { // Soft cap in token units uint public tokenGoal; // As long as the goal is not reached funds of purchases are held back // and investments are assigned to investors here to enable a refunding // if the goal is missed upon finalization mapping(address => uint) public investments; // Log entry upon investor refund event event InvestorRefund(address indexed investor, uint value); /// @dev Constructor /// @param _token The token /// @param _tokenCapOfPublicSale Available token units for public sale /// @param _tokenCapOfPrivateSale Available token units for private sale /// @param _tokenGoal Minimum number of sold token units to be successful /// @param _tokenPurchaseMinimum Minimum amount of tokens an investor has to buy at once /// @param _tokenPurchaseLimit Maximum total token amounts individually buyable in limit phase /// @param _tokenReservePerMill Additional reserve tokens in per mill of sold tokens /// @param _tokenPrice Price of a token in EUR cent /// @param _rateSource Ethereum address of ether rate setting authority /// @param _openingTime Block (Unix) timestamp of sale opening time /// @param _closingTime Block (Unix) timestamp of sale closing time /// @param _limitEndTime Block (Unix) timestamp until token purchases are limited /// @param _companyWallet Ethereum account who will receive sent ether /// @param _reserveAccount An address constructor( RateSource _rateSource, StokrToken _token, uint _tokenCapOfPublicSale, uint _tokenCapOfPrivateSale, uint _tokenGoal, uint _tokenPurchaseMinimum, uint _tokenPurchaseLimit, uint _tokenReservePerMill, uint _tokenPrice, uint _openingTime, uint _closingTime, uint _limitEndTime, address payable _companyWallet, address _reserveAccount ) public MintingCrowdsale( _rateSource, _token, _tokenCapOfPublicSale, _tokenCapOfPrivateSale, _tokenPurchaseMinimum, _tokenPurchaseLimit, _tokenReservePerMill, _tokenPrice, _openingTime, _closingTime, _limitEndTime, _companyWallet, _reserveAccount ) { require( _tokenGoal <= _tokenCapOfPublicSale + _tokenCapOfPrivateSale, "Goal is not attainable" ); tokenGoal = _tokenGoal; } /// @dev Wether the goal of sold tokens was reached or not /// @return True if the sale can be considered successful function goalReached() public view returns (bool) { return tokenSold() >= tokenGoal; } /// @dev Investors can claim refunds here if crowdsale was unsuccessful function distributeRefunds(address payable[] calldata _investors) external { for (uint i = 0; i < _investors.length; ++i) { refundInvestor(_investors[i]); } } /// @dev Investors can claim refunds here if crowdsale was unsuccessful function claimRefund() public { refundInvestor(msg.sender); } /// @dev Overwritten. Kill the token if goal was missed function finalize() public onlyOwner { super.finalize(); if (!goalReached()) { StokrToken(address(token)).destruct(); } } function distributeTokensViaPublicSale( address[] memory beneficiaries, uint[] memory amounts ) public { super.distributeTokensViaPublicSale(beneficiaries, amounts); // The goal may get reached due to token distribution, // so forward any accumulated funds to the company wallet. forwardFunds(); } function distributeTokensViaPrivateSale( address[] memory beneficiaries, uint[] memory amounts ) public { super.distributeTokensViaPrivateSale(beneficiaries, amounts); // The goal may get reached due to token distribution, // so forward any accumulated funds to the company wallet. forwardFunds(); } /// @dev Overwritten. Funds are held back until goal was reached function forwardFunds() internal { if (goalReached()) { super.forwardFunds(); } else { investments[msg.sender] = investments[msg.sender].add(msg.value); } } /// @dev Refund an investor if the sale was not successful /// @param _investor Ethereum address of investor function refundInvestor(address payable _investor) internal { require(isFinalized, "Sale has not been finalized"); require(!goalReached(), "Goal was reached"); uint investment = investments[_investor]; if (investment > 0) { investments[_investor] = 0; _investor.transfer(investment); emit InvestorRefund(_investor, investment); } } }
Set the address of whitelist _newWhitelist An Ethereum address
function setWhitelist(Whitelist _newWhitelist) public onlyOwner { require(address(_newWhitelist) != address(0x0), "Whitelist address is zero"); if (address(_newWhitelist) != address(whitelist)) { emit WhitelistChange(address(whitelist), address(_newWhitelist)); whitelist = Whitelist(_newWhitelist); } }
1,786,929
./partial_match/1/0x7e55ccB0bCe9A9094aE5cf75EF71b3275B45658A/sources/Tettoken.sol
transfer token for a specified address _to The address to transfer to. _value The amount to be transferred./
function transfer(address _to, uint256 _value) public onlyPayloadSize(2 * 32) whenNotPaused returns (bool success) { require (!(_to == 0x0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; }
3,553,619
./full_match/1/0x5EE84583f67D5EcEa5420dBb42b462896E7f8D06/sources/contracts/tokens/ASIC.sol
Burns existing tokens. Only the owner of contract can run this function account Address of the account to have the tokens burned amount Amount of tokens to be burned
function burn(address account, uint256 amount) external onlyOwner { _burn(account, amount); }
3,068,869
./full_match/3/0x967328588D821b4306fe8F0592faFE94eC930429/sources/contracts/Token5.sol
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), "BSC: approve from the zero address"); require(spender != address(0), "BSC: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
8,243,790
./full_match/1/0x29Cc5b56C25a7A2fcd933F4936E46347A648B427/sources/contracts/3_Ballot.sol
Give your vote (including votes delegated to you) to proposal 'proposals[proposal].name'. proposal index of proposal in the proposals array/ If 'proposal' is out of the range of the array, this will throw automatically and revert all changes.
function vote(uint proposal) public { Voter storage sender = voters[msg.sender]; require(this.getUserJFCBalance(msg.sender) > 0, "You dont have JFC to vote!"); require(!sender.voted, "Out of votes."); sender.vote = proposal; sender.voted = true; proposals[proposal].voteCount += this.getUserJFCBalance(msg.sender)* 7; }
4,887,260
// 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); } /** * @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 Reentrancy Guard. */ 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. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @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"); } } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev 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); } } /** * @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; } } // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface ISoulERC20 is IERC20 { function mint(address to, uint256 amount) external; } contract SoulVault is Ownable, ReentrancyGuard { address constant _trustedForwarder = 0x0D0b4862F5FfA3A47D04DDf0351356d20C830460; // Trusted forwarder using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. uint256 rewardLockedUp; // Reward locked up. uint256 nextHarvestUntil; // When can the user harvest again. uint256 lastInteraction; // Last time when user deposited or claimed rewards, renewing the lock } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract uint256 allocPoint; // How many allocation points assigned to this pool. Soul to distribute per block. uint256 lastRewardBlock; // Last block number that Soul distribution occurs. uint256 accSoulPerShare; // Accumulated Soul per share, times 1e12. See below. uint16 depositFeeBP; // Deposit fee in basis points uint256 harvestInterval; // Harvest interval in seconds uint256 totalLp; // Total token in Pool uint256 lockupDuration; // time the user will be locked in the pool after depositing or claiming rewards } ISoulERC20 public soul; // The operator can only update EmissionRate and AllocPoint to protect tokenomics //i.e some wrong setting and a pools get too much allocation accidentally address private _operator; // Dev address. address public devAddress; // Deposit Fee address address public feeAddress; // Soul tokens created per block uint256 public soulPerBlock; // Max harvest interval: 14 days uint256 public constant MAXIMUM_HARVEST_INTERVAL = 14 days; // Maximum deposit fee rate: 10% uint16 public constant MAXIMUM_DEPOSIT_FEE_RATE = 1000; // 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 Soul mining starts. uint256 public startBlock; // Total locked up rewards uint256 public totalLockedUpRewards; // Total Soul in Soul Pools (can be multiple pools) uint256 public totalSoulInPools = 0; // Control support for EIP-2771 Meta Transactions bool public metaTxnsEnabled = false; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); event EmissionRateUpdated( address indexed caller, uint256 previousAmount, uint256 newAmount ); event RewardLockedUp( address indexed user, uint256 indexed pid, uint256 amountLockedUp ); event OperatorTransferred( address indexed previousOperator, address indexed newOperator ); event DevAddressChanged( address indexed caller, address oldAddress, address newAddress ); event FeeAddressChanged( address indexed caller, address oldAddress, address newAddress ); event AllocPointsUpdated( address indexed caller, uint256 previousAmount, uint256 newAmount ); event MetaTxnsEnabled(address indexed caller); event MetaTxnsDisabled(address indexed caller); modifier onlyOperator() { require( _operator == msg.sender, "Operator: caller is not the operator" ); _; } constructor(ISoulERC20 _soul, uint256 _soulPerBlock) { //StartBlock always many years later from contract construct, will be set later in StartFarming function startBlock = block.number + (10 * 365 * 24 * 60 * 60); soul = _soul; soulPerBlock = _soulPerBlock; devAddress = msg.sender; feeAddress = msg.sender; _operator = msg.sender; emit OperatorTransferred(address(0), _operator); } function isTrustedForwarder(address forwarder) public view virtual returns (bool) { return metaTxnsEnabled && forwarder == _trustedForwarder; } function _msgSender() internal view virtual override returns (address sender) { if (isTrustedForwarder(msg.sender)) { // The assembly code is more direct than the Solidity version using `abi.decode`. assembly { sender := shr(96, calldataload(sub(calldatasize(), 20))) } } else { return super._msgSender(); } } function _msgData() internal view virtual override returns (bytes calldata) { if (isTrustedForwarder(msg.sender)) { return msg.data[:msg.data.length - 20]; } else { return super._msgData(); } } function operator() public view returns (address) { return _operator; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) { return _to.sub(_from); } function transferOperator(address newOperator) public onlyOperator { require( newOperator != address(0), "TransferOperator: new operator is the zero address" ); emit OperatorTransferred(_operator, newOperator); _operator = newOperator; } // Set farming start, can call only once function startFarming() public onlyOwner { require(block.number < startBlock, "Error: farm started already"); uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { PoolInfo storage pool = poolInfo[pid]; pool.lastRewardBlock = block.number; } startBlock = block.number; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // Can add multiple pool with same lp token without messing up rewards, // because each pool's balance is tracked using its own totalLp function add( uint256 _allocPoint, IERC20 _lpToken, uint16 _depositFeeBP, uint256 _harvestInterval, uint256 _lockupDuration, bool _withUpdate ) public onlyOwner { require( _depositFeeBP <= MAXIMUM_DEPOSIT_FEE_RATE, "Add: deposit fee too high" ); require( _harvestInterval <= MAXIMUM_HARVEST_INTERVAL, "Add: invalid harvest interval" ); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSoulPerShare: 0, depositFeeBP: _depositFeeBP, harvestInterval: _harvestInterval, totalLp: 0, lockupDuration: _lockupDuration }) ); } // View function to see pending Soul on frontend. function pendingSoul(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accSoulPerShare = pool.accSoulPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 soulReward = multiplier .mul(soulPerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); accSoulPerShare = accSoulPerShare.add( soulReward.mul(1e12).div(lpSupply) ); } uint256 pending = user.amount.mul(accSoulPerShare).div(1e12).sub( user.rewardDebt ); return pending.add(user.rewardLockedUp); } // View function to see when user will be unlocked from pool function userLockedUntil(uint256 _pid, address _user) public view returns (uint256) { UserInfo storage user = userInfo[_pid][_user]; PoolInfo storage pool = poolInfo[_pid]; return user.lastInteraction + pool.lockupDuration; } // View function to see if user can harvest Soul. function canHarvest(uint256 _pid, address _user) public view returns (bool) { UserInfo storage user = userInfo[_pid][_user]; return block.number >= startBlock && block.timestamp >= user.nextHarvestUntil; } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.totalLp; if (lpSupply == 0 || pool.allocPoint == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 soulReward = multiplier .mul(soulPerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); soul.mint(devAddress, soulReward.div(10)); soul.mint(address(this), soulReward); pool.accSoulPerShare = pool.accSoulPerShare.add( soulReward.mul(1e12).div(pool.totalLp) ); pool.lastRewardBlock = block.number; } // Deposit LP tokens to SoulVault for Soul allocation function deposit(uint256 _pid, uint256 _amount) public nonReentrant { require( block.number >= startBlock, "SoulVault: cannot deposit before farming start" ); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_msgSender()]; updatePool(_pid); payOrLockupPendingSoul(_pid); if (_amount > 0) { uint256 beforeDeposit = pool.lpToken.balanceOf(address(this)); pool.lpToken.safeTransferFrom(_msgSender(), address(this), _amount); uint256 afterDeposit = pool.lpToken.balanceOf(address(this)); _amount = afterDeposit.sub(beforeDeposit); if (pool.depositFeeBP > 0) { uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); pool.lpToken.safeTransfer(feeAddress, depositFee); _amount = _amount.sub(depositFee); } user.amount = user.amount.add(_amount); pool.totalLp = pool.totalLp.add(_amount); if (address(pool.lpToken) == address(soul)) { totalSoulInPools = totalSoulInPools.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accSoulPerShare).div(1e12); user.lastInteraction = block.timestamp; emit Deposit(_msgSender(), _pid, _amount); } // Withdraw tokens function withdraw(uint256 _pid, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_msgSender()]; //this will make sure that user can only withdraw from his pool require(user.amount >= _amount, "Withdraw: user amount is not enough"); //Cannot withdraw more than pool's balance require(pool.totalLp >= _amount, "Withdraw: pool total is not enough"); //Cannot withdraw before lock time require( block.timestamp > user.lastInteraction + pool.lockupDuration, "Withdraw: you cannot withdraw yet" ); updatePool(_pid); payOrLockupPendingSoul(_pid); if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.totalLp = pool.totalLp.sub(_amount); if (address(pool.lpToken) == address(soul)) { totalSoulInPools = totalSoulInPools.sub(_amount); } pool.lpToken.safeTransfer(_msgSender(), _amount); } user.rewardDebt = user.amount.mul(pool.accSoulPerShare).div(1e12); user.lastInteraction = block.timestamp; emit Withdraw(_msgSender(), _pid, _amount); } // Pay or lockup pending Soul. function payOrLockupPendingSoul(uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_msgSender()]; if (user.nextHarvestUntil == 0 && block.number >= startBlock) { user.nextHarvestUntil = block.timestamp.add(pool.harvestInterval); } uint256 pending = user.amount.mul(pool.accSoulPerShare).div(1e12).sub( user.rewardDebt ); if (canHarvest(_pid, _msgSender())) { if (pending > 0 || user.rewardLockedUp > 0) { uint256 totalRewards = pending.add(user.rewardLockedUp); // reset lockup totalLockedUpRewards = totalLockedUpRewards.sub( user.rewardLockedUp ); user.rewardLockedUp = 0; user.lastInteraction = block.timestamp; user.nextHarvestUntil = block.timestamp.add( pool.harvestInterval ); // send rewards safeSoulTransfer(_msgSender(), totalRewards); } } else if (pending > 0) { user.rewardLockedUp = user.rewardLockedUp.add(pending); user.lastInteraction = block.timestamp; totalLockedUpRewards = totalLockedUpRewards.add(pending); emit RewardLockedUp(_msgSender(), _pid, pending); } } // Safe Soul transfer function, just in case if rounding error causes pool do not have enough Soul. function safeSoulTransfer(address _to, uint256 _amount) internal { if (soul.balanceOf(address(this)) > totalSoulInPools) { //SoulBal = total Soul in SoulVault - total Soul in Soul pools, // this will make sure that SoulVault never transfer rewards from deposited Soul pools. uint256 SoulBal = soul.balanceOf(address(this)).sub( totalSoulInPools ); if (_amount >= SoulBal) { soul.transfer(_to, SoulBal); } else if (_amount > 0) { soul.transfer(_to, _amount); } } } // Update dev address by the previous dev. function setDevAddress(address _devAddress) public { require(_msgSender() == devAddress, "setDevAddress: FORBIDDEN"); require(_devAddress != address(0), "setDevAddress: ZERO"); emit DevAddressChanged(_msgSender(), devAddress, _devAddress); devAddress = _devAddress; } function setFeeAddress(address _feeAddress) public { require(_msgSender() == feeAddress, "setFeeAddress: FORBIDDEN"); require(_feeAddress != address(0), "setFeeAddress: ZERO"); emit FeeAddressChanged(_msgSender(), feeAddress, _feeAddress); feeAddress = _feeAddress; } // here we make it simple and transparent to all. function updateEmissionRate(uint256 _soulPerBlock) public onlyOperator { massUpdatePools(); emit EmissionRateUpdated(msg.sender, soulPerBlock, _soulPerBlock); soulPerBlock = _soulPerBlock; } function updateAllocPoint( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOperator { if (_withUpdate) { massUpdatePools(); } emit AllocPointsUpdated( _msgSender(), poolInfo[_pid].allocPoint, _allocPoint ); totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // Enable support for meta transactions function enableMetaTxns() public onlyOperator { require(!metaTxnsEnabled, "SoulVault: meta transactions are already enabled"); metaTxnsEnabled = true; emit MetaTxnsEnabled(_msgSender()); } // Disable support for meta transactions function disableMetaTxns() public onlyOperator { require(metaTxnsEnabled, "SoulVault: meta transactions are already disabled"); metaTxnsEnabled = false; emit MetaTxnsDisabled(_msgSender()); } }
Interface of the ERC20 standard as defined in the EIP./
interface ISoulERC20 is IERC20 { function mint(address to, uint256 amount) external; }
12,558,927
pragma solidity ^0.5.16; 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 LockIdGen { uint256 public requestCount; constructor() public { requestCount = 0; } function generateLockId() internal returns (bytes32 lockId) { return keccak256(abi.encodePacked(blockhash(block.number-1), address(this), ++requestCount)); } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing 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. */ 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. // 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 != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(StandardToken token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(StandardToken token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(StandardToken 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(StandardToken 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(StandardToken token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(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(ERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ManagerUpgradeable is LockIdGen { struct ChangeRequest { address proposedNew; address proposedClear; } // address public custodian; mapping (address => address) public managers; mapping (bytes32 => ChangeRequest) public changeReqs; uint256 public mancount ; // CONSTRUCTOR constructor( address [] memory _mans ) LockIdGen() public { uint256 numMans = _mans.length; for (uint256 i = 0; i < numMans; i++) { address pto = _mans[i]; require(pto != address(0)); managers[pto] = pto; } mancount = 0; } modifier onlyManager { require(msg.sender == managers[msg.sender],"onlyManger must use"); _; } //replace managers function replaceManager(address _new,address _clear) public onlyManager { require( _clear != address(0) || _new != address(0) ); require( _clear == address(0) || managers[_clear] == _clear); if(_new != address(0)) { managers[_new] = _new; mancount = mancount + 1; } if(_clear != address(0)) { delete managers[_clear]; mancount = mancount - 1; } } // for manager change function requestChange(address _new,address _clear) public onlyManager returns (bytes32 lockId) { require( _clear != address(0) || _new != address(0) ); require( _clear == address(0) || managers[_clear] == _clear); lockId = generateLockId(); changeReqs[lockId] = ChangeRequest({ proposedNew: _new, proposedClear: _clear }); emit ChangeRequested(lockId, msg.sender, _new,_clear); } event ChangeRequested( bytes32 _lockId, address _msgSender, address _new, address _clear ); function confirmChange(bytes32 _lockId) public onlyManager { ChangeRequest storage changeRequest = changeReqs[_lockId]; require( changeRequest.proposedNew != address(0) || changeRequest.proposedClear != address(0)); if(changeRequest.proposedNew != address(0)) { managers[changeRequest.proposedNew] = changeRequest.proposedNew; mancount = mancount + 1; } if(changeRequest.proposedClear != address(0)) { delete managers[changeRequest.proposedClear]; mancount = mancount - 1; } delete changeReqs[_lockId]; emit ChangeConfirmed(_lockId, changeRequest.proposedNew,changeRequest.proposedClear); } event ChangeConfirmed(bytes32 _lockId, address _newCustodian, address _clearCustodian); function sweepChange(bytes32 _lockId) public onlyManager { ChangeRequest storage changeRequest=changeReqs[_lockId]; require((changeRequest.proposedNew != address(0) || changeRequest.proposedClear != address(0) )); delete changeReqs[_lockId]; emit ChangeSweep(_lockId, msg.sender); } event ChangeSweep(bytes32 _lockId, address _sender); function sweeptoken(address tokenaddr,uint256 amount) public onlyManager{ TransferHelper.safeTransfer(tokenaddr,msg.sender,amount); } function sweepeth(uint256 amount) public onlyManager{ msg.sender.transfer(amount); } } contract ERC20Basic { // events event Transfer(address indexed from, address indexed to, uint256 value); // public functions function totalSupply() public view returns (uint256); function balanceOf(address addr) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); } contract ERC20 is ERC20Basic { // events event Approval(address indexed owner, address indexed agent, uint256 value); // public functions function allowance(address owner, address agent) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address agent, uint256 value) public returns (bool); } contract BasicToken is ERC20Basic { using SafeMath for uint256; // public variables string public name; string public symbol; uint8 public decimals = 18; // internal variables uint256 _totalSupply; mapping(address => uint256) _balances; // events // public functions function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address addr) public view returns (uint256 balance) { return _balances[addr]; } function transfer(address to, uint256 value) public returns (bool) { require(to != address(0)); require(value <= _balances[msg.sender]); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(msg.sender, to, value); return true; } // internal functions } contract StandardToken is ERC20, BasicToken { // public variables // internal variables mapping (address => mapping (address => uint256)) _allowances; // events // public functions function transferFrom(address from, address to, uint256 value) public returns (bool) { require(to != address(0)); require(value <= _balances[from],"value lt from"); require(value <= _allowances[from][msg.sender],"value lt _allowances from "); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); _allowances[from][msg.sender] = _allowances[from][msg.sender].sub(value); emit Transfer(from, to, value); return true; } function approve(address agent, uint256 value) public returns (bool) { _allowances[msg.sender][agent] = value; emit Approval(msg.sender, agent, value); return true; } function allowance(address owner, address agent) public view returns (uint256) { return _allowances[owner][agent]; } function increaseApproval(address agent, uint value) public returns (bool) { _allowances[msg.sender][agent] = _allowances[msg.sender][agent].add(value); emit Approval(msg.sender, agent, _allowances[msg.sender][agent]); return true; } function decreaseApproval(address agent, uint value) public returns (bool) { uint allowanceValue = _allowances[msg.sender][agent]; if (value > allowanceValue) { _allowances[msg.sender][agent] = 0; } else { _allowances[msg.sender][agent] = allowanceValue.sub(value); } emit Approval(msg.sender, agent, _allowances[msg.sender][agent]); return true; } // internal functions } contract MinableToken is StandardToken,ManagerUpgradeable{ uint256 maxMined =0; constructor(uint256 _maxMined,address [] memory _mans) public ManagerUpgradeable(_mans){ maxMined = _maxMined; } function _mint(address to, uint256 value) public onlyManager { require(maxMined==0||_totalSupply.add(value)<=maxMined,"_mint value invalid"); _totalSupply = _totalSupply.add(value); _balances[to] = _balances[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) public { _balances[from] = _balances[from].sub(value); _totalSupply = _totalSupply.sub(value); emit Transfer(from, address(0), value); } } contract DFKII is MinableToken { // public variables string public name = "Defiking.finance Version 2.0"; string public symbol = "DFKII"; uint8 public decimals = 18; // internal variables // events // public functions constructor(address [] memory _mans,uint256 _maxMined) public MinableToken(_maxMined,_mans) { //init _totalSupply // _totalSupply = 1000*10000 * (10 ** uint256(decimals)); // _balances[msg.sender] = _totalSupply; // emit Transfer(address(0x0), msg.sender, _totalSupply); } // internal functions } contract USDT is MinableToken { // public variables string public name = "Defiking.finance Version 2.0"; string public symbol = "USDT"; uint8 public decimals = 6; // internal variables // events // public functions constructor(address [] memory _mans,uint256 _maxMined) public MinableToken(_maxMined,_mans) { //init _totalSupply // _totalSupply = 1000*10000 * (10 ** uint256(decimals)); // _balances[msg.sender] = _totalSupply; // emit Transfer(address(0x0), msg.sender, _totalSupply); } // internal functions } contract DFK is ManagerUpgradeable { //liquidity + function stakingDeposit(uint256 value) public payable returns (bool); //profit + function profit2Staking(uint256 value)public returns (bool success); function withdrawProfit(address to)public returns (bool success); function withdrawStaking(address to,uint256 value)public returns (bool success); function withdrawAll(address to)public returns (bool success); function totalMiners() public view returns (uint256); function totalStaking() public view returns (uint256); function poolBalance() public view returns (uint256); function minedBalance() public view returns (uint256); function stakingBalance(address miner) public view returns (uint256); function profitBalance(address miner) public view returns (uint256); function pauseStaking()public returns (bool success); function resumeStaking()public returns (bool success); } contract DFKImplement is DFK { using SafeMath for uint256; using SafeERC20 for StandardToken; int public status; struct StakingLog{ uint256 staking_time; uint256 profit_time; uint256 staking_value; uint256 unstaking_value; } mapping(address => StakingLog) public stakings; uint256 public cleanup_time; uint256 public profit_period; uint256 public period_bonus; mapping(address => uint256) public balanceProfit; mapping(address => uint256) public balanceStaking; StandardToken public dfkToken; uint256 public _totalMiners; uint256 public _totalStaking; uint256 public totalProfit; uint256 public minePoolBalance; modifier onStaking { require(status == 1,"please start minner"); _; } event ProfitLog( address indexed from, uint256 profit_time, uint256 staking_value, uint256 unstaking_value, uint256 profit_times, uint256 profit ); constructor(address _dfkToken,int decimals,address [] memory _mans) public ManagerUpgradeable(_mans){ status = 0; cleanup_time = now; profit_period = 24*3600; period_bonus = 100000*(10 ** uint256(decimals)); cleanup_time = now; dfkToken = StandardToken(_dfkToken); } function addMinePool(uint256 stakevalue) public onStaking payable returns (uint256){ require(stakevalue>0); // user must call prove first. dfkToken.safeTransferFrom(msg.sender,address(this),stakevalue); minePoolBalance = minePoolBalance.add(stakevalue); return minePoolBalance; } function stakingDeposit(uint256 stakevalue) public onStaking payable returns (bool){ require(stakevalue>0,"stakevalue is gt zero"); // user must call prove first. dfkToken.transferFrom(msg.sender,address(this),stakevalue); _totalStaking = _totalStaking.add(stakevalue); return addMinerStaking(msg.sender,stakevalue); } function addMinerStaking(address miner,uint256 stakevalue) internal returns (bool){ balanceStaking[miner] = balanceStaking[miner].add(stakevalue); StakingLog memory slog=stakings[miner]; if(slog.profit_time < cleanup_time){ stakings[miner] = StakingLog({ staking_time:now, profit_time:now, staking_value:0, unstaking_value:stakevalue }); _totalMiners = _totalMiners.add(1); }else if(now.sub(slog.profit_time) >= profit_period){ uint256 profit_times = now.sub(slog.profit_time).div(profit_period); stakings[miner] = StakingLog({ staking_time:now, profit_time:now, staking_value:slog.staking_value.add(slog.unstaking_value), unstaking_value:stakevalue }); uint256 profit = period_bonus.mul(stakings[miner].staking_value).mul(profit_times).div(_totalStaking); emit ProfitLog(miner,stakings[miner].profit_time,stakings[miner].staking_value,stakings[miner].unstaking_value,profit_times,profit); require(minePoolBalance>=profit,"minePoolBalance lt profit"); minePoolBalance = minePoolBalance.sub(profit); balanceProfit[miner]=balanceProfit[miner].add(profit); totalProfit = totalProfit.add(profit); }else { stakings[miner] = StakingLog({ staking_time:now, profit_time:slog.profit_time, staking_value:slog.staking_value, unstaking_value:slog.unstaking_value.add(stakevalue) }); } return true; } function profit2Staking(uint256 value)public onStaking returns (bool success){ require(balanceProfit[msg.sender]>=value); balanceProfit[msg.sender] = balanceProfit[msg.sender].sub(value); return addMinerStaking(msg.sender,value); } function withdrawProfit(address to)public returns (bool success){ require(to != address(0)); addMinerStaking(msg.sender,0); uint256 profit = balanceProfit[msg.sender]; balanceProfit[msg.sender] = 0; require(dfkToken.transfer(to,profit)); return true; } function withdrawStaking(address to,uint256 value)public returns (bool success){ require(value>0); require(to != address(0)); require(balanceStaking[msg.sender]>=value); require(_totalStaking>=value); _totalStaking=_totalStaking.sub(value); balanceStaking[msg.sender] = balanceStaking[msg.sender].sub(value); StakingLog memory slog=stakings[msg.sender]; stakings[msg.sender] = StakingLog({ staking_time:now, profit_time:slog.profit_time, staking_value:0, unstaking_value:balanceStaking[msg.sender] }); require(dfkToken.transfer(to,value)); return true; } function withdrawAll(address to)public returns (bool success){ require(to != address(0)); addMinerStaking(msg.sender,0); _totalStaking=_totalStaking.sub(balanceStaking[msg.sender]); uint256 total=balanceStaking[msg.sender].add(balanceProfit[msg.sender]); balanceProfit[msg.sender]=0; balanceStaking[msg.sender] = 0; stakings[msg.sender] = StakingLog({ staking_time:0, profit_time:0, staking_value:0, unstaking_value:0 }); // _totalMiners=_totalMiners.sub(1); require(dfkToken.transfer(to,total)); return true; } function totalMiners() public view returns (uint256){ return _totalMiners; } function totalStaking() public view returns (uint256){ return _totalStaking; } function poolBalance() public view returns (uint256){ return minePoolBalance; } function minedBalance() public view returns (uint256){ return totalProfit; } function stakingBalance(address miner) public view returns (uint256){ return balanceStaking[miner]; } function profitBalance(address miner) public view returns (uint256){ return balanceProfit[miner]; } function pauseStaking()public onlyManager returns (bool ){ status = 0; } function resumeStaking()public onlyManager returns (bool ){ status = 1; } } contract DFKImplHelper{ using SafeMath for uint256; DFKImplement public dfkImpl; constructor(address _dfkImpl) public{ dfkImpl = DFKImplement(_dfkImpl); } function calcProfit(address miner) public view returns (uint256) { (,uint256 profit_time,uint256 staking_value,) = dfkImpl.stakings(miner); if(profit_time < dfkImpl.cleanup_time()){ return 0; }else if(now.sub(profit_time) >= dfkImpl.profit_period()){ uint256 profit_times = now.sub(profit_time).div(dfkImpl.profit_period()); uint256 profit = dfkImpl.period_bonus().mul(staking_value).mul(profit_times).div(dfkImpl._totalStaking()); return profit; }else { return 0; } } function calcProfitForFee(address miner,uint256 totalFee,uint256 lastFetchFee) public view returns (uint256) { (,uint256 profit_time,uint256 staking_value,) = dfkImpl.stakings(miner); if(staking_value == 0) { return 0; } if(profit_time < dfkImpl.cleanup_time()){ return 0; }else { // uint256 profit_times = now.sub(profit_time).div(dfkImpl.profit_period()); uint256 profit = totalFee.mul(staking_value).div(dfkImpl._totalStaking()); if(profit>lastFetchFee){ return profit.sub(lastFetchFee); }else{ return 0; } } } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } contract DTradeLiquids is StandardToken { // public variables string public name = "Defiking.finance swap"; string public symbol = "DTrade-V1 LP"; uint8 public decimals = 18; // internal variables // events address owner; // public functions constructor() public { //init _totalSupply owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function _mint(address to, uint value) public onlyOwner { _totalSupply = _totalSupply.add(value); _balances[to] = _balances[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) public onlyOwner{ _balances[from] = _balances[from].sub(value); _totalSupply = _totalSupply.sub(value); emit Transfer(from, address(0), value); } //function initialize(string _symbol) public{ // symbol = _symbol; // } // internal functions } interface Refers { function rewards2Super(address user,uint256 totalReward) external returns (bool); } contract DFKExPair is ManagerUpgradeable{ using SafeMath for uint256; using SafeERC20 for ERC20; address public token0;//usdt,basic token address public token1;//dfkii uint8 public price_decimal = 8; uint256 public cur_price = 0; uint public fee2Liquid = 22; uint public fee2Refs = 3; uint public fee2Burn = 5; uint256 public feeTotal=30; uint256 public PRICE_MOD=10000;//基数10000 uint256 public FEE_MOD=10000;//基数10000 uint256 public TOKEN_DECIMAL_DIF;//基数10000 uint256 public reserve0 =0;//liquid.token0 uint256 public reserve1 =0;//liquid.token1 uint256 public decimal0;//liquid.token0 uint256 public decimal1;//liquid.token1 uint256 public fee = 0; uint256 public priceFlips = 1;//flips for each 10000 token1 uint256 public totalProfitForLiquids =0; //fee.for liquid uint256 public totalProfitRefs =0; //fee.for dfk1 staking uint256 public totalProfitBurn =0; //fee.for burn uint256 public totalLiquids = 0; // mapping(address => uint256) public profits4DFK1; mapping(address => uint256[]) public liquidBonusLog; address public liquidToken;// Refers public refers; address public isDfkiiRefs; uint256 public unlocked = 0; uint256 public miniLiquid = 100000*(10 **18); modifier onLiquity { require(unlocked == 1,"please wait liquity"); _; } function pauseLiquity() public onlyManager returns (bool ){ unlocked = 0; } function resumeLiquity() public onlyManager returns (bool ){ unlocked = 1; } constructor(address _token0,address _token1,address refs,uint256 initprice,address []memory _mans,uint256 _miniLiquid) public ManagerUpgradeable(_mans){ //init _totalSupply token0 = _token0; token1 = _token1; if(_token0 == address(0x0)){ decimal0 = 10 **18; } else { decimal0 = 10 **uint256(StandardToken(_token0).decimals()); } if(_token1 == address(0x0)){ decimal1 = 10 **18; } else { decimal1 = 10 **uint256(StandardToken(_token1).decimals()); } cur_price = initprice; TOKEN_DECIMAL_DIF = decimal1.div(decimal0); refers = Refers(refs); bytes memory bytecode = type(DTradeLiquids).creationCode; bytes32 salt = keccak256(abi.encodePacked(token0, token1)); address _swapV2; assembly { _swapV2 := create2(0, add(bytecode, 32), mload(bytecode), salt) } liquidToken = _swapV2; miniLiquid=_miniLiquid; } function setPriceMod(uint256 price_mod) onlyManager public { require(price_mod>0); PRICE_MOD=price_mod; } //修正价格,手续费分配比例 function fixPrice (uint256 price,uint _fee2Liquid,uint _fee2Refs,uint _fee2Burn,uint256 _priceFlips,uint256 _miniLiquid) onlyManager public { cur_price = price; fee2Liquid = _fee2Liquid; fee2Refs = _fee2Refs; fee2Burn = _fee2Burn; feeTotal = fee2Liquid+fee2Refs+fee2Burn; priceFlips = _priceFlips; miniLiquid=_miniLiquid; } //增加池子流动性 function poolTokens(uint256 amount0,uint256 amount1) payable onlyManager public { if(token0 == address(0x0)){ require(msg.value>=amount0); } else{ TransferHelper.safeTransferFrom(token0,msg.sender,address(this),amount0); } if(token1 == address(0x0)){ require(msg.value>=amount1,"eth not enough"); }else{ TransferHelper.safeTransferFrom(token1,msg.sender,address(this),amount1); } reserve0 = reserve0.add(amount0); reserve1 = reserve1.add(amount1); } event TotalEvent( uint256 totalProfitBurn, uint256 totalProfitRefs, uint256 totalProfitForLiquids, uint256 cur_price, uint256 liquidfee, uint256 liquidRefs, uint256 liquidburn ); event TotalAmount( uint256 amount0, uint256 amount1, uint256 avg_price, uint256 fee ); //swap token0 or token1 function swap(uint256 amount0,uint256 amount1 ,bool toLiquids) payable public returns(uint256,uint256){ require(cur_price>0); if(amount1>0 && amount0 == 0){//sell token get basic token //uint256 price_float = amount1.mul(priceFlips).div(decimal1).div(PRICE_MOD); // require (ERC20(token1).balanceOf(msg.sender) >= amount1 ); uint256 price_float = amount1.mul(priceFlips).div(decimal1); require(price_float<cur_price,"too large amount"); uint256 next_price = cur_price.sub(price_float); uint256 avg_price = cur_price.add(next_price).div(2); if(token1 == address(0x0)){ require(msg.value>=amount1); }else{ require (ERC20(token1).balanceOf(msg.sender) >= amount1 ); TransferHelper.safeTransferFrom(token1,msg.sender,address(this),amount1); } uint256 liquidfee = amount1.mul(fee2Liquid).div(FEE_MOD); uint256 liquidRefs = amount1.mul(fee2Refs).div(FEE_MOD); uint256 liquidburn = amount1.mul(fee2Burn).div(FEE_MOD); amount1 = amount1.sub(liquidfee).sub(liquidRefs).sub(liquidburn); if(address(refers)!=address(0x0)){ TransferHelper.safeTransfer(token1,address(refers),liquidRefs); refers.rewards2Super(msg.sender,liquidRefs); } totalProfitBurn = totalProfitBurn.add(liquidburn); totalProfitRefs = totalProfitRefs.add(liquidRefs); totalProfitForLiquids = totalProfitForLiquids.add(liquidfee); amount0 = amount1.mul(avg_price).div(TOKEN_DECIMAL_DIF).div(PRICE_MOD); cur_price = next_price; if(toLiquids){ reserve0 = reserve0.add(amount0); reserve1 = reserve1.add(amount1); }else{ if(token0==address(0x0)) {//eth msg.sender.transfer(amount0); }else{ TransferHelper.safeTransfer(token0,msg.sender,amount0); } } } else if(amount0 > 0 && amount1 == 0){//using eth/usdt to buy token1 if(token0 == address(0x0)) { require(msg.value >= amount0 ); } else { require (ERC20(token0).balanceOf(msg.sender) >= amount0 ); TransferHelper.safeTransferFrom(token0,msg.sender,address(this),amount0); } amount1 = amount0.mul(PRICE_MOD).div(cur_price); uint256 price_float = amount1.mul(priceFlips).div(decimal0); uint256 next_price = cur_price.add(price_float); uint256 avg_price = cur_price.add(next_price).div(2); amount1 = amount0.mul(TOKEN_DECIMAL_DIF).mul(PRICE_MOD).div(avg_price); uint256 liquidfee = amount1.mul(fee2Liquid).div(FEE_MOD); uint256 liquidRefs = amount1.mul(fee2Refs).div(FEE_MOD); uint256 liquidburn = amount1.mul(fee2Burn).div(FEE_MOD); amount1 = amount1.sub(liquidfee).sub(liquidRefs).sub(liquidburn); if(address(refers)!=address(0x0)){ TransferHelper.safeTransfer(token1,address(refers),liquidRefs); refers.rewards2Super(msg.sender,liquidRefs); } totalProfitBurn = totalProfitBurn.add(liquidburn); totalProfitRefs = totalProfitRefs.add(liquidRefs); totalProfitForLiquids = totalProfitForLiquids.add(liquidfee); cur_price = next_price; if(toLiquids){ reserve0 = reserve0.add(amount0); reserve1 = reserve1.add(amount1); }else{ if(token1 == address(0x0)){ msg.sender.transfer(amount1); }else{ TransferHelper.safeTransfer(token1,msg.sender,amount1); } } } return (amount0,amount1); } function addLiquid(uint256 amount0) public onLiquity payable returns(uint256) { if(token0 == address(0x0)){ require (msg.value >= amount0); }else{ require (ERC20(token0).balanceOf(msg.sender) >= amount0 ); TransferHelper.safeTransferFrom(token0,msg.sender,address(this),amount0.div(2)); } (,uint256 buyamount1) = swap(amount0.div(2),0,true); uint256 totalLiquid = reserve1.add(reserve1); uint256 poolLiquid = ERC20(address(token1)).balanceOf(address(this)); if(poolLiquid<miniLiquid){ poolLiquid=miniLiquid; } uint256 mineCoin = buyamount1.add(buyamount1).mul(totalLiquid).div(poolLiquid); DTradeLiquids(liquidToken)._mint(msg.sender,mineCoin); uint256 leftCoin = amount0.sub(amount0.div(2).mul(2)); if(leftCoin>0&&token0!=address(0x0)){ TransferHelper.safeTransferFrom(token0,msg.sender,address(this),leftCoin); } return mineCoin; } function removeLiquid(uint256 amountL) payable public returns(uint256,uint256) { require(DTradeLiquids(liquidToken).balanceOf(msg.sender)>=amountL); uint256 totalLiquid = reserve1.add(reserve1); uint256 amount1 = amountL.mul((ERC20(address(token1)).balanceOf(address(this)))).div(totalLiquid).div(2); uint256 amount0 = amount1.mul(cur_price).div(TOKEN_DECIMAL_DIF).div(PRICE_MOD); require(ERC20(token1).balanceOf(address(this))>=amount1); reserve1 = reserve1.sub(amount1); reserve0 = reserve0.sub(amount0); DTradeLiquids(liquidToken)._burn(msg.sender,amountL); if(token0==address(0x0)) {//eth require(address(this).balance>=amount0); msg.sender.transfer(amount0); }else{ require(ERC20(token0).balanceOf(address(this))>=amount0); TransferHelper.safeTransfer(token0,msg.sender,amount0); } if(token1==address(0x0)) {//eth require(address(this).balance>=amount1); msg.sender.transfer(amount1); }else{ require(ERC20(token1).balanceOf(address(this))>=amount1); TransferHelper.safeTransfer(token1,msg.sender,amount1); } return (amount0,amount1); } } contract UserRefers is ManagerUpgradeable,Refers{ using SafeMath for uint256; using SafeERC20 for ERC20; mapping(address => address) public relations; mapping(address => address[]) public superiors; mapping(address => address) public callers; mapping(address => uint256) public rewards; address public topAddr; address public token; constructor(address _token,address []memory _mans) public ManagerUpgradeable(_mans){ relations[address(0x0)] = address(0x0); topAddr = msg.sender; token = _token; } function addCaller(address _newCaller) onlyManager public { callers[_newCaller] = _newCaller; } function removeCaller(address rmCaller) onlyManager public { callers[rmCaller] = address(0x0); } function buildSuperoir(address ref,uint256 maxLayer) public { if(relations[msg.sender]==address(0x0)) { relations[msg.sender] = ref; superiors[msg.sender].push(ref); address[] memory supers = superiors[ref]; if(supers.length>0){ superiors[msg.sender].push(supers[0]); } uint256 cc = 2; for(uint256 i=1;i<supers.length && cc < maxLayer;i++){ superiors[msg.sender].push(supers[i]); cc++; } } } function withdrawRewards() public{ require(rewards[msg.sender]>0); TransferHelper.safeTransfer(token,msg.sender,rewards[msg.sender]); rewards[msg.sender] = 0; } // 0.03%分配给邀请人(其中0.01%分配给直接推荐人30%,0.005%分配给间接推荐人,15%,0.015%均分给第3代至第12代) function rewards2Super(address user,uint256 totalReward) external returns (bool) { require(callers[msg.sender]==msg.sender,"caller is empty") ; // rewards[user] = rewards[user].add(totalReward); address[] memory supers = superiors[user]; uint256 leftReward = totalReward; uint256 bonus0; uint256 bonus1; uint256 bonus2; if(supers.length>0){ uint256 bonus = totalReward.mul(30).div(100); rewards[supers[0]] = bonus; // TransferHelper.safeTransfer(token,supers[0],bonus); leftReward = leftReward.sub(bonus); bonus0=bonus; } if(supers.length>1){ uint256 bonus = totalReward.mul(15).div(100); rewards[supers[1]] = bonus; // TransferHelper.safeTransfer(token,supers[1],bonus); leftReward = leftReward.sub(bonus); bonus1=bonus; } if(supers.length>2){ uint256 preReward = leftReward.div(supers.length.sub(2)); for(uint256 i=2;i<supers.length ;i++){ // TransferHelper.safeTransfer(token,supers[i],preReward); rewards[supers[i]] = preReward; leftReward = leftReward.sub(preReward); } bonus2=preReward; } if(leftReward>0){ // TransferHelper.safeTransfer(token,topAddr,leftReward); rewards[topAddr] = leftReward; } return true; } } contract TestRefs { Refers public refs; constructor(address _ref) public { refs = Refers(_ref); } function testReward(uint256 amount) public { refs.rewards2Super(msg.sender,amount); } } contract DTrade is ManagerUpgradeable{ using SafeMath for uint256; using SafeERC20 for ERC20; mapping(address => mapping(address =>uint256 )) public uniswapLiquids;//(liquid.addr=>(user.address=>amount) mapping(address => address) public liquidsMap; mapping(address => uint256)public liquidPools; mapping(address => uint256) public profits4DFK1; mapping(address => uint256) public bonusWithdraw; mapping(address => uint256) public checkpointHistory; mapping(address => uint256) public joinTime; address [] public liquidPairs; uint256 public peroid_total_bonus = 90000*(10 **18); uint256 public peroid_left_bonus = 0; uint256 public bonus_per_block = 9*(10 **18); uint256 public bonus_percent_LP = 10; uint256 public checkpoint_number = 0; // uint256 totalProfitDFK1 = 0; uint256 public totalLiquids; uint256 public totalMint; DFKImplHelper public dfk1Helper; uint256 public peroid_mined_coin = 0; address public token1; uint256 public totalFactor = 0; address public liquidToken; DFKII public dfkii; constructor(address _token1,address []memory _mans) public ManagerUpgradeable(_mans){ token1 = _token1; checkpoint_number = block.number+5*60; bytes memory bytecode = type(DTradeLiquids).creationCode; bytes32 salt = keccak256(abi.encodePacked(msg.sender, token1)); address _swapV2; assembly { _swapV2 := create2(0, add(bytecode, 32), mload(bytecode), salt) } liquidToken = _swapV2; } function setDFKII(address _dfkii) public onlyManager { dfkii = DFKII(_dfkii); } function setDfk1Helper(address _dfk1Helper) public onlyManager { dfk1Helper = DFKImplHelper(_dfk1Helper); } function nextPeroid(uint256 total,uint256 perblock,uint256 percentLP) public onlyManager { totalMint = totalMint.add(peroid_total_bonus); peroid_total_bonus = total; bonus_per_block = perblock; bonus_percent_LP = percentLP; peroid_left_bonus = total; peroid_mined_coin = 0; checkpoint_number = block.number; joinTime[address(0x0)] = block.number; } function addUniswapPair(address uniAddr,uint256 factor) public onlyManager { if(liquidsMap[uniAddr]==address(0x0)){ uniswapLiquids[uniAddr][address(0x0)]=factor; totalFactor = totalFactor.add(factor); // uniswapLiquids[address(0x0)][address(0x0)] = uniswapLiquids[address(0x0)][address(0x0)].add(factor); liquidsMap[uniAddr] = uniAddr; liquidPairs.push(uniAddr); } } function removeUniswapPair(address uniAddr) public onlyManager { totalFactor = totalFactor.sub(uniswapLiquids[uniAddr][address(0x0)]); uniswapLiquids[uniAddr][address(0x0)]=0; } function addDfkPair(address uniAddr,uint256 factor) public onlyManager { if(liquidsMap[uniAddr]==address(0x0)){ uniswapLiquids[uniAddr][address(0x0)]=factor; totalFactor = totalFactor.add(factor); liquidsMap[uniAddr] = uniAddr; liquidPairs.push(uniAddr); } } function removeDfkPair(address uniAddr) public onlyManager { totalFactor = totalFactor.sub(uniswapLiquids[uniAddr][address(0x0)]); uniswapLiquids[uniAddr][address(0x0)]=0; } function addLiquid(address uniAddr,uint256 amountUL) public { require(uniswapLiquids[uniAddr][address(0x0)]>0);//factor must large than zero uint256 realBonus=calcBonus(msg.sender); if(realBonus>0) { dfkii._mint(msg.sender,realBonus); } TransferHelper.safeTransferFrom(uniAddr,msg.sender,address(this),amountUL); liquidPools[uniAddr] = liquidPools[uniAddr].add(amountUL); uniswapLiquids[uniAddr][msg.sender]=uniswapLiquids[uniAddr][msg.sender].add(amountUL); uint256 mine_liquid=amountUL.mul(uniswapLiquids[uniAddr][address(0x0)]); // totalLiquids = totalLiquids.add(mine_liquid); DTradeLiquids(liquidToken)._mint(msg.sender,mine_liquid); joinTime[msg.sender] = block.number; bonusWithdraw[msg.sender] = 0; } function removeLiquid(address uniAddr,uint256 amountUL) public { require(uniswapLiquids[uniAddr][msg.sender]>=amountUL,'amountUL is not enough'); uint256 realBonus=calcBonus(msg.sender); if(realBonus>0) { dfkii._mint(msg.sender,realBonus); } TransferHelper.safeTransfer(address(uniAddr),msg.sender,amountUL); uint256 mine_liquid=amountUL.mul(uniswapLiquids[uniAddr][address(0x0)]); DTradeLiquids(liquidToken)._burn(msg.sender,mine_liquid); uniswapLiquids[uniAddr][msg.sender]=uniswapLiquids[uniAddr][msg.sender].sub(amountUL); if(DTradeLiquids(liquidToken).balanceOf(msg.sender)==0){ joinTime[msg.sender] = 0; } else { joinTime[msg.sender] = block.number; } bonusWithdraw[msg.sender] = 0; } function mintCoin(address user) public view returns (uint256){ if(joinTime[user]==0){ return 0; } uint256 checkTime = checkpoint_number; if(joinTime[user]>checkpoint_number){ checkTime = joinTime[user]; } uint256 currentBonus = bonus_per_block.mul(block.number.sub(checkTime)); if(currentBonus>peroid_left_bonus){ currentBonus = peroid_left_bonus; } // return currentBonus; } modifier onlyJoin { require(joinTime[msg.sender] > 0,"onlyJoin time gt 0"); _; } function calcDFK1Bonus(address addr) public view returns(uint256){ if(joinTime[msg.sender] == 0){ return 0; } return dfk1Helper.calcProfitForFee(addr,mintCoin(address(0x0)).mul(bonus_percent_LP).div(100),profits4DFK1[addr]); } function withdrawDFK1Bonus() public onlyJoin returns(uint256){ uint256 bonus=calcDFK1Bonus(msg.sender); if(bonus>0){ profits4DFK1[msg.sender] = profits4DFK1[msg.sender].add(bonus); // totalProfitDFK1 = totalProfitDFK1.sub(bonus); // TransferHelper.safeTransfer(token1,msg.sender,bonus); dfkii._mint(msg.sender,bonus); return bonus; }else{ return 0; } } function withdrawBonus() public onlyJoin returns(uint256){ uint256 realBonus=calcBonus(msg.sender); if(realBonus>0) { bonusWithdraw[msg.sender] = bonusWithdraw[msg.sender].add(realBonus); dfkii._mint(msg.sender,realBonus); joinTime[msg.sender] = block.number; bonusWithdraw[msg.sender] = 0; } return realBonus; } function calcBonus(address addr) public view returns (uint256){ if(joinTime[addr] == 0){ return 0; } if(joinTime[addr]<block.number){ return (ERC20(liquidToken).balanceOf(addr)).div(ERC20(liquidToken).totalSupply()).mul(mintCoin(addr)); }else{ return 0; } } } // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } // function safeTransferETH(address to, uint value) internal { // (bool success,bt) = to.call{value:value}(new bytes(0)); // require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); // } }
uint256 profit_times = now.sub(profit_time).div(dfkImpl.profit_period());
function calcProfitForFee(address miner,uint256 totalFee,uint256 lastFetchFee) public view returns (uint256) { (,uint256 profit_time,uint256 staking_value,) = dfkImpl.stakings(miner); if(staking_value == 0) { return 0; } if(profit_time < dfkImpl.cleanup_time()){ return 0; uint256 profit = totalFee.mul(staking_value).div(dfkImpl._totalStaking()); if(profit>lastFetchFee){ return profit.sub(lastFetchFee); return 0; } } }
9,826,440
/* HTTPS://SYNCBOND.COM HTTPS://APP.SYNCBOND.COM ███████╗██╗░░░██╗███╗░░░██╗░██████╗░░░░██████╗░░██████╗░██╗░░░░██╗███████╗██████╗░███████╗██████╗░ ██╔════╝╚██╗░██╔╝████╗░░██║██╔════╝░░░░██╔══██╗██╔═══██╗██║░░░░██║██╔════╝██╔══██╗██╔════╝██╔══██╗ ███████╗░╚████╔╝░██╔██╗░██║██║░░░░░░░░░██████╔╝██║░░░██║██║░█╗░██║█████╗░░██████╔╝█████╗░░██║░░██║ ╚════██║░░╚██╔╝░░██║╚██╗██║██║░░░░░░░░░██╔═══╝░██║░░░██║██║███╗██║██╔══╝░░██╔══██╗██╔══╝░░██║░░██║ ███████║░░░██║░░░██║░╚████║╚██████╗░░░░██║░░░░░╚██████╔╝╚███╔███╔╝███████╗██║░░██║███████╗██████╔╝ ╚══════╝░░░╚═╝░░░╚═╝░░╚═══╝░╚═════╝░░░░╚═╝░░░░░░╚═════╝░░╚══╝╚══╝░╚══════╝╚═╝░░╚═╝╚══════╝╚═════╝░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░██████╗██████╗░██╗░░░██╗██████╗░████████╗░██████╗░██████╗░░██████╗░███╗░░░██╗██████╗░███████╗░░░░ ██╔════╝██╔══██╗╚██╗░██╔╝██╔══██╗╚══██╔══╝██╔═══██╗██╔══██╗██╔═══██╗████╗░░██║██╔══██╗██╔════╝░░░░ ██║░░░░░██████╔╝░╚████╔╝░██████╔╝░░░██║░░░██║░░░██║██████╔╝██║░░░██║██╔██╗░██║██║░░██║███████╗░░░░ ██║░░░░░██╔══██╗░░╚██╔╝░░██╔═══╝░░░░██║░░░██║░░░██║██╔══██╗██║░░░██║██║╚██╗██║██║░░██║╚════██║░░░░ ╚██████╗██║░░██║░░░██║░░░██║░░░░░░░░██║░░░╚██████╔╝██████╔╝╚██████╔╝██║░╚████║██████╔╝███████║░░░░ ░╚═════╝╚═╝░░╚═╝░░░╚═╝░░░╚═╝░░░░░░░░╚═╝░░░░╚═════╝░╚═════╝░░╚═════╝░╚═╝░░╚═══╝╚═════╝░╚══════╝░░░░ */ pragma solidity ^0.6.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); } interface ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes calldata data) external; } /** * @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 Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } library SquareRoot { function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } /* https://ethereum.stackexchange.com/a/8447 */ library AddressStrings { function toString(address x) internal pure returns (string memory) { bytes memory s = new bytes(40); for (uint i = 0; i < 20; i++) { byte b = byte(uint8(uint(x) / (2**(8*(19 - i))))); byte hi = byte(uint8(b) / 16); byte lo = byte(uint8(b) - 16 * uint8(hi)); s[2*i] = char(hi); s[2*i+1] = char(lo); } return string(s); } function char(byte b) internal pure returns (byte c) { if (uint8(b) < 10) return byte(uint8(b) + 0x30); else return byte(uint8(b) + 0x57); } } interface Oracle{ function liquidityValues(address token) external view returns(uint);//returns usd value of token (consider usd an 18 decimal stablecoin), or 0 if not listed function syncValue() external view returns(uint);//returns usd value of SYNC } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transfered from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } /** * @title 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); } /** * @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); } /** * @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); } /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } /** * @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 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)); } } /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { return _get(map, key, "EnumerableMap: nonexistent key"); } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint256(value))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key)))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint256(_get(map._inner, bytes32(key), errorMessage))); } } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = 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 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 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 mecanisms 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 returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(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); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } function _approve(address to, uint256 tokenId) private { _tokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } /** * @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 { } } /** * @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); } } /** * @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; } } contract Sync is IERC20, Ownable { using SafeMath for uint256; mapping (address => uint256) private balances; mapping (address => mapping (address => uint256)) private allowed; string public constant name = "SYNC"; string public constant symbol = "SYNC"; uint8 public constant decimals = 18; uint256 _totalSupply = 16000000 * (10 ** 18); // 16 million supply mapping (address => bool) public mintContracts; modifier isMintContract() { require(mintContracts[msg.sender],"calling address is not allowed to mint"); _; } constructor() public Ownable(){ balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function setMintAccess(address account, bool canMint) public onlyOwner { mintContracts[account]=canMint; } function _mint(address account, uint256 amount) public isMintContract { 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); } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address user) public view override returns (uint256) { return balances[user]; } function allowance(address user, address spender) public view override returns (uint256) { return allowed[user][spender]; } function transfer(address to, uint256 value) public override returns (bool) { require(value <= balances[msg.sender],"insufficient balance"); require(to != address(0),"cannot send to zero address"); balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); emit Transfer(msg.sender, to, value); return true; } function approve(address spender, uint256 value) public override returns (bool) { require(spender != address(0),"cannot approve the zero address"); allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function approveAndCall(address spender, uint256 tokens, bytes calldata data) external returns (bool) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } function transferFrom(address from, address to, uint256 value) public override returns (bool) { require(value <= balances[from],"insufficient balance"); require(value <= allowed[from][msg.sender],"insufficient allowance"); require(to != address(0),"cannot send to the zero address"); 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; } function burn(uint256 amount) external { require(amount != 0,"must burn more than zero"); require(amount <= balances[msg.sender],"insufficient balance"); _totalSupply = _totalSupply.sub(amount); balances[msg.sender] = balances[msg.sender].sub(amount); emit Transfer(msg.sender, address(0), amount); } } contract CBOND is ERC721, Ownable { using SafeMath for uint256; using Strings for uint256; using AddressStrings for address; event Created(address token,uint256 syncAmount,uint256 tokenAmount,uint256 syncPrice,uint256 tokenPrice,uint256 tokenId); event Matured(address token,uint256 syncReturned,uint256 tokenAmount,uint256 tokenId); event DivsPaid(address token,uint256 syncReturned,uint256 tokenId); //read only counter values uint256 public totalCBONDS=0;//Total number of Cbonds created. uint256 public totalQuarterlyCBONDS=0;//Total number of quarterly Cbonds created. uint256 public totalCBONDSCashedout=0;//Total number of Cbonds that have been matured. uint256 public totalSYNCLocked=0;//Total amount of Sync locked in Cbonds. mapping(address => uint256) public totalLiquidityLockedByPair;//Total amount of tokens locked in Cbonds of the given liquidity token. //values contained in individual CBONDs, by token id mapping(uint256 => address) public lAddrById;//The address of the liquidity token used to create the given Cbond. mapping(uint256 => uint256) public lTokenPriceById;//The relative price of the liquidity token at the time the given Cbond was created. mapping(uint256 => uint256) public lTokenAmountById;//The amount of liquidity tokens initially deposited into the given Cbond. mapping(uint256 => uint256) public syncPriceById;//The relative price of Sync at the time the given Cbond was created. mapping(uint256 => uint256) public syncAmountById;//The amount of Sync initially deposited into the given Cbond. mapping(uint256 => uint256) public syncInterestById;//The amount of Sync interest on the initially deposited Sync awarded by the given Cbond. For quarterly Cbonds, this variable will represent only the interest of a single quarter. mapping(uint256 => uint256) public syncRewardedOnMaturity;//The amount of Sync returned to the user on maturation of the given Cbond. mapping(uint256 => uint256) public timestampById;//The time the given Cbond was created. mapping(uint256 => bool) public gradualDivsById;//Whether the given Cbond awards dividends quarterly. mapping(uint256 => uint256) public lastDivsCashoutById;//For Quarterly Cbonds, this variable represents the last cashout timestamp. mapping(uint256 => uint256) public totalDivsCashoutById;//For Quarterly Cbonds, the total dividends cashed out to date. Frontend use only, not used for calculations within the contract. mapping(uint256 => uint256) public termLengthById;//Length of term in seconds for the given Cbond. //constant and pseudo-constant (never changed after constructor) values uint256 constant public PERCENTAGE_PRECISION=10000;//Divide percentages by this to get the real multiplier. uint256 constant public INCENTIVE_MAX_PERCENT=220;//2.2%, the maximum value the liquidity incentive rate can be. uint256 constant public MAX_SYNC_GLOBAL=100000 * (10 ** 18);//Maximum Sync in a Cbond. Cbonds with higher amounts of Sync cannot be created. uint256 constant public QUARTER_LENGTH=90 days;//The length of a quarter, the interval of time between quarterly dividends. uint256 public STARTING_TIME=block.timestamp;//The time the contract was deployed. uint256 constant public BASE_INTEREST_RATE_START=220;//2.2%, starting value for base interest rate. uint256 constant public MINIMUM_BASE_INTEREST_RATE=10;//0.1%, the minimum value base interest rate can be. uint256 constant public MAXIMUM_BASE_INTEREST_RATE=4500;//45%, the maximum value base interest rate can be. uint256[] public LUCKY_EXTRAS=[500,1000];//Bonus interest awarded to user on creating lucky and extra lucky Cbonds. uint256 public YEAR_LENGTH=360 days;//Time length of approximately 1 year uint256[] public TERM_DURATIONS=[90 days,180 days,360 days,720 days,1080 days];//Possible term durations for Cbonds, index values corresponding to the following variables: uint256[] public DURATION_MODIFIERS=[825,1650,3300,6600,10000];//The percentage values used as duration modifiers for the given term lengths. uint256[] public DURATION_CALC_LOOPS=[0,0,3,7,11];//Number of loops for the duration rate formula approximation function, for the given term duration. mapping(uint256 => uint256) public INDEX_BY_DURATION;//Mapping of term durations to index values, as relates to the above variables. uint256 public RISK_FACTOR = 5;//Constant used in duration rate calculation //Index variables for tracking uint256 public lastDaySyncSupplyUpdated=0;//The previously recorded day on which the supply of Sync was last recorded into syncSupplyByDay. uint256 public currentDaySyncSupplyUpdated=0;//The day on which the supply of Sync was last recorded into syncSupplyByDay. mapping(address => mapping(uint256 => uint256)) public cbondsHeldByUser;//Mapping of cbond ids held by user. The second mapping is a list, length given by cbondsHeldByUserCursor. mapping(address => uint256) public cbondsHeldByUserCursor;//The number of Cbonds held by the given user. mapping(address => uint256) public lastDayTokenSupplyUpdated;//The previously recorded day on which the supply of the given token was last recorded into liqTokenTotalsByDay. mapping(address => uint256) public currentDayTokenSupplyUpdated;//The day on which the supply of the given token was last recorded into liqTokenTotalsByDay. mapping(uint256 => uint256) public syncSupplyByDay;//The recorded total supply of the Sync token for the given day. This value is written once and thereafter cannot be changed for a given day. mapping(uint256 => uint256) public interestRateByDay;//The recorded base interest rate for the given day. This value is written once and thereafter cannot be changed for a given day, and is recorded simultaneously with syncSupplyByDay. mapping(address => mapping(uint256 => uint256)) public liqTokenTotalsByDay;//The recorded total for the given liquidity token on the given day. This value is written once and thereafter cannot be changed for a given token/day. uint256 public _currentTokenId = 0;//Variable for tracking next NFT identifier. //Read only tracking variables (not used within the smart contract) mapping(uint256 => uint256) public cbondsMaturingByDay;//Mapping of days to number of cbonds maturing that day. //admin adjustable values mapping(address => bool) public tokenAccepted;//Whether a given liquidity token has been approved for use by admins. Cbonds can only be created using tokens listed here. uint256 public syncMinimum = 25 * (10 ** 18);//Cbonds cannot be created unless at least this amount of Sync is being included in them. bool public luckyEnabled = true;//Whether it is possible to create Lucky Cbonds //external contracts Oracle public priceChecker;//Used to determine the ratio in price between Sync and a given liquidity token. The value returned should not significantly affect user incentives and does not need to be guaranteed not to be exploitable by the user. Contract can be replaced by admin. Sync syncToken;//The Sync token contract. Sync is contained in every Cbond and is minted to provide interest on Cbonds. constructor(Oracle o,Sync s) public Ownable() ERC721("CBOND","CBOND"){ priceChecker=o; syncToken=s; syncSupplyByDay[0]=syncToken.totalSupply(); interestRateByDay[0]=BASE_INTEREST_RATE_START; _setBaseURI("api.syncbond.com"); for(uint256 i=0;i<TERM_DURATIONS.length;i++){ INDEX_BY_DURATION[TERM_DURATIONS[i]]=i; } } /* Admin functions */ /* Admin function to set the base URI for metadata access. */ function setBaseURI(string calldata baseURI_) external onlyOwner{ _setBaseURI(baseURI_); } /* Admin function to set liquidity tokens which may be used to create Cbonds. */ function setLiquidityTokenAccepted(address token,bool accepted) external onlyOwner{ tokenAccepted[token]=accepted; } /* Admin function to set liquidity tokens which may be used to create Cbonds. */ function setLiquidityTokenAcceptedMulti(address[] calldata tokens,bool accepted) external onlyOwner{ for(uint256 i=0;i<tokens.length;i++){ tokenAccepted[tokens[i]]=accepted; } } /* Admin function to reduce the minimum amount of Sync that can be used to create a Cbond. */ function setSyncMinimum(uint256 newMinimum) public onlyOwner{ require(newMinimum<syncMinimum,"increasing minimum sync required is not permitted"); syncMinimum=newMinimum; } /* Admin function to change the price oracle. */ function setPriceOracle(Oracle o) external onlyOwner{ priceChecker=o; } /* Admin function to toggle on/off the lucky bonus. */ function toggleLuckyBonus(bool enabled) external onlyOwner{ luckyEnabled=enabled; } /* Admin function for updating the daily Sync total supply and token supply for various tokens, for use in case of low activity. */ function recordSyncAndTokens(address[] calldata tokens) external onlyOwner{ recordSyncSupply(); for(uint256 i=0;i<tokens.length;i++){ recordTokenSupply(tokens[i]); } } /* Retrieves available dividends for the given token. Dividends accrue every 3 months. */ function cashOutDivs(uint256 tokenId) external{ require(msg.sender==ownerOf(tokenId),"only token owner can call this"); require(gradualDivsById[tokenId],"must be in quarterly dividends mode"); //record current Sync supply and liquidity token supply for the day if needed recordSyncSupply(); recordTokenSupply(lAddrById[tokenId]); //reward user with appropriate amount. If none is due it will provide an amount of 0 tokens. uint256 divs=dividendsOf(tokenId); syncToken._mint(msg.sender,divs); //register the timestamp of this transaction so future div payouts can be accurately calculated lastDivsCashoutById[tokenId]=block.timestamp; //update read variables totalDivsCashoutById[tokenId]=totalDivsCashoutById[tokenId].add(divs); emit DivsPaid(lAddrById[tokenId],divs,tokenId); } /* Returns liquidity tokens, mints Sync to pay back initial amount plus rewards. */ function matureCBOND(uint256 tokenId) public{ require(msg.sender==ownerOf(tokenId),"only token owner can call this"); require(block.timestamp>termLengthById[tokenId].add(timestampById[tokenId]),"cbond term not yet completed"); //record current Sync supply and liquidity token supply for the day if needed recordSyncSupply(); recordTokenSupply(lAddrById[tokenId]); //amount of sync provided to user is initially deposited amount plus interest uint256 syncRetrieved=syncRewardedOnMaturity[tokenId]; //provide user with their Sync tokens and their initially deposited liquidity tokens uint256 beforeMint=syncToken.balanceOf(msg.sender); syncToken._mint(msg.sender,syncRetrieved); require(IERC20(lAddrById[tokenId]).transfer(msg.sender,lTokenAmountById[tokenId]),"transfer must succeed"); //update read only counter totalCBONDSCashedout=totalCBONDSCashedout.add(1); emit Matured(lAddrById[tokenId],syncRetrieved,lTokenAmountById[tokenId],tokenId); //burn the nft _burn(tokenId); } /* Public function for creating a new Cbond. */ function createCBOND(address liquidityToken,uint256 amount,uint256 syncMaximum,uint256 secondsInTerm,bool gradualDivs) external returns(uint256){ return _createCBOND(liquidityToken,amount,syncMaximum,secondsInTerm,gradualDivs,msg.sender); } /* Function for creating a new Cbond. User specifies a liquidity token and an amount, this is transferred from their account to this contract, along with a corresponding amount of Sync (transaction reverts if this is greater than the user provided maximum at the time of execution). A permitted term length is also provided, and whether the Cbond should provide gradual divs (Quarterly variety Cbond). */ function _createCBOND(address liquidityToken,uint256 amount,uint256 syncMaximum,uint256 secondsInTerm,bool gradualDivs,address sender) private returns(uint256){ require(tokenAccepted[liquidityToken],"liquidity token must be on the list of approved tokens"); //record current Sync supply and liquidity token supply for the day if needed recordSyncSupply(); recordTokenSupply(liquidityToken); //determine amount of Sync required, given the amount of liquidity tokens specified, and transfer that amount from the user uint256 liquidityValue=priceChecker.liquidityValues(liquidityToken); uint256 syncValue=priceChecker.syncValue(); //Since syncRequired is the exact amount of Sync that will be transferred from the user, integer division truncations propagating to other values derived from this one is the correct behavior. uint256 syncRequired=liquidityValue.mul(amount).div(syncValue); require(syncRequired>=syncMinimum,"input tokens too few, sync transferred must be above the minimum"); require(syncRequired<=syncMaximum,"price changed too much since transaction submitted"); require(syncRequired<=MAX_SYNC_GLOBAL,"CBOND amount too large"); syncToken.transferFrom(sender,address(this),syncRequired); require(IERC20(liquidityToken).transferFrom(sender,address(this),amount),"transfer must succeed"); //burn sync tokens provided syncToken.burn(syncRequired); //get the token id of the new NFT uint256 tokenId=_getNextTokenId(); //set all nft variables lAddrById[tokenId]=liquidityToken; syncPriceById[tokenId]=syncValue; syncAmountById[tokenId]=syncRequired; lTokenPriceById[tokenId]=liquidityValue; lTokenAmountById[tokenId]=amount; timestampById[tokenId]=block.timestamp; lastDivsCashoutById[tokenId]=block.timestamp; gradualDivsById[tokenId]=gradualDivs; termLengthById[tokenId]=secondsInTerm; //set the interest rate and final maturity withdraw amount setInterestRate(tokenId,syncRequired,liquidityToken,secondsInTerm,gradualDivs); //update global counters cbondsMaturingByDay[getDay(block.timestamp.add(secondsInTerm))]=cbondsMaturingByDay[getDay(block.timestamp.add(secondsInTerm))].add(1); cbondsHeldByUser[sender][cbondsHeldByUserCursor[sender]]=tokenId; cbondsHeldByUserCursor[sender]=cbondsHeldByUserCursor[sender].add(1); totalCBONDS=totalCBONDS.add(1); totalSYNCLocked=totalSYNCLocked.add(syncRequired); totalLiquidityLockedByPair[liquidityToken]=totalLiquidityLockedByPair[liquidityToken].add(amount); //create NFT _safeMint(sender,tokenId); _incrementTokenId(); //submit event emit Created(liquidityToken,syncRequired,amount,syncValue,liquidityValue,tokenId); return tokenId; } /* Creates a metadata string from a token id. Should not be used onchain. */ function putTogetherMetadataString(uint256 tokenId) public view returns(string memory){ //TODO: add the rest of the variables, separate with appropriate url variable separators for ease of use string memory isDivs=gradualDivsById[tokenId]?"true":"false"; return string(abi.encodePacked("/?tokenId=",tokenId.toString(),"&lAddr=",lAddrById[tokenId].toString(),"&syncPrice=", syncPriceById[tokenId].toString(),"&syncAmount=",syncAmountById[tokenId].toString(),"&mPayout=",syncRewardedOnMaturity[tokenId].toString(),"&lPrice=",lTokenPriceById[tokenId].toString(),"&lAmount=",lTokenAmountById[tokenId].toString(),"&startTime=",timestampById[tokenId].toString(),"&isDivs=",isDivs,"&termLength=",termLengthById[tokenId].toString(),"&divsNow=",dividendsOf(tokenId).toString())); } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); //this line altered from //string memory _tokenURI = _tokenURIs[tokenId]; //use of gas to manipulate strings can be avoided by putting them together at time of retrieval rather than in the token creation transaction. string memory _tokenURI = putTogetherMetadataString(tokenId); // If there is no base URI, return the token URI. if (bytes(baseURI()).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(baseURI(), _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(baseURI(), tokenId.toString())); } /* Increments a counter used to produce the identifier for the next token to be created. */ function _incrementTokenId() private { _currentTokenId=_currentTokenId.add(1); } /* view functions */ /* Returns the next unused token identifier. */ function _getNextTokenId() private view returns (uint256) { return _currentTokenId.add(1); } /* Convenience function to get the current block time directly from the contract. */ function getTime() public view returns(uint256){ return block.timestamp; } /* Returns the current dividends owed to the given token, payable to its current owner. */ function dividendsOf(uint256 tokenId) public view returns(uint256){ //determine the number of periods worth of divs the token owner is owed, by subtracting the current period by the period when divs were last withdrawn. require(lastDivsCashoutById[tokenId]>=timestampById[tokenId],"dof1"); uint256 lastCashoutInPeriod=lastDivsCashoutById[tokenId].sub(timestampById[tokenId]).div(QUARTER_LENGTH);//0 - first quarter, 1 - second, etc. This variable also represents the number of quarters previously cashed out require(block.timestamp>=timestampById[tokenId],"dof2"); uint256 currentCashoutInPeriod=block.timestamp.sub(timestampById[tokenId]).div(QUARTER_LENGTH); require(currentCashoutInPeriod>=lastCashoutInPeriod,"dof3"); uint256 periodsToCashout=currentCashoutInPeriod.sub(lastCashoutInPeriod); //only accrue divs before the maturation date. The final div payment will be paid as part of the matureCBOND transaction, so set the maximum number of periods to cash out be one less than the ultimate total. if(currentCashoutInPeriod>=termLengthById[tokenId].div(90 days)){ //possible for lastCashout period to be greater due to being able to cash out after CBOND has ended (which records lastCashout as being after that date, despite only paying out for earlier periods). In this case, set periodsToCashout to 0 and ultimately return 0, there are no divs left. if(lastCashoutInPeriod>termLengthById[tokenId].div(90 days).sub(1)){ periodsToCashout=0; } else{ periodsToCashout=termLengthById[tokenId].div(90 days).sub(1).sub(lastCashoutInPeriod); } } //multiply the number of periods to pay out with the amount of divs owed for one period. Note: if this is a Quarterly Cbond, syncInterestById will have been recorded as the interest per quarter, rather than the total interest for the Cbond, as with a normal Cbond. uint quarterlyDividend=syncInterestById[tokenId]; return periodsToCashout.mul(syncAmountById[tokenId]).mul(quarterlyDividend).div(PERCENTAGE_PRECISION); } /* Returns the amount of Sync needed to create a Cbond with the given amount of the given liquidity token. Consults the price oracle for the appropriate ratio. */ function getSyncRequiredForCreation(IERC20 liquidityToken,uint256 amount) external view returns(uint256){ return priceChecker.liquidityValues(address(liquidityToken)).mul(amount).div(priceChecker.syncValue()); } /* Set the sync rewarded on maturity and interest rate for the given CBOND */ function setInterestRate(uint256 tokenId,uint256 syncRequired,address liquidityToken,uint256 secondsInTerm,bool gradualDivs) private{ (uint256 lastSupply,uint256 currentSupply,uint256 lastTSupply,uint256 currentTSupply,uint256 lastInterestRate)=getSuppliesNow(liquidityToken); (uint256 interestRate,uint256 totalReturn)=getCbondTotalReturn(tokenId,syncRequired,liquidityToken,secondsInTerm,gradualDivs); syncRewardedOnMaturity[tokenId]=totalReturn; syncInterestById[tokenId]=interestRate; if(gradualDivs){ require(secondsInTerm>=TERM_DURATIONS[2],"dividend bearing CBONDs must be at least 1 year duration"); totalQuarterlyCBONDS=totalQuarterlyCBONDS.add(1); } } /* Following two functions work immediately after all the Cbond variables except the interest rate have been set, will be inaccurate other times. To be used as part of Cbond creation. */ /* Gets the amount of Sync for the given Cbond to return on maturity. */ function getCbondTotalReturn(uint256 tokenId,uint256 syncAmount,address liqAddr,uint256 duration,bool isDivs) public view returns(uint256 interestRate,uint256 totalReturn){ // This is an integer math translation of P*(1+I) where P is principle I is interest rate. The new, equivalent formula is P*(c+I*c)/c where c is a constant of amount PERCENTAGE_PRECISION. interestRate=getCbondInterestRateNow(liqAddr, duration,getLuckyExtra(tokenId),isDivs); totalReturn = syncAmount.mul(PERCENTAGE_PRECISION.add(interestRate)).div(PERCENTAGE_PRECISION); } /* Gets the interest rate for a Cbond given its relevant properties. */ function getCbondInterestRateNow( address liqAddr, uint256 duration, uint256 luckyExtra, bool quarterly) public view returns(uint256){ return getCbondInterestRate( duration, liqTokenTotalsByDay[liqAddr][lastDayTokenSupplyUpdated[liqAddr]], liqTokenTotalsByDay[liqAddr][getDay(block.timestamp)], syncSupplyByDay[lastDaySyncSupplyUpdated], syncSupplyByDay[getDay(block.timestamp)], interestRateByDay[lastDaySyncSupplyUpdated], luckyExtra, quarterly); } /* This returns the Cbond interest rate. Divide by PERCENTAGE_PRECISION to get the real rate. */ function getCbondInterestRate( uint256 duration, uint256 liqTotalLast, uint256 liqTotalCurrent, uint256 syncTotalLast, uint256 syncTotalCurrent, uint256 lastBaseInterestRate, uint256 luckyExtra, bool quarterly) public view returns(uint256){ uint256 liquidityPairIncentiveRate=getLiquidityPairIncentiveRate(liqTotalCurrent,liqTotalLast); uint256 baseInterestRate=getBaseInterestRate(lastBaseInterestRate,syncTotalCurrent,syncTotalLast); if(!quarterly){ return getDurationRate(duration,baseInterestRate.add(liquidityPairIncentiveRate).add(luckyExtra)); } else{ uint numYears=duration.div(YEAR_LENGTH); require(numYears>0,"invalid duration");//Quarterly Cbonds must have a duration 1 year or longer. uint numQuarters=duration.div(QUARTER_LENGTH); uint termModifier=RISK_FACTOR.mul(numYears.mul(4).sub(1)); //Interest rate is the sum of base interest rate, liquidity incentive rate, and risk/term based modifier. Because this is the Quarterly Cbond rate, we also divide by the number of quarters in the Cbond, to set the recorded rate to the amount withdrawable per quarter. return baseInterestRate.add(liquidityPairIncentiveRate).add(luckyExtra).add(termModifier); } } /* This returns the Lucky Extra bonus of the given Cbond. This is based on whether the id of the Cbond ends in two or three 7's, and whether admins have disabled this feature. */ function getLuckyExtra(uint256 tokenId) public view returns(uint256){ if(luckyEnabled){ if(tokenId.mod(100)==77){ return LUCKY_EXTRAS[0]; } if(tokenId.mod(1000)==777){ return LUCKY_EXTRAS[1]; } } return 0; } /* New implementation of duration modifier. Approximation of intended formula. */ function getDurationRate(uint duration, uint baseInterestRate) public view returns(uint){ require(duration==TERM_DURATIONS[0] || duration==TERM_DURATIONS[1] || duration==TERM_DURATIONS[2] || duration==TERM_DURATIONS[3] || duration==TERM_DURATIONS[4],"Invalid CBOND term length provided"); if(duration==TERM_DURATIONS[0]){ return baseInterestRate; } if(duration==TERM_DURATIONS[1]){ uint preExponential = PERCENTAGE_PRECISION.add(baseInterestRate).add(RISK_FACTOR); uint exponential = preExponential.mul(preExponential).div(PERCENTAGE_PRECISION); return exponential.sub(PERCENTAGE_PRECISION); } if(duration==TERM_DURATIONS[2]){//1 year uint preExponential = PERCENTAGE_PRECISION.add(baseInterestRate).add(RISK_FACTOR.mul(3)); uint exponential = preExponential.mul(preExponential).div(PERCENTAGE_PRECISION); for (uint8 i=0;i<2;i++) { exponential = exponential.mul(preExponential).div(PERCENTAGE_PRECISION); } return exponential.sub(PERCENTAGE_PRECISION); } if(duration==TERM_DURATIONS[3]){//2 years uint preExponential = PERCENTAGE_PRECISION.add(baseInterestRate).add(RISK_FACTOR.mul(7)); uint exponential = preExponential.mul(preExponential).div(PERCENTAGE_PRECISION); for (uint8 i=0;i<6;i++) { exponential = exponential.mul(preExponential).div(PERCENTAGE_PRECISION); } return exponential.sub(PERCENTAGE_PRECISION); } if(duration==TERM_DURATIONS[4]){//3 years uint preExponential = PERCENTAGE_PRECISION.add(baseInterestRate).add(RISK_FACTOR.mul(11)); uint exponential = preExponential.mul(preExponential).div(PERCENTAGE_PRECISION); for (uint8 i=0;i<10;i++) { exponential = exponential.mul(preExponential).div(PERCENTAGE_PRECISION); } return exponential.sub(PERCENTAGE_PRECISION); } } /* Returns the liquidity pair incentive rate. To use, multiply by a value then divide result by PERCENTAGE_PRECISION */ function getLiquidityPairIncentiveRate(uint256 totalToday,uint256 totalYesterday) public view returns(uint256){ //instead of reverting due to division by zero, if tokens in this contract go to zero give the max bonus if(totalToday==0){ return INCENTIVE_MAX_PERCENT; } return Math.min(INCENTIVE_MAX_PERCENT,INCENTIVE_MAX_PERCENT.mul(totalYesterday).div(totalToday)); } /* Returns the base interest rate, derived from the previous day interest rate, the current Sync total supply, and the previous day Sync total supply. */ function getBaseInterestRate(uint256 lastdayInterestRate,uint256 syncSupplyToday,uint256 syncSupplyLast) public pure returns(uint256){ return Math.min(MAXIMUM_BASE_INTEREST_RATE,Math.max(MINIMUM_BASE_INTEREST_RATE,lastdayInterestRate.mul(syncSupplyToday).div(syncSupplyLast))); } /* Returns the interest rate a Cbond with the given parameters would end up with if it were created. */ function getCbondInterestRateIfUpdated(address liqAddr,uint256 duration,uint256 luckyExtra,bool quarterly) public view returns(uint256){ (uint256 lastSupply,uint256 currentSupply,uint256 lastTSupply,uint256 currentTSupply,uint256 lastInterestRate)=getSuppliesIfUpdated(liqAddr); return getCbondInterestRate(duration,lastTSupply,currentTSupply,lastSupply,currentSupply,lastInterestRate,luckyExtra,quarterly); } /* Convenience function for frontend use which returns current and previous recorded Sync total supply, and tokens held for the provided token. */ function getSuppliesNow(address tokenAddr) public view returns(uint256 lastSupply,uint256 currentSupply,uint256 lastTSupply,uint256 currentTSupply,uint256 lastInterestRate){ currentSupply=syncSupplyByDay[currentDaySyncSupplyUpdated]; lastSupply=syncSupplyByDay[lastDaySyncSupplyUpdated]; lastInterestRate=interestRateByDay[lastDaySyncSupplyUpdated]; currentTSupply=liqTokenTotalsByDay[tokenAddr][currentDayTokenSupplyUpdated[tokenAddr]]; lastTSupply=liqTokenTotalsByDay[tokenAddr][lastDayTokenSupplyUpdated[tokenAddr]]; } /* Gets what the Sync and liquidity token current and last supplies would become, if updated now. Intended for frontend use. */ function getSuppliesIfUpdated(address tokenAddr) public view returns(uint256 lastSupply,uint256 currentSupply,uint256 lastTSupply,uint256 currentTSupply,uint256 lastInterestRate){ uint256 day=getDay(block.timestamp); if(liqTokenTotalsByDay[tokenAddr][getDay(block.timestamp)]==0){ currentTSupply=IERC20(tokenAddr).balanceOf(address(this)); lastTSupply=liqTokenTotalsByDay[tokenAddr][currentDayTokenSupplyUpdated[tokenAddr]]; } else{ currentTSupply=liqTokenTotalsByDay[tokenAddr][currentDayTokenSupplyUpdated[tokenAddr]]; lastTSupply=liqTokenTotalsByDay[tokenAddr][lastDayTokenSupplyUpdated[tokenAddr]]; } if(syncSupplyByDay[day]==0){ currentSupply=syncToken.totalSupply(); lastSupply=syncSupplyByDay[currentDaySyncSupplyUpdated]; //TODO: interest rate lastInterestRate=interestRateByDay[currentDaySyncSupplyUpdated]; } else{ currentSupply=syncSupplyByDay[currentDaySyncSupplyUpdated]; lastSupply=syncSupplyByDay[lastDaySyncSupplyUpdated]; lastInterestRate=interestRateByDay[lastDaySyncSupplyUpdated]; } } /* Function for recording the Sync total supply and base interest rate by day. Records only at the first time it is called in a given day (see getDay). */ function recordSyncSupply() public{ if(syncSupplyByDay[getDay(block.timestamp)]==0){ uint256 day=getDay(block.timestamp); syncSupplyByDay[day]=syncToken.totalSupply(); lastDaySyncSupplyUpdated=currentDaySyncSupplyUpdated; currentDaySyncSupplyUpdated=day; //interest rate interestRateByDay[day]=getBaseInterestRate(interestRateByDay[lastDaySyncSupplyUpdated],syncSupplyByDay[day],syncSupplyByDay[lastDaySyncSupplyUpdated]); } } /* Records the current amount of the given token held by this contract for the current day. Like recordSyncSupply, only records the first time it is called in a day. */ function recordTokenSupply(address tokenAddr) private{ if(liqTokenTotalsByDay[tokenAddr][getDay(block.timestamp)]==0){ uint256 day=getDay(block.timestamp); liqTokenTotalsByDay[tokenAddr][day]=IERC20(tokenAddr).balanceOf(address(this)); lastDayTokenSupplyUpdated[tokenAddr]=currentDayTokenSupplyUpdated[tokenAddr]; currentDayTokenSupplyUpdated[tokenAddr]=day; } } /* Gets the current day since the contract began. Starts at 1. */ function getDay(uint256 timestamp) public view returns(uint256){ return timestamp.sub(STARTING_TIME).div(24 hours).add(1); } /* Gets the current day since the contract began, at the current block time. */ function getDayNow() public view returns(uint256){ return getDay(block.timestamp); } }
returns usd value of SYNC
function syncValue() external view returns(uint);
7,280,082
// SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity ^0.6.12; import "./Interfaces/LiquidityMathModelInterface.sol"; import "./MToken.sol"; import "./Utils/ErrorReporter.sol"; import "./Utils/ExponentialNoError.sol"; import "./Utils/AssetHelpers.sol"; import "./Moartroller.sol"; import "./SimplePriceOracle.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract LiquidityMathModelV1 is LiquidityMathModelInterface, LiquidityMathModelErrorReporter, ExponentialNoError, Ownable, AssetHelpers { /** * @notice get the maximum asset value that can be still optimized. * @notice if protectionId is supplied, the maxOptimizableValue is increased by the protection lock value' * which is helpful to recalculate how much of this protection can be optimized again */ function getMaxOptimizableValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) external override view returns (uint){ uint returnValue; uint hypotheticalOptimizableValue = getHypotheticalOptimizableValue(arguments); uint totalProtectionLockedValue; (totalProtectionLockedValue, ) = getTotalProtectionLockedValue(arguments); if(hypotheticalOptimizableValue <= totalProtectionLockedValue){ returnValue = 0; } else{ returnValue = sub_(hypotheticalOptimizableValue, totalProtectionLockedValue); } return returnValue; } /** * @notice get the maximum value of an asset that can be optimized by protection for the given user * @dev optimizable = asset value * MPC * @return the hypothetical optimizable value * TODO: replace hardcoded 1e18 values */ function getHypotheticalOptimizableValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) public override view returns(uint) { uint assetValue = div_( mul_( div_( mul_( arguments.asset.balanceOf(arguments.account), arguments.asset.exchangeRateStored() ), 1e18 ), arguments.oracle.getUnderlyingPrice(arguments.asset) ), getAssetDecimalsMantissa(arguments.asset.getUnderlying()) ); uint256 hypotheticalOptimizableValue = div_( mul_( assetValue, arguments.asset.maxProtectionComposition() ), arguments.asset.maxProtectionCompositionMantissa() ); return hypotheticalOptimizableValue; } /** * @dev gets all locked protections values with mark to market value. Used by Moartroller. */ function getTotalProtectionLockedValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet memory arguments) public override view returns(uint, uint) { uint _lockedValue = 0; uint _markToMarket = 0; uint _protectionCount = arguments.cprotection.getUserUnderlyingProtectionTokenIdByCurrencySize(arguments.account, arguments.asset.underlying()); for (uint j = 0; j < _protectionCount; j++) { uint protectionId = arguments.cprotection.getUserUnderlyingProtectionTokenIdByCurrency(arguments.account, arguments.asset.underlying(), j); bool protectionIsAlive = arguments.cprotection.isProtectionAlive(protectionId); if(protectionIsAlive){ _lockedValue = add_(_lockedValue, arguments.cprotection.getUnderlyingProtectionLockedValue(protectionId)); uint assetSpotPrice = arguments.oracle.getUnderlyingPrice(arguments.asset); uint protectionStrikePrice = arguments.cprotection.getUnderlyingStrikePrice(protectionId); if( assetSpotPrice > protectionStrikePrice) { _markToMarket = _markToMarket + div_( mul_( div_( mul_( assetSpotPrice - protectionStrikePrice, arguments.cprotection.getUnderlyingProtectionLockedAmount(protectionId) ), getAssetDecimalsMantissa(arguments.asset.underlying()) ), arguments.collateralFactorMantissa ), 1e18 ); } } } return (_lockedValue , _markToMarket); } } // SPDX-License-Identifier: MIT pragma experimental ABIEncoderV2; pragma solidity ^0.6.12; import "../MToken.sol"; import "../MProtection.sol"; import "../Interfaces/PriceOracle.sol"; interface LiquidityMathModelInterface { struct LiquidityMathArgumentsSet { MToken asset; address account; uint collateralFactorMantissa; MProtection cprotection; PriceOracle oracle; } function getMaxOptimizableValue(LiquidityMathArgumentsSet memory _arguments) external view returns (uint); function getHypotheticalOptimizableValue(LiquidityMathArgumentsSet memory _arguments) external view returns(uint); function getTotalProtectionLockedValue(LiquidityMathArgumentsSet memory _arguments) external view returns(uint, uint); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./Utils/ErrorReporter.sol"; import "./Utils/Exponential.sol"; import "./Interfaces/EIP20Interface.sol"; import "./MTokenStorage.sol"; import "./Interfaces/MTokenInterface.sol"; import "./Interfaces/MProxyInterface.sol"; import "./Moartroller.sol"; import "./AbstractInterestRateModel.sol"; /** * @title MOAR's MToken Contract * @notice Abstract base for MTokens * @author MOAR */ abstract contract MToken is MTokenInterface, Exponential, TokenErrorReporter, MTokenStorage { /** * @notice Indicator that this is a MToken contract (for inspection) */ bool public constant isMToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address MTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when moartroller is changed */ event NewMoartroller(Moartroller oldMoartroller, Moartroller newMoartroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModelInterface oldInterestRateModel, InterestRateModelInterface newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); /** * @notice Max protection composition value updated event */ event MpcUpdated(uint newValue); /** * @notice Initialize the money market * @param moartroller_ The address of the Moartroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function init(Moartroller moartroller_, AbstractInterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { require(msg.sender == admin, "not_admin"); require(accrualBlockNumber == 0 && borrowIndex == 0, "already_init"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "too_low"); // Set the moartroller uint err = _setMoartroller(moartroller_); require(err == uint(Error.NO_ERROR), "setting moartroller failed"); // Initialize block number and borrow index (block number mocks depend on moartroller being set) accrualBlockNumber = getBlockNumber(); borrowIndex = mantissaOne; // Set the interest rate model (depends on block number / borrow index) err = _setInterestRateModelFresh(interestRateModel_); require(err == uint(Error.NO_ERROR), "setting IRM failed"); name = name_; symbol = symbol_; decimals = decimals_; // The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund) _notEntered = true; maxProtectionComposition = 5000; maxProtectionCompositionMantissa = 1e4; reserveFactorMaxMantissa = 1e18; borrowRateMaxMantissa = 0.0005e16; } /** * @notice Transfer `tokens` tokens from `src` to `dst` by `spender` * @dev Called by both `transfer` and `transferFrom` internally * @param spender The address of the account performing the transfer * @param src The address of the source account * @param dst The address of the destination account * @param tokens The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) { /* Fail if transfer not allowed */ uint allowed = moartroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.TRANSFER_MOARTROLLER_REJECTION, allowed); } /* Do not allow self-transfers */ if (src == dst) { return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED); } /* Get the allowance, infinite for the account owner */ uint startingAllowance = 0; if (spender == src) { startingAllowance = uint(-1); } else { startingAllowance = transferAllowances[src][spender]; } /* Do the calculations, checking for {under,over}flow */ MathError mathErr; uint allowanceNew; uint srmTokensNew; uint dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srmTokensNew) = subUInt(accountTokens[src], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH); } (mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) accountTokens[src] = srmTokensNew; accountTokens[dst] = dstTokensNew; /* Eat some of the allowance (if necessary) */ if (startingAllowance != uint(-1)) { transferAllowances[src][spender] = allowanceNew; } /* We emit a Transfer event */ emit Transfer(src, dst, tokens); // unused function // moartroller.transferVerify(address(this), src, dst, tokens); return uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external virtual override nonReentrant returns (bool) { return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external virtual override nonReentrant returns (bool) { return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external virtual override returns (bool) { address src = msg.sender; transferAllowances[src][spender] = amount; emit Approval(src, spender, amount); return true; } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external virtual override view returns (uint256) { return transferAllowances[owner][spender]; } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external virtual override view returns (uint256) { return accountTokens[owner]; } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external virtual override returns (uint) { Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()}); (MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]); require(mErr == MathError.NO_ERROR, "balance_calculation_failed"); return balance; } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by moartroller to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external virtual override view returns (uint, uint, uint, uint) { uint mTokenBalance = accountTokens[account]; uint borrowBalance; uint exchangeRateMantissa; MathError mErr; (mErr, borrowBalance) = borrowBalanceStoredInternal(account); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } (mErr, exchangeRateMantissa) = exchangeRateStoredInternal(); if (mErr != MathError.NO_ERROR) { return (uint(Error.MATH_ERROR), 0, 0, 0); } return (uint(Error.NO_ERROR), mTokenBalance, borrowBalance, exchangeRateMantissa); } /** * @dev Function to simply retrieve block number * This exists mainly for inheriting test contracts to stub this result. */ function getBlockNumber() internal view returns (uint) { return block.number; } /** * @notice Returns the current per-block borrow interest rate for this mToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external virtual override view returns (uint) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this mToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external virtual override view returns (uint) { return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external virtual override nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return totalBorrows; } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external virtual override nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return borrowBalanceStored(account); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public virtual view returns (uint) { (MathError err, uint result) = borrowBalanceStoredInternal(account); require(err == MathError.NO_ERROR, "borrowBalanceStored failed"); return result; } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return (error code, the calculated balance or 0 if error code is non-zero) */ function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) { /* Note: we do not assert that the market is up to date */ MathError mathErr; uint principalTimesIndex; uint result; /* Get borrowBalance and borrowIndex */ BorrowSnapshot storage borrowSnapshot = accountBorrows[account]; /* If borrowBalance = 0 then borrowIndex is likely also 0. * Rather than failing the calculation with a division by 0, we immediately return 0 in this case. */ if (borrowSnapshot.principal == 0) { return (MathError.NO_ERROR, 0); } /* Calculate new borrow balance using the interest index: * recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex */ (mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, result); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public virtual nonReentrant returns (uint) { require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed"); return exchangeRateStored(); } /** * @notice Calculates the exchange rate from the underlying to the MToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public virtual view returns (uint) { (MathError err, uint result) = exchangeRateStoredInternal(); require(err == MathError.NO_ERROR, "exchangeRateStored failed"); return result; } /** * @notice Calculates the exchange rate from the underlying to the MToken * @dev This function does not accrue interest before calculating the exchange rate * @return (error code, calculated exchange rate scaled by 1e18) */ function exchangeRateStoredInternal() internal view returns (MathError, uint) { uint _totalSupply = totalSupply; if (_totalSupply == 0) { /* * If there are no tokens minted: * exchangeRate = initialExchangeRate */ return (MathError.NO_ERROR, initialExchangeRateMantissa); } else { /* * Otherwise: * exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply */ uint totalCash = getCashPrior(); uint cashPlusBorrowsMinusReserves; Exp memory exchangeRate; MathError mathErr; (mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } (mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply); if (mathErr != MathError.NO_ERROR) { return (mathErr, 0); } return (MathError.NO_ERROR, exchangeRate.mantissa); } } /** * @notice Get cash balance of this mToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external virtual override view returns (uint) { return getCashPrior(); } function getRealBorrowIndex() public view returns (uint) { uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high"); (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calc block delta"); Exp memory simpleInterestFactor; uint borrowIndexNew; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); require(mathErr == MathError.NO_ERROR, "could not calc simpleInterestFactor"); (mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); require(mathErr == MathError.NO_ERROR, "could not calc borrowIndex"); return borrowIndexNew; } /** * @notice Applies accrued interest to total borrows and reserves * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public virtual returns (uint) { /* Remember the initial block number */ uint currentBlockNumber = getBlockNumber(); uint accrualBlockNumberPrior = accrualBlockNumber; /* Short-circuit accumulating 0 interest */ if (accrualBlockNumberPrior == currentBlockNumber) { return uint(Error.NO_ERROR); } /* Read the previous values out of storage */ uint cashPrior = getCashPrior(); uint borrowsPrior = totalBorrows; uint reservesPrior = totalReserves; uint borrowIndexPrior = borrowIndex; /* Calculate the current borrow interest rate */ uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior); require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high"); /* Calculate the number of blocks elapsed since the last accrual */ (MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior); require(mathErr == MathError.NO_ERROR, "could not calc block delta"); /* * Calculate the interest accumulated into borrows and reserves and the new index: * simpleInterestFactor = borrowRate * blockDelta * interestAccumulated = simpleInterestFactor * totalBorrows * totalBorrowsNew = interestAccumulated + totalBorrows * totalReservesNew = interestAccumulated * reserveFactor + totalReserves * borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex */ Exp memory simpleInterestFactor; AccrueInterestTempStorage memory temp; (mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.totalBorrowsNew) = addUInt(temp.interestAccumulated, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.reservesAdded) = mulScalarTruncate(Exp({mantissa: reserveFactorMantissa}), temp.interestAccumulated); if(mathErr != MathError.NO_ERROR){ return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.splitedReserves_2) = mulScalarTruncate(Exp({mantissa: reserveSplitFactorMantissa}), temp.reservesAdded); if(mathErr != MathError.NO_ERROR){ return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.splitedReserves_1) = subUInt(temp.reservesAdded, temp.splitedReserves_2); if(mathErr != MathError.NO_ERROR){ return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.totalReservesNew) = addUInt(temp.splitedReserves_1, reservesPrior); if(mathErr != MathError.NO_ERROR){ return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, temp.borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accrualBlockNumber = currentBlockNumber; borrowIndex = temp.borrowIndexNew; totalBorrows = temp.totalBorrowsNew; totalReserves = temp.totalReservesNew; if(temp.splitedReserves_2 > 0){ address mProxy = moartroller.mProxy(); EIP20Interface(underlying).approve(mProxy, temp.splitedReserves_2); MProxyInterface(mProxy).proxySplitReserves(underlying, temp.splitedReserves_2); } /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, temp.interestAccumulated, temp.borrowIndexNew, temp.totalBorrowsNew); return uint(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives mTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0); } // mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to return mintFresh(msg.sender, mintAmount); } struct MintLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint mintTokens; uint totalSupplyNew; uint accountTokensNew; uint actualMintAmount; } /** * @notice User supplies assets into the market and receives mTokens in exchange * @dev Assumes interest has already been accrued up to the current block * @param minter The address of the account which is supplying the assets * @param mintAmount The amount of the underlying asset to supply * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount. */ function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) { /* Fail if mint not allowed */ uint allowed = moartroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.MINT_MOARTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0); } MintLocalVars memory vars; (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call `doTransferIn` for the minter and the mintAmount. * Note: The mToken must handle variations between ERC-20 and ETH underlying. * `doTransferIn` reverts if anything goes wrong, since we can't be sure if * side-effects occurred. The function returns the amount actually transferred, * in case of a fee. On success, the mToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of mTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); require(vars.mathErr == MathError.NO_ERROR, "MINT_E"); /* * We calculate the new total supply of mTokens and minter token balance, checking for overflow: * totalSupplyNew = totalSupply + mintTokens * accountTokensNew = accountTokens[minter] + mintTokens */ (vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_E"); (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_E"); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[minter] = vars.accountTokensNew; /* We emit a Mint event, and a Transfer event */ emit Mint(minter, vars.actualMintAmount, vars.mintTokens); emit Transfer(address(this), minter, vars.mintTokens); /* We call the defense hook */ // unused function // moartroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); } /** * @notice Sender redeems mTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of mTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, redeemTokens, 0); } /** * @notice Sender redeems mTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming mTokens * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED); } // redeemFresh emits redeem-specific logs on errors, so we don't need to return redeemFresh(msg.sender, 0, redeemAmount); } struct RedeemLocalVars { Error err; MathError mathErr; uint exchangeRateMantissa; uint redeemTokens; uint redeemAmount; uint totalSupplyNew; uint accountTokensNew; } /** * @notice User redeems mTokens in exchange for the underlying asset * @dev Assumes interest has already been accrued up to the current block * @param redeemer The address of the account which is redeeming the tokens * @param redeemTokensIn The number of mTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @param redeemAmountIn The number of underlying tokens to receive from redeeming mTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero) * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) { require(redeemTokensIn == 0 || redeemAmountIn == 0, "redeemFresh_missing_zero"); RedeemLocalVars memory vars; /* exchangeRate = invoke Exchange Rate Stored() */ (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)); } /* If redeemTokensIn > 0: */ if (redeemTokensIn > 0) { /* * We calculate the exchange rate and the amount of underlying to be redeemed: * redeemTokens = redeemTokensIn * redeemAmount = redeemTokensIn x exchangeRateCurrent */ vars.redeemTokens = redeemTokensIn; (vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr)); } } else { /* * We get the current exchange rate and calculate the amount to be redeemed: * redeemTokens = redeemAmountIn / exchangeRate * redeemAmount = redeemAmountIn */ (vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa})); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr)); } vars.redeemAmount = redeemAmountIn; } /* Fail if redeem not allowed */ uint allowed = moartroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.REDEEM_MOARTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK); } /* * We calculate the new total supply and redeemer balance, checking for underflow: * totalSupplyNew = totalSupply - redeemTokens * accountTokensNew = accountTokens[redeemer] - redeemTokens */ (vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } /* Fail gracefully if protocol has insufficient cash */ if (getCashPrior() < vars.redeemAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } /* Fail if user tries to redeem more than he has locked with c-op*/ // TODO: update error codes uint newTokensAmount = div_(mul_(vars.accountTokensNew, vars.exchangeRateMantissa), 1e18); if (newTokensAmount < moartroller.getUserLockedAmount(this, redeemer)) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The mToken must handle variations between ERC-20 and ETH underlying. * On success, the mToken has redeemAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(redeemer, vars.redeemAmount); /* We write previously calculated values into storage */ totalSupply = vars.totalSupplyNew; accountTokens[redeemer] = vars.accountTokensNew; /* We emit a Transfer event, and a Redeem event */ emit Transfer(redeemer, address(this), vars.redeemTokens); emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens); /* We call the defense hook */ moartroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens); return uint(Error.NO_ERROR); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(msg.sender, borrowAmount); } function borrowForInternal(address payable borrower, uint borrowAmount) internal nonReentrant returns (uint) { require(moartroller.isPrivilegedAddress(msg.sender), "permission_missing"); uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED); } // borrowFresh emits borrow-specific logs on errors, so we don't need to return borrowFresh(borrower, borrowAmount); } struct BorrowLocalVars { MathError mathErr; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; } /** * @notice Users borrow assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) { /* Fail if borrow not allowed */ uint allowed = moartroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.BORROW_MOARTROLLER_REJECTION, allowed); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK); } /* Fail gracefully if protocol has insufficient underlying cash */ if (getCashPrior() < borrowAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE); } BorrowLocalVars memory vars; /* * We calculate the new borrower and total borrow balances, failing on overflow: * accountBorrowsNew = accountBorrows + borrowAmount * totalBorrowsNew = totalBorrows + borrowAmount */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } (vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the borrower and the borrowAmount. * Note: The mToken must handle variations between ERC-20 and ETH underlying. * On success, the mToken borrowAmount less of cash. * doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. */ doTransferOut(borrower, borrowAmount); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a Borrow event */ emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ //unused function // moartroller.borrowVerify(address(this), borrower, borrowAmount); return uint(Error.NO_ERROR); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, msg.sender, repayAmount); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0); } // repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to return repayBorrowFresh(msg.sender, borrower, repayAmount); } struct RepayBorrowLocalVars { Error err; MathError mathErr; uint repayAmount; uint borrowerIndex; uint accountBorrows; uint accountBorrowsNew; uint totalBorrowsNew; uint actualRepayAmount; } /** * @notice Borrows are repaid by another user (possibly the borrower). * @param payer the account paying off the borrow * @param borrower the account with the debt being payed off * @param repayAmount the amount of undelrying tokens being returned * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) { /* Fail if repayBorrow not allowed */ uint allowed = moartroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.REPAY_BORROW_MOARTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0); } RepayBorrowLocalVars memory vars; /* We remember the original borrowerIndex for verification purposes */ vars.borrowerIndex = accountBorrows[borrower].interestIndex; /* We fetch the amount the borrower owes, with accumulated interest */ (vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower); if (vars.mathErr != MathError.NO_ERROR) { return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0); } /* If repayAmount == -1, repayAmount = accountBorrows */ /* If the borrow is repaid by another user -1 cannot be used to prevent borrow front-running */ if (repayAmount == uint(-1)) { require(tx.origin == borrower, "specify a precise amount"); vars.repayAmount = vars.accountBorrows; } else { vars.repayAmount = repayAmount; } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the payer and the repayAmount * Note: The mToken must handle variations between ERC-20 and ETH underlying. * On success, the mToken holds an additional repayAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount); /* * We calculate the new borrower and total borrow balances, failing on underflow: * accountBorrowsNew = accountBorrows - actualRepayAmount * totalBorrowsNew = totalBorrows - actualRepayAmount */ (vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "BORROW_BALANCE_CALCULATION_FAILED"); (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "TOTAL_BALANCE_CALCULATION_FAILED"); /* We write the previously calculated values into storage */ accountBorrows[borrower].principal = vars.accountBorrowsNew; accountBorrows[borrower].interestIndex = borrowIndex; totalBorrows = vars.totalBorrowsNew; /* We emit a RepayBorrow event */ emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew); /* We call the defense hook */ // unused function // moartroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex); return (uint(Error.NO_ERROR), vars.actualRepayAmount); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this mToken to be liquidated * @param mTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowInternal(address borrower, uint repayAmount, MToken mTokenCollateral) internal nonReentrant returns (uint, uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0); } error = mTokenCollateral.accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0); } // liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to return liquidateBorrowFresh(msg.sender, borrower, repayAmount, mTokenCollateral); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this mToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param mTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount. */ function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, MToken mTokenCollateral) internal returns (uint, uint) { /* Fail if liquidate not allowed */ uint allowed = moartroller.liquidateBorrowAllowed(address(this), address(mTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.LIQUIDATE_MOARTROLLER_REJECTION, allowed), 0); } /* Verify market's block number equals current block number */ if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0); } /* Verify mTokenCollateral market's block number equals current block number */ if (mTokenCollateral.accrualBlockNumber() != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0); } /* Fail if repayAmount = 0 */ if (repayAmount == 0) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0); } /* Fail if repayAmount = -1 */ if (repayAmount == uint(-1)) { return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0); } /* Fail if repayBorrow fails */ (uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount); if (repayBorrowError != uint(Error.NO_ERROR)) { return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We calculate the number of collateral tokens that will be seized */ (uint amountSeizeError, uint seizeTokens) = moartroller.liquidateCalculateSeizeUserTokens(address(this), address(mTokenCollateral), actualRepayAmount, borrower); require(amountSeizeError == uint(Error.NO_ERROR), "CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(mTokenCollateral.balanceOf(borrower) >= seizeTokens, "TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint seizeError; if (address(mTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = mTokenCollateral.seize(liquidator, borrower, seizeTokens); } /* Revert if seize tokens fails (since we cannot be sure of side effects) */ require(seizeError == uint(Error.NO_ERROR), "token seizure failed"); /* We emit a LiquidateBorrow event */ emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(mTokenCollateral), seizeTokens); /* We call the defense hook */ // unused function // moartroller.liquidateBorrowVerify(address(this), address(mTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens); return (uint(Error.NO_ERROR), actualRepayAmount); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another mToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed mToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of mTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external virtual override nonReentrant returns (uint) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another MToken. * Its absolutely critical to use msg.sender as the seizer mToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed mToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of mTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { /* Fail if seize not allowed */ uint allowed = moartroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.MOARTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_MOARTROLLER_REJECTION, allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } MathError mathErr; uint borrowerTokensNew; uint liquidatorTokensNew; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr)); } (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ accountTokens[borrower] = borrowerTokensNew; accountTokens[liquidator] = liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, seizeTokens); /* We call the defense hook */ // unused function // moartroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens); return uint(Error.NO_ERROR); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external virtual override returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external virtual override returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Sets a new moartroller for the market * @dev Admin function to set a new moartroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setMoartroller(Moartroller newMoartroller) public virtual returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MOARTROLLER_OWNER_CHECK); } Moartroller oldMoartroller = moartroller; // Ensure invoke moartroller.isMoartroller() returns true require(newMoartroller.isMoartroller(), "not_moartroller"); // Set market's moartroller to newMoartroller moartroller = newMoartroller; // Emit NewMoartroller(oldMoartroller, newMoartroller) emit NewMoartroller(oldMoartroller, newMoartroller); return uint(Error.NO_ERROR); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external virtual override nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed. return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED); } // _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to. return _setReserveFactorFresh(newReserveFactorMantissa); } function _setReserveSplitFactor(uint newReserveSplitFactorMantissa) external nonReentrant returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } reserveSplitFactorMantissa = newReserveSplitFactorMantissa; return uint(Error.NO_ERROR); } /** * @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual) * @dev Admin function to set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK); } // Verify market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK); } // Check newReserveFactor ≤ maxReserveFactor if (newReserveFactorMantissa > reserveFactorMaxMantissa) { return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK); } uint oldReserveFactorMantissa = reserveFactorMantissa; reserveFactorMantissa = newReserveFactorMantissa; emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Accrues interest and reduces reserves by transferring from msg.sender * @param addAmount Amount of addition to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED); } // _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to. (error, ) = _addReservesFresh(addAmount); return error; } /** * @notice Add reserves by transferring from caller * @dev Requires fresh interest accrual * @param addAmount Amount of addition to reserves * @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees */ function _addReservesFresh(uint addAmount) internal returns (uint, uint) { // totalReserves + actualAddAmount uint totalReservesNew; uint actualAddAmount; // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We call doTransferIn for the caller and the addAmount * Note: The mToken must handle variations between ERC-20 and ETH underlying. * On success, the mToken holds an additional addAmount of cash. * doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred. * it returns the amount actually transferred, in case of a fee. */ actualAddAmount = doTransferIn(msg.sender, addAmount); totalReservesNew = totalReserves + actualAddAmount; /* Revert on overflow */ require(totalReservesNew >= totalReserves, "overflow"); // Store reserves[n+1] = reserves[n] + actualAddAmount totalReserves = totalReservesNew; /* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */ emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew); /* Return (NO_ERROR, actualAddAmount) */ return (uint(Error.NO_ERROR), actualAddAmount); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external virtual override nonReentrant returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed. return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED); } // _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to. return _reduceReservesFresh(reduceAmount); } /** * @notice Reduces reserves by transferring to admin * @dev Requires fresh interest accrual * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReservesFresh(uint reduceAmount) internal returns (uint) { // totalReserves - reduceAmount uint totalReservesNew; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK); } // Fail gracefully if protocol has insufficient underlying cash if (getCashPrior() < reduceAmount) { return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE); } // Check reduceAmount ≤ reserves[n] (totalReserves) if (reduceAmount > totalReserves) { return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) totalReservesNew = totalReserves - reduceAmount; // We checked reduceAmount <= totalReserves above, so this should never revert. require(totalReservesNew <= totalReserves, "underflow"); // Store reserves[n+1] = reserves[n] - reduceAmount totalReserves = totalReservesNew; // doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred. doTransferOut(admin, reduceAmount); emit ReservesReduced(admin, reduceAmount, totalReservesNew); return uint(Error.NO_ERROR); } /** * @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(AbstractInterestRateModel newInterestRateModel) public virtual returns (uint) { uint error = accrueInterest(); if (error != uint(Error.NO_ERROR)) { // accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED); } // _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to. return _setInterestRateModelFresh(newInterestRateModel); } /** * @notice updates the interest rate model (*requires fresh interest accrual) * @dev Admin function to update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModelFresh(AbstractInterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModelInterface oldInterestRateModel; // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } // We fail gracefully unless market's block number equals current block number if (accrualBlockNumber != getBlockNumber()) { return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK); } // Track the market's current interest rate model oldInterestRateModel = interestRateModel; // Ensure invoke newInterestRateModel.isInterestRateModel() returns true require(newInterestRateModel.isInterestRateModel(), "not_interest_model"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint(Error.NO_ERROR); } /** * @notice Sets new value for max protection composition parameter * @param newMPC New value of MPC * @return uint 0=success, otherwise a failure */ function _setMaxProtectionComposition(uint256 newMPC) external returns(uint){ if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } maxProtectionComposition = newMPC; emit MpcUpdated(newMPC); return uint(Error.NO_ERROR); } /** * @notice Returns address of underlying token * @return address of underlying token */ function getUnderlying() external override view returns(address){ return underlying; } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying owned by this contract */ function getCashPrior() internal virtual view returns (uint); /** * @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee. * This may revert due to insufficient balance or insufficient allowance. */ function doTransferIn(address from, uint amount) internal virtual returns (uint); /** * @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting. * If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract. * If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions. */ function doTransferOut(address payable to, uint amount) internal virtual; /*** Reentrancy Guard ***/ /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; contract MoartrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, MOARTROLLER_MISMATCH, INSUFFICIENT_SHORTFALL, INSUFFICIENT_LIQUIDITY, INVALID_CLOSE_FACTOR, INVALID_COLLATERAL_FACTOR, INVALID_LIQUIDATION_INCENTIVE, MARKET_NOT_ENTERED, // no longer possible MARKET_NOT_LISTED, MARKET_ALREADY_LISTED, MATH_ERROR, NONZERO_BORROW_BALANCE, PRICE_ERROR, REJECTION, SNAPSHOT_ERROR, TOO_MANY_ASSETS, TOO_MUCH_REPAY } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, EXIT_MARKET_BALANCE_OWED, EXIT_MARKET_REJECTION, SET_CLOSE_FACTOR_OWNER_CHECK, SET_CLOSE_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_NO_EXISTS, SET_COLLATERAL_FACTOR_VALIDATION, SET_COLLATERAL_FACTOR_WITHOUT_PRICE, SET_IMPLEMENTATION_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, SET_LIQUIDATION_INCENTIVE_VALIDATION, SET_MAX_ASSETS_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK, SET_PRICE_ORACLE_OWNER_CHECK, SUPPORT_MARKET_EXISTS, SUPPORT_MARKET_OWNER_CHECK, SUPPORT_PROTECTION_OWNER_CHECK, SET_PAUSE_GUARDIAN_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract TokenErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, BAD_INPUT, MOARTROLLER_REJECTION, MOARTROLLER_CALCULATION_ERROR, INTEREST_RATE_MODEL_ERROR, INVALID_ACCOUNT_PAIR, INVALID_CLOSE_AMOUNT_REQUESTED, INVALID_COLLATERAL_FACTOR, MATH_ERROR, MARKET_NOT_FRESH, MARKET_NOT_LISTED, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_IN_FAILED, TOKEN_TRANSFER_OUT_FAILED } /* * Note: FailureInfo (but not Error) is kept in alphabetical order * This is because FailureInfo grows significantly faster, and * the order of Error has some meaning, while the order of FailureInfo * is entirely arbitrary. */ enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_ACCRUE_INTEREST_FAILED, BORROW_CASH_NOT_AVAILABLE, BORROW_FRESHNESS_CHECK, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, BORROW_MARKET_NOT_LISTED, BORROW_MOARTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_MOARTROLLER_REJECTION, LIQUIDATE_MOARTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, LIQUIDATE_FRESHNESS_CHECK, LIQUIDATE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_REPAY_BORROW_FRESH_FAILED, LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, LIQUIDATE_SEIZE_MOARTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_MOARTROLLER_REJECTION, MINT_EXCHANGE_CALCULATION_FAILED, MINT_EXCHANGE_RATE_READ_FAILED, MINT_FRESHNESS_CHECK, MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, MINT_TRANSFER_IN_FAILED, MINT_TRANSFER_IN_NOT_POSSIBLE, REDEEM_ACCRUE_INTEREST_FAILED, REDEEM_MOARTROLLER_REJECTION, REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, REDEEM_EXCHANGE_RATE_READ_FAILED, REDEEM_FRESHNESS_CHECK, REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, REDEEM_TRANSFER_OUT_NOT_POSSIBLE, REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, REDUCE_RESERVES_ADMIN_CHECK, REDUCE_RESERVES_CASH_NOT_AVAILABLE, REDUCE_RESERVES_FRESH_CHECK, REDUCE_RESERVES_VALIDATION, REPAY_BEHALF_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCRUE_INTEREST_FAILED, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_MOARTROLLER_REJECTION, REPAY_BORROW_FRESHNESS_CHECK, REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_COLLATERAL_FACTOR_OWNER_CHECK, SET_COLLATERAL_FACTOR_VALIDATION, SET_MOARTROLLER_OWNER_CHECK, SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, SET_INTEREST_RATE_MODEL_FRESH_CHECK, SET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_MAX_ASSETS_OWNER_CHECK, SET_ORACLE_MARKET_NOT_LISTED, SET_PENDING_ADMIN_OWNER_CHECK, SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, SET_RESERVE_FACTOR_ADMIN_CHECK, SET_RESERVE_FACTOR_FRESH_CHECK, SET_RESERVE_FACTOR_BOUNDS_CHECK, TRANSFER_MOARTROLLER_REJECTION, TRANSFER_NOT_ALLOWED, TRANSFER_NOT_ENOUGH, TRANSFER_TOO_MUCH, ADD_RESERVES_ACCRUE_INTEREST_FAILED, ADD_RESERVES_FRESH_CHECK, ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract LiquidityMathModelErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, PRICE_ERROR, SNAPSHOT_ERROR } enum FailureInfo { ORACLE_PRICE_CHECK_FAILED } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /** * @title Exponential module for storing fixed-precision decimals * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract ExponentialNoError { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return truncate(product); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return add_(truncate(product), addend); } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "../Interfaces/EIP20Interface.sol"; contract AssetHelpers { /** * @dev return asset decimals mantissa. Returns 1e18 if ETH */ function getAssetDecimalsMantissa(address assetAddress) public view returns (uint256){ uint assetDecimals = 1e18; if (assetAddress != address(0)) { EIP20Interface token = EIP20Interface(assetAddress); assetDecimals = 10 ** uint256(token.decimals()); } return assetDecimals; } } // SPDX-License-Identifier: BSD-3-Clause // Thanks to Compound for their foundational work in DeFi and open-sourcing their code from which we build upon. pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; // import "hardhat/console.sol"; import "./MToken.sol"; import "./Utils/ErrorReporter.sol"; import "./Utils/ExponentialNoError.sol"; import "./Interfaces/PriceOracle.sol"; import "./Interfaces/MoartrollerInterface.sol"; import "./Interfaces/Versionable.sol"; import "./Interfaces/MProxyInterface.sol"; import "./MoartrollerStorage.sol"; import "./Governance/UnionGovernanceToken.sol"; import "./MProtection.sol"; import "./Interfaces/LiquidityMathModelInterface.sol"; import "./LiquidityMathModelV1.sol"; import "./Utils/SafeEIP20.sol"; import "./Interfaces/EIP20Interface.sol"; import "./Interfaces/LiquidationModelInterface.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title MOAR's Moartroller Contract * @author MOAR */ contract Moartroller is MoartrollerV6Storage, MoartrollerInterface, MoartrollerErrorReporter, ExponentialNoError, Versionable, Initializable { using SafeEIP20 for EIP20Interface; /// @notice Indicator that this is a Moartroller contract (for inspection) bool public constant isMoartroller = true; /// @notice Emitted when an admin supports a market event MarketListed(MToken mToken); /// @notice Emitted when an account enters a market event MarketEntered(MToken mToken, address account); /// @notice Emitted when an account exits a market event MarketExited(MToken mToken, address account); /// @notice Emitted when close factor is changed by admin event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa); /// @notice Emitted when a collateral factor is changed by admin event NewCollateralFactor(MToken mToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa); /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa); /// @notice Emitted when price oracle is changed event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle); /// @notice Emitted when protection is changed event NewCProtection(MProtection oldCProtection, MProtection newCProtection); /// @notice Emitted when pause guardian is changed event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); /// @notice Emitted when an action is paused globally event ActionPaused(string action, bool pauseState); /// @notice Emitted when an action is paused on a market event ActionPausedMToken(MToken mToken, string action, bool pauseState); /// @notice Emitted when a new MOAR speed is calculated for a market event MoarSpeedUpdated(MToken indexed mToken, uint newSpeed); /// @notice Emitted when a new MOAR speed is set for a contributor event ContributorMoarSpeedUpdated(address indexed contributor, uint newSpeed); /// @notice Emitted when MOAR is distributed to a supplier event DistributedSupplierMoar(MToken indexed mToken, address indexed supplier, uint moarDelta, uint moarSupplyIndex); /// @notice Emitted when MOAR is distributed to a borrower event DistributedBorrowerMoar(MToken indexed mToken, address indexed borrower, uint moarDelta, uint moarBorrowIndex); /// @notice Emitted when borrow cap for a mToken is changed event NewBorrowCap(MToken indexed mToken, uint newBorrowCap); /// @notice Emitted when borrow cap guardian is changed event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian); /// @notice Emitted when MOAR is granted by admin event MoarGranted(address recipient, uint amount); event NewLiquidityMathModel(address oldLiquidityMathModel, address newLiquidityMathModel); event NewLiquidationModel(address oldLiquidationModel, address newLiquidationModel); /// @notice The initial MOAR index for a market uint224 public constant moarInitialIndex = 1e36; // closeFactorMantissa must be strictly greater than this value uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 // No collateralFactorMantissa may exceed this value uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9 // Custom initializer function initialize(LiquidityMathModelInterface mathModel, LiquidationModelInterface lqdModel) public initializer { admin = msg.sender; liquidityMathModel = mathModel; liquidationModel = lqdModel; rewardClaimEnabled = false; } /*** Assets You Are In ***/ /** * @notice Returns the assets an account has entered * @param account The address of the account to pull assets for * @return A dynamic list with the assets the account has entered */ function getAssetsIn(address account) external view returns (MToken[] memory) { MToken[] memory assetsIn = accountAssets[account]; return assetsIn; } /** * @notice Returns whether the given account is entered in the given asset * @param account The address of the account to check * @param mToken The mToken to check * @return True if the account is in the asset, otherwise false. */ function checkMembership(address account, MToken mToken) external view returns (bool) { return markets[address(mToken)].accountMembership[account]; } /** * @notice Add assets to be included in account liquidity calculation * @param mTokens The list of addresses of the mToken markets to be enabled * @return Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] memory mTokens) public override returns (uint[] memory) { uint len = mTokens.length; uint[] memory results = new uint[](len); for (uint i = 0; i < len; i++) { MToken mToken = MToken(mTokens[i]); results[i] = uint(addToMarketInternal(mToken, msg.sender)); } return results; } /** * @notice Add the market to the borrower's "assets in" for liquidity calculations * @param mToken The market to enter * @param borrower The address of the account to modify * @return Success indicator for whether the market was entered */ function addToMarketInternal(MToken mToken, address borrower) internal returns (Error) { Market storage marketToJoin = markets[address(mToken)]; if (!marketToJoin.isListed) { // market is not listed, cannot join return Error.MARKET_NOT_LISTED; } if (marketToJoin.accountMembership[borrower] == true) { // already joined return Error.NO_ERROR; } // survived the gauntlet, add to list // NOTE: we store these somewhat redundantly as a significant optimization // this avoids having to iterate through the list for the most common use cases // that is, only when we need to perform liquidity checks // and not whenever we want to check if an account is in a particular market marketToJoin.accountMembership[borrower] = true; accountAssets[borrower].push(mToken); emit MarketEntered(mToken, borrower); return Error.NO_ERROR; } /** * @notice Removes asset from sender's account liquidity calculation * @dev Sender must not have an outstanding borrow balance in the asset, * or be providing necessary collateral for an outstanding borrow. * @param mTokenAddress The address of the asset to be removed * @return Whether or not the account successfully exited the market */ function exitMarket(address mTokenAddress) external override returns (uint) { MToken mToken = MToken(mTokenAddress); /* Get sender tokensHeld and amountOwed underlying from the mToken */ (uint oErr, uint tokensHeld, uint amountOwed, ) = mToken.getAccountSnapshot(msg.sender); require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code /* Fail if the sender has a borrow balance */ if (amountOwed != 0) { return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED); } /* Fail if the sender is not permitted to redeem all of their tokens */ uint allowed = redeemAllowedInternal(mTokenAddress, msg.sender, tokensHeld); if (allowed != 0) { return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed); } Market storage marketToExit = markets[address(mToken)]; /* Return true if the sender is not already ‘in’ the market */ if (!marketToExit.accountMembership[msg.sender]) { return uint(Error.NO_ERROR); } /* Set mToken account membership to false */ delete marketToExit.accountMembership[msg.sender]; /* Delete mToken from the account’s list of assets */ // load into memory for faster iteration MToken[] memory userAssetList = accountAssets[msg.sender]; uint len = userAssetList.length; uint assetIndex = len; for (uint i = 0; i < len; i++) { if (userAssetList[i] == mToken) { assetIndex = i; break; } } // We *must* have found the asset in the list or our redundant data structure is broken assert(assetIndex < len); // copy last item in list to location of item to be removed, reduce length by 1 MToken[] storage storedList = accountAssets[msg.sender]; storedList[assetIndex] = storedList[storedList.length - 1]; storedList.pop(); emit MarketExited(mToken, msg.sender); return uint(Error.NO_ERROR); } /*** Policy Hooks ***/ /** * @notice Checks if the account should be allowed to mint tokens in the given market * @param mToken The market to verify the mint against * @param minter The account which would get the minted tokens * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function mintAllowed(address mToken, address minter, uint mintAmount) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!mintGuardianPaused[mToken], "mint is paused"); // Shh - currently unused minter; mintAmount; if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving updateMoarSupplyIndex(mToken); distributeSupplierMoar(mToken, minter); return uint(Error.NO_ERROR); } /** * @notice Checks if the account should be allowed to redeem tokens in the given market * @param mToken The market to verify the redeem against * @param redeemer The account which would redeem the tokens * @param redeemTokens The number of mTokens to exchange for the underlying asset in the market * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function redeemAllowed(address mToken, address redeemer, uint redeemTokens) external override returns (uint) { uint allowed = redeemAllowedInternal(mToken, redeemer, redeemTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateMoarSupplyIndex(mToken); distributeSupplierMoar(mToken, redeemer); return uint(Error.NO_ERROR); } function redeemAllowedInternal(address mToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */ if (!markets[mToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */ (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, MToken(mToken), redeemTokens, 0); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); } /** * @notice Validates redeem and reverts on rejection. May emit logs. * @param mToken Asset being redeemed * @param redeemer The address redeeming the tokens * @param redeemAmount The amount of the underlying asset being redeemed * @param redeemTokens The number of tokens being redeemed */ function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) external override { // Shh - currently unused mToken; redeemer; // Require tokens is zero or amount is also zero if (redeemTokens == 0 && redeemAmount > 0) { revert("redeemTokens zero"); } } /** * @notice Checks if the account should be allowed to borrow the underlying asset of the given market * @param mToken The market to verify the borrow against * @param borrower The account which would borrow the asset * @param borrowAmount The amount of underlying the account would borrow * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function borrowAllowed(address mToken, address borrower, uint borrowAmount) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!borrowGuardianPaused[mToken], "borrow is paused"); if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[mToken].accountMembership[borrower]) { // only mTokens may call borrowAllowed if borrower not in market require(msg.sender == mToken, "sender must be mToken"); // attempt to add borrower to the market Error err = addToMarketInternal(MToken(msg.sender), borrower); if (err != Error.NO_ERROR) { return uint(err); } // it should be impossible to break the important invariant assert(markets[mToken].accountMembership[borrower]); } if (oracle.getUnderlyingPrice(MToken(mToken)) == 0) { return uint(Error.PRICE_ERROR); } uint borrowCap = borrowCaps[mToken]; // Borrow cap of 0 corresponds to unlimited borrowing if (borrowCap != 0) { uint totalBorrows = MToken(mToken).totalBorrows(); uint nextTotalBorrows = add_(totalBorrows, borrowAmount); require(nextTotalBorrows < borrowCap, "market borrow cap reached"); } (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, MToken(mToken), 0, borrowAmount); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: MToken(mToken).borrowIndex()}); updateMoarBorrowIndex(mToken, borrowIndex); distributeBorrowerMoar(mToken, borrower, borrowIndex); return uint(Error.NO_ERROR); } /** * @notice Checks if the account should be allowed to repay a borrow in the given market * @param mToken The market to verify the repay against * @param payer The account which would repay the asset * @param borrower The account which would borrowed the asset * @param repayAmount The amount of the underlying asset the account would repay * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function repayBorrowAllowed( address mToken, address payer, address borrower, uint repayAmount) external override returns (uint) { // Shh - currently unused payer; borrower; repayAmount; if (!markets[mToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } // Keep the flywheel moving Exp memory borrowIndex = Exp({mantissa: MToken(mToken).borrowIndex()}); updateMoarBorrowIndex(mToken, borrowIndex); distributeBorrowerMoar(mToken, borrower, borrowIndex); return uint(Error.NO_ERROR); } /** * @notice Checks if the liquidation should be allowed to occur * @param mTokenBorrowed Asset which was borrowed by the borrower * @param mTokenCollateral Asset which was used as collateral and will be seized * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param repayAmount The amount of underlying being repaid */ function liquidateBorrowAllowed( address mTokenBorrowed, address mTokenCollateral, address liquidator, address borrower, uint repayAmount) external override returns (uint) { // Shh - currently unused liquidator; if (!markets[mTokenBorrowed].isListed || !markets[mTokenCollateral].isListed) { return uint(Error.MARKET_NOT_LISTED); } /* The borrower must have shortfall in order to be liquidatable */ (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower); if (err != Error.NO_ERROR) { return uint(err); } if (shortfall == 0) { return uint(Error.INSUFFICIENT_SHORTFALL); } /* The liquidator may not repay more than what is allowed by the closeFactor */ uint borrowBalance = MToken(mTokenBorrowed).borrowBalanceStored(borrower); uint maxClose = mul_ScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance); if (repayAmount > maxClose) { return uint(Error.TOO_MUCH_REPAY); } return uint(Error.NO_ERROR); } /** * @notice Checks if the seizing of assets should be allowed to occur * @param mTokenCollateral Asset which was used as collateral and will be seized * @param mTokenBorrowed Asset which was borrowed by the borrower * @param liquidator The address repaying the borrow and seizing the collateral * @param borrower The address of the borrower * @param seizeTokens The number of collateral tokens to seize */ function seizeAllowed( address mTokenCollateral, address mTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!seizeGuardianPaused, "seize is paused"); // Shh - currently unused seizeTokens; if (!markets[mTokenCollateral].isListed || !markets[mTokenBorrowed].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (MToken(mTokenCollateral).moartroller() != MToken(mTokenBorrowed).moartroller()) { return uint(Error.MOARTROLLER_MISMATCH); } // Keep the flywheel moving updateMoarSupplyIndex(mTokenCollateral); distributeSupplierMoar(mTokenCollateral, borrower); distributeSupplierMoar(mTokenCollateral, liquidator); return uint(Error.NO_ERROR); } /** * @notice Checks if the account should be allowed to transfer tokens in the given market * @param mToken The market to verify the transfer against * @param src The account which sources the tokens * @param dst The account which receives the tokens * @param transferTokens The number of mTokens to transfer * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol) */ function transferAllowed(address mToken, address src, address dst, uint transferTokens) external override returns (uint) { // Pausing is a very serious situation - we revert to sound the alarms require(!transferGuardianPaused, "transfer is paused"); // Currently the only consideration is whether or not // the src is allowed to redeem this many tokens uint allowed = redeemAllowedInternal(mToken, src, transferTokens); if (allowed != uint(Error.NO_ERROR)) { return allowed; } // Keep the flywheel moving updateMoarSupplyIndex(mToken); distributeSupplierMoar(mToken, src); distributeSupplierMoar(mToken, dst); return uint(Error.NO_ERROR); } /*** Liquidity/Liquidation Calculations ***/ /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code (semi-opaque), account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidity(address account) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0); return (uint(err), liquidity, shortfall); } /** * @notice Determine the current account liquidity wrt collateral requirements * @return (possible error code, account liquidity in excess of collateral requirements, * account shortfall below collateral requirements) */ function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) { return getHypotheticalAccountLiquidityInternal(account, MToken(0), 0, 0); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param mTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @return (possible error code (semi-opaque), hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidity( address account, address mTokenModify, uint redeemTokens, uint borrowAmount) public view returns (uint, uint, uint) { (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, MToken(mTokenModify), redeemTokens, borrowAmount); return (uint(err), liquidity, shortfall); } /** * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed * @param mTokenModify The market to hypothetically redeem/borrow in * @param account The account to determine liquidity for * @param redeemTokens The number of tokens to hypothetically redeem * @param borrowAmount The amount of underlying to hypothetically borrow * @dev Note that we calculate the exchangeRateStored for each collateral mToken using stored data, * without calculating accumulated interest. * @return (possible error code, hypothetical account liquidity in excess of collateral requirements, * hypothetical account shortfall below collateral requirements) */ function getHypotheticalAccountLiquidityInternal( address account, MToken mTokenModify, uint redeemTokens, uint borrowAmount) internal view returns (Error, uint, uint) { AccountLiquidityLocalVars memory vars; // Holds all our calculation results uint oErr; // For each asset the account is in MToken[] memory assets = accountAssets[account]; for (uint i = 0; i < assets.length; i++) { MToken asset = assets[i]; address _account = account; // Read the balances and exchange rate from the mToken (oErr, vars.mTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(_account); if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades return (Error.SNAPSHOT_ERROR, 0, 0); } vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa}); vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa}); // Get the normalized price of the asset vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset); if (vars.oraclePriceMantissa == 0) { return (Error.PRICE_ERROR, 0, 0); } vars.oraclePrice = mul_(Exp({mantissa: vars.oraclePriceMantissa}), 10**uint256(18 - EIP20Interface(asset.getUnderlying()).decimals())); // Pre-compute a conversion factor from tokens -> dai (normalized price value) vars.tokensToDenom = mul_(mul_(vars.collateralFactor, vars.exchangeRate), vars.oraclePrice); // sumCollateral += tokensToDenom * mTokenBalance vars.sumCollateral = mul_ScalarTruncateAddUInt(vars.tokensToDenom, vars.mTokenBalance, vars.sumCollateral); // Protection value calculation sumCollateral += protectionValueLocked // Mark to market value calculation sumCollateral += markToMarketValue uint protectionValueLocked; uint markToMarketValue; (protectionValueLocked, markToMarketValue) = liquidityMathModel.getTotalProtectionLockedValue(LiquidityMathModelInterface.LiquidityMathArgumentsSet(asset, _account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle)); if (vars.sumCollateral < mul_( protectionValueLocked, vars.collateralFactor)) { vars.sumCollateral = 0; } else { vars.sumCollateral = sub_(vars.sumCollateral, mul_( protectionValueLocked, vars.collateralFactor)); } vars.sumCollateral = add_(vars.sumCollateral, protectionValueLocked); vars.sumCollateral = add_(vars.sumCollateral, markToMarketValue); // sumBorrowPlusEffects += oraclePrice * borrowBalance vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects); // Calculate effects of interacting with mTokenModify if (asset == mTokenModify) { // redeem effect // sumBorrowPlusEffects += tokensToDenom * redeemTokens vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects); // borrow effect // sumBorrowPlusEffects += oraclePrice * borrowAmount vars.sumBorrowPlusEffects = mul_ScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects); _account = account; } } // These are safe, as the underflow condition is checked first if (vars.sumCollateral > vars.sumBorrowPlusEffects) { return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0); } else { return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral); } } /** * @notice Returns the value of possible optimization left for asset * @param asset The MToken address * @param account The owner of asset * @return The value of possible optimization */ function getMaxOptimizableValue(MToken asset, address account) public view returns(uint){ return liquidityMathModel.getMaxOptimizableValue( LiquidityMathModelInterface.LiquidityMathArgumentsSet( asset, account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle ) ); } /** * @notice Returns the value of hypothetical optimization (ignoring existing optimization used) for asset * @param asset The MToken address * @param account The owner of asset * @return The amount of hypothetical optimization */ function getHypotheticalOptimizableValue(MToken asset, address account) public view returns(uint){ return liquidityMathModel.getHypotheticalOptimizableValue( LiquidityMathModelInterface.LiquidityMathArgumentsSet( asset, account, markets[address(asset)].collateralFactorMantissa, cprotection, oracle ) ); } function liquidateCalculateSeizeUserTokens(address mTokenBorrowed, address mTokenCollateral, uint actualRepayAmount, address account) external override view returns (uint, uint) { return LiquidationModelInterface(liquidationModel).liquidateCalculateSeizeUserTokens( LiquidationModelInterface.LiquidateCalculateSeizeUserTokensArgumentsSet( oracle, this, mTokenBorrowed, mTokenCollateral, actualRepayAmount, account, liquidationIncentiveMantissa ) ); } /** * @notice Returns the amount of a specific asset that is locked under all c-ops * @param asset The MToken address * @param account The owner of asset * @return The amount of asset locked under c-ops */ function getUserLockedAmount(MToken asset, address account) public override view returns(uint) { uint protectionLockedAmount; address currency = asset.underlying(); uint256 numOfProtections = cprotection.getUserUnderlyingProtectionTokenIdByCurrencySize(account, currency); for (uint i = 0; i < numOfProtections; i++) { uint cProtectionId = cprotection.getUserUnderlyingProtectionTokenIdByCurrency(account, currency, i); if(cprotection.isProtectionAlive(cProtectionId)){ protectionLockedAmount = protectionLockedAmount + cprotection.getUnderlyingProtectionLockedAmount(cProtectionId); } } return protectionLockedAmount; } /*** Admin Functions ***/ /** * @notice Sets a new price oracle for the moartroller * @dev Admin function to set a new price oracle * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPriceOracle(PriceOracle newOracle) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } // Track the old oracle for the moartroller PriceOracle oldOracle = oracle; // Set moartroller's oracle to newOracle oracle = newOracle; // Emit NewPriceOracle(oldOracle, newOracle) emit NewPriceOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); } /** * @notice Sets a new CProtection that is allowed to use as a collateral optimisation * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setProtection(address newCProtection) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK); } MProtection oldCProtection = cprotection; cprotection = MProtection(newCProtection); // Emit NewPriceOracle(oldOracle, newOracle) emit NewCProtection(oldCProtection, cprotection); return uint(Error.NO_ERROR); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param newCloseFactorMantissa New close factor, scaled by 1e18 * @return uint 0=success, otherwise a failure */ function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) { // Check caller is admin require(msg.sender == admin, "only admin can set close factor"); uint oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = newCloseFactorMantissa; emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets the collateralFactor for a market * @dev Admin function to set per-market collateralFactor * @param mToken The market to set the factor on * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setCollateralFactor(MToken mToken, uint newCollateralFactorMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK); } // Verify market is listed Market storage market = markets[address(mToken)]; if (!market.isListed) { return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS); } // TODO: this check is temporary switched off. we can make exception for UNN later // Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa}); // // // Check collateral factor <= 0.9 // Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa}); // if (lessThanExp(highLimit, newCollateralFactorExp)) { // return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION); // } // If collateral factor != 0, fail if price == 0 if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(mToken) == 0) { return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE); } // Set market's collateral factor to new collateral factor, remember old value uint oldCollateralFactorMantissa = market.collateralFactorMantissa; market.collateralFactorMantissa = newCollateralFactorMantissa; // Emit event with asset, old collateral factor, and new collateral factor emit NewCollateralFactor(mToken, oldCollateralFactorMantissa, newCollateralFactorMantissa); return uint(Error.NO_ERROR); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 * @return uint 0=success, otherwise a failure. (See ErrorReporter for details) */ function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK); } // Save current value for use in log uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; // Set liquidation incentive to new incentive liquidationIncentiveMantissa = newLiquidationIncentiveMantissa; // Emit event with old incentive, new incentive emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa); return uint(Error.NO_ERROR); } function _setRewardClaimEnabled(bool status) external returns (uint) { // Check caller is admin require(msg.sender == admin, "only admin can set close factor"); rewardClaimEnabled = status; return uint(Error.NO_ERROR); } /** * @notice Add the market to the markets mapping and set it as listed * @dev Admin function to set isListed and add support for the market * @param mToken The address of the market (token) to list * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _supportMarket(MToken mToken) external returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } if (markets[address(mToken)].isListed) { return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS); } mToken.isMToken(); // Sanity check to make sure its really a MToken // Note that isMoared is not in active use anymore markets[address(mToken)] = Market({isListed: true, isMoared: false, collateralFactorMantissa: 0}); tokenAddressToMToken[address(mToken.underlying())] = mToken; _addMarketInternal(address(mToken)); emit MarketListed(mToken); return uint(Error.NO_ERROR); } function _addMarketInternal(address mToken) internal { for (uint i = 0; i < allMarkets.length; i ++) { require(allMarkets[i] != MToken(mToken), "market already added"); } allMarkets.push(MToken(mToken)); } /** * @notice Set the given borrow caps for the given mToken markets. Borrowing that brings total borrows to or above borrow cap will revert. * @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. * @param mTokens The addresses of the markets (tokens) to change the borrow caps for * @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing. */ function _setMarketBorrowCaps(MToken[] calldata mTokens, uint[] calldata newBorrowCaps) external { require(msg.sender == admin || msg.sender == borrowCapGuardian, "only admin or borrow cap guardian can set borrow caps"); uint numMarkets = mTokens.length; uint numBorrowCaps = newBorrowCaps.length; require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input"); for(uint i = 0; i < numMarkets; i++) { borrowCaps[address(mTokens[i])] = newBorrowCaps[i]; emit NewBorrowCap(mTokens[i], newBorrowCaps[i]); } } /** * @notice Admin function to change the Borrow Cap Guardian * @param newBorrowCapGuardian The address of the new Borrow Cap Guardian */ function _setBorrowCapGuardian(address newBorrowCapGuardian) external { require(msg.sender == admin, "only admin can set borrow cap guardian"); // Save current value for inclusion in log address oldBorrowCapGuardian = borrowCapGuardian; // Store borrowCapGuardian with value newBorrowCapGuardian borrowCapGuardian = newBorrowCapGuardian; // Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian) emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian); } /** * @notice Admin function to change the Pause Guardian * @param newPauseGuardian The address of the new Pause Guardian * @return uint 0=success, otherwise a failure. (See enum Error for details) */ function _setPauseGuardian(address newPauseGuardian) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK); } // Save current value for inclusion in log address oldPauseGuardian = pauseGuardian; // Store pauseGuardian with value newPauseGuardian pauseGuardian = newPauseGuardian; // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian) emit NewPauseGuardian(oldPauseGuardian, pauseGuardian); return uint(Error.NO_ERROR); } function _setMintPaused(MToken mToken, bool state) public returns (bool) { require(markets[address(mToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); mintGuardianPaused[address(mToken)] = state; emit ActionPausedMToken(mToken, "Mint", state); return state; } function _setBorrowPaused(MToken mToken, bool state) public returns (bool) { require(markets[address(mToken)].isListed, "cannot pause a market that is not listed"); require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); borrowGuardianPaused[address(mToken)] = state; emit ActionPausedMToken(mToken, "Borrow", state); return state; } function _setTransferPaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); transferGuardianPaused = state; emit ActionPaused("Transfer", state); return state; } function _setSeizePaused(bool state) public returns (bool) { require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause"); require(msg.sender == admin || state == true, "only admin can unpause"); seizeGuardianPaused = state; emit ActionPaused("Seize", state); return state; } /** * @notice Checks caller is admin, or this contract is becoming the new implementation */ function adminOrInitializing() internal view returns (bool) { return msg.sender == admin || msg.sender == moartrollerImplementation; } /*** MOAR Distribution ***/ /** * @notice Set MOAR speed for a single market * @param mToken The market whose MOAR speed to update * @param moarSpeed New MOAR speed for market */ function setMoarSpeedInternal(MToken mToken, uint moarSpeed) internal { uint currentMoarSpeed = moarSpeeds[address(mToken)]; if (currentMoarSpeed != 0) { // note that MOAR speed could be set to 0 to halt liquidity rewards for a market Exp memory borrowIndex = Exp({mantissa: mToken.borrowIndex()}); updateMoarSupplyIndex(address(mToken)); updateMoarBorrowIndex(address(mToken), borrowIndex); } else if (moarSpeed != 0) { // Add the MOAR market Market storage market = markets[address(mToken)]; require(market.isListed == true, "MOAR market is not listed"); if (moarSupplyState[address(mToken)].index == 0 && moarSupplyState[address(mToken)].block == 0) { moarSupplyState[address(mToken)] = MoarMarketState({ index: moarInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } if (moarBorrowState[address(mToken)].index == 0 && moarBorrowState[address(mToken)].block == 0) { moarBorrowState[address(mToken)] = MoarMarketState({ index: moarInitialIndex, block: safe32(getBlockNumber(), "block number exceeds 32 bits") }); } } if (currentMoarSpeed != moarSpeed) { moarSpeeds[address(mToken)] = moarSpeed; emit MoarSpeedUpdated(mToken, moarSpeed); } } /** * @notice Accrue MOAR to the market by updating the supply index * @param mToken The market whose supply index to update */ function updateMoarSupplyIndex(address mToken) internal { MoarMarketState storage supplyState = moarSupplyState[mToken]; uint supplySpeed = moarSpeeds[mToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(supplyState.block)); if (deltaBlocks > 0 && supplySpeed > 0) { uint supplyTokens = MToken(mToken).totalSupply(); uint moarAccrued = mul_(deltaBlocks, supplySpeed); Double memory ratio = supplyTokens > 0 ? fraction(moarAccrued, supplyTokens) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: supplyState.index}), ratio); moarSupplyState[mToken] = MoarMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { supplyState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Accrue MOAR to the market by updating the borrow index * @param mToken The market whose borrow index to update */ function updateMoarBorrowIndex(address mToken, Exp memory marketBorrowIndex) internal { MoarMarketState storage borrowState = moarBorrowState[mToken]; uint borrowSpeed = moarSpeeds[mToken]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, uint(borrowState.block)); if (deltaBlocks > 0 && borrowSpeed > 0) { uint borrowAmount = div_(MToken(mToken).totalBorrows(), marketBorrowIndex); uint moarAccrued = mul_(deltaBlocks, borrowSpeed); Double memory ratio = borrowAmount > 0 ? fraction(moarAccrued, borrowAmount) : Double({mantissa: 0}); Double memory index = add_(Double({mantissa: borrowState.index}), ratio); moarBorrowState[mToken] = MoarMarketState({ index: safe224(index.mantissa, "new index exceeds 224 bits"), block: safe32(blockNumber, "block number exceeds 32 bits") }); } else if (deltaBlocks > 0) { borrowState.block = safe32(blockNumber, "block number exceeds 32 bits"); } } /** * @notice Calculate MOAR accrued by a supplier and possibly transfer it to them * @param mToken The market in which the supplier is interacting * @param supplier The address of the supplier to distribute MOAR to */ function distributeSupplierMoar(address mToken, address supplier) internal { MoarMarketState storage supplyState = moarSupplyState[mToken]; Double memory supplyIndex = Double({mantissa: supplyState.index}); Double memory supplierIndex = Double({mantissa: moarSupplierIndex[mToken][supplier]}); moarSupplierIndex[mToken][supplier] = supplyIndex.mantissa; if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) { supplierIndex.mantissa = moarInitialIndex; } Double memory deltaIndex = sub_(supplyIndex, supplierIndex); uint supplierTokens = MToken(mToken).balanceOf(supplier); uint supplierDelta = mul_(supplierTokens, deltaIndex); uint supplierAccrued = add_(moarAccrued[supplier], supplierDelta); moarAccrued[supplier] = supplierAccrued; emit DistributedSupplierMoar(MToken(mToken), supplier, supplierDelta, supplyIndex.mantissa); } /** * @notice Calculate MOAR accrued by a borrower and possibly transfer it to them * @dev Borrowers will not begin to accrue until after the first interaction with the protocol. * @param mToken The market in which the borrower is interacting * @param borrower The address of the borrower to distribute MOAR to */ function distributeBorrowerMoar(address mToken, address borrower, Exp memory marketBorrowIndex) internal { MoarMarketState storage borrowState = moarBorrowState[mToken]; Double memory borrowIndex = Double({mantissa: borrowState.index}); Double memory borrowerIndex = Double({mantissa: moarBorrowerIndex[mToken][borrower]}); moarBorrowerIndex[mToken][borrower] = borrowIndex.mantissa; if (borrowerIndex.mantissa > 0) { Double memory deltaIndex = sub_(borrowIndex, borrowerIndex); uint borrowerAmount = div_(MToken(mToken).borrowBalanceStored(borrower), marketBorrowIndex); uint borrowerDelta = mul_(borrowerAmount, deltaIndex); uint borrowerAccrued = add_(moarAccrued[borrower], borrowerDelta); moarAccrued[borrower] = borrowerAccrued; emit DistributedBorrowerMoar(MToken(mToken), borrower, borrowerDelta, borrowIndex.mantissa); } } /** * @notice Calculate additional accrued MOAR for a contributor since last accrual * @param contributor The address to calculate contributor rewards for */ function updateContributorRewards(address contributor) public { uint moarSpeed = moarContributorSpeeds[contributor]; uint blockNumber = getBlockNumber(); uint deltaBlocks = sub_(blockNumber, lastContributorBlock[contributor]); if (deltaBlocks > 0 && moarSpeed > 0) { uint newAccrued = mul_(deltaBlocks, moarSpeed); uint contributorAccrued = add_(moarAccrued[contributor], newAccrued); moarAccrued[contributor] = contributorAccrued; lastContributorBlock[contributor] = blockNumber; } } /** * @notice Claim all the MOAR accrued by holder in all markets * @param holder The address to claim MOAR for */ function claimMoarReward(address holder) public { return claimMoar(holder, allMarkets); } /** * @notice Claim all the MOAR accrued by holder in the specified markets * @param holder The address to claim MOAR for * @param mTokens The list of markets to claim MOAR in */ function claimMoar(address holder, MToken[] memory mTokens) public { address[] memory holders = new address[](1); holders[0] = holder; claimMoar(holders, mTokens, true, true); } /** * @notice Claim all MOAR accrued by the holders * @param holders The addresses to claim MOAR for * @param mTokens The list of markets to claim MOAR in * @param borrowers Whether or not to claim MOAR earned by borrowing * @param suppliers Whether or not to claim MOAR earned by supplying */ function claimMoar(address[] memory holders, MToken[] memory mTokens, bool borrowers, bool suppliers) public { require(rewardClaimEnabled, "reward claim is disabled"); for (uint i = 0; i < mTokens.length; i++) { MToken mToken = mTokens[i]; require(markets[address(mToken)].isListed, "market must be listed"); if (borrowers == true) { Exp memory borrowIndex = Exp({mantissa: mToken.borrowIndex()}); updateMoarBorrowIndex(address(mToken), borrowIndex); for (uint j = 0; j < holders.length; j++) { distributeBorrowerMoar(address(mToken), holders[j], borrowIndex); moarAccrued[holders[j]] = grantMoarInternal(holders[j], moarAccrued[holders[j]]); } } if (suppliers == true) { updateMoarSupplyIndex(address(mToken)); for (uint j = 0; j < holders.length; j++) { distributeSupplierMoar(address(mToken), holders[j]); moarAccrued[holders[j]] = grantMoarInternal(holders[j], moarAccrued[holders[j]]); } } } } /** * @notice Transfer MOAR to the user * @dev Note: If there is not enough MOAR, we do not perform the transfer all. * @param user The address of the user to transfer MOAR to * @param amount The amount of MOAR to (possibly) transfer * @return The amount of MOAR which was NOT transferred to the user */ function grantMoarInternal(address user, uint amount) internal returns (uint) { EIP20Interface moar = EIP20Interface(getMoarAddress()); uint moarRemaining = moar.balanceOf(address(this)); if (amount > 0 && amount <= moarRemaining) { moar.approve(mProxy, amount); MProxyInterface(mProxy).proxyClaimReward(getMoarAddress(), user, amount); return 0; } return amount; } /*** MOAR Distribution Admin ***/ /** * @notice Transfer MOAR to the recipient * @dev Note: If there is not enough MOAR, we do not perform the transfer all. * @param recipient The address of the recipient to transfer MOAR to * @param amount The amount of MOAR to (possibly) transfer */ function _grantMoar(address recipient, uint amount) public { require(adminOrInitializing(), "only admin can grant MOAR"); uint amountLeft = grantMoarInternal(recipient, amount); require(amountLeft == 0, "insufficient MOAR for grant"); emit MoarGranted(recipient, amount); } /** * @notice Set MOAR speed for a single market * @param mToken The market whose MOAR speed to update * @param moarSpeed New MOAR speed for market */ function _setMoarSpeed(MToken mToken, uint moarSpeed) public { require(adminOrInitializing(), "only admin can set MOAR speed"); setMoarSpeedInternal(mToken, moarSpeed); } /** * @notice Set MOAR speed for a single contributor * @param contributor The contributor whose MOAR speed to update * @param moarSpeed New MOAR speed for contributor */ function _setContributorMoarSpeed(address contributor, uint moarSpeed) public { require(adminOrInitializing(), "only admin can set MOAR speed"); // note that MOAR speed could be set to 0 to halt liquidity rewards for a contributor updateContributorRewards(contributor); if (moarSpeed == 0) { // release storage delete lastContributorBlock[contributor]; } else { lastContributorBlock[contributor] = getBlockNumber(); } moarContributorSpeeds[contributor] = moarSpeed; emit ContributorMoarSpeedUpdated(contributor, moarSpeed); } /** * @notice Set liquidity math model implementation * @param mathModel the math model implementation */ function _setLiquidityMathModel(LiquidityMathModelInterface mathModel) public { require(msg.sender == admin, "only admin can set liquidity math model implementation"); LiquidityMathModelInterface oldLiquidityMathModel = liquidityMathModel; liquidityMathModel = mathModel; emit NewLiquidityMathModel(address(oldLiquidityMathModel), address(liquidityMathModel)); } /** * @notice Set liquidation model implementation * @param newLiquidationModel the liquidation model implementation */ function _setLiquidationModel(LiquidationModelInterface newLiquidationModel) public { require(msg.sender == admin, "only admin can set liquidation model implementation"); LiquidationModelInterface oldLiquidationModel = liquidationModel; liquidationModel = newLiquidationModel; emit NewLiquidationModel(address(oldLiquidationModel), address(liquidationModel)); } function _setMoarToken(address moarTokenAddress) public { require(msg.sender == admin, "only admin can set MOAR token address"); moarToken = moarTokenAddress; } function _setMProxy(address mProxyAddress) public { require(msg.sender == admin, "only admin can set MProxy address"); mProxy = mProxyAddress; } /** * @notice Add new privileged address * @param privilegedAddress address to add */ function _addPrivilegedAddress(address privilegedAddress) public { require(msg.sender == admin, "only admin can set liquidity math model implementation"); privilegedAddresses[privilegedAddress] = 1; } /** * @notice Remove privileged address * @param privilegedAddress address to remove */ function _removePrivilegedAddress(address privilegedAddress) public { require(msg.sender == admin, "only admin can set liquidity math model implementation"); delete privilegedAddresses[privilegedAddress]; } /** * @notice Check if address if privileged * @param privilegedAddress address to check */ function isPrivilegedAddress(address privilegedAddress) public view returns (bool) { return privilegedAddresses[privilegedAddress] == 1; } /** * @notice Return all of the markets * @dev The automatic getter may be used to access an individual market. * @return The list of market addresses */ function getAllMarkets() public view returns (MToken[] memory) { return allMarkets; } function getBlockNumber() public view returns (uint) { return block.number; } /** * @notice Return the address of the MOAR token * @return The address of MOAR */ function getMoarAddress() public view returns (address) { return moarToken; } function getContractVersion() external override pure returns(string memory){ return "V1"; } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./Interfaces/PriceOracle.sol"; import "./CErc20.sol"; /** * Temporary simple price feed */ contract SimplePriceOracle is PriceOracle { /// @notice Indicator that this is a PriceOracle contract (for inspection) bool public constant isPriceOracle = true; mapping(address => uint) prices; event PricePosted(address asset, uint previousPriceMantissa, uint requestedPriceMantissa, uint newPriceMantissa); function getUnderlyingPrice(MToken mToken) public override view returns (uint) { if (compareStrings(mToken.symbol(), "mDAI")) { return 1e18; } else { return prices[address(MErc20(address(mToken)).underlying())]; } } function setUnderlyingPrice(MToken mToken, uint underlyingPriceMantissa) public { address asset = address(MErc20(address(mToken)).underlying()); emit PricePosted(asset, prices[asset], underlyingPriceMantissa, underlyingPriceMantissa); prices[asset] = underlyingPriceMantissa; } function setDirectPrice(address asset, uint price) public { emit PricePosted(asset, prices[asset], price, price); prices[asset] = price; } // v1 price oracle interface for use as backing of proxy function assetPrices(address asset) external view returns (uint) { return prices[asset]; } function compareStrings(string memory a, string memory b) internal pure returns (bool) { return (keccak256(abi.encodePacked((a))) == keccak256(abi.encodePacked((b)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "./Interfaces/CopMappingInterface.sol"; import "./Interfaces/Versionable.sol"; import "./Moartroller.sol"; import "./Utils/ExponentialNoError.sol"; import "./Utils/ErrorReporter.sol"; import "./Utils/AssetHelpers.sol"; import "./MToken.sol"; import "./Interfaces/EIP20Interface.sol"; import "./Utils/SafeEIP20.sol"; /** * @title MOAR's MProtection Contract * @notice Collateral optimization ERC-721 wrapper * @author MOAR */ contract MProtection is ERC721Upgradeable, OwnableUpgradeable, ExponentialNoError, AssetHelpers, Versionable { using Counters for Counters.Counter; using EnumerableSet for EnumerableSet.UintSet; /** * @notice Event emitted when new MProtection token is minted */ event Mint(address minter, uint tokenId, uint underlyingTokenId, address asset, uint amount, uint strikePrice, uint expirationTime); /** * @notice Event emitted when MProtection token is redeemed */ event Redeem(address redeemer, uint tokenId, uint underlyingTokenId); /** * @notice Event emitted when MProtection token changes its locked value */ event LockValue(uint tokenId, uint underlyingTokenId, uint optimizationValue); /** * @notice Event emitted when maturity window parameter is changed */ event MaturityWindowUpdated(uint newMaturityWindow); Counters.Counter private _tokenIds; address private _copMappingAddress; address private _moartrollerAddress; mapping (uint256 => uint256) private _underlyingProtectionTokensMapping; mapping (uint256 => uint256) private _underlyingProtectionLockedValue; mapping (address => mapping (address => EnumerableSet.UintSet)) private _protectionCurrencyMapping; uint256 public _maturityWindow; struct ProtectionMappedData{ address pool; address underlyingAsset; uint256 amount; uint256 strike; uint256 premium; uint256 lockedValue; uint256 totalValue; uint issueTime; uint expirationTime; bool isProtectionAlive; } /** * @notice Constructor for MProtection contract * @param copMappingAddress The address of data mapper for C-OP * @param moartrollerAddress The address of the Moartroller */ function initialize(address copMappingAddress, address moartrollerAddress) public initializer { __Ownable_init(); __ERC721_init("c-uUNN OC-Protection", "c-uUNN"); _copMappingAddress = copMappingAddress; _moartrollerAddress = moartrollerAddress; _setMaturityWindow(10800); // 3 hours default } /** * @notice Returns C-OP mapping contract */ function copMapping() private view returns (CopMappingInterface){ return CopMappingInterface(_copMappingAddress); } /** * @notice Mint new MProtection token * @param underlyingTokenId Id of C-OP token that will be deposited * @return ID of minted MProtection token */ function mint(uint256 underlyingTokenId) public returns (uint256) { return mintFor(underlyingTokenId, msg.sender); } /** * @notice Mint new MProtection token for specified address * @param underlyingTokenId Id of C-OP token that will be deposited * @param receiver Address that will receive minted Mprotection token * @return ID of minted MProtection token */ function mintFor(uint256 underlyingTokenId, address receiver) public returns (uint256) { CopMappingInterface copMappingInstance = copMapping(); ERC721Upgradeable(copMappingInstance.getTokenAddress()).transferFrom(msg.sender, address(this), underlyingTokenId); _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(receiver, newItemId); addUProtectionIndexes(receiver, newItemId, underlyingTokenId); emit Mint( receiver, newItemId, underlyingTokenId, copMappingInstance.getUnderlyingAsset(underlyingTokenId), copMappingInstance.getUnderlyingAmount(underlyingTokenId), copMappingInstance.getUnderlyingStrikePrice(underlyingTokenId), copMappingInstance.getUnderlyingDeadline(underlyingTokenId) ); return newItemId; } /** * @notice Redeem C-OP token * @param tokenId Id of MProtection token that will be withdrawn * @return ID of redeemed C-OP token */ function redeem(uint256 tokenId) external returns (uint256) { require(_isApprovedOrOwner(_msgSender(), tokenId), "cuUNN: caller is not owner nor approved"); uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); ERC721Upgradeable(copMapping().getTokenAddress()).transferFrom(address(this), msg.sender, underlyingTokenId); removeProtectionIndexes(tokenId); _burn(tokenId); emit Redeem(msg.sender, tokenId, underlyingTokenId); return underlyingTokenId; } /** * @notice Returns set of C-OP data * @param tokenId Id of MProtection token * @return ProtectionMappedData struct filled with C-OP data */ function getMappedProtectionData(uint256 tokenId) public view returns (ProtectionMappedData memory){ ProtectionMappedData memory data; (address pool, uint256 amount, uint256 strike, uint256 premium, uint issueTime , uint expirationTime) = getProtectionData(tokenId); data = ProtectionMappedData(pool, getUnderlyingAsset(tokenId), amount, strike, premium, getUnderlyingProtectionLockedValue(tokenId), getUnderlyingProtectionTotalValue(tokenId), issueTime, expirationTime, isProtectionAlive(tokenId)); return data; } /** * @notice Returns underlying token ID * @param tokenId Id of MProtection token */ function getUnderlyingProtectionTokenId(uint256 tokenId) public view returns (uint256){ return _underlyingProtectionTokensMapping[tokenId]; } /** * @notice Returns size of C-OPs filtered by asset address * @param owner Address of wallet holding C-OPs * @param currency Address of asset used to filter C-OPs */ function getUserUnderlyingProtectionTokenIdByCurrencySize(address owner, address currency) public view returns (uint256){ return _protectionCurrencyMapping[owner][currency].length(); } /** * @notice Returns list of C-OP IDs filtered by asset address * @param owner Address of wallet holding C-OPs * @param currency Address of asset used to filter C-OPs */ function getUserUnderlyingProtectionTokenIdByCurrency(address owner, address currency, uint256 index) public view returns (uint256){ return _protectionCurrencyMapping[owner][currency].at(index); } /** * @notice Checks if address is owner of MProtection * @param owner Address of potential owner to check * @param tokenId ID of MProtection to check */ function isUserProtection(address owner, uint256 tokenId) public view returns(bool) { if(Moartroller(_moartrollerAddress).isPrivilegedAddress(msg.sender)){ return true; } return owner == ownerOf(tokenId); } /** * @notice Checks if MProtection is stil alive * @param tokenId ID of MProtection to check */ function isProtectionAlive(uint256 tokenId) public view returns(bool) { uint256 deadline = getUnderlyingDeadline(tokenId); return (deadline - _maturityWindow) > now; } /** * @notice Creates appropriate indexes for C-OP * @param owner C-OP owner address * @param tokenId ID of MProtection * @param underlyingTokenId ID of C-OP */ function addUProtectionIndexes(address owner, uint256 tokenId, uint256 underlyingTokenId) private{ address currency = copMapping().getUnderlyingAsset(underlyingTokenId); _underlyingProtectionTokensMapping[tokenId] = underlyingTokenId; _protectionCurrencyMapping[owner][currency].add(tokenId); } /** * @notice Remove indexes for C-OP * @param tokenId ID of MProtection */ function removeProtectionIndexes(uint256 tokenId) private{ address owner = ownerOf(tokenId); address currency = getUnderlyingAsset(tokenId); _underlyingProtectionTokensMapping[tokenId] = 0; _protectionCurrencyMapping[owner][currency].remove(tokenId); } /** * @notice Returns C-OP total value * @param tokenId ID of MProtection */ function getUnderlyingProtectionTotalValue(uint256 tokenId) public view returns(uint256){ address underlyingAsset = getUnderlyingAsset(tokenId); uint256 assetDecimalsMantissa = getAssetDecimalsMantissa(underlyingAsset); return div_( mul_( getUnderlyingStrikePrice(tokenId), getUnderlyingAmount(tokenId) ), assetDecimalsMantissa ); } /** * @notice Returns C-OP locked value * @param tokenId ID of MProtection */ function getUnderlyingProtectionLockedValue(uint256 tokenId) public view returns(uint256){ return _underlyingProtectionLockedValue[tokenId]; } /** * @notice get the amount of underlying asset that is locked * @param tokenId CProtection tokenId * @return amount locked */ function getUnderlyingProtectionLockedAmount(uint256 tokenId) public view returns(uint256){ address underlyingAsset = getUnderlyingAsset(tokenId); uint256 assetDecimalsMantissa = getAssetDecimalsMantissa(underlyingAsset); // calculates total protection value uint256 protectionValue = div_( mul_( getUnderlyingAmount(tokenId), getUnderlyingStrikePrice(tokenId) ), assetDecimalsMantissa ); // return value is lockedValue / totalValue * amount return div_( mul_( getUnderlyingAmount(tokenId), div_( mul_( _underlyingProtectionLockedValue[tokenId], 1e18 ), protectionValue ) ), 1e18 ); } /** * @notice Locks the given protection value as collateral optimization * @param tokenId The MProtection token id * @param value The value in stablecoin of protection to be locked as collateral optimization. 0 = max available optimization * @return locked protection value * TODO: convert semantic errors to standarized error codes */ function lockProtectionValue(uint256 tokenId, uint value) external returns(uint) { //check if the protection belongs to the caller require(isUserProtection(msg.sender, tokenId), "ERROR: CALLER IS NOT THE OWNER OF PROTECTION"); address currency = getUnderlyingAsset(tokenId); Moartroller moartroller = Moartroller(_moartrollerAddress); MToken mToken = moartroller.tokenAddressToMToken(currency); require(moartroller.oracle().getUnderlyingPrice(mToken) <= getUnderlyingStrikePrice(tokenId), "ERROR: C-OP STRIKE PRICE IS LOWER THAN ASSET SPOT PRICE"); uint protectionTotalValue = getUnderlyingProtectionTotalValue(tokenId); uint maxOptimizableValue = moartroller.getMaxOptimizableValue(mToken, ownerOf(tokenId)); // add protection locked value if any uint protectionLockedValue = getUnderlyingProtectionLockedValue(tokenId); if ( protectionLockedValue > 0) { maxOptimizableValue = add_(maxOptimizableValue, protectionLockedValue); } uint valueToLock; if (value != 0) { // check if lock value is at most max optimizable value require(value <= maxOptimizableValue, "ERROR: VALUE TO BE LOCKED EXCEEDS ALLOWED OPTIMIZATION VALUE"); // check if lock value is at most protection total value require( value <= protectionTotalValue, "ERROR: VALUE TO BE LOCKED EXCEEDS PROTECTION TOTAL VALUE"); valueToLock = value; } else { // if we want to lock maximum protection value let's lock the value that is at most max optimizable value if (protectionTotalValue > maxOptimizableValue) { valueToLock = maxOptimizableValue; } else { valueToLock = protectionTotalValue; } } _underlyingProtectionLockedValue[tokenId] = valueToLock; emit LockValue(tokenId, getUnderlyingProtectionTokenId(tokenId), valueToLock); return valueToLock; } function _setCopMapping(address newMapping) public onlyOwner { _copMappingAddress = newMapping; } function _setMoartroller(address newMoartroller) public onlyOwner { _moartrollerAddress = newMoartroller; } function _setMaturityWindow(uint256 maturityWindow) public onlyOwner { emit MaturityWindowUpdated(maturityWindow); _maturityWindow = maturityWindow; } // MAPPINGS function getProtectionData(uint256 tokenId) public view returns (address, uint256, uint256, uint256, uint, uint){ uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); return copMapping().getProtectionData(underlyingTokenId); } function getUnderlyingAsset(uint256 tokenId) public view returns (address){ uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); return copMapping().getUnderlyingAsset(underlyingTokenId); } function getUnderlyingAmount(uint256 tokenId) public view returns (uint256){ uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); return copMapping().getUnderlyingAmount(underlyingTokenId); } function getUnderlyingStrikePrice(uint256 tokenId) public view returns (uint){ uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); return copMapping().getUnderlyingStrikePrice(underlyingTokenId); } function getUnderlyingDeadline(uint256 tokenId) public view returns (uint){ uint256 underlyingTokenId = getUnderlyingProtectionTokenId(tokenId); return copMapping().getUnderlyingDeadline(underlyingTokenId); } function getContractVersion() external override pure returns(string memory){ return "V1"; } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "../MToken.sol"; interface PriceOracle { /** * @notice Get the underlying price of a mToken asset * @param mToken The mToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(MToken mToken) external view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "./CarefulMath.sol"; import "./ExponentialNoError.sol"; /** * @title Exponential module for storing fixed-precision decimals * @dev Legacy contract for compatibility reasons with existing contracts that still use MathError * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath, ExponentialNoError { /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return balance The balance */ function balanceOf(address owner) external view returns (uint256); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return success Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return success Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return success Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return remaining The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./Moartroller.sol"; import "./AbstractInterestRateModel.sol"; abstract contract MTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @dev EIP-20 token name for this token */ string public name; /** * @dev EIP-20 token symbol for this token */ string public symbol; /** * @dev EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Underlying asset for this MToken */ address public underlying; /** * @dev Maximum borrow rate that can ever be applied (.0005% / block) */ uint internal borrowRateMaxMantissa; /** * @dev Maximum fraction of interest that can be set aside for reserves */ uint internal reserveFactorMaxMantissa; /** * @dev Administrator for this contract */ address payable public admin; /** * @dev Pending administrator for this contract */ address payable public pendingAdmin; /** * @dev Contract which oversees inter-mToken operations */ Moartroller public moartroller; /** * @dev Model which tells what the current interest rate should be */ AbstractInterestRateModel public interestRateModel; /** * @dev Initial exchange rate used when minting the first MTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @dev Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @dev Fraction of reserves currently set aside for other usage */ uint public reserveSplitFactorMantissa; /** * @dev Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @dev Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @dev Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @dev Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @dev Total number of tokens in circulation */ uint public totalSupply; /** * @dev The Maximum Protection Moarosition (MPC) factor for collateral optimisation, default: 50% = 5000 */ uint public maxProtectionComposition; /** * @dev The Maximum Protection Moarosition (MPC) mantissa, default: 1e5 */ uint public maxProtectionCompositionMantissa; /** * @dev Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @dev Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; struct ProtectionUsage { uint256 protectionValueUsed; } /** * @dev Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; mapping (uint256 => ProtectionUsage) protectionsUsed; } struct AccrueInterestTempStorage{ uint interestAccumulated; uint reservesAdded; uint splitedReserves_1; uint splitedReserves_2; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew; } /** * @dev Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) public accountBorrows; } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./EIP20Interface.sol"; interface MTokenInterface { /*** User contract ***/ function transfer(address dst, uint256 amount) external returns (bool); function transferFrom(address src, address dst, uint256 amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function getCash() external view returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); function getUnderlying() external view returns(address); function sweepToken(EIP20Interface token) external; /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint); function _acceptAdmin() external returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; interface MProxyInterface { function proxyClaimReward(address asset, address recipient, uint amount) external; function proxySplitReserves(address asset, uint amount) external; } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./Interfaces/InterestRateModelInterface.sol"; abstract contract AbstractInterestRateModel is InterestRateModelInterface { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; /** * @title Careful Math * @author MOAR * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "../MToken.sol"; import "../Utils/ExponentialNoError.sol"; interface MoartrollerInterface { /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `mTokenBalance` is the number of mTokens the account owns in the market, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountLiquidityLocalVars { uint sumCollateral; uint sumBorrowPlusEffects; uint mTokenBalance; uint borrowBalance; uint exchangeRateMantissa; uint oraclePriceMantissa; ExponentialNoError.Exp collateralFactor; ExponentialNoError.Exp exchangeRate; ExponentialNoError.Exp oraclePrice; ExponentialNoError.Exp tokensToDenom; } /*** Assets You Are In ***/ function enterMarkets(address[] calldata mTokens) external returns (uint[] memory); function exitMarket(address mToken) external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address mToken, address minter, uint mintAmount) external returns (uint); function redeemAllowed(address mToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address mToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address mToken, address borrower, uint borrowAmount) external returns (uint); function repayBorrowAllowed( address mToken, address payer, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowAllowed( address mTokenBorrowed, address mTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function seizeAllowed( address mTokenCollateral, address mTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function transferAllowed(address mToken, address src, address dst, uint transferTokens) external returns (uint); /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeUserTokens( address mTokenBorrowed, address mTokenCollateral, uint repayAmount, address account) external view returns (uint, uint); function getUserLockedAmount(MToken asset, address account) external view returns(uint); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; interface Versionable { function getContractVersion() external pure returns (string memory); } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./MToken.sol"; import "./Interfaces/PriceOracle.sol"; import "./Interfaces/LiquidityMathModelInterface.sol"; import "./Interfaces/LiquidationModelInterface.sol"; import "./MProtection.sol"; abstract contract UnitrollerAdminStorage { /** * @dev Administrator for this contract */ address public admin; /** * @dev Pending administrator for this contract */ address public pendingAdmin; /** * @dev Active brains of Unitroller */ address public moartrollerImplementation; /** * @dev Pending brains of Unitroller */ address public pendingMoartrollerImplementation; } contract MoartrollerV1Storage is UnitrollerAdminStorage { /** * @dev Oracle which gives the price of any given asset */ PriceOracle public oracle; /** * @dev Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint public closeFactorMantissa; /** * @dev Multiplier representing the discount on collateral that a liquidator receives */ uint public liquidationIncentiveMantissa; /** * @dev Max number of assets a single account can participate in (borrow or use as collateral) */ uint public maxAssets; /** * @dev Per-account mapping of "assets you are in", capped by maxAssets */ mapping(address => MToken[]) public accountAssets; } contract MoartrollerV2Storage is MoartrollerV1Storage { struct Market { // Whether or not this market is listed bool isListed; // Multiplier representing the most one can borrow against their collateral in this market. // For instance, 0.9 to allow borrowing 90% of collateral value. // Must be between 0 and 1, and stored as a mantissa. uint collateralFactorMantissa; // Per-market mapping of "accounts in this asset" mapping(address => bool) accountMembership; // Whether or not this market receives MOAR bool isMoared; } /** * @dev Official mapping of mTokens -> Market metadata * @dev Used e.g. to determine if a market is supported */ mapping(address => Market) public markets; /** * @dev The Pause Guardian can pause certain actions as a safety mechanism. * Actions which allow users to remove their own assets cannot be paused. * Liquidation / seizing / transfer can only be paused globally, not by market. */ address public pauseGuardian; bool public _mintGuardianPaused; bool public _borrowGuardianPaused; bool public transferGuardianPaused; bool public seizeGuardianPaused; mapping(address => bool) public mintGuardianPaused; mapping(address => bool) public borrowGuardianPaused; } contract MoartrollerV3Storage is MoartrollerV2Storage { struct MoarMarketState { // The market's last updated moarBorrowIndex or moarSupplyIndex uint224 index; // The block number the index was last updated at uint32 block; } /// @dev A list of all markets MToken[] public allMarkets; /// @dev The rate at which the flywheel distributes MOAR, per block uint public moarRate; /// @dev The portion of moarRate that each market currently receives mapping(address => uint) public moarSpeeds; /// @dev The MOAR market supply state for each market mapping(address => MoarMarketState) public moarSupplyState; /// @dev The MOAR market borrow state for each market mapping(address => MoarMarketState) public moarBorrowState; /// @dev The MOAR borrow index for each market for each supplier as of the last time they accrued MOAR mapping(address => mapping(address => uint)) public moarSupplierIndex; /// @dev The MOAR borrow index for each market for each borrower as of the last time they accrued MOAR mapping(address => mapping(address => uint)) public moarBorrowerIndex; /// @dev The MOAR accrued but not yet transferred to each user mapping(address => uint) public moarAccrued; } contract MoartrollerV4Storage is MoartrollerV3Storage { // @dev The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market. address public borrowCapGuardian; // @dev Borrow caps enforced by borrowAllowed for each mToken address. Defaults to zero which corresponds to unlimited borrowing. mapping(address => uint) public borrowCaps; } contract MoartrollerV5Storage is MoartrollerV4Storage { /// @dev The portion of MOAR that each contributor receives per block mapping(address => uint) public moarContributorSpeeds; /// @dev Last block at which a contributor's MOAR rewards have been allocated mapping(address => uint) public lastContributorBlock; } contract MoartrollerV6Storage is MoartrollerV5Storage { /** * @dev Moar token address */ address public moarToken; /** * @dev MProxy address */ address public mProxy; /** * @dev CProtection contract which can be used for collateral optimisation */ MProtection public cprotection; /** * @dev Mapping for basic token address to mToken */ mapping(address => MToken) public tokenAddressToMToken; /** * @dev Math model for liquidity calculation */ LiquidityMathModelInterface public liquidityMathModel; /** * @dev Liquidation model for liquidation related functions */ LiquidationModelInterface public liquidationModel; /** * @dev List of addresses with privileged access */ mapping(address => uint) public privilegedAddresses; /** * @dev Determines if reward claim feature is enabled */ bool public rewardClaimEnabled; } // Copyright (c) 2020 The UNION Protocol Foundation // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // import "hardhat/console.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; /** * @title UNION Protocol Governance Token * @dev Implementation of the basic standard token. */ contract UnionGovernanceToken is AccessControl, IERC20 { using Address for address; using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; /** * @notice Struct for marking number of votes from a given block * @member from * @member votes */ struct VotingCheckpoint { uint256 from; uint256 votes; } /** * @notice Struct for locked tokens * @member amount * @member releaseTime * @member votable */ struct LockedTokens{ uint amount; uint releaseTime; bool votable; } /** * @notice Struct for EIP712 Domain * @member name * @member version * @member chainId * @member verifyingContract * @member salt */ struct EIP712Domain { string name; string version; uint256 chainId; address verifyingContract; bytes32 salt; } /** * @notice Struct for EIP712 VotingDelegate call * @member owner * @member delegate * @member nonce * @member expirationTime */ struct VotingDelegate { address owner; address delegate; uint256 nonce; uint256 expirationTime; } /** * @notice Struct for EIP712 Permit call * @member owner * @member spender * @member value * @member nonce * @member deadline */ struct Permit { address owner; address spender; uint256 value; uint256 nonce; uint256 deadline; } /** * @notice Vote Delegation Events */ event VotingDelegateChanged(address indexed _owner, address indexed _fromDelegate, address indexed _toDelegate); event VotingDelegateRemoved(address indexed _owner); /** * @notice Vote Balance Events * Emmitted when a delegate account's vote balance changes at the time of a written checkpoint */ event VoteBalanceChanged(address indexed _account, uint256 _oldBalance, uint256 _newBalance); /** * @notice Transfer/Allocator Events */ event TransferStatusChanged(bool _newTransferStatus); /** * @notice Reversion Events */ event ReversionStatusChanged(bool _newReversionSetting); /** * @notice EIP-20 Approval event */ event Approval(address indexed _owner, address indexed _spender, uint256 _value); /** * @notice EIP-20 Transfer event */ event Transfer(address indexed _from, address indexed _to, uint256 _value); event Burn(address indexed _from, uint256 _value); event AddressPermitted(address indexed _account); event AddressRestricted(address indexed _account); /** * @dev AccessControl recognized roles */ bytes32 public constant ROLE_ADMIN = keccak256("ROLE_ADMIN"); bytes32 public constant ROLE_ALLOCATE = keccak256("ROLE_ALLOCATE"); bytes32 public constant ROLE_GOVERN = keccak256("ROLE_GOVERN"); bytes32 public constant ROLE_MINT = keccak256("ROLE_MINT"); bytes32 public constant ROLE_LOCK = keccak256("ROLE_LOCK"); bytes32 public constant ROLE_TRUSTED = keccak256("ROLE_TRUSTED"); bytes32 public constant ROLE_TEST = keccak256("ROLE_TEST"); bytes32 public constant EIP712DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)" ); bytes32 public constant DELEGATE_TYPEHASH = keccak256( "DelegateVote(address owner,address delegate,uint256 nonce,uint256 expirationTime)" ); //keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; address private constant BURN_ADDRESS = address(0); address public UPGT_CONTRACT_ADDRESS; /** * @dev hashes to support EIP-712 signing and validating, EIP712DOMAIN_SEPARATOR is set at time of contract instantiation and token minting. */ bytes32 public immutable EIP712DOMAIN_SEPARATOR; /** * @dev EIP-20 token name */ string public name = "UNION Protocol Governance Token"; /** * @dev EIP-20 token symbol */ string public symbol = "UNN"; /** * @dev EIP-20 token decimals */ uint8 public decimals = 18; /** * @dev Contract version */ string public constant version = '0.0.1'; /** * @dev Initial amount of tokens */ uint256 private uint256_initialSupply = 100000000000 * 10**18; /** * @dev Total amount of tokens */ uint256 private uint256_totalSupply; /** * @dev Chain id */ uint256 private uint256_chain_id; /** * @dev general transfer restricted as function of public sale not complete */ bool private b_canTransfer = false; /** * @dev private variable that determines if failed EIP-20 functions revert() or return false. Reversion short-circuits the return from these functions. */ bool private b_revert = false; //false allows false return values /** * @dev Locked destinations list */ mapping(address => bool) private m_lockedDestinations; /** * @dev EIP-20 allowance and balance maps */ mapping(address => mapping(address => uint256)) private m_allowances; mapping(address => uint256) private m_balances; mapping(address => LockedTokens[]) private m_lockedBalances; /** * @dev nonces used by accounts to this contract for signing and validating signatures under EIP-712 */ mapping(address => uint256) private m_nonces; /** * @dev delegated account may for off-line vote delegation */ mapping(address => address) private m_delegatedAccounts; /** * @dev delegated account inverse map is needed to live calculate voting power */ mapping(address => EnumerableSet.AddressSet) private m_delegatedAccountsInverseMap; /** * @dev indexed mapping of vote checkpoints for each account */ mapping(address => mapping(uint256 => VotingCheckpoint)) private m_votingCheckpoints; /** * @dev mapping of account addrresses to voting checkpoints */ mapping(address => uint256) private m_accountVotingCheckpoints; /** * @dev Contructor for the token * @param _owner address of token contract owner * @param _initialSupply of tokens generated by this contract * Sets Transfer the total suppply to the owner. * Sets default admin role to the owner. * Sets ROLE_ALLOCATE to the owner. * Sets ROLE_GOVERN to the owner. * Sets ROLE_MINT to the owner. * Sets EIP 712 Domain Separator. */ constructor(address _owner, uint256 _initialSupply) public { //set internal contract references UPGT_CONTRACT_ADDRESS = address(this); //setup roles using AccessControl _setupRole(DEFAULT_ADMIN_ROLE, _owner); _setupRole(ROLE_ADMIN, _owner); _setupRole(ROLE_ADMIN, _msgSender()); _setupRole(ROLE_ALLOCATE, _owner); _setupRole(ROLE_ALLOCATE, _msgSender()); _setupRole(ROLE_TRUSTED, _owner); _setupRole(ROLE_TRUSTED, _msgSender()); _setupRole(ROLE_GOVERN, _owner); _setupRole(ROLE_MINT, _owner); _setupRole(ROLE_LOCK, _owner); _setupRole(ROLE_TEST, _owner); m_balances[_owner] = _initialSupply; uint256_totalSupply = _initialSupply; b_canTransfer = false; uint256_chain_id = _getChainId(); EIP712DOMAIN_SEPARATOR = _hash(EIP712Domain({ name : name, version : version, chainId : uint256_chain_id, verifyingContract : address(this), salt : keccak256(abi.encodePacked(name)) } )); emit Transfer(BURN_ADDRESS, _owner, uint256_totalSupply); } /** * @dev Sets transfer status to lock token transfer * @param _canTransfer value can be true or false. * disables transfer when set to false and enables transfer when true * Only a member of ADMIN role can call to change transfer status */ function setCanTransfer(bool _canTransfer) public { if(hasRole(ROLE_ADMIN, _msgSender())){ b_canTransfer = _canTransfer; emit TransferStatusChanged(_canTransfer); } } /** * @dev Gets status of token transfer lock * @return true or false status of whether the token can be transfered */ function getCanTransfer() public view returns (bool) { return b_canTransfer; } /** * @dev Sets transfer reversion status to either return false or throw on error * @param _reversion value can be true or false. * disables return of false values for transfer failures when set to false and enables transfer-related exceptions when true * Only a member of ADMIN role can call to change transfer reversion status */ function setReversion(bool _reversion) public { if(hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TEST, _msgSender()) ) { b_revert = _reversion; emit ReversionStatusChanged(_reversion); } } /** * @dev Gets status of token transfer reversion * @return true or false status of whether the token transfer failures return false or are reverted */ function getReversion() public view returns (bool) { return b_revert; } /** * @dev retrieve current chain id * @return chain id */ function getChainId() public pure returns (uint256) { return _getChainId(); } /** * @dev Retrieve current chain id * @return chain id */ function _getChainId() internal pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * @dev Retrieve total supply of tokens * @return uint256 total supply of tokens */ function totalSupply() public view override returns (uint256) { return uint256_totalSupply; } /** * Balance related functions */ /** * @dev Retrieve balance of a specified account * @param _account address of account holding balance * @return uint256 balance of the specified account address */ function balanceOf(address _account) public view override returns (uint256) { return m_balances[_account].add(_calculateReleasedBalance(_account)); } /** * @dev Retrieve locked balance of a specified account * @param _account address of account holding locked balance * @return uint256 locked balance of the specified account address */ function lockedBalanceOf(address _account) public view returns (uint256) { return _calculateLockedBalance(_account); } /** * @dev Retrieve lenght of locked balance array for specific address * @param _account address of account holding locked balance * @return uint256 locked balance array lenght */ function getLockedTokensListSize(address _account) public view returns (uint256){ require(_msgSender() == _account || hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TRUSTED, _msgSender()), "UPGT_ERROR: insufficient permissions"); return m_lockedBalances[_account].length; } /** * @dev Retrieve locked tokens struct from locked balance array for specific address * @param _account address of account holding locked tokens * @param _index index in array with locked tokens position * @return amount of locked tokens * @return releaseTime descibes time when tokens will be unlocked * @return votable flag is describing votability of tokens */ function getLockedTokens(address _account, uint256 _index) public view returns (uint256 amount, uint256 releaseTime, bool votable){ require(_msgSender() == _account || hasRole(ROLE_ADMIN, _msgSender()) || hasRole(ROLE_TRUSTED, _msgSender()), "UPGT_ERROR: insufficient permissions"); require(_index < m_lockedBalances[_account].length, "UPGT_ERROR: LockedTokens position doesn't exist on given index"); LockedTokens storage lockedTokens = m_lockedBalances[_account][_index]; return (lockedTokens.amount, lockedTokens.releaseTime, lockedTokens.votable); } /** * @dev Calculates locked balance of a specified account * @param _account address of account holding locked balance * @return uint256 locked balance of the specified account address */ function _calculateLockedBalance(address _account) private view returns (uint256) { uint256 lockedBalance = 0; for (uint i=0; i<m_lockedBalances[_account].length; i++) { if(m_lockedBalances[_account][i].releaseTime > block.timestamp){ lockedBalance = lockedBalance.add(m_lockedBalances[_account][i].amount); } } return lockedBalance; } /** * @dev Calculates released balance of a specified account * @param _account address of account holding released balance * @return uint256 released balance of the specified account address */ function _calculateReleasedBalance(address _account) private view returns (uint256) { uint256 releasedBalance = 0; for (uint i=0; i<m_lockedBalances[_account].length; i++) { if(m_lockedBalances[_account][i].releaseTime <= block.timestamp){ releasedBalance = releasedBalance.add(m_lockedBalances[_account][i].amount); } } return releasedBalance; } /** * @dev Calculates locked votable balance of a specified account * @param _account address of account holding locked votable balance * @return uint256 locked votable balance of the specified account address */ function _calculateLockedVotableBalance(address _account) private view returns (uint256) { uint256 lockedVotableBalance = 0; for (uint i=0; i<m_lockedBalances[_account].length; i++) { if(m_lockedBalances[_account][i].votable == true){ lockedVotableBalance = lockedVotableBalance.add(m_lockedBalances[_account][i].amount); } } return lockedVotableBalance; } /** * @dev Moves released balance to normal balance for a specified account * @param _account address of account holding released balance */ function _moveReleasedBalance(address _account) internal virtual{ uint256 releasedToMove = 0; for (uint i=0; i<m_lockedBalances[_account].length; i++) { if(m_lockedBalances[_account][i].releaseTime <= block.timestamp){ releasedToMove = releasedToMove.add(m_lockedBalances[_account][i].amount); m_lockedBalances[_account][i] = m_lockedBalances[_account][m_lockedBalances[_account].length - 1]; m_lockedBalances[_account].pop(); } } m_balances[_account] = m_balances[_account].add(releasedToMove); } /** * Allowance related functinons */ /** * @dev Retrieve the spending allowance for a token holder by a specified account * @param _owner Token account holder * @param _spender Account given allowance * @return uint256 allowance value */ function allowance(address _owner, address _spender) public override virtual view returns (uint256) { return m_allowances[_owner][_spender]; } /** * @dev Message sender approval to spend for a specified amount * @param _spender address of party approved to spend * @param _value amount of the approval * @return boolean success status * public wrapper for _approve, _owner is msg.sender */ function approve(address _spender, uint256 _value) public override returns (bool) { bool success = _approveUNN(_msgSender(), _spender, _value); if(!success && b_revert){ revert("UPGT_ERROR: APPROVE ERROR"); } return success; } /** * @dev Token owner approval of amount for specified spender * @param _owner address of party that owns the tokens being granted approval for spending * @param _spender address of party that is granted approval for spending * @param _value amount approved for spending * @return boolean approval status * if _spender allownace for a given _owner is greater than 0, * increaseAllowance/decreaseAllowance should be used to prevent a race condition whereby the spender is able to spend the total value of both the old and new allowance. _spender cannot be burn or this governance token contract address. Addresses github.com/ethereum/EIPs/issues738 */ function _approveUNN(address _owner, address _spender, uint256 _value) internal returns (bool) { bool retval = false; if(_spender != BURN_ADDRESS && _spender != UPGT_CONTRACT_ADDRESS && (m_allowances[_owner][_spender] == 0 || _value == 0) ){ m_allowances[_owner][_spender] = _value; emit Approval(_owner, _spender, _value); retval = true; } return retval; } /** * @dev Increase spender allowance by specified incremental value * @param _spender address of party that is granted approval for spending * @param _addedValue specified incremental increase * @return boolean increaseAllowance status * public wrapper for _increaseAllowance, _owner restricted to msg.sender */ function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) { bool success = _increaseAllowanceUNN(_msgSender(), _spender, _addedValue); if(!success && b_revert){ revert("UPGT_ERROR: INCREASE ALLOWANCE ERROR"); } return success; } /** * @dev Allow owner to increase spender allowance by specified incremental value * @param _owner address of the token owner * @param _spender address of the token spender * @param _addedValue specified incremental increase * @return boolean return value status * increase the number of tokens that an _owner provides as allowance to a _spender-- does not requrire the number of tokens allowed to be set first to 0. _spender cannot be either burn or this goverance token contract address. */ function _increaseAllowanceUNN(address _owner, address _spender, uint256 _addedValue) internal returns (bool) { bool retval = false; if(_spender != BURN_ADDRESS && _spender != UPGT_CONTRACT_ADDRESS && _addedValue > 0 ){ m_allowances[_owner][_spender] = m_allowances[_owner][_spender].add(_addedValue); retval = true; emit Approval(_owner, _spender, m_allowances[_owner][_spender]); } return retval; } /** * @dev Decrease spender allowance by specified incremental value * @param _spender address of party that is granted approval for spending * @param _subtractedValue specified incremental decrease * @return boolean success status * public wrapper for _decreaseAllowance, _owner restricted to msg.sender */ //public wrapper for _decreaseAllowance, _owner restricted to msg.sender function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) { bool success = _decreaseAllowanceUNN(_msgSender(), _spender, _subtractedValue); if(!success && b_revert){ revert("UPGT_ERROR: DECREASE ALLOWANCE ERROR"); } return success; } /** * @dev Allow owner to decrease spender allowance by specified incremental value * @param _owner address of the token owner * @param _spender address of the token spender * @param _subtractedValue specified incremental decrease * @return boolean return value status * decrease the number of tokens than an _owner provdes as allowance to a _spender. A _spender cannot have a negative allowance. Does not require existing allowance to be set first to 0. _spender cannot be burn or this governance token contract address. */ function _decreaseAllowanceUNN(address _owner, address _spender, uint256 _subtractedValue) internal returns (bool) { bool retval = false; if(_spender != BURN_ADDRESS && _spender != UPGT_CONTRACT_ADDRESS && _subtractedValue > 0 && m_allowances[_owner][_spender] >= _subtractedValue ){ m_allowances[_owner][_spender] = m_allowances[_owner][_spender].sub(_subtractedValue); retval = true; emit Approval(_owner, _spender, m_allowances[_owner][_spender]); } return retval; } /** * LockedDestination related functions */ /** * @dev Adds address as a designated destination for tokens when locked for allocation only * @param _address Address of approved desitnation for movement during lock * @return success in setting address as eligible for transfer independent of token lock status */ function setAsEligibleLockedDestination(address _address) public returns (bool) { bool retVal = false; if(hasRole(ROLE_ADMIN, _msgSender())){ m_lockedDestinations[_address] = true; retVal = true; } return retVal; } /** * @dev removes desitnation as eligible for transfer * @param _address address being removed */ function removeEligibleLockedDestination(address _address) public { if(hasRole(ROLE_ADMIN, _msgSender())){ require(_address != BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address"); delete(m_lockedDestinations[_address]); } } /** * @dev checks whether a destination is eligible as recipient of transfer independent of token lock status * @param _address address being checked * @return whether desitnation is locked */ function checkEligibleLockedDesination(address _address) public view returns (bool) { return m_lockedDestinations[_address]; } /** * @dev Adds address as a designated allocator that can move tokens when they are locked * @param _address Address receiving the role of ROLE_ALLOCATE * @return success as true or false */ function setAsAllocator(address _address) public returns (bool) { bool retVal = false; if(hasRole(ROLE_ADMIN, _msgSender())){ grantRole(ROLE_ALLOCATE, _address); retVal = true; } return retVal; } /** * @dev Removes address as a designated allocator that can move tokens when they are locked * @param _address Address being removed from the ROLE_ALLOCATE * @return success as true or false */ function removeAsAllocator(address _address) public returns (bool) { bool retVal = false; if(hasRole(ROLE_ADMIN, _msgSender())){ if(hasRole(ROLE_ALLOCATE, _address)){ revokeRole(ROLE_ALLOCATE, _address); retVal = true; } } return retVal; } /** * @dev Checks to see if an address has the role of being an allocator * @param _address Address being checked for ROLE_ALLOCATE * @return true or false whether the address has ROLE_ALLOCATE assigned */ function checkAsAllocator(address _address) public view returns (bool) { return hasRole(ROLE_ALLOCATE, _address); } /** * Transfer related functions */ /** * @dev Public wrapper for transfer function to move tokens of specified value to a given address * @param _to specified recipient * @param _value amount being transfered to recipient * @return status of transfer success */ function transfer(address _to, uint256 _value) external override returns (bool) { bool success = _transferUNN(_msgSender(), _to, _value); if(!success && b_revert){ revert("UPGT_ERROR: ERROR ON TRANSFER"); } return success; } /** * @dev Transfer token for a specified address, but cannot transfer tokens to either the burn or this governance contract address. Also moves voting delegates as required. * @param _owner The address owner where transfer originates * @param _to The address to transfer to * @param _value The amount to be transferred * @return status of transfer success */ function _transferUNN(address _owner, address _to, uint256 _value) internal returns (bool) { bool retval = false; if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) { if( _to != BURN_ADDRESS && _to != UPGT_CONTRACT_ADDRESS && (balanceOf(_owner) >= _value) && (_value >= 0) ){ _moveReleasedBalance(_owner); m_balances[_owner] = m_balances[_owner].sub(_value); m_balances[_to] = m_balances[_to].add(_value); retval = true; //need to move voting delegates with transfer of tokens retval = retval && _moveVotingDelegates(m_delegatedAccounts[_owner], m_delegatedAccounts[_to], _value); emit Transfer(_owner, _to, _value); } } return retval; } /** * @dev Public wrapper for transferAndLock function to move tokens of specified value to a given address and lock them for a period of time * @param _to specified recipient * @param _value amount being transfered to recipient * @param _releaseTime time in seconds after amount will be released * @param _votable flag which describes if locked tokens are votable or not * @return status of transfer success * Requires ROLE_LOCK */ function transferAndLock(address _to, uint256 _value, uint256 _releaseTime, bool _votable) public virtual returns (bool) { bool retval = false; if(hasRole(ROLE_LOCK, _msgSender())){ retval = _transferAndLock(msg.sender, _to, _value, _releaseTime, _votable); } if(!retval && b_revert){ revert("UPGT_ERROR: ERROR ON TRANSFER AND LOCK"); } return retval; } /** * @dev Transfers tokens of specified value to a given address and lock them for a period of time * @param _owner The address owner where transfer originates * @param _to specified recipient * @param _value amount being transfered to recipient * @param _releaseTime time in seconds after amount will be released * @param _votable flag which describes if locked tokens are votable or not * @return status of transfer success */ function _transferAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) internal virtual returns (bool){ bool retval = false; if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) { if( _to != BURN_ADDRESS && _to != UPGT_CONTRACT_ADDRESS && (balanceOf(_owner) >= _value) && (_value >= 0) ){ _moveReleasedBalance(_owner); m_balances[_owner] = m_balances[_owner].sub(_value); m_lockedBalances[_to].push(LockedTokens(_value, _releaseTime, _votable)); retval = true; //need to move voting delegates with transfer of tokens // retval = retval && _moveVotingDelegates(m_delegatedAccounts[_owner], m_delegatedAccounts[_to], _value); emit Transfer(_owner, _to, _value); } } return retval; } /** * @dev Public wrapper for transferFrom function * @param _owner The address to transfer from * @param _spender cannot be the burn address * @param _value The amount to be transferred * @return status of transferFrom success * _spender cannot be either this goverance token contract or burn */ function transferFrom(address _owner, address _spender, uint256 _value) external override returns (bool) { bool success = _transferFromUNN(_owner, _spender, _value); if(!success && b_revert){ revert("UPGT_ERROR: ERROR ON TRANSFER FROM"); } return success; } /** * @dev Transfer token for a specified address. _spender cannot be either this goverance token contract or burn * @param _owner The address to transfer from * @param _spender cannot be the burn address * @param _value The amount to be transferred * @return status of transferFrom success * _spender cannot be either this goverance token contract or burn */ function _transferFromUNN(address _owner, address _spender, uint256 _value) internal returns (bool) { bool retval = false; if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_spender)) { if( _spender != BURN_ADDRESS && _spender != UPGT_CONTRACT_ADDRESS && (balanceOf(_owner) >= _value) && (_value > 0) && (m_allowances[_owner][_msgSender()] >= _value) ){ _moveReleasedBalance(_owner); m_balances[_owner] = m_balances[_owner].sub(_value); m_balances[_spender] = m_balances[_spender].add(_value); m_allowances[_owner][_msgSender()] = m_allowances[_owner][_msgSender()].sub(_value); retval = true; //need to move delegates that exist for this owner in line with transfer retval = retval && _moveVotingDelegates(_owner, _spender, _value); emit Transfer(_owner, _spender, _value); } } return retval; } /** * @dev Public wrapper for transferFromAndLock function to move tokens of specified value from given address to another address and lock them for a period of time * @param _owner The address owner where transfer originates * @param _to specified recipient * @param _value amount being transfered to recipient * @param _releaseTime time in seconds after amount will be released * @param _votable flag which describes if locked tokens are votable or not * @return status of transfer success * Requires ROLE_LOCK */ function transferFromAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) public virtual returns (bool) { bool retval = false; if(hasRole(ROLE_LOCK, _msgSender())){ retval = _transferFromAndLock(_owner, _to, _value, _releaseTime, _votable); } if(!retval && b_revert){ revert("UPGT_ERROR: ERROR ON TRANSFER FROM AND LOCK"); } return retval; } /** * @dev Transfers tokens of specified value from a given address to another address and lock them for a period of time * @param _owner The address owner where transfer originates * @param _to specified recipient * @param _value amount being transfered to recipient * @param _releaseTime time in seconds after amount will be released * @param _votable flag which describes if locked tokens are votable or not * @return status of transfer success */ function _transferFromAndLock(address _owner, address _to, uint256 _value, uint256 _releaseTime, bool _votable) internal returns (bool) { bool retval = false; if(b_canTransfer || hasRole(ROLE_ALLOCATE, _msgSender()) || checkEligibleLockedDesination(_to)) { if( _to != BURN_ADDRESS && _to != UPGT_CONTRACT_ADDRESS && (balanceOf(_owner) >= _value) && (_value > 0) && (m_allowances[_owner][_msgSender()] >= _value) ){ _moveReleasedBalance(_owner); m_balances[_owner] = m_balances[_owner].sub(_value); m_lockedBalances[_to].push(LockedTokens(_value, _releaseTime, _votable)); m_allowances[_owner][_msgSender()] = m_allowances[_owner][_msgSender()].sub(_value); retval = true; //need to move delegates that exist for this owner in line with transfer // retval = retval && _moveVotingDelegates(_owner, _to, _value); emit Transfer(_owner, _to, _value); } } return retval; } /** * @dev Public function to burn tokens * @param _value number of tokens to be burned * @return whether tokens were burned * Only ROLE_MINTER may burn tokens */ function burn(uint256 _value) external returns (bool) { bool success = _burn(_value); if(!success && b_revert){ revert("UPGT_ERROR: FAILED TO BURN"); } return success; } /** * @dev Private function Burn tokens * @param _value number of tokens to be burned * @return bool whether the tokens were burned * only a minter may burn tokens, meaning that tokens being burned must be previously send to a ROLE_MINTER wallet. */ function _burn(uint256 _value) internal returns (bool) { bool retval = false; if(hasRole(ROLE_MINT, _msgSender()) && (m_balances[_msgSender()] >= _value) ){ m_balances[_msgSender()] -= _value; uint256_totalSupply = uint256_totalSupply.sub(_value); retval = true; emit Burn(_msgSender(), _value); } return retval; } /** * Voting related functions */ /** * @dev Public wrapper for _calculateVotingPower function which calulates voting power * @dev voting power = balance + locked votable balance + delegations * @return uint256 voting power */ function calculateVotingPower() public view returns (uint256) { return _calculateVotingPower(_msgSender()); } /** * @dev Calulates voting power of specified address * @param _account address of token holder * @return uint256 voting power */ function _calculateVotingPower(address _account) private view returns (uint256) { uint256 votingPower = m_balances[_account].add(_calculateLockedVotableBalance(_account)); for (uint i=0; i<m_delegatedAccountsInverseMap[_account].length(); i++) { if(m_delegatedAccountsInverseMap[_account].at(i) != address(0)){ address delegatedAccount = m_delegatedAccountsInverseMap[_account].at(i); votingPower = votingPower.add(m_balances[delegatedAccount]).add(_calculateLockedVotableBalance(delegatedAccount)); } } return votingPower; } /** * @dev Moves a number of votes from a token holder to a designated representative * @param _source address of token holder * @param _destination address of voting delegate * @param _amount of voting delegation transfered to designated representative * @return bool whether move was successful * Requires ROLE_TEST */ function moveVotingDelegates( address _source, address _destination, uint256 _amount) public returns (bool) { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); return _moveVotingDelegates(_source, _destination, _amount); } /** * @dev Moves a number of votes from a token holder to a designated representative * @param _source address of token holder * @param _destination address of voting delegate * @param _amount of voting delegation transfered to designated representative * @return bool whether move was successful */ function _moveVotingDelegates( address _source, address _destination, uint256 _amount ) internal returns (bool) { if(_source != _destination && _amount > 0) { if(_source != BURN_ADDRESS) { uint256 sourceNumberOfVotingCheckpoints = m_accountVotingCheckpoints[_source]; uint256 sourceNumberOfVotingCheckpointsOriginal = (sourceNumberOfVotingCheckpoints > 0)? m_votingCheckpoints[_source][sourceNumberOfVotingCheckpoints.sub(1)].votes : 0; if(sourceNumberOfVotingCheckpointsOriginal >= _amount) { uint256 sourceNumberOfVotingCheckpointsNew = sourceNumberOfVotingCheckpointsOriginal.sub(_amount); _writeVotingCheckpoint(_source, sourceNumberOfVotingCheckpoints, sourceNumberOfVotingCheckpointsOriginal, sourceNumberOfVotingCheckpointsNew); } } if(_destination != BURN_ADDRESS) { uint256 destinationNumberOfVotingCheckpoints = m_accountVotingCheckpoints[_destination]; uint256 destinationNumberOfVotingCheckpointsOriginal = (destinationNumberOfVotingCheckpoints > 0)? m_votingCheckpoints[_source][destinationNumberOfVotingCheckpoints.sub(1)].votes : 0; uint256 destinationNumberOfVotingCheckpointsNew = destinationNumberOfVotingCheckpointsOriginal.add(_amount); _writeVotingCheckpoint(_destination, destinationNumberOfVotingCheckpoints, destinationNumberOfVotingCheckpointsOriginal, destinationNumberOfVotingCheckpointsNew); } } return true; } /** * @dev Writes voting checkpoint for a given voting delegate * @param _votingDelegate exercising votes * @param _numberOfVotingCheckpoints number of voting checkpoints for current vote * @param _oldVotes previous number of votes * @param _newVotes new number of votes * Public function for writing voting checkpoint * Requires ROLE_TEST */ function writeVotingCheckpoint( address _votingDelegate, uint256 _numberOfVotingCheckpoints, uint256 _oldVotes, uint256 _newVotes) public { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); _writeVotingCheckpoint(_votingDelegate, _numberOfVotingCheckpoints, _oldVotes, _newVotes); } /** * @dev Writes voting checkpoint for a given voting delegate * @param _votingDelegate exercising votes * @param _numberOfVotingCheckpoints number of voting checkpoints for current vote * @param _oldVotes previous number of votes * @param _newVotes new number of votes * Private function for writing voting checkpoint */ function _writeVotingCheckpoint( address _votingDelegate, uint256 _numberOfVotingCheckpoints, uint256 _oldVotes, uint256 _newVotes) internal { if(_numberOfVotingCheckpoints > 0 && m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints.sub(1)].from == block.number) { m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints-1].votes = _newVotes; } else { m_votingCheckpoints[_votingDelegate][_numberOfVotingCheckpoints] = VotingCheckpoint(block.number, _newVotes); _numberOfVotingCheckpoints = _numberOfVotingCheckpoints.add(1); } emit VoteBalanceChanged(_votingDelegate, _oldVotes, _newVotes); } /** * @dev Calculate account votes as of a specific block * @param _account address whose votes are counted * @param _blockNumber from which votes are being counted * @return number of votes counted */ function getVoteCountAtBlock( address _account, uint256 _blockNumber) public view returns (uint256) { uint256 voteCount = 0; if(_blockNumber < block.number) { if(m_accountVotingCheckpoints[_account] != 0) { if(m_votingCheckpoints[_account][m_accountVotingCheckpoints[_account].sub(1)].from <= _blockNumber) { voteCount = m_votingCheckpoints[_account][m_accountVotingCheckpoints[_account].sub(1)].votes; } else if(m_votingCheckpoints[_account][0].from > _blockNumber) { voteCount = 0; } else { uint256 lower = 0; uint256 upper = m_accountVotingCheckpoints[_account].sub(1); while(upper > lower) { uint256 center = upper.sub((upper.sub(lower).div(2))); VotingCheckpoint memory votingCheckpoint = m_votingCheckpoints[_account][center]; if(votingCheckpoint.from == _blockNumber) { voteCount = votingCheckpoint.votes; break; } else if(votingCheckpoint.from < _blockNumber) { lower = center; } else { upper = center.sub(1); } } } } } return voteCount; } /** * @dev Vote Delegation Functions * @param _to address where message sender is assigning votes * @return success of message sender delegating vote * delegate function does not allow assignment to burn */ function delegateVote(address _to) public returns (bool) { return _delegateVote(_msgSender(), _to); } /** * @dev Delegate votes from token holder to another address * @param _from Token holder * @param _toDelegate Address that will be delegated to for purpose of voting * @return success as to whether delegation has been a success */ function _delegateVote( address _from, address _toDelegate) internal returns (bool) { bool retval = false; if(_toDelegate != BURN_ADDRESS) { address currentDelegate = m_delegatedAccounts[_from]; uint256 fromAccountBalance = m_balances[_from].add(_calculateLockedVotableBalance(_from)); address oldToDelegate = m_delegatedAccounts[_from]; m_delegatedAccounts[_from] = _toDelegate; m_delegatedAccountsInverseMap[oldToDelegate].remove(_from); if(_from != _toDelegate){ m_delegatedAccountsInverseMap[_toDelegate].add(_from); } retval = true; retval = retval && _moveVotingDelegates(currentDelegate, _toDelegate, fromAccountBalance); if(retval) { if(_from == _toDelegate){ emit VotingDelegateRemoved(_from); } else{ emit VotingDelegateChanged(_from, currentDelegate, _toDelegate); } } } return retval; } /** * @dev Revert voting delegate control to owner account * @param _account The account that has delegated its vote * @return success of reverting delegation to owner */ function _revertVotingDelegationToOwner(address _account) internal returns (bool) { return _delegateVote(_account, _account); } /** * @dev Used by an message sending account to recall its voting delegates * @return success of reverting delegation to owner */ function recallVotingDelegate() public returns (bool) { return _revertVotingDelegationToOwner(_msgSender()); } /** * @dev Retrieve the voting delegate for a specified account * @param _account The account that has delegated its vote */ function getVotingDelegate(address _account) public view returns (address) { return m_delegatedAccounts[_account]; } /** * EIP-712 related functions */ /** * @dev EIP-712 Ethereum Typed Structured Data Hashing and Signing for Allocation Permit * @param _owner address of token owner * @param _spender address of designated spender * @param _value value permitted for spend * @param _deadline expiration of signature * @param _ecv ECDSA v parameter * @param _ecr ECDSA r parameter * @param _ecs ECDSA s parameter */ function permit( address _owner, address _spender, uint256 _value, uint256 _deadline, uint8 _ecv, bytes32 _ecr, bytes32 _ecs ) external returns (bool) { require(block.timestamp <= _deadline, "UPGT_ERROR: wrong timestamp"); require(uint256_chain_id == _getChainId(), "UPGT_ERROR: chain_id is incorrect"); bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", EIP712DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, _owner, _spender, _value, m_nonces[_owner]++, _deadline)) ) ); require(_owner == _recoverSigner(digest, _ecv, _ecr, _ecs), "UPGT_ERROR: sign does not match user"); require(_owner != BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address"); return _approveUNN(_owner, _spender, _value); } /** * @dev EIP-712 ETH Typed Structured Data Hashing and Signing for Delegate Vote * @param _owner address of token owner * @param _delegate address of voting delegate * @param _expiretimestamp expiration of delegation signature * @param _ecv ECDSA v parameter * @param _ecr ECDSA r parameter * @param _ecs ECDSA s parameter * @ @return bool true or false depedening on whether vote was successfully delegated */ function delegateVoteBySignature( address _owner, address _delegate, uint256 _expiretimestamp, uint8 _ecv, bytes32 _ecr, bytes32 _ecs ) external returns (bool) { require(block.timestamp <= _expiretimestamp, "UPGT_ERROR: wrong timestamp"); require(uint256_chain_id == _getChainId(), "UPGT_ERROR: chain_id is incorrect"); bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", EIP712DOMAIN_SEPARATOR, _hash(VotingDelegate( { owner : _owner, delegate : _delegate, nonce : m_nonces[_owner]++, expirationTime : _expiretimestamp }) ) ) ); require(_owner == _recoverSigner(digest, _ecv, _ecr, _ecs), "UPGT_ERROR: sign does not match user"); require(_owner!= BURN_ADDRESS, "UPGT_ERROR: address cannot be burn address"); return _delegateVote(_owner, _delegate); } /** * @dev Public hash EIP712Domain struct for EIP-712 * @param _eip712Domain EIP712Domain struct * @return bytes32 hash of _eip712Domain * Requires ROLE_TEST */ function hashEIP712Domain(EIP712Domain memory _eip712Domain) public view returns (bytes32) { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); return _hash(_eip712Domain); } /** * @dev Hash Delegate struct for EIP-712 * @param _delegate VotingDelegate struct * @return bytes32 hash of _delegate * Requires ROLE_TEST */ function hashDelegate(VotingDelegate memory _delegate) public view returns (bytes32) { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); return _hash(_delegate); } /** * @dev Public hash Permit struct for EIP-712 * @param _permit Permit struct * @return bytes32 hash of _permit * Requires ROLE_TEST */ function hashPermit(Permit memory _permit) public view returns (bytes32) { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); return _hash(_permit); } /** * @param _digest signed, hashed message * @param _ecv ECDSA v parameter * @param _ecr ECDSA r parameter * @param _ecs ECDSA s parameter * @return address of the validated signer * based on openzeppelin/contracts/cryptography/ECDSA.sol recover() function * Requires ROLE_TEST */ function recoverSigner(bytes32 _digest, uint8 _ecv, bytes32 _ecr, bytes32 _ecs) public view returns (address) { require(hasRole(ROLE_TEST, _msgSender()), "UPGT_ERROR: ROLE_TEST Required"); return _recoverSigner(_digest, _ecv, _ecr, _ecs); } /** * @dev Private hash EIP712Domain struct for EIP-712 * @param _eip712Domain EIP712Domain struct * @return bytes32 hash of _eip712Domain */ function _hash(EIP712Domain memory _eip712Domain) internal pure returns (bytes32) { return keccak256( abi.encode( EIP712DOMAIN_TYPEHASH, keccak256(bytes(_eip712Domain.name)), keccak256(bytes(_eip712Domain.version)), _eip712Domain.chainId, _eip712Domain.verifyingContract, _eip712Domain.salt ) ); } /** * @dev Private hash Delegate struct for EIP-712 * @param _delegate VotingDelegate struct * @return bytes32 hash of _delegate */ function _hash(VotingDelegate memory _delegate) internal pure returns (bytes32) { return keccak256( abi.encode( DELEGATE_TYPEHASH, _delegate.owner, _delegate.delegate, _delegate.nonce, _delegate.expirationTime ) ); } /** * @dev Private hash Permit struct for EIP-712 * @param _permit Permit struct * @return bytes32 hash of _permit */ function _hash(Permit memory _permit) internal pure returns (bytes32) { return keccak256(abi.encode( PERMIT_TYPEHASH, _permit.owner, _permit.spender, _permit.value, _permit.nonce, _permit.deadline )); } /** * @dev Recover signer information from provided digest * @param _digest signed, hashed message * @param _ecv ECDSA v parameter * @param _ecr ECDSA r parameter * @param _ecs ECDSA s parameter * @return address of the validated signer * based on openzeppelin/contracts/cryptography/ECDSA.sol recover() function */ function _recoverSigner(bytes32 _digest, uint8 _ecv, bytes32 _ecr, bytes32 _ecs) internal pure returns (address) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if(uint256(_ecs) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if(_ecv != 27 && _ecv != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(_digest, _ecv, _ecr, _ecs); require(signer != BURN_ADDRESS, "ECDSA: invalid signature"); return signer; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../Interfaces/EIP20Interface.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /** * @title SafeEIP20 * @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. * This is a forked version of Openzeppelin's SafeERC20 contract but supporting * EIP20Interface instead of Openzeppelin's IERC20 * 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 SafeEIP20 { using SafeMath for uint256; using Address for address; function safeTransfer(EIP20Interface token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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(EIP20Interface 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 experimental ABIEncoderV2; import "./PriceOracle.sol"; import "./MoartrollerInterface.sol"; pragma solidity ^0.6.12; interface LiquidationModelInterface { function liquidateCalculateSeizeUserTokens(LiquidateCalculateSeizeUserTokensArgumentsSet memory arguments) external view returns (uint, uint); function liquidateCalculateSeizeTokens(LiquidateCalculateSeizeUserTokensArgumentsSet memory arguments) external view returns (uint, uint); struct LiquidateCalculateSeizeUserTokensArgumentsSet { PriceOracle oracle; MoartrollerInterface moartroller; address mTokenBorrowed; address mTokenCollateral; uint actualRepayAmount; address accountForLiquidation; uint liquidationIncentiveMantissa; } } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; /** * @title MOAR's InterestRateModel Interface * @author MOAR */ interface InterestRateModelInterface { /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC721Upgradeable.sol"; import "./IERC721MetadataUpgradeable.sol"; import "./IERC721EnumerableUpgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "../../introspection/ERC165Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/EnumerableSetUpgradeable.sol"; import "../../utils/EnumerableMapUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable, IERC721EnumerableUpgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet; using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap; using StringsUpgradeable for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSetUpgradeable.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMapUpgradeable.UintToAddressMap private _tokenOwners; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721Upgradeable.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721Upgradeable.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (!to.isContract()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721ReceiverUpgradeable(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); // internal owner } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } uint256[41] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; interface CopMappingInterface { function getTokenAddress() external view returns (address); function getProtectionData(uint256 underlyingTokenId) external view returns (address, uint256, uint256, uint256, uint, uint); function getUnderlyingAsset(uint256 underlyingTokenId) external view returns (address); function getUnderlyingAmount(uint256 underlyingTokenId) external view returns (uint256); function getUnderlyingStrikePrice(uint256 underlyingTokenId) external view returns (uint); function getUnderlyingDeadline(uint256 underlyingTokenId) external view returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; 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 pragma solidity >=0.6.2 <0.8.0; import "./IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 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.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165Upgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMapUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev String operations. */ library StringsUpgradeable { /** * @dev Converts a `uint256` to its ASCII `string` representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "./MToken.sol"; import "./Interfaces/MErc20Interface.sol"; import "./Moartroller.sol"; import "./AbstractInterestRateModel.sol"; import "./Interfaces/EIP20Interface.sol"; import "./Utils/SafeEIP20.sol"; /** * @title MOAR's MErc20 Contract * @notice MTokens which wrap an EIP-20 underlying */ contract MErc20 is MToken, MErc20Interface { using SafeEIP20 for EIP20Interface; /** * @notice Initialize the new money market * @param underlying_ The address of the underlying asset * @param moartroller_ The address of the Moartroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function init(address underlying_, Moartroller moartroller_, AbstractInterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { // MToken initialize does the bulk of the work super.init(moartroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_); // Set underlying and sanity check it underlying = underlying_; EIP20Interface(underlying).totalSupply(); } /*** User Interface ***/ /** * @notice Sender supplies assets into the market and receives mTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external override returns (uint) { (uint err,) = mintInternal(mintAmount); return err; } /** * @notice Sender redeems mTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of mTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external override returns (uint) { return redeemInternal(redeemTokens); } /** * @notice Sender redeems mTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external override returns (uint) { return redeemUnderlyingInternal(redeemAmount); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external override returns (uint) { return borrowInternal(borrowAmount); } function borrowFor(address payable borrower, uint borrowAmount) external override returns (uint) { return borrowForInternal(borrower, borrowAmount); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external override returns (uint) { (uint err,) = repayBorrowInternal(repayAmount); return err; } /** * @notice Sender repays a borrow belonging to borrower. * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint repayAmount) external override returns (uint) { (uint err,) = repayBorrowBehalfInternal(borrower, repayAmount); return err; } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this mToken to be liquidated * @param repayAmount The amount of the underlying borrowed asset to repay * @param mTokenCollateral The market in which to seize collateral from the borrower * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, MToken mTokenCollateral) external override returns (uint) { (uint err,) = liquidateBorrowInternal(borrower, repayAmount, mTokenCollateral); return err; } /** * @notice A public function to sweep accidental ERC-20 transfers to this contract. Tokens are sent to admin (timelock) * @param token The address of the ERC-20 token to sweep */ function sweepToken(EIP20Interface token) override external { require(address(token) != underlying, "MErc20::sweepToken: can not sweep underlying token"); uint256 balance = token.balanceOf(address(this)); token.safeTransfer(admin, balance); } /** * @notice The sender adds to reserves. * @param addAmount The amount fo underlying token to add as reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external override returns (uint) { return _addReservesInternal(addAmount); } /*** Safe Token ***/ /** * @notice Gets balance of this contract in terms of the underlying * @dev This excludes the value of the current message, if any * @return The quantity of underlying tokens owned by this contract */ function getCashPrior() internal override view returns (uint) { EIP20Interface token = EIP20Interface(underlying); return token.balanceOf(address(this)); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case. * This will revert due to insufficient balance or insufficient allowance. * This function returns the actual amount received, * which may be less than `amount` if there is a fee attached to the transfer. *` * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address from, uint amount) internal override returns (uint) { EIP20Interface token = EIP20Interface(underlying); uint balanceBefore = token.balanceOf(address(this)); token.safeTransferFrom(from, address(this), amount); // Calculate the amount that was *actually* transferred uint balanceAfter = token.balanceOf(address(this)); require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW"); return balanceAfter - balanceBefore; // underflow already checked above, just subtract } /** * @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address payable to, uint amount) internal override { EIP20Interface token = EIP20Interface(underlying); token.safeTransfer(to, amount); } } // SPDX-License-Identifier: BSD-3-Clause pragma solidity ^0.6.12; import "../MToken.sol"; interface MErc20Interface { /*** User contract ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function borrowFor(address payable borrower, uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, MToken mTokenCollateral) external returns (uint); /*** Admin Functions ***/ function _addReserves(uint addAmount) external returns (uint); }
Sets new value for max protection composition parameter newMPC New value of MPC return uint 0=success, otherwise a failure/
function _setMaxProtectionComposition(uint256 newMPC) external returns(uint){ if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK); } maxProtectionComposition = newMPC; emit MpcUpdated(newMPC); return uint(Error.NO_ERROR); }
11,818,159
./full_match/1/0x6C32D8DC35A4063E0AD3AAC756111e462eA38D27/sources/contracts/periphery/utils/AvailableRootsRegistry.sol
Unregister a root, available for all contracts root Root to unregister/
function unregisterRootForAll(uint256 root) external onlyOwner { _unregisterRootForAttester(address(0), root); }
3,849,621
pragma solidity ^0.4.13; contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 public rate; // Amount of wei raised uint256 public weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); /** * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ constructor(uint256 _rate, address _wallet, ERC20 _token) public { require(_rate > 0); require(_wallet != address(0)); require(_token != address(0)); rate = _rate; wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); _processPurchase(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens( address _beneficiary, uint256 _tokenAmount ) internal { token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase( address _beneficiary, uint256 _tokenAmount ) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState( address _beneficiary, uint256 _weiAmount ) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } 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; } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract WhitelistedCrowdsale is Crowdsale, Ownable { mapping(address => bool) public whitelist; /** * @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract. */ modifier isWhitelisted(address _beneficiary) { require(whitelist[_beneficiary]); _; } /** * @dev Adds single address to whitelist. * @param _beneficiary Address to be added to the whitelist */ function addToWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = true; } /** * @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. * @param _beneficiaries Addresses to be added to the whitelist */ function addManyToWhitelist(address[] _beneficiaries) external onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; } } /** * @dev Removes single address from whitelist. * @param _beneficiary Address to be removed to the whitelist */ function removeFromWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = false; } /** * @dev Extend parent behavior requiring beneficiary to be in whitelist. * @param _beneficiary Token beneficiary * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase( address _beneficiary, uint256 _weiAmount ) internal isWhitelisted(_beneficiary) { super._preValidatePurchase(_beneficiary, _weiAmount); } } 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(); } } contract OMICrowdsale is WhitelistedCrowdsale, Pausable { using SafeMath for uint256; /* * Constants */ uint256 constant crowdsaleStartTime = 1530273600; // Pacific/Auckland 2018-06-30 00:00:00 uint256 constant crowdsaleFinishTime = 1538222400; // Pacific/Auckland 2018-09-30 00:00:00 uint256 constant crowdsaleUSDGoal = 22125000; uint256 constant crowdsaleTokenGoal = 362500000*1e18; uint256 constant minimumTokenPurchase = 2500*1e18; uint256 constant maximumTokenPurchase = 5000000*1e18; /* * Storage */ OMIToken public token; OMITokenLock public tokenLock; uint256 public totalUSDRaised; uint256 public totalTokensSold; bool public isFinalized = false; mapping(address => uint256) public purchaseRecords; /* * Events */ event RateChanged(uint256 newRate); event USDRaisedUpdated(uint256 newTotal); event WhitelistAddressAdded(address newWhitelistAddress); event WhitelistAddressRemoved(address removedWhitelistAddress); event CrowdsaleStarted(); event CrowdsaleFinished(); /* * Modifiers */ modifier whenNotFinalized () { require(!isFinalized); _; } /* * Public Functions */ /// @dev Contract constructor sets... function OMICrowdsale ( uint256 _startingRate, address _ETHWallet, address _OMIToken, address _OMITokenLock ) Crowdsale(_startingRate, _ETHWallet, ERC20(_OMIToken)) public { token = OMIToken(_OMIToken); require(token.isOMITokenContract()); tokenLock = OMITokenLock(_OMITokenLock); require(tokenLock.isOMITokenLockContract()); rate = _startingRate; } /// @dev Function to call from other contracts to ensure that this is the proper contract function isOMICrowdsaleContract() public pure returns(bool) { return true; } /// @dev Function to check if crowdsale is open function isOpen() public view whenNotPaused whenNotFinalized returns(bool) { return now >= crowdsaleStartTime; } /// @dev Allows the owner to set the current rate for calculating the number of tokens for a purchase. /// @dev An external cron job will fetch the ETH/USD daily average from the cryptocompare API and call this function. function setRate(uint256 _newRate) public onlyOwner whenNotFinalized returns(bool) { require(_newRate > 0); rate = _newRate; RateChanged(rate); return true; } /// @dev Allows the owner to update the total amount of USD raised. T function setUSDRaised(uint256 _total) public onlyOwner whenNotFinalized { require(_total > 0); totalUSDRaised = _total; USDRaisedUpdated(_total); } /// @dev Gets the purchase records for a given address /// @param _beneficiary Tokan purchaser function getPurchaseRecord(address _beneficiary) public view isWhitelisted(_beneficiary) returns(uint256) { return purchaseRecords[_beneficiary]; } /// @dev Adds single address to whitelist /// @param _beneficiary Address to be added to the whitelist function addToWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = true; WhitelistAddressAdded(_beneficiary); } /// @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. /// @param _beneficiaries Addresses to be added to the whitelist function addManyToWhitelist(address[] _beneficiaries) external onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { whitelist[_beneficiaries[i]] = true; WhitelistAddressAdded(_beneficiaries[i]); } } /// @dev Removes single address from whitelist. /// @param _beneficiary Address to be removed to the whitelist function removeFromWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = false; WhitelistAddressRemoved(_beneficiary); } /// @dev Finalizes the crowdsale function finalize() external onlyOwner { _finalization(); } /* * Internal Functions */ /// @dev Extend parent behavior to check if current stage should close. Must call super to ensure the enforcement of the whitelist. /// @param _beneficiary Token purchaser /// @param _weiAmount Amount of wei contributed function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal whenNotPaused whenNotFinalized { super._preValidatePurchase(_beneficiary, _weiAmount); // Beneficiary's total should be between the minimum and maximum purchase amounts uint256 _totalPurchased = purchaseRecords[_beneficiary].add(_getTokenAmount(_weiAmount)); require(_totalPurchased >= minimumTokenPurchase); require(_totalPurchased <= maximumTokenPurchase); // Must make the purchase from the intended whitelisted address require(msg.sender == _beneficiary); // Must be after the start time require(now >= crowdsaleStartTime); } /// @dev Overrides parent by storing balances in timelock contract instead of issuing tokens right away. /// @param _beneficiary Token purchaser /// @param _tokenAmount Amount of tokens purchased function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { // Lock beneficiary's tokens tokenLock.lockTokens(_beneficiary, 1 weeks, _tokenAmount); } /// @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) /// @param _beneficiary Address receiving the tokens /// @param _weiAmount Value in wei involved in the purchase function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { uint256 _tokenAmount = _getTokenAmount(_weiAmount); // Add token amount to the purchase history purchaseRecords[_beneficiary] = purchaseRecords[_beneficiary].add(_tokenAmount); // Add token amount to total tokens sold totalTokensSold = totalTokensSold.add(_tokenAmount); // Finish the crowdsale... // ...if there is not a minimum purchase left if (crowdsaleTokenGoal.sub(totalTokensSold) < minimumTokenPurchase) { _finalization(); } // ...if USD funding goal has been reached if (totalUSDRaised >= crowdsaleUSDGoal) { _finalization(); } // ...if the time is after the crowdsale end time if (now > crowdsaleFinishTime) { _finalization(); } } /// @dev Finalizes crowdsale function _finalization() internal whenNotFinalized { isFinalized = true; tokenLock.finishCrowdsale(); CrowdsaleFinished(); } } contract OMITokenLock is Ownable, Pausable { using SafeMath for uint256; /* * Storage */ OMIToken public token; OMICrowdsale public crowdsale; address public allowanceProvider; bool public crowdsaleFinished = false; uint256 public crowdsaleEndTime; struct Lock { uint256 amount; uint256 lockDuration; bool released; bool revoked; } struct TokenLockVault { address beneficiary; uint256 tokenBalance; uint256 lockIndex; Lock[] locks; } mapping(address => TokenLockVault) public tokenLocks; address[] public lockIndexes; uint256 public totalTokensLocked; /* * Modifiers */ modifier ownerOrCrowdsale () { require(msg.sender == owner || OMICrowdsale(msg.sender) == crowdsale); _; } /* * Events */ event LockedTokens(address indexed beneficiary, uint256 amount, uint256 releaseTime); event UnlockedTokens(address indexed beneficiary, uint256 amount); event FinishedCrowdsale(); /* * Public Functions */ /// @dev Constructor function function OMITokenLock (address _token, address _allowanceProvider) public { token = OMIToken(_token); require(token.isOMITokenContract()); allowanceProvider = _allowanceProvider; } /// @dev Function to call from other contracts to ensure that this is the proper contract function isOMITokenLockContract() public pure returns(bool) { return true; } /// @dev Sets the crowdsale address to allow authorize locking permissions /// @param _crowdsale The address of the crowdsale function setCrowdsaleAddress (address _crowdsale) public onlyOwner returns (bool) { crowdsale = OMICrowdsale(_crowdsale); require(crowdsale.isOMICrowdsaleContract()); return true; } /// @dev Sets the token allowance provider address /// @param _allowanceProvider The address of the token allowance provider function setAllowanceAddress (address _allowanceProvider) public onlyOwner returns (bool) { allowanceProvider = _allowanceProvider; return true; } /// @dev Marks the crowdsale as being finished and sets the crowdsale finish date function finishCrowdsale() public ownerOrCrowdsale whenNotPaused { require(!crowdsaleFinished); crowdsaleFinished = true; crowdsaleEndTime = now; FinishedCrowdsale(); } /// @dev Gets the total amount of tokens for a given address /// @param _beneficiary The address for which to look up the total token amount function getTokenBalance(address _beneficiary) public view returns (uint) { return tokenLocks[_beneficiary].tokenBalance; } /// @dev Gets the total number of locks for a given address /// @param _beneficiary The address for which to look up the total number of locks function getNumberOfLocks(address _beneficiary) public view returns (uint) { return tokenLocks[_beneficiary].locks.length; } /// @dev Gets the lock at a given index for a given address /// @param _beneficiary The address used to look up the lock /// @param _lockIndex The index used to look up the lock function getLockByIndex(address _beneficiary, uint256 _lockIndex) public view returns (uint256 amount, uint256 lockDuration, bool released, bool revoked) { require(_lockIndex >= 0); require(_lockIndex <= tokenLocks[_beneficiary].locks.length.sub(1)); return ( tokenLocks[_beneficiary].locks[_lockIndex].amount, tokenLocks[_beneficiary].locks[_lockIndex].lockDuration, tokenLocks[_beneficiary].locks[_lockIndex].released, tokenLocks[_beneficiary].locks[_lockIndex].revoked ); } /// @dev Revokes the lock at a given index for a given address /// @param _beneficiary The address used to look up the lock /// @param _lockIndex The lock index to be revoked function revokeLockByIndex(address _beneficiary, uint256 _lockIndex) public onlyOwner returns (bool) { require(_lockIndex >= 0); require(_lockIndex <= tokenLocks[_beneficiary].locks.length.sub(1)); require(!tokenLocks[_beneficiary].locks[_lockIndex].revoked); tokenLocks[_beneficiary].locks[_lockIndex].revoked = true; return true; } /// @dev Locks tokens for a given beneficiary /// @param _beneficiary The address to which the tokens will be released /// @param _lockDuration The duration of time that must elapse after the crowdsale end date /// @param _tokens The amount of tokens to be locked function lockTokens(address _beneficiary, uint256 _lockDuration, uint256 _tokens) external ownerOrCrowdsale whenNotPaused { // Lock duration must be greater than zero seconds require(_lockDuration >= 0); // Token amount must be greater than zero require(_tokens > 0); // Token Lock must have a sufficient allowance prior to creating locks require(_tokens.add(totalTokensLocked) <= token.allowance(allowanceProvider, address(this))); TokenLockVault storage lock = tokenLocks[_beneficiary]; // If this is the first lock for this beneficiary, add their address to the lock indexes if (lock.beneficiary == 0) { lock.beneficiary = _beneficiary; lock.lockIndex = lockIndexes.length; lockIndexes.push(_beneficiary); } // Add the lock lock.locks.push(Lock(_tokens, _lockDuration, false, false)); // Update the total tokens for this beneficiary lock.tokenBalance = lock.tokenBalance.add(_tokens); // Update the number of locked tokens totalTokensLocked = _tokens.add(totalTokensLocked); LockedTokens(_beneficiary, _tokens, _lockDuration); } /// @dev Transfers any tokens held in a timelock vault to beneficiary if they are due for release. function releaseTokens() public whenNotPaused returns(bool) { require(crowdsaleFinished); require(_release(msg.sender)); return true; } /// @dev Transfers tokens held by timelock to all beneficiaries within the provided range. /// @param _beneficiary The user for which token locks should be released. function releaseTokensByAddress(address _beneficiary) external whenNotPaused onlyOwner returns (bool) { require(crowdsaleFinished); require(_release(_beneficiary)); return true; } /* * Internal Functions */ /// @dev Reviews and releases token for a given beneficiary /// @param _beneficiary address for which a token release should be attempted function _release(address _beneficiary) internal whenNotPaused returns (bool) { TokenLockVault memory lock = tokenLocks[_beneficiary]; require(lock.beneficiary == _beneficiary); require(_beneficiary != 0x0); bool hasUnDueLocks = false; for (uint256 i = 0; i < lock.locks.length; i++) { Lock memory currentLock = lock.locks[i]; // Skip any locks which are already released or revoked if (currentLock.released || currentLock.revoked) { continue; } // Skip any locks that are not due for release if (crowdsaleEndTime.add(currentLock.lockDuration) >= now) { hasUnDueLocks = true; continue; } // The amount of tokens to transfer must be less than the number of locked tokens require(currentLock.amount <= token.allowance(allowanceProvider, address(this))); // Release Tokens UnlockedTokens(_beneficiary, currentLock.amount); tokenLocks[_beneficiary].locks[i].released = true; tokenLocks[_beneficiary].tokenBalance = tokenLocks[_beneficiary].tokenBalance.sub(currentLock.amount); totalTokensLocked = totalTokensLocked.sub(currentLock.amount); assert(token.transferFrom(allowanceProvider, _beneficiary, currentLock.amount)); } // If there are no future locks to be released, delete the lock vault if (!hasUnDueLocks) { delete tokenLocks[_beneficiary]; lockIndexes[lock.lockIndex] = 0x0; } return true; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } 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 ); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } contract CappedToken is MintableToken { uint256 public cap; constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) onlyOwner canMint public returns (bool) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } } contract PausableToken is StandardToken, Pausable { function transfer( address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve( address _spender, uint256 _value ) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval( address _spender, uint _addedValue ) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval( address _spender, uint _subtractedValue ) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract OMIToken is CappedToken, PausableToken { string public constant name = "Ecomi Token"; string public constant symbol = "OMI"; uint256 public decimals = 18; function OMIToken() public CappedToken(1000000000*1e18) {} /// @dev Function to call from other contracts to ensure that this is the proper contract function isOMITokenContract() public pure returns(bool) { return true; } }
Adds single address to whitelist _beneficiary Address to be added to the whitelist
function addToWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = true; WhitelistAddressAdded(_beneficiary); }
14,484,598
pragma solidity ^0.4.24; import "../../TransferManager/ITransferManager.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /** * @title Transfer Manager module to automate blacklist and restrict transfers */ contract BlacklistTransferManager is ITransferManager { using SafeMath for uint256; bytes32 public constant ADMIN = "ADMIN"; struct BlacklistsDetails { uint256 startTime; uint256 endTime; uint256 repeatPeriodTime; } //hold the different blacklist details corresponds to its name mapping(bytes32 => BlacklistsDetails) public blacklists; //hold the different name of blacklist corresponds to a investor mapping(address => bytes32[]) investorToBlacklist; //get list of the addresses for a particular blacklist mapping(bytes32 => address[]) blacklistToInvestor; //mapping use to store the indexes for different blacklist types for a investor mapping(address => mapping(bytes32 => uint256)) investorToIndex; //mapping use to store the indexes for different investor for a blacklist type mapping(bytes32 => mapping(address => uint256)) blacklistToIndex; bytes32[] allBlacklists; // Emit when new blacklist type is added event AddBlacklistType( uint256 _startTime, uint256 _endTime, bytes32 _blacklistName, uint256 _repeatPeriodTime ); // Emit when there is a change in the blacklist type event ModifyBlacklistType( uint256 _startTime, uint256 _endTime, bytes32 _blacklistName, uint256 _repeatPeriodTime ); // Emit when the added blacklist type is deleted event DeleteBlacklistType( bytes32 _blacklistName ); // Emit when new investor is added to the blacklist type event AddInvestorToBlacklist( address indexed _investor, bytes32 _blacklistName ); // Emit when investor is deleted from the blacklist type event DeleteInvestorFromBlacklist( address indexed _investor, bytes32 _blacklistName ); /** * @notice Constructor * @param _securityToken Address of the security token * @param _polyAddress Address of the polytoken */ constructor (address _securityToken, address _polyAddress) public Module(_securityToken, _polyAddress) { } /** * @notice This function returns the signature of configure function */ function getInitFunction() public pure returns (bytes4) { return bytes4(0); } /** * @notice Used to verify the transfer transaction * @param _from Address of the sender * @dev Restrict the blacklist address to transfer tokens * if the current time is between the timeframe define for the * blacklist type associated with the _from address */ function verifyTransfer(address _from, address /* _to */, uint256 /* _amount */, bytes /* _data */, bool /* _isTransfer */) public returns(Result) { if (!paused) { if (investorToBlacklist[_from].length != 0) { for (uint256 i = 0; i < investorToBlacklist[_from].length; i++) { uint256 endTimeTemp = blacklists[investorToBlacklist[_from][i]].endTime; uint256 startTimeTemp = blacklists[investorToBlacklist[_from][i]].startTime; uint256 repeatPeriodTimeTemp = blacklists[investorToBlacklist[_from][i]].repeatPeriodTime * 1 days; /*solium-disable-next-line security/no-block-members*/ if (now > startTimeTemp) { // Find the repeating parameter that will be used to calculate the new startTime and endTime // based on the new current time value /*solium-disable-next-line security/no-block-members*/ uint256 repeater = (now.sub(startTimeTemp)).div(repeatPeriodTimeTemp); /*solium-disable-next-line security/no-block-members*/ if (startTimeTemp.add(repeatPeriodTimeTemp.mul(repeater)) <= now && endTimeTemp.add(repeatPeriodTimeTemp.mul(repeater)) >= now) { return Result.INVALID; } } } } } return Result.NA; } /** * @notice Used to add the blacklist type * @param _startTime Start date of the blacklist type * @param _endTime End date of the blacklist type * @param _blacklistName Name of the blacklist type * @param _repeatPeriodTime Repeat period of the blacklist type */ function addBlacklistType(uint256 _startTime, uint256 _endTime, bytes32 _blacklistName, uint256 _repeatPeriodTime) public withPerm(ADMIN) { _addBlacklistType(_startTime, _endTime, _blacklistName, _repeatPeriodTime); } /** * @notice Used to add the multiple blacklist type * @param _startTimes Start date of the blacklist type * @param _endTimes End date of the blacklist type * @param _blacklistNames Name of the blacklist type * @param _repeatPeriodTimes Repeat period of the blacklist type */ function addBlacklistTypeMulti(uint256[] _startTimes, uint256[] _endTimes, bytes32[] _blacklistNames, uint256[] _repeatPeriodTimes) external withPerm(ADMIN) { require (_startTimes.length == _endTimes.length && _endTimes.length == _blacklistNames.length && _blacklistNames.length == _repeatPeriodTimes.length, "Input array's length mismatch"); for (uint256 i = 0; i < _startTimes.length; i++){ _addBlacklistType(_startTimes[i], _endTimes[i], _blacklistNames[i], _repeatPeriodTimes[i]); } } /** * @notice Internal function */ function _validParams(uint256 _startTime, uint256 _endTime, bytes32 _blacklistName, uint256 _repeatPeriodTime) internal view { require(_blacklistName != bytes32(0), "Invalid blacklist name"); require(_startTime >= now && _startTime < _endTime, "Invalid start or end date"); require(_repeatPeriodTime.mul(1 days) >= _endTime.sub(_startTime) || _repeatPeriodTime == 0); } /** * @notice Used to modify the details of a given blacklist type * @param _startTime Start date of the blacklist type * @param _endTime End date of the blacklist type * @param _blacklistName Name of the blacklist type * @param _repeatPeriodTime Repeat period of the blacklist type */ function modifyBlacklistType(uint256 _startTime, uint256 _endTime, bytes32 _blacklistName, uint256 _repeatPeriodTime) public withPerm(ADMIN) { require(blacklists[_blacklistName].endTime != 0, "Blacklist type doesn't exist"); _validParams(_startTime, _endTime, _blacklistName, _repeatPeriodTime); blacklists[_blacklistName] = BlacklistsDetails(_startTime, _endTime, _repeatPeriodTime); emit ModifyBlacklistType(_startTime, _endTime, _blacklistName, _repeatPeriodTime); } /** * @notice Used to modify the details of a given multpile blacklist types * @param _startTimes Start date of the blacklist type * @param _endTimes End date of the blacklist type * @param _blacklistNames Name of the blacklist type * @param _repeatPeriodTimes Repeat period of the blacklist type */ function modifyBlacklistTypeMulti(uint256[] _startTimes, uint256[] _endTimes, bytes32[] _blacklistNames, uint256[] _repeatPeriodTimes) external withPerm(ADMIN) { require (_startTimes.length == _endTimes.length && _endTimes.length == _blacklistNames.length && _blacklistNames.length == _repeatPeriodTimes.length, "Input array's length mismatch"); for (uint256 i = 0; i < _startTimes.length; i++){ modifyBlacklistType(_startTimes[i], _endTimes[i], _blacklistNames[i], _repeatPeriodTimes[i]); } } /** * @notice Used to delete the blacklist type * @param _blacklistName Name of the blacklist type */ function deleteBlacklistType(bytes32 _blacklistName) public withPerm(ADMIN) { require(blacklists[_blacklistName].endTime != 0, "Blacklist type doesn’t exist"); require(blacklistToInvestor[_blacklistName].length == 0, "Investors are associated with the blacklist"); // delete blacklist type delete(blacklists[_blacklistName]); uint256 i = 0; for (i = 0; i < allBlacklists.length; i++) { if (allBlacklists[i] == _blacklistName) { break; } } if (i != allBlacklists.length -1) { allBlacklists[i] = allBlacklists[allBlacklists.length -1]; } allBlacklists.length--; emit DeleteBlacklistType(_blacklistName); } /** * @notice Used to delete the multiple blacklist type * @param _blacklistNames Name of the blacklist type */ function deleteBlacklistTypeMulti(bytes32[] _blacklistNames) external withPerm(ADMIN) { for(uint256 i = 0; i < _blacklistNames.length; i++){ deleteBlacklistType(_blacklistNames[i]); } } /** * @notice Used to assign the blacklist type to the investor * @param _investor Address of the investor * @param _blacklistName Name of the blacklist */ function addInvestorToBlacklist(address _investor, bytes32 _blacklistName) public withPerm(ADMIN) { require(blacklists[_blacklistName].endTime != 0, "Blacklist type doesn't exist"); require(_investor != address(0), "Invalid investor address"); uint256 index = investorToIndex[_investor][_blacklistName]; if (index < investorToBlacklist[_investor].length) require(investorToBlacklist[_investor][index] != _blacklistName, "Blacklist already added to investor"); uint256 investorIndex = investorToBlacklist[_investor].length; // Add blacklist index to the investor investorToIndex[_investor][_blacklistName] = investorIndex; uint256 blacklistIndex = blacklistToInvestor[_blacklistName].length; // Add investor index to the blacklist blacklistToIndex[_blacklistName][_investor] = blacklistIndex; investorToBlacklist[_investor].push(_blacklistName); blacklistToInvestor[_blacklistName].push(_investor); emit AddInvestorToBlacklist(_investor, _blacklistName); } /** * @notice Used to assign the blacklist type to the multiple investor * @param _investors Address of the investor * @param _blacklistName Name of the blacklist */ function addInvestorToBlacklistMulti(address[] _investors, bytes32 _blacklistName) external withPerm(ADMIN){ for(uint256 i = 0; i < _investors.length; i++){ addInvestorToBlacklist(_investors[i], _blacklistName); } } /** * @notice Used to assign the multiple blacklist type to the multiple investor * @param _investors Address of the investor * @param _blacklistNames Name of the blacklist */ function addMultiInvestorToBlacklistMulti(address[] _investors, bytes32[] _blacklistNames) external withPerm(ADMIN){ require (_investors.length == _blacklistNames.length, "Input array's length mismatch"); for(uint256 i = 0; i < _investors.length; i++){ addInvestorToBlacklist(_investors[i], _blacklistNames[i]); } } /** * @notice Used to assign the new blacklist type to the investor * @param _startTime Start date of the blacklist type * @param _endTime End date of the blacklist type * @param _blacklistName Name of the blacklist type * @param _repeatPeriodTime Repeat period of the blacklist type * @param _investor Address of the investor */ function addInvestorToNewBlacklist(uint256 _startTime, uint256 _endTime, bytes32 _blacklistName, uint256 _repeatPeriodTime, address _investor) external withPerm(ADMIN){ _addBlacklistType(_startTime, _endTime, _blacklistName, _repeatPeriodTime); addInvestorToBlacklist(_investor, _blacklistName); } /** * @notice Used to delete the investor from all the associated blacklist types * @param _investor Address of the investor */ function deleteInvestorFromAllBlacklist(address _investor) public withPerm(ADMIN) { require(_investor != address(0), "Invalid investor address"); require(investorToBlacklist[_investor].length != 0, "Investor is not associated to any blacklist type"); uint256 index = investorToBlacklist[_investor].length - 1; for (uint256 i = index; i >= 0 && i <= index; i--){ deleteInvestorFromBlacklist(_investor, investorToBlacklist[_investor][i]); } } /** * @notice Used to delete the multiple investor from all the associated blacklist types * @param _investor Address of the investor */ function deleteInvestorFromAllBlacklistMulti(address[] _investor) external withPerm(ADMIN) { for(uint256 i = 0; i < _investor.length; i++){ deleteInvestorFromAllBlacklist(_investor[i]); } } /** * @notice Used to delete the investor from the blacklist * @param _investor Address of the investor * @param _blacklistName Name of the blacklist */ function deleteInvestorFromBlacklist(address _investor, bytes32 _blacklistName) public withPerm(ADMIN) { require(_investor != address(0), "Invalid investor address"); require(_blacklistName != bytes32(0),"Invalid blacklist name"); require(investorToBlacklist[_investor][investorToIndex[_investor][_blacklistName]] == _blacklistName, "Investor not associated to the blacklist"); // delete the investor from the blacklist type uint256 _blacklistIndex = blacklistToIndex[_blacklistName][_investor]; uint256 _len = blacklistToInvestor[_blacklistName].length; if ( _blacklistIndex < _len -1) { blacklistToInvestor[_blacklistName][_blacklistIndex] = blacklistToInvestor[_blacklistName][_len - 1]; blacklistToIndex[_blacklistName][blacklistToInvestor[_blacklistName][_blacklistIndex]] = _blacklistIndex; } blacklistToInvestor[_blacklistName].length--; // delete the investor index from the blacklist delete(blacklistToIndex[_blacklistName][_investor]); // delete the blacklist from the investor uint256 _investorIndex = investorToIndex[_investor][_blacklistName]; _len = investorToBlacklist[_investor].length; if ( _investorIndex < _len -1) { investorToBlacklist[_investor][_investorIndex] = investorToBlacklist[_investor][_len - 1]; investorToIndex[_investor][investorToBlacklist[_investor][_investorIndex]] = _investorIndex; } investorToBlacklist[_investor].length--; // delete the blacklist index from the invetsor delete(investorToIndex[_investor][_blacklistName]); emit DeleteInvestorFromBlacklist(_investor, _blacklistName); } /** * @notice Used to delete the multiple investor from the blacklist * @param _investors address of the investor * @param _blacklistNames name of the blacklist */ function deleteMultiInvestorsFromBlacklistMulti(address[] _investors, bytes32[] _blacklistNames) external withPerm(ADMIN) { require (_investors.length == _blacklistNames.length, "Input array's length mismatch"); for(uint256 i = 0; i < _investors.length; i++){ deleteInvestorFromBlacklist(_investors[i], _blacklistNames[i]); } } function _addBlacklistType(uint256 _startTime, uint256 _endTime, bytes32 _blacklistName, uint256 _repeatPeriodTime) internal { require(blacklists[_blacklistName].endTime == 0, "Blacklist type already exist"); _validParams(_startTime, _endTime, _blacklistName, _repeatPeriodTime); blacklists[_blacklistName] = BlacklistsDetails(_startTime, _endTime, _repeatPeriodTime); allBlacklists.push(_blacklistName); emit AddBlacklistType(_startTime, _endTime, _blacklistName, _repeatPeriodTime); } /** * @notice get the list of the investors of a blacklist type * @param _blacklistName Name of the blacklist type * @return address List of investors associated with the blacklist */ function getListOfAddresses(bytes32 _blacklistName) external view returns(address[]) { require(blacklists[_blacklistName].endTime != 0, "Blacklist type doesn't exist"); return blacklistToInvestor[_blacklistName]; } /** * @notice get the list of the investors of a blacklist type * @param _user Address of the user * @return bytes32 List of blacklist names associated with the given address */ function getBlacklistNamesToUser(address _user) external view returns(bytes32[]) { return investorToBlacklist[_user]; } /** * @notice get the list of blacklist names * @return bytes32 Array of blacklist names */ function getAllBlacklists() external view returns(bytes32[]) { return allBlacklists; } /** * @notice Return the permissions flag that are associated with blacklist transfer manager */ function getPermissions() public view returns(bytes32[]) { bytes32[] memory allPermissions = new bytes32[](1); allPermissions[0] = ADMIN; return allPermissions; } }
Used to assign the multiple blacklist type to the multiple investor _investors Address of the investor _blacklistNames Name of the blacklist/
function addMultiInvestorToBlacklistMulti(address[] _investors, bytes32[] _blacklistNames) external withPerm(ADMIN){ require (_investors.length == _blacklistNames.length, "Input array's length mismatch"); for(uint256 i = 0; i < _investors.length; i++){ addInvestorToBlacklist(_investors[i], _blacklistNames[i]); } }
12,896,674
pragma solidity 0.5.12; import "./Handler.sol"; import "./interface/ILendFMe.sol"; import "./library/ReentrancyGuard.sol"; contract MoneyMarketHandler is Handler, ReentrancyGuard { address public targetAddr; // market address mapping(address => uint256) public interestDetails; event NewdTargetAddr( address indexed originalTargetAddr, address indexed newTargetAddr ); constructor(address _HNITokenController, address _targetAddr) public { initialize(_HNITokenController, _targetAddr); } // --- Init --- // This function is used with contract proxy, do not modify this function. function initialize(address _HNITokenController, address _targetAddr) public { super.initialize(_HNITokenController); initReentrancyStatus(); targetAddr = _targetAddr; } /** * @dev Update market contract address. * @param _newTargetAddr The new market contract address. */ function setTargetAddr(address _newTargetAddr) external auth { require( _newTargetAddr != targetAddr, "setTargetAddr: The same market address!" ); address _originalTargetAddr = targetAddr; targetAddr = _newTargetAddr; emit NewdTargetAddr(_originalTargetAddr, _newTargetAddr); } /** * @dev This token `_underlyingToken` approves to market and HNIToken contract. * @param _underlyingToken Token address to approve. */ function approve(address _underlyingToken, uint256 amount) public { require( doApprove(_underlyingToken, targetAddr, amount), "approve: Approve market failed!" ); super.approve(_underlyingToken, amount); } /** * @dev Deposit token to market, but only for HNIToken contract. * @param _underlyingToken Token to deposit. * @return True is success, false is failure. */ function deposit(address _underlyingToken, uint256 _amount) external auth whenNotPaused nonReentrant returns (uint256) { require( tokenIsEnabled(_underlyingToken), "deposit: Token is disabled!" ); require( _amount > 0, "deposit: Deposit amount should be greater than 0!" ); // Update the stored interest with the market balance before the deposit uint256 _MarketBalanceBefore = _updateInterest(_underlyingToken); // Mint all the token balance of the handler, // which should be the exact deposit amount normally, // but there could be some unexpected transfers before. uint256 _handlerBalance = IERC20(_underlyingToken).balanceOf( address(this) ); require( ILendFMe(targetAddr).supply(_underlyingToken, _handlerBalance) == 0, "deposit: Fail to supply to money market!" ); // including unexpected transfers. uint256 _MarketBalanceAfter = getBalance(_underlyingToken); uint256 _changedAmount = _MarketBalanceAfter.sub(_MarketBalanceBefore); // return a smaller value as unexpected transfers were also included. return _changedAmount > _amount ? _amount : _changedAmount; } /** * @dev Withdraw token from market, but only for HNIToken contract. * @param _underlyingToken Token to withdraw. * @param _amount Token amount to withdraw. * @return Actually withdraw token amount. */ function withdraw(address _underlyingToken, uint256 _amount) external auth whenNotPaused nonReentrant returns (uint256) { require( _amount > 0, "withdraw: Withdraw amount should be greater than 0!" ); _updateInterest(_underlyingToken); uint256 _handlerBalanceBefore = IERC20(_underlyingToken).balanceOf( address(this) ); require( ILendFMe(targetAddr).withdraw(_underlyingToken, _amount) == 0, "withdraw: Fail to withdraw from money market!" ); // including unexpected transfer. uint256 _handlerBalanceAfter = IERC20(_underlyingToken).balanceOf( address(this) ); uint256 _changedAmount = _handlerBalanceAfter.sub( _handlerBalanceBefore ); // return a smaller value. return _changedAmount > _amount ? _amount : _changedAmount; } /** * @dev Update the handler deposit interest based on the underlying token. */ function _updateInterest(address _underlyingToken) internal returns (uint256) { uint256 _balance = getBalance(_underlyingToken); (uint256 _underlyingBalance, ) = ILendFMe(targetAddr).supplyBalances( address(this), _underlyingToken ); // Interest = Balance - UnderlyingBalance. uint256 _interest = _balance.sub(_underlyingBalance); // Update the stored interest interestDetails[_underlyingToken] = interestDetails[_underlyingToken] .add(_interest); return _balance; } /** * @dev Total balance with any accumulated interest for _underlyingToken belonging to handler * @param _underlyingToken Token to get balance. */ function getRealBalance(address _underlyingToken) public view returns (uint256) { return ILendFMe(targetAddr).getSupplyBalance( address(this), _underlyingToken ); } /** * @dev The maximum withdrawable _underlyingToken in the market. * @param _underlyingToken Token to get liquidity. */ function getRealLiquidity(address _underlyingToken) public view returns (uint256) { uint256 _underlyingBalance = getRealBalance(_underlyingToken); uint256 _cash = IERC20(_underlyingToken).balanceOf(targetAddr); return _underlyingBalance > _cash ? _cash : _underlyingBalance; } /***************************************************/ /*** View Interfaces For Backwards compatibility ***/ /***************************************************/ /** * @dev Total balance with any accumulated interest for `_underlyingToken` belonging to `handler`. * @param _underlyingToken Token to get balance. */ function getBalance(address _underlyingToken) public view returns (uint256) { return getRealBalance(_underlyingToken); } /** * @dev The maximum withdrawable amount of token `_underlyingToken` in the market. * @param _underlyingToken Token to get balance. */ function getLiquidity(address _underlyingToken) public view returns (uint256) { return getRealLiquidity(_underlyingToken); } }
--- Init --- This function is used with contract proxy, do not modify this function.
function initialize(address _HNITokenController, address _targetAddr) public { super.initialize(_HNITokenController); initReentrancyStatus(); targetAddr = _targetAddr; }
2,543,653
pragma solidity ^0.4.18; import "truffle/Assert.sol"; import "truffle/DeployedAddresses.sol"; import "../contracts/ContestManager.sol"; import "../contracts/Contest.sol"; contract TestContestManager { ContestManager cm = new ContestManager(); function testBalanceOf0() public { uint b = cm.balanceOf(0); Assert.equal(b, 0, "testBalanceOf() failed, balance should be 0"); } function testAddTokens() public { cm.addTokens(10,address(this)); Assert.equal(10, cm.balanceOf(address(this)), "testAddTokens() failed, balance should be 10"); } function testNewContest() public { Contest contest = Contest(cm.newContest(1525937318, 1525937319, "testNewContest",100, 2)); Assert.equal(address(cm), address(contest.cm()), "testNewContest() failed, bad contest->cm"); Assert.equal(cm.contests(contest), true, "testNewContest() failed, ContestManager->contests[] array not updated"); } function testClaimTicket() public { // solium-disable-next-line security/no-block-members uint contestdeadline = now + 86400; // contest is tomorrow! Contest contest = Contest(cm.newContest(contestdeadline, contestdeadline + 1, "testClaimTicket",100, 2)); Assert.equal(10, cm.balanceOf(address(this)), "testClaimTicket() failed, initial balance should be 10"); Assert.equal(false, contest.claimedTickets(address(this)), "testClaimTicket() failed, ticket is already claimed"); Assert.equal(contest.claimTicket(), true, "testClaimTicket() failed"); Assert.equal(8, cm.balanceOf(address(this)), "testClaimTicket() failed, final balance should be 8"); Assert.equal(true, contest.claimedTickets(address(this)), "testClaimTicket() failed, ticket is unclaimed"); } function testClaimLastTicket() public { // solium-disable-next-line security/no-block-members uint contestdeadline = now + 86400; // contest is tomorrow! Contest contest = Contest(cm.newContest(contestdeadline, contestdeadline + 1, "testClaimLastTicket", 1, 2)); Assert.equal(contest.claimTicket(), true, "testClaimLastTicket() failed"); Assert.equal(6, cm.balanceOf(address(this)), "testClaimLastTicket() failed, final balance should be 6"); Assert.equal(true, contest.claimedTickets(address(this)), "testClaimLastTicket() failed, ticket is unclaimed"); } function testSpendLastToken() public { // solium-disable-next-line security/no-block-members uint contestdeadline = now + 86400; // contest is tomorrow! Contest contest = Contest(cm.newContest(contestdeadline, contestdeadline + 1, "testClaimTicket",100, 2)); cm.setTotalTokens(address(this), 2); contest.claimTicket(); Assert.equal(0, cm.balanceOf(address(this)), "testSpendLastToken() failed, final balance should be 0"); Assert.equal(true, contest.claimedTickets(address(this)), "testSpendLastToken() failed, ticket is unclaimed"); } function testFreeTicket() public { // solium-disable-next-line security/no-block-members uint contestdeadline = now + 86400; // contest is tomorrow! Contest contest = Contest(cm.newContest(contestdeadline, contestdeadline + 1, "testFreeTicket",100, 2)); cm.setTotalTokens(address(this), 2); contest.claimTicket(); Assert.equal(true, contest.freeTicket(), "testFreeTicket() failed, freeTicket() failed"); Assert.equal(1, cm.balanceOf(address(this)), "testFreeTicket() failed, balance should be 1"); Assert.equal(false, contest.claimedTickets(address(this)), "testFreeTicket() failed, ticket is claimed"); Assert.equal(100, contest.availableTickets(), "testFreeTicket() failed, availableTickets should be 100"); } }
solium-disable-next-line security/no-block-members
function testSpendLastToken() public { Contest contest = Contest(cm.newContest(contestdeadline, contestdeadline + 1, "testClaimTicket",100, 2)); cm.setTotalTokens(address(this), 2); contest.claimTicket(); Assert.equal(0, cm.balanceOf(address(this)), "testSpendLastToken() failed, final balance should be 0"); Assert.equal(true, contest.claimedTickets(address(this)), "testSpendLastToken() failed, ticket is unclaimed"); }
12,800,431
./full_match/1/0x18faf3cdF637D6054C64fE76cEA218C6e009c261/sources/contracts/DogMoneyAuctionHouse.sol
Create a bid for an Auction, with a given amount. This contract only accepts payment in ETH./ Refund the last bidder, if applicable
function _createBid( uint256 auctionId, IERC20 token, bytes memory swapPath, uint256 amountIn, uint256 amountOutMinimum, address to ) internal { IDogMoneyAuctionHouse.Auction memory _auction = auction; require( _auction.id == auctionId, "DogMoneyAuctionHouse: Wrong auctionId" ); require( block.timestamp < _auction.endTime, "DogMoneyAuctionHouse: Auction expired" ); require(!_auction.cancelled, "DogMoneyAuctionHouse: Auction cancelled"); uint256 amountInReserveCurrency = _acceptReserveCurrency( token, swapPath, amountIn, amountOutMinimum ); require( amountInReserveCurrency >= reservePrice && amountInReserveCurrency >= _auction.auctionPack.reservePrice, "DogMoneyAuctionHouse: Must send at least reservePrice" ); require( amountInReserveCurrency >= _auction.amount + ((_auction.amount * minBidIncrementPercentage) / 100), "DogMoneyAuctionHouse: Must send more than last bid by minBidIncrementPercentage amount" ); address payable lastBidder = _auction.bidder; if (lastBidder != address(0)) { reserveCurrency.transfer(lastBidder, _auction.amount); } auction.amount = amountInReserveCurrency; auction.bidder = payable(to); if (extended) { auction.endTime = _auction.endTime = block.timestamp + timeBuffer; } emit AuctionBid(_auction.id, to, amountInReserveCurrency, extended); if (extended) { emit AuctionExtended(_auction.id, _auction.endTime); } }
8,448,292
pragma solidity ^0.4.25; contract IStdToken { function balanceOf(address _owner) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns(bool); } contract EtheramaCommon { //main adrministrators of the Etherama network mapping(address => bool) private _administrators; //main managers of the Etherama network mapping(address => bool) private _managers; modifier onlyAdministrator() { require(_administrators[msg.sender]); _; } modifier onlyAdministratorOrManager() { require(_administrators[msg.sender] || _managers[msg.sender]); _; } constructor() public { _administrators[msg.sender] = true; } function addAdministator(address addr) onlyAdministrator public { _administrators[addr] = true; } function removeAdministator(address addr) onlyAdministrator public { _administrators[addr] = false; } function isAdministrator(address addr) public view returns (bool) { return _administrators[addr]; } function addManager(address addr) onlyAdministrator public { _managers[addr] = true; } function removeManager(address addr) onlyAdministrator public { _managers[addr] = false; } function isManager(address addr) public view returns (bool) { return _managers[addr]; } } contract EtheramaGasPriceLimit is EtheramaCommon { uint256 public MAX_GAS_PRICE = 0 wei; event onSetMaxGasPrice(uint256 val); //max gas price modifier for buy/sell transactions in order to avoid a "front runner" vulnerability. //It is applied to all network contracts modifier validGasPrice(uint256 val) { require(val > 0); _; } constructor(uint256 maxGasPrice) public validGasPrice(maxGasPrice) { setMaxGasPrice(maxGasPrice); } //only main administators or managers can set max gas price function setMaxGasPrice(uint256 val) public validGasPrice(val) onlyAdministratorOrManager { MAX_GAS_PRICE = val; emit onSetMaxGasPrice(val); } } // Core contract for Etherama network contract EtheramaCore is EtheramaGasPriceLimit { uint256 constant public MAGNITUDE = 2**64; // Max and min amount of tokens which can be bought or sold. There are such limits because of math precision uint256 constant public MIN_TOKEN_DEAL_VAL = 0.1 ether; uint256 constant public MAX_TOKEN_DEAL_VAL = 1000000 ether; // same same for ETH uint256 constant public MIN_ETH_DEAL_VAL = 0.001 ether; uint256 constant public MAX_ETH_DEAL_VAL = 200000 ether; // percent of a transaction commission which is taken for Big Promo bonus uint256 public _bigPromoPercent = 5 ether; // percent of a transaction commission which is taken for Quick Promo bonus uint256 public _quickPromoPercent = 5 ether; // percent of a transaction commission which is taken for Etherama DEV team uint256 public _devRewardPercent = 15 ether; // percent of a transaction commission which is taken for Token Owner. uint256 public _tokenOwnerRewardPercent = 30 ether; // percent of a transaction commission which is taken for share reward. Each token holder receives a small reward from each buy or sell transaction proportionally his holding. uint256 public _shareRewardPercent = 25 ether; // percent of a transaction commission which is taken for a feraral link owner. If there is no any referal then this part of commission goes to share reward. uint256 public _refBonusPercent = 20 ether; // interval of blocks for Big Promo bonus. It means that a user which buy a bunch of tokens for X ETH in that particular block will receive a special bonus uint128 public _bigPromoBlockInterval = 9999; // same same for Quick Promo uint128 public _quickPromoBlockInterval = 100; // minimum eth amount of a purchase which is required to participate in promo. uint256 public _promoMinPurchaseEth = 1 ether; // minimum eth purchase which is required to get a referal link. uint256 public _minRefEthPurchase = 0.5 ether; // percent of fee which is supposed to distribute. uint256 public _totalIncomeFeePercent = 100 ether; // current collected big promo bonus uint256 public _currentBigPromoBonus; // current collected quick promo bonus uint256 public _currentQuickPromoBonus; uint256 public _devReward; uint256 public _initBlockNum; mapping(address => bool) private _controllerContracts; mapping(uint256 => address) private _controllerIndexer; uint256 private _controllerContractCount; //user token balances per data contracts mapping(address => mapping(address => uint256)) private _userTokenLocalBalances; //user reward payouts per data contracts mapping(address => mapping(address => uint256)) private _rewardPayouts; //user ref rewards per data contracts mapping(address => mapping(address => uint256)) private _refBalances; //user won quick promo bonuses per data contracts mapping(address => mapping(address => uint256)) private _promoQuickBonuses; //user won big promo bonuses per data contracts mapping(address => mapping(address => uint256)) private _promoBigBonuses; //user saldo between buys and sels in eth per data contracts mapping(address => mapping(address => uint256)) private _userEthVolumeSaldos; //bonuses per share per data contracts mapping(address => uint256) private _bonusesPerShare; //buy counts per data contracts mapping(address => uint256) private _buyCounts; //sell counts per data contracts mapping(address => uint256) private _sellCounts; //total volume eth per data contracts mapping(address => uint256) private _totalVolumeEth; //total volume tokens per data contracts mapping(address => uint256) private _totalVolumeToken; event onWithdrawUserBonus(address indexed userAddress, uint256 ethWithdrawn); modifier onlyController() { require(_controllerContracts[msg.sender]); _; } constructor(uint256 maxGasPrice) EtheramaGasPriceLimit(maxGasPrice) public { _initBlockNum = block.number; } function getInitBlockNum() public view returns (uint256) { return _initBlockNum; } function addControllerContract(address addr) onlyAdministrator public { _controllerContracts[addr] = true; _controllerIndexer[_controllerContractCount] = addr; _controllerContractCount = SafeMath.add(_controllerContractCount, 1); } function removeControllerContract(address addr) onlyAdministrator public { _controllerContracts[addr] = false; } function changeControllerContract(address oldAddr, address newAddress) onlyAdministrator public { _controllerContracts[oldAddr] = false; _controllerContracts[newAddress] = true; } function setBigPromoInterval(uint128 val) onlyAdministrator public { _bigPromoBlockInterval = val; } function setQuickPromoInterval(uint128 val) onlyAdministrator public { _quickPromoBlockInterval = val; } function addBigPromoBonus() onlyController payable public { _currentBigPromoBonus = SafeMath.add(_currentBigPromoBonus, msg.value); } function addQuickPromoBonus() onlyController payable public { _currentQuickPromoBonus = SafeMath.add(_currentQuickPromoBonus, msg.value); } function setPromoMinPurchaseEth(uint256 val) onlyAdministrator public { _promoMinPurchaseEth = val; } function setMinRefEthPurchase(uint256 val) onlyAdministrator public { _minRefEthPurchase = val; } function setTotalIncomeFeePercent(uint256 val) onlyController public { require(val > 0 && val <= 100 ether); _totalIncomeFeePercent = val; } // set reward persentages of buy/sell fee. Token owner cannot take more than 40%. function setRewardPercentages(uint256 tokenOwnerRewardPercent, uint256 shareRewardPercent, uint256 refBonusPercent, uint256 bigPromoPercent, uint256 quickPromoPercent) onlyAdministrator public { require(tokenOwnerRewardPercent <= 40 ether); require(shareRewardPercent <= 100 ether); require(refBonusPercent <= 100 ether); require(bigPromoPercent <= 100 ether); require(quickPromoPercent <= 100 ether); require(tokenOwnerRewardPercent + shareRewardPercent + refBonusPercent + _devRewardPercent + _bigPromoPercent + _quickPromoPercent == 100 ether); _tokenOwnerRewardPercent = tokenOwnerRewardPercent; _shareRewardPercent = shareRewardPercent; _refBonusPercent = refBonusPercent; _bigPromoPercent = bigPromoPercent; _quickPromoPercent = quickPromoPercent; } function payoutQuickBonus(address userAddress) onlyController public { address dataContractAddress = Etherama(msg.sender).getDataContractAddress(); _promoQuickBonuses[dataContractAddress][userAddress] = SafeMath.add(_promoQuickBonuses[dataContractAddress][userAddress], _currentQuickPromoBonus); _currentQuickPromoBonus = 0; } function payoutBigBonus(address userAddress) onlyController public { address dataContractAddress = Etherama(msg.sender).getDataContractAddress(); _promoBigBonuses[dataContractAddress][userAddress] = SafeMath.add(_promoBigBonuses[dataContractAddress][userAddress], _currentBigPromoBonus); _currentBigPromoBonus = 0; } function addDevReward() onlyController payable public { _devReward = SafeMath.add(_devReward, msg.value); } function withdrawDevReward() onlyAdministrator public { uint256 reward = _devReward; _devReward = 0; msg.sender.transfer(reward); } function getBlockNumSinceInit() public view returns(uint256) { return block.number - getInitBlockNum(); } function getQuickPromoRemainingBlocks() public view returns(uint256) { uint256 d = getBlockNumSinceInit() % _quickPromoBlockInterval; d = d == 0 ? _quickPromoBlockInterval : d; return _quickPromoBlockInterval - d; } function getBigPromoRemainingBlocks() public view returns(uint256) { uint256 d = getBlockNumSinceInit() % _bigPromoBlockInterval; d = d == 0 ? _bigPromoBlockInterval : d; return _bigPromoBlockInterval - d; } function getBonusPerShare(address dataContractAddress) public view returns(uint256) { return _bonusesPerShare[dataContractAddress]; } function getTotalBonusPerShare() public view returns (uint256 res) { for (uint256 i = 0; i < _controllerContractCount; i++) { res = SafeMath.add(res, _bonusesPerShare[Etherama(_controllerIndexer[i]).getDataContractAddress()]); } } function addBonusPerShare() onlyController payable public { EtheramaData data = Etherama(msg.sender)._data(); uint256 shareBonus = (msg.value * MAGNITUDE) / data.getTotalTokenSold(); _bonusesPerShare[address(data)] = SafeMath.add(_bonusesPerShare[address(data)], shareBonus); } function getUserRefBalance(address dataContractAddress, address userAddress) public view returns(uint256) { return _refBalances[dataContractAddress][userAddress]; } function getUserRewardPayouts(address dataContractAddress, address userAddress) public view returns(uint256) { return _rewardPayouts[dataContractAddress][userAddress]; } function resetUserRefBalance(address userAddress) onlyController public { resetUserRefBalance(Etherama(msg.sender).getDataContractAddress(), userAddress); } function resetUserRefBalance(address dataContractAddress, address userAddress) internal { _refBalances[dataContractAddress][userAddress] = 0; } function addUserRefBalance(address userAddress) onlyController payable public { address dataContractAddress = Etherama(msg.sender).getDataContractAddress(); _refBalances[dataContractAddress][userAddress] = SafeMath.add(_refBalances[dataContractAddress][userAddress], msg.value); } function addUserRewardPayouts(address userAddress, uint256 val) onlyController public { addUserRewardPayouts(Etherama(msg.sender).getDataContractAddress(), userAddress, val); } function addUserRewardPayouts(address dataContractAddress, address userAddress, uint256 val) internal { _rewardPayouts[dataContractAddress][userAddress] = SafeMath.add(_rewardPayouts[dataContractAddress][userAddress], val); } function resetUserPromoBonus(address userAddress) onlyController public { resetUserPromoBonus(Etherama(msg.sender).getDataContractAddress(), userAddress); } function resetUserPromoBonus(address dataContractAddress, address userAddress) internal { _promoQuickBonuses[dataContractAddress][userAddress] = 0; _promoBigBonuses[dataContractAddress][userAddress] = 0; } function trackBuy(address userAddress, uint256 volEth, uint256 volToken) onlyController public { address dataContractAddress = Etherama(msg.sender).getDataContractAddress(); _buyCounts[dataContractAddress] = SafeMath.add(_buyCounts[dataContractAddress], 1); _userEthVolumeSaldos[dataContractAddress][userAddress] = SafeMath.add(_userEthVolumeSaldos[dataContractAddress][userAddress], volEth); trackTotalVolume(dataContractAddress, volEth, volToken); } function trackSell(address userAddress, uint256 volEth, uint256 volToken) onlyController public { address dataContractAddress = Etherama(msg.sender).getDataContractAddress(); _sellCounts[dataContractAddress] = SafeMath.add(_sellCounts[dataContractAddress], 1); _userEthVolumeSaldos[dataContractAddress][userAddress] = SafeMath.sub(_userEthVolumeSaldos[dataContractAddress][userAddress], volEth); trackTotalVolume(dataContractAddress, volEth, volToken); } function trackTotalVolume(address dataContractAddress, uint256 volEth, uint256 volToken) internal { _totalVolumeEth[dataContractAddress] = SafeMath.add(_totalVolumeEth[dataContractAddress], volEth); _totalVolumeToken[dataContractAddress] = SafeMath.add(_totalVolumeToken[dataContractAddress], volToken); } function getBuyCount(address dataContractAddress) public view returns (uint256) { return _buyCounts[dataContractAddress]; } function getTotalBuyCount() public view returns (uint256 res) { for (uint256 i = 0; i < _controllerContractCount; i++) { res = SafeMath.add(res, _buyCounts[Etherama(_controllerIndexer[i]).getDataContractAddress()]); } } function getSellCount(address dataContractAddress) public view returns (uint256) { return _sellCounts[dataContractAddress]; } function getTotalSellCount() public view returns (uint256 res) { for (uint256 i = 0; i < _controllerContractCount; i++) { res = SafeMath.add(res, _sellCounts[Etherama(_controllerIndexer[i]).getDataContractAddress()]); } } function getTotalVolumeEth(address dataContractAddress) public view returns (uint256) { return _totalVolumeEth[dataContractAddress]; } function getTotalVolumeToken(address dataContractAddress) public view returns (uint256) { return _totalVolumeToken[dataContractAddress]; } function getUserEthVolumeSaldo(address dataContractAddress, address userAddress) public view returns (uint256) { return _userEthVolumeSaldos[dataContractAddress][userAddress]; } function getUserTotalEthVolumeSaldo(address userAddress) public view returns (uint256 res) { for (uint256 i = 0; i < _controllerContractCount; i++) { res = SafeMath.add(res, _userEthVolumeSaldos[Etherama(_controllerIndexer[i]).getDataContractAddress()][userAddress]); } } function getTotalCollectedPromoBonus() public view returns (uint256) { return SafeMath.add(_currentBigPromoBonus, _currentQuickPromoBonus); } function getUserTotalPromoBonus(address dataContractAddress, address userAddress) public view returns (uint256) { return SafeMath.add(_promoQuickBonuses[dataContractAddress][userAddress], _promoBigBonuses[dataContractAddress][userAddress]); } function getUserQuickPromoBonus(address dataContractAddress, address userAddress) public view returns (uint256) { return _promoQuickBonuses[dataContractAddress][userAddress]; } function getUserBigPromoBonus(address dataContractAddress, address userAddress) public view returns (uint256) { return _promoBigBonuses[dataContractAddress][userAddress]; } function getUserTokenLocalBalance(address dataContractAddress, address userAddress) public view returns(uint256) { return _userTokenLocalBalances[dataContractAddress][userAddress]; } function addUserTokenLocalBalance(address userAddress, uint256 val) onlyController public { address dataContractAddress = Etherama(msg.sender).getDataContractAddress(); _userTokenLocalBalances[dataContractAddress][userAddress] = SafeMath.add(_userTokenLocalBalances[dataContractAddress][userAddress], val); } function subUserTokenLocalBalance(address userAddress, uint256 val) onlyController public { address dataContractAddress = Etherama(msg.sender).getDataContractAddress(); _userTokenLocalBalances[dataContractAddress][userAddress] = SafeMath.sub(_userTokenLocalBalances[dataContractAddress][userAddress], val); } function getUserReward(address dataContractAddress, address userAddress, bool incShareBonus, bool incRefBonus, bool incPromoBonus) public view returns(uint256 reward) { EtheramaData data = EtheramaData(dataContractAddress); if (incShareBonus) { reward = data.getBonusPerShare() * data.getActualUserTokenBalance(userAddress); reward = ((reward < data.getUserRewardPayouts(userAddress)) ? 0 : SafeMath.sub(reward, data.getUserRewardPayouts(userAddress))) / MAGNITUDE; } if (incRefBonus) reward = SafeMath.add(reward, data.getUserRefBalance(userAddress)); if (incPromoBonus) reward = SafeMath.add(reward, data.getUserTotalPromoBonus(userAddress)); return reward; } //user's total reward from all the tokens on the table. includes share reward + referal bonus + promo bonus function getUserTotalReward(address userAddress, bool incShareBonus, bool incRefBonus, bool incPromoBonus) public view returns(uint256 res) { for (uint256 i = 0; i < _controllerContractCount; i++) { address dataContractAddress = Etherama(_controllerIndexer[i]).getDataContractAddress(); res = SafeMath.add(res, getUserReward(dataContractAddress, userAddress, incShareBonus, incRefBonus, incPromoBonus)); } } //current user's reward function getCurrentUserReward(bool incRefBonus, bool incPromoBonus) public view returns(uint256) { return getUserTotalReward(msg.sender, true, incRefBonus, incPromoBonus); } //current user's total reward from all the tokens on the table function getCurrentUserTotalReward() public view returns(uint256) { return getUserTotalReward(msg.sender, true, true, true); } //user's share bonus from all the tokens on the table function getCurrentUserShareBonus() public view returns(uint256) { return getUserTotalReward(msg.sender, true, false, false); } //current user's ref bonus from all the tokens on the table function getCurrentUserRefBonus() public view returns(uint256) { return getUserTotalReward(msg.sender, false, true, false); } //current user's promo bonus from all the tokens on the table function getCurrentUserPromoBonus() public view returns(uint256) { return getUserTotalReward(msg.sender, false, false, true); } //is ref link available for the user function isRefAvailable(address refAddress) public view returns(bool) { return getUserTotalEthVolumeSaldo(refAddress) >= _minRefEthPurchase; } //is ref link available for the current user function isRefAvailable() public view returns(bool) { return isRefAvailable(msg.sender); } //Withdraws all of the user earnings. function withdrawUserReward() public { uint256 reward = getRewardAndPrepareWithdraw(); require(reward > 0); msg.sender.transfer(reward); emit onWithdrawUserBonus(msg.sender, reward); } //gather all the user's reward and prepare it to withdaw function getRewardAndPrepareWithdraw() internal returns(uint256 reward) { for (uint256 i = 0; i < _controllerContractCount; i++) { address dataContractAddress = Etherama(_controllerIndexer[i]).getDataContractAddress(); reward = SafeMath.add(reward, getUserReward(dataContractAddress, msg.sender, true, false, false)); // add share reward to payouts addUserRewardPayouts(dataContractAddress, msg.sender, reward * MAGNITUDE); // add ref bonus reward = SafeMath.add(reward, getUserRefBalance(dataContractAddress, msg.sender)); resetUserRefBalance(dataContractAddress, msg.sender); // add promo bonus reward = SafeMath.add(reward, getUserTotalPromoBonus(dataContractAddress, msg.sender)); resetUserPromoBonus(dataContractAddress, msg.sender); } return reward; } //withdaw all the remamining ETH if there is no one active contract. We don't want to leave them here forever function withdrawRemainingEthAfterAll() onlyAdministrator public { for (uint256 i = 0; i < _controllerContractCount; i++) { if (Etherama(_controllerIndexer[i]).isActive()) revert(); } msg.sender.transfer(address(this).balance); } function calcPercent(uint256 amount, uint256 percent) public pure returns(uint256) { return SafeMath.div(SafeMath.mul(SafeMath.div(amount, 100), percent), 1 ether); } //Converts real num to uint256. Works only with positive numbers. function convertRealTo256(int128 realVal) public pure returns(uint256) { int128 roundedVal = RealMath.fromReal(RealMath.mul(realVal, RealMath.toReal(1e12))); return SafeMath.mul(uint256(roundedVal), uint256(1e6)); } //Converts uint256 to real num. Possible a little loose of precision function convert256ToReal(uint256 val) public pure returns(int128) { uint256 intVal = SafeMath.div(val, 1e6); require(RealMath.isUInt256ValidIn64(intVal)); return RealMath.fraction(int64(intVal), 1e12); } } // Data contract for Etherama contract controller. Data contract cannot be changed so no data can be lost. On the other hand Etherama controller can be replaced if some error is found. contract EtheramaData { // tranding token address address constant public TOKEN_CONTRACT_ADDRESS = 0x83cee9e086A77e492eE0bB93C2B0437aD6fdECCc; // token price in the begining uint256 constant public TOKEN_PRICE_INITIAL = 0.0023 ether; // a percent of the token price which adds/subs each _priceSpeedInterval tokens uint64 constant public PRICE_SPEED_PERCENT = 5; // Token price speed interval. For instance, if PRICE_SPEED_PERCENT = 5 and PRICE_SPEED_INTERVAL = 10000 it means that after 10000 tokens are bought/sold token price will increase/decrease for 5%. uint64 constant public PRICE_SPEED_INTERVAL = 10000; // lock-up period in days. Until this period is expeired nobody can close the contract or withdraw users' funds uint64 constant public EXP_PERIOD_DAYS = 365; mapping(address => bool) private _administrators; uint256 private _administratorCount; uint64 public _initTime; uint64 public _expirationTime; uint256 public _tokenOwnerReward; uint256 public _totalSupply; int128 public _realTokenPrice; address public _controllerAddress = address(0x0); EtheramaCore public _core; uint256 public _initBlockNum; bool public _hasMaxPurchaseLimit = false; IStdToken public _token; //only main contract modifier onlyController() { require(msg.sender == _controllerAddress); _; } constructor(address coreAddress) public { require(coreAddress != address(0x0)); _core = EtheramaCore(coreAddress); _initBlockNum = block.number; } function init() public { require(_controllerAddress == address(0x0)); require(TOKEN_CONTRACT_ADDRESS != address(0x0)); require(RealMath.isUInt64ValidIn64(PRICE_SPEED_PERCENT) && PRICE_SPEED_PERCENT > 0); require(RealMath.isUInt64ValidIn64(PRICE_SPEED_INTERVAL) && PRICE_SPEED_INTERVAL > 0); _controllerAddress = msg.sender; _token = IStdToken(TOKEN_CONTRACT_ADDRESS); _initTime = uint64(now); _expirationTime = _initTime + EXP_PERIOD_DAYS * 1 days; _realTokenPrice = _core.convert256ToReal(TOKEN_PRICE_INITIAL); } function isInited() public view returns(bool) { return (_controllerAddress != address(0x0)); } function getCoreAddress() public view returns(address) { return address(_core); } function setNewControllerAddress(address newAddress) onlyController public { _controllerAddress = newAddress; } function getPromoMinPurchaseEth() public view returns(uint256) { return _core._promoMinPurchaseEth(); } function addAdministator(address addr) onlyController public { _administrators[addr] = true; _administratorCount = SafeMath.add(_administratorCount, 1); } function removeAdministator(address addr) onlyController public { _administrators[addr] = false; _administratorCount = SafeMath.sub(_administratorCount, 1); } function getAdministratorCount() public view returns(uint256) { return _administratorCount; } function isAdministrator(address addr) public view returns(bool) { return _administrators[addr]; } function getCommonInitBlockNum() public view returns (uint256) { return _core.getInitBlockNum(); } function resetTokenOwnerReward() onlyController public { _tokenOwnerReward = 0; } function addTokenOwnerReward(uint256 val) onlyController public { _tokenOwnerReward = SafeMath.add(_tokenOwnerReward, val); } function getCurrentBigPromoBonus() public view returns (uint256) { return _core._currentBigPromoBonus(); } function getCurrentQuickPromoBonus() public view returns (uint256) { return _core._currentQuickPromoBonus(); } function getTotalCollectedPromoBonus() public view returns (uint256) { return _core.getTotalCollectedPromoBonus(); } function setTotalSupply(uint256 val) onlyController public { _totalSupply = val; } function setRealTokenPrice(int128 val) onlyController public { _realTokenPrice = val; } function setHasMaxPurchaseLimit(bool val) onlyController public { _hasMaxPurchaseLimit = val; } function getUserTokenLocalBalance(address userAddress) public view returns(uint256) { return _core.getUserTokenLocalBalance(address(this), userAddress); } function getActualUserTokenBalance(address userAddress) public view returns(uint256) { return SafeMath.min(getUserTokenLocalBalance(userAddress), _token.balanceOf(userAddress)); } function getBonusPerShare() public view returns(uint256) { return _core.getBonusPerShare(address(this)); } function getUserRewardPayouts(address userAddress) public view returns(uint256) { return _core.getUserRewardPayouts(address(this), userAddress); } function getUserRefBalance(address userAddress) public view returns(uint256) { return _core.getUserRefBalance(address(this), userAddress); } function getUserReward(address userAddress, bool incRefBonus, bool incPromoBonus) public view returns(uint256) { return _core.getUserReward(address(this), userAddress, true, incRefBonus, incPromoBonus); } function getUserTotalPromoBonus(address userAddress) public view returns(uint256) { return _core.getUserTotalPromoBonus(address(this), userAddress); } function getUserBigPromoBonus(address userAddress) public view returns(uint256) { return _core.getUserBigPromoBonus(address(this), userAddress); } function getUserQuickPromoBonus(address userAddress) public view returns(uint256) { return _core.getUserQuickPromoBonus(address(this), userAddress); } function getRemainingTokenAmount() public view returns(uint256) { return _token.balanceOf(_controllerAddress); } function getTotalTokenSold() public view returns(uint256) { return _totalSupply - getRemainingTokenAmount(); } function getUserEthVolumeSaldo(address userAddress) public view returns(uint256) { return _core.getUserEthVolumeSaldo(address(this), userAddress); } } contract Etherama { IStdToken public _token; EtheramaData public _data; EtheramaCore public _core; bool public isActive = false; bool public isMigrationToNewControllerInProgress = false; bool public isActualContractVer = true; address public migrationContractAddress = address(0x0); bool public isMigrationApproved = false; address private _creator = address(0x0); event onTokenPurchase(address indexed userAddress, uint256 incomingEth, uint256 tokensMinted, address indexed referredBy); event onTokenSell(address indexed userAddress, uint256 tokensBurned, uint256 ethEarned); event onReinvestment(address indexed userAddress, uint256 ethReinvested, uint256 tokensMinted); event onWithdrawTokenOwnerReward(address indexed toAddress, uint256 ethWithdrawn); event onWinQuickPromo(address indexed userAddress, uint256 ethWon); event onWinBigPromo(address indexed userAddress, uint256 ethWon); // only people with tokens modifier onlyContractUsers() { require(getUserLocalTokenBalance(msg.sender) > 0); _; } // administrators can: // -> change minimal amout of tokens to get a ref link. // administrators CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens // -> suspend the contract modifier onlyAdministrator() { require(isCurrentUserAdministrator()); _; } //core administrator can only approve contract migration after its code review modifier onlyCoreAdministrator() { require(_core.isAdministrator(msg.sender)); _; } // only active state of the contract. Administator can activate it, but canncon deactive untill lock-up period is expired. modifier onlyActive() { require(isActive); _; } // maximum gas price for buy/sell transactions to avoid "front runner" vulnerability. modifier validGasPrice() { require(tx.gasprice <= _core.MAX_GAS_PRICE()); _; } // eth value must be greater than 0 for purchase transactions modifier validPayableValue() { require(msg.value > 0); _; } modifier onlyCoreContract() { require(msg.sender == _data.getCoreAddress()); _; } // dataContractAddress - data contract address where all the data is collected and separated from the controller constructor(address dataContractAddress) public { require(dataContractAddress != address(0x0)); _data = EtheramaData(dataContractAddress); if (!_data.isInited()) { _data.init(); _data.addAdministator(msg.sender); _creator = msg.sender; } _token = _data._token(); _core = _data._core(); } function addAdministator(address addr) onlyAdministrator public { _data.addAdministator(addr); } function removeAdministator(address addr) onlyAdministrator public { _data.removeAdministator(addr); } // transfer ownership request of the contract to token owner from contract creator. The new administator has to accept ownership to finish the transferring. function transferOwnershipRequest(address addr) onlyAdministrator public { addAdministator(addr); } // accept transfer ownership. function acceptOwnership() onlyAdministrator public { require(_creator != address(0x0)); removeAdministator(_creator); require(_data.getAdministratorCount() == 1); } // if there is a maximim purchase limit then a user can buy only amount of tokens which he had before, not more. function setHasMaxPurchaseLimit(bool val) onlyAdministrator public { _data.setHasMaxPurchaseLimit(val); } // activate the controller contract. After calling this function anybody can start trading the contrant's tokens function activate() onlyAdministrator public { require(!isActive); if (getTotalTokenSupply() == 0) setTotalSupply(); require(getTotalTokenSupply() > 0); isActive = true; isMigrationToNewControllerInProgress = false; } // Close the contract and withdraw all the funds. The contract cannot be closed before lock up period is expired. function finish() onlyActive onlyAdministrator public { require(uint64(now) >= _data._expirationTime()); _token.transfer(msg.sender, getRemainingTokenAmount()); msg.sender.transfer(getTotalEthBalance()); isActive = false; } //Converts incoming eth to tokens function buy(address refAddress, uint256 minReturn) onlyActive validGasPrice validPayableValue public payable returns(uint256) { return purchaseTokens(msg.value, refAddress, minReturn); } //sell tokens for eth. before call this func you have to call "approve" in the ERC20 token contract function sell(uint256 tokenAmount, uint256 minReturn) onlyActive onlyContractUsers validGasPrice public returns(uint256) { if (tokenAmount > getCurrentUserLocalTokenBalance() || tokenAmount == 0) return 0; uint256 ethAmount = 0; uint256 totalFeeEth = 0; uint256 tokenPrice = 0; (ethAmount, totalFeeEth, tokenPrice) = estimateSellOrder(tokenAmount, true); require(ethAmount >= minReturn); subUserTokens(msg.sender, tokenAmount); msg.sender.transfer(ethAmount); updateTokenPrice(-_core.convert256ToReal(tokenAmount)); distributeFee(totalFeeEth, address(0x0)); uint256 userEthVol = _data.getUserEthVolumeSaldo(msg.sender); _core.trackSell(msg.sender, ethAmount > userEthVol ? userEthVol : ethAmount, tokenAmount); emit onTokenSell(msg.sender, tokenAmount, ethAmount); return ethAmount; } function transferTokens(address toUser, uint256 tokenAmount) onlyActive onlyContractUsers public { require(getUserLocalTokenBalance(msg.sender) >= tokenAmount); _core.subUserTokenLocalBalance(msg.sender, tokenAmount); _core.addUserTokenLocalBalance(toUser, tokenAmount); _token.transferFrom(msg.sender, toUser, tokenAmount); } //Fallback function to handle eth that was sent straight to the contract function() onlyActive validGasPrice validPayableValue payable external { purchaseTokens(msg.value, address(0x0), 1); } // withdraw token owner's reward function withdrawTokenOwnerReward() onlyAdministrator public { uint256 reward = getTokenOwnerReward(); require(reward > 0); _data.resetTokenOwnerReward(); msg.sender.transfer(reward); emit onWithdrawTokenOwnerReward(msg.sender, reward); } // prepare the contract for migration to another one in case of some errors or refining function prepareForMigration() onlyAdministrator public { require(!isMigrationToNewControllerInProgress); isMigrationToNewControllerInProgress = true; } // accept funds transfer to a new controller during a migration. function migrateFunds() payable public { require(isMigrationToNewControllerInProgress); } //HELPERS // max gas price for buy/sell transactions function getMaxGasPrice() public view returns(uint256) { return _core.MAX_GAS_PRICE(); } // max gas price for buy/sell transactions function getExpirationTime() public view returns (uint256) { return _data._expirationTime(); } // time till lock-up period is expired function getRemainingTimeTillExpiration() public view returns (uint256) { if (_data._expirationTime() <= uint64(now)) return 0; return _data._expirationTime() - uint64(now); } function isCurrentUserAdministrator() public view returns(bool) { return _data.isAdministrator(msg.sender); } //data contract address where all the data is holded function getDataContractAddress() public view returns(address) { return address(_data); } // get trading token contract address function getTokenAddress() public view returns(address) { return address(_token); } // request migration to new contract. After request Etherama dev team should review its code and approve it if it is OK function requestControllerContractMigration(address newControllerAddr) onlyAdministrator public { require(!isMigrationApproved); migrationContractAddress = newControllerAddr; } // Dev team gives a pervission to updagrade the contract after code review, transfer all the funds, activate new abilities or fix some errors. function approveControllerContractMigration() onlyCoreAdministrator public { isMigrationApproved = true; } //migrate to new controller contract in case of some mistake in the contract and transfer there all the tokens and eth. It can be done only after code review by Etherama developers. function migrateToNewNewControllerContract() onlyAdministrator public { require(isMigrationApproved && migrationContractAddress != address(0x0) && isActualContractVer); isActive = false; Etherama newController = Etherama(address(migrationContractAddress)); _data.setNewControllerAddress(migrationContractAddress); uint256 remainingTokenAmount = getRemainingTokenAmount(); uint256 ethBalance = getTotalEthBalance(); if (remainingTokenAmount > 0) _token.transfer(migrationContractAddress, remainingTokenAmount); if (ethBalance > 0) newController.migrateFunds.value(ethBalance)(); isActualContractVer = false; } //total buy count function getBuyCount() public view returns(uint256) { return _core.getBuyCount(getDataContractAddress()); } //total sell count function getSellCount() public view returns(uint256) { return _core.getSellCount(getDataContractAddress()); } //total eth volume function getTotalVolumeEth() public view returns(uint256) { return _core.getTotalVolumeEth(getDataContractAddress()); } //total token volume function getTotalVolumeToken() public view returns(uint256) { return _core.getTotalVolumeToken(getDataContractAddress()); } //current bonus per 1 token in ETH function getBonusPerShare() public view returns (uint256) { return SafeMath.div(SafeMath.mul(_data.getBonusPerShare(), 1 ether), _core.MAGNITUDE()); } //token initial price in ETH function getTokenInitialPrice() public view returns(uint256) { return _data.TOKEN_PRICE_INITIAL(); } function getDevRewardPercent() public view returns(uint256) { return _core._devRewardPercent(); } function getTokenOwnerRewardPercent() public view returns(uint256) { return _core._tokenOwnerRewardPercent(); } function getShareRewardPercent() public view returns(uint256) { return _core._shareRewardPercent(); } function getRefBonusPercent() public view returns(uint256) { return _core._refBonusPercent(); } function getBigPromoPercent() public view returns(uint256) { return _core._bigPromoPercent(); } function getQuickPromoPercent() public view returns(uint256) { return _core._quickPromoPercent(); } function getBigPromoBlockInterval() public view returns(uint256) { return _core._bigPromoBlockInterval(); } function getQuickPromoBlockInterval() public view returns(uint256) { return _core._quickPromoBlockInterval(); } function getPromoMinPurchaseEth() public view returns(uint256) { return _core._promoMinPurchaseEth(); } function getPriceSpeedPercent() public view returns(uint64) { return _data.PRICE_SPEED_PERCENT(); } function getPriceSpeedTokenBlock() public view returns(uint64) { return _data.PRICE_SPEED_INTERVAL(); } function getMinRefEthPurchase() public view returns (uint256) { return _core._minRefEthPurchase(); } function getTotalCollectedPromoBonus() public view returns (uint256) { return _data.getTotalCollectedPromoBonus(); } function getCurrentBigPromoBonus() public view returns (uint256) { return _data.getCurrentBigPromoBonus(); } function getCurrentQuickPromoBonus() public view returns (uint256) { return _data.getCurrentQuickPromoBonus(); } //current token price function getCurrentTokenPrice() public view returns(uint256) { return _core.convertRealTo256(_data._realTokenPrice()); } //contract's eth balance function getTotalEthBalance() public view returns(uint256) { return address(this).balance; } //amount of tokens which were funded to the contract initially function getTotalTokenSupply() public view returns(uint256) { return _data._totalSupply(); } //amount of tokens which are still available for selling on the contract function getRemainingTokenAmount() public view returns(uint256) { return _token.balanceOf(address(this)); } //amount of tokens which where sold by the contract function getTotalTokenSold() public view returns(uint256) { return getTotalTokenSupply() - getRemainingTokenAmount(); } //user's token amount which were bought from the contract function getUserLocalTokenBalance(address userAddress) public view returns(uint256) { return _data.getUserTokenLocalBalance(userAddress); } //current user's token amount which were bought from the contract function getCurrentUserLocalTokenBalance() public view returns(uint256) { return getUserLocalTokenBalance(msg.sender); } //is referal link available for the current user function isCurrentUserRefAvailable() public view returns(bool) { return _core.isRefAvailable(); } function getCurrentUserRefBonus() public view returns(uint256) { return _data.getUserRefBalance(msg.sender); } function getCurrentUserPromoBonus() public view returns(uint256) { return _data.getUserTotalPromoBonus(msg.sender); } //max and min values of a deal in tokens function getTokenDealRange() public view returns(uint256, uint256) { return (_core.MIN_TOKEN_DEAL_VAL(), _core.MAX_TOKEN_DEAL_VAL()); } //max and min values of a deal in ETH function getEthDealRange() public view returns(uint256, uint256) { uint256 minTokenVal; uint256 maxTokenVal; (minTokenVal, maxTokenVal) = getTokenDealRange(); return ( SafeMath.max(_core.MIN_ETH_DEAL_VAL(), tokensToEth(minTokenVal, true)), SafeMath.min(_core.MAX_ETH_DEAL_VAL(), tokensToEth(maxTokenVal, true)) ); } //user's total reward from all the tokens on the table. includes share reward + referal bonus + promo bonus function getUserReward(address userAddress, bool isTotal) public view returns(uint256) { return isTotal ? _core.getUserTotalReward(userAddress, true, true, true) : _data.getUserReward(userAddress, true, true); } //price for selling 1 token. mostly useful only for frontend function get1TokenSellPrice() public view returns(uint256) { uint256 tokenAmount = 1 ether; uint256 ethAmount = 0; uint256 totalFeeEth = 0; uint256 tokenPrice = 0; (ethAmount, totalFeeEth, tokenPrice) = estimateSellOrder(tokenAmount, true); return ethAmount; } //price for buying 1 token. mostly useful only for frontend function get1TokenBuyPrice() public view returns(uint256) { uint256 ethAmount = 1 ether; uint256 tokenAmount = 0; uint256 totalFeeEth = 0; uint256 tokenPrice = 0; (tokenAmount, totalFeeEth, tokenPrice) = estimateBuyOrder(ethAmount, true); return SafeMath.div(ethAmount * 1 ether, tokenAmount); } //calc current reward for holding @tokenAmount tokens function calcReward(uint256 tokenAmount) public view returns(uint256) { return (uint256) ((int256)(_data.getBonusPerShare() * tokenAmount)) / _core.MAGNITUDE(); } //esimate buy order by amount of ETH/tokens. returns tokens/eth amount after the deal, total fee in ETH and average token price function estimateBuyOrder(uint256 amount, bool fromEth) public view returns(uint256, uint256, uint256) { uint256 minAmount; uint256 maxAmount; (minAmount, maxAmount) = fromEth ? getEthDealRange() : getTokenDealRange(); //require(amount >= minAmount && amount <= maxAmount); uint256 ethAmount = fromEth ? amount : tokensToEth(amount, true); require(ethAmount > 0); uint256 tokenAmount = fromEth ? ethToTokens(amount, true) : amount; uint256 totalFeeEth = calcTotalFee(tokenAmount, true); require(ethAmount > totalFeeEth); uint256 tokenPrice = SafeMath.div(ethAmount * 1 ether, tokenAmount); return (fromEth ? tokenAmount : SafeMath.add(ethAmount, totalFeeEth), totalFeeEth, tokenPrice); } //esimate sell order by amount of tokens/ETH. returns eth/tokens amount after the deal, total fee in ETH and average token price function estimateSellOrder(uint256 amount, bool fromToken) public view returns(uint256, uint256, uint256) { uint256 minAmount; uint256 maxAmount; (minAmount, maxAmount) = fromToken ? getTokenDealRange() : getEthDealRange(); //require(amount >= minAmount && amount <= maxAmount); uint256 tokenAmount = fromToken ? amount : ethToTokens(amount, false); require(tokenAmount > 0); uint256 ethAmount = fromToken ? tokensToEth(tokenAmount, false) : amount; uint256 totalFeeEth = calcTotalFee(tokenAmount, false); require(ethAmount > totalFeeEth); uint256 tokenPrice = SafeMath.div(ethAmount * 1 ether, tokenAmount); return (fromToken ? ethAmount : tokenAmount, totalFeeEth, tokenPrice); } //returns max user's purchase limit in tokens if _hasMaxPurchaseLimit pamam is set true. If it is a user cannot by more tokens that hs already bought on some other exchange function getUserMaxPurchase(address userAddress) public view returns(uint256) { return _token.balanceOf(userAddress) - SafeMath.mul(getUserLocalTokenBalance(userAddress), 2); } //current urser's max purchase limit in tokens function getCurrentUserMaxPurchase() public view returns(uint256) { return getUserMaxPurchase(msg.sender); } //token owener collected reward function getTokenOwnerReward() public view returns(uint256) { return _data._tokenOwnerReward(); } //current user's won promo bonuses function getCurrentUserTotalPromoBonus() public view returns(uint256) { return _data.getUserTotalPromoBonus(msg.sender); } //current user's won big promo bonuses function getCurrentUserBigPromoBonus() public view returns(uint256) { return _data.getUserBigPromoBonus(msg.sender); } //current user's won quick promo bonuses function getCurrentUserQuickPromoBonus() public view returns(uint256) { return _data.getUserQuickPromoBonus(msg.sender); } //amount of block since core contract is deployed function getBlockNumSinceInit() public view returns(uint256) { return _core.getBlockNumSinceInit(); } //remaing amount of blocks to win a quick promo bonus function getQuickPromoRemainingBlocks() public view returns(uint256) { return _core.getQuickPromoRemainingBlocks(); } //remaing amount of blocks to win a big promo bonus function getBigPromoRemainingBlocks() public view returns(uint256) { return _core.getBigPromoRemainingBlocks(); } // INTERNAL FUNCTIONS function purchaseTokens(uint256 ethAmount, address refAddress, uint256 minReturn) internal returns(uint256) { uint256 tokenAmount = 0; uint256 totalFeeEth = 0; uint256 tokenPrice = 0; (tokenAmount, totalFeeEth, tokenPrice) = estimateBuyOrder(ethAmount, true); require(tokenAmount >= minReturn); if (_data._hasMaxPurchaseLimit()) { //user has to have at least equal amount of tokens which he's willing to buy require(getCurrentUserMaxPurchase() >= tokenAmount); } require(tokenAmount > 0 && (SafeMath.add(tokenAmount, getTotalTokenSold()) > getTotalTokenSold())); if (refAddress == msg.sender || !_core.isRefAvailable(refAddress)) refAddress = address(0x0); distributeFee(totalFeeEth, refAddress); addUserTokens(msg.sender, tokenAmount); // the user is not going to receive any reward for the current purchase _core.addUserRewardPayouts(msg.sender, _data.getBonusPerShare() * tokenAmount); checkAndSendPromoBonus(ethAmount); updateTokenPrice(_core.convert256ToReal(tokenAmount)); _core.trackBuy(msg.sender, ethAmount, tokenAmount); emit onTokenPurchase(msg.sender, ethAmount, tokenAmount, refAddress); return tokenAmount; } function setTotalSupply() internal { require(_data._totalSupply() == 0); uint256 tokenAmount = _token.balanceOf(address(this)); _data.setTotalSupply(tokenAmount); } function checkAndSendPromoBonus(uint256 purchaseAmountEth) internal { if (purchaseAmountEth < _data.getPromoMinPurchaseEth()) return; if (getQuickPromoRemainingBlocks() == 0) sendQuickPromoBonus(); if (getBigPromoRemainingBlocks() == 0) sendBigPromoBonus(); } function sendQuickPromoBonus() internal { _core.payoutQuickBonus(msg.sender); emit onWinQuickPromo(msg.sender, _data.getCurrentQuickPromoBonus()); } function sendBigPromoBonus() internal { _core.payoutBigBonus(msg.sender); emit onWinBigPromo(msg.sender, _data.getCurrentBigPromoBonus()); } function distributeFee(uint256 totalFeeEth, address refAddress) internal { addProfitPerShare(totalFeeEth, refAddress); addDevReward(totalFeeEth); addTokenOwnerReward(totalFeeEth); addBigPromoBonus(totalFeeEth); addQuickPromoBonus(totalFeeEth); } function addProfitPerShare(uint256 totalFeeEth, address refAddress) internal { uint256 refBonus = calcRefBonus(totalFeeEth); uint256 totalShareReward = calcTotalShareRewardFee(totalFeeEth); if (refAddress != address(0x0)) { _core.addUserRefBalance.value(refBonus)(refAddress); } else { totalShareReward = SafeMath.add(totalShareReward, refBonus); } if (getTotalTokenSold() == 0) { _data.addTokenOwnerReward(totalShareReward); } else { _core.addBonusPerShare.value(totalShareReward)(); } } function addDevReward(uint256 totalFeeEth) internal { _core.addDevReward.value(calcDevReward(totalFeeEth))(); } function addTokenOwnerReward(uint256 totalFeeEth) internal { _data.addTokenOwnerReward(calcTokenOwnerReward(totalFeeEth)); } function addBigPromoBonus(uint256 totalFeeEth) internal { _core.addBigPromoBonus.value(calcBigPromoBonus(totalFeeEth))(); } function addQuickPromoBonus(uint256 totalFeeEth) internal { _core.addQuickPromoBonus.value(calcQuickPromoBonus(totalFeeEth))(); } function addUserTokens(address user, uint256 tokenAmount) internal { _core.addUserTokenLocalBalance(user, tokenAmount); _token.transfer(msg.sender, tokenAmount); } function subUserTokens(address user, uint256 tokenAmount) internal { _core.subUserTokenLocalBalance(user, tokenAmount); _token.transferFrom(user, address(this), tokenAmount); } function updateTokenPrice(int128 realTokenAmount) public { _data.setRealTokenPrice(calc1RealTokenRateFromRealTokens(realTokenAmount)); } function ethToTokens(uint256 ethAmount, bool isBuy) internal view returns(uint256) { int128 realEthAmount = _core.convert256ToReal(ethAmount); int128 t0 = RealMath.div(realEthAmount, _data._realTokenPrice()); int128 s = getRealPriceSpeed(); int128 tn = RealMath.div(t0, RealMath.toReal(100)); for (uint i = 0; i < 100; i++) { int128 tns = RealMath.mul(tn, s); int128 exptns = RealMath.exp( RealMath.mul(tns, RealMath.toReal(isBuy ? int64(1) : int64(-1))) ); int128 tn1 = RealMath.div( RealMath.mul( RealMath.mul(tns, tn), exptns ) + t0, RealMath.mul( exptns, RealMath.toReal(1) + tns ) ); if (RealMath.abs(tn-tn1) < RealMath.fraction(1, 1e18)) break; tn = tn1; } return _core.convertRealTo256(tn); } function tokensToEth(uint256 tokenAmount, bool isBuy) internal view returns(uint256) { int128 realTokenAmount = _core.convert256ToReal(tokenAmount); int128 s = getRealPriceSpeed(); int128 expArg = RealMath.mul(RealMath.mul(realTokenAmount, s), RealMath.toReal(isBuy ? int64(1) : int64(-1))); int128 realEthAmountFor1Token = RealMath.mul(_data._realTokenPrice(), RealMath.exp(expArg)); int128 realEthAmount = RealMath.mul(realTokenAmount, realEthAmountFor1Token); return _core.convertRealTo256(realEthAmount); } function calcTotalFee(uint256 tokenAmount, bool isBuy) internal view returns(uint256) { int128 realTokenAmount = _core.convert256ToReal(tokenAmount); int128 factor = RealMath.toReal(isBuy ? int64(1) : int64(-1)); int128 rateAfterDeal = calc1RealTokenRateFromRealTokens(RealMath.mul(realTokenAmount, factor)); int128 delta = RealMath.div(rateAfterDeal - _data._realTokenPrice(), RealMath.toReal(2)); int128 fee = RealMath.mul(realTokenAmount, delta); //commission for sells is a bit lower due to rounding error if (!isBuy) fee = RealMath.mul(fee, RealMath.fraction(95, 100)); return _core.calcPercent(_core.convertRealTo256(RealMath.mul(fee, factor)), _core._totalIncomeFeePercent()); } function calc1RealTokenRateFromRealTokens(int128 realTokenAmount) internal view returns(int128) { int128 expArg = RealMath.mul(realTokenAmount, getRealPriceSpeed()); return RealMath.mul(_data._realTokenPrice(), RealMath.exp(expArg)); } function getRealPriceSpeed() internal view returns(int128) { require(RealMath.isUInt64ValidIn64(_data.PRICE_SPEED_PERCENT())); require(RealMath.isUInt64ValidIn64(_data.PRICE_SPEED_INTERVAL())); return RealMath.div(RealMath.fraction(int64(_data.PRICE_SPEED_PERCENT()), 100), RealMath.toReal(int64(_data.PRICE_SPEED_INTERVAL()))); } function calcTotalShareRewardFee(uint256 totalFee) internal view returns(uint256) { return _core.calcPercent(totalFee, _core._shareRewardPercent()); } function calcRefBonus(uint256 totalFee) internal view returns(uint256) { return _core.calcPercent(totalFee, _core._refBonusPercent()); } function calcTokenOwnerReward(uint256 totalFee) internal view returns(uint256) { return _core.calcPercent(totalFee, _core._tokenOwnerRewardPercent()); } function calcDevReward(uint256 totalFee) internal view returns(uint256) { return _core.calcPercent(totalFee, _core._devRewardPercent()); } function calcQuickPromoBonus(uint256 totalFee) internal view returns(uint256) { return _core.calcPercent(totalFee, _core._quickPromoPercent()); } function calcBigPromoBonus(uint256 totalFee) internal view returns(uint256) { return _core.calcPercent(totalFee, _core._bigPromoPercent()); } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } function max(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? b : a; } } //taken from https://github.com/NovakDistributed/macroverse/blob/master/contracts/RealMath.sol and a bit modified library RealMath { int64 constant MIN_INT64 = int64((uint64(1) << 63)); int64 constant MAX_INT64 = int64(~((uint64(1) << 63))); /** * How many total bits are there? */ int256 constant REAL_BITS = 128; /** * How many fractional bits are there? */ int256 constant REAL_FBITS = 64; /** * How many integer bits are there? */ int256 constant REAL_IBITS = REAL_BITS - REAL_FBITS; /** * What's the first non-fractional bit */ int128 constant REAL_ONE = int128(1) << REAL_FBITS; /** * What's the last fractional bit? */ int128 constant REAL_HALF = REAL_ONE >> 1; /** * What's two? Two is pretty useful. */ int128 constant REAL_TWO = REAL_ONE << 1; /** * And our logarithms are based on ln(2). */ int128 constant REAL_LN_TWO = 762123384786; /** * It is also useful to have Pi around. */ int128 constant REAL_PI = 3454217652358; /** * And half Pi, to save on divides. * TODO: That might not be how the compiler handles constants. */ int128 constant REAL_HALF_PI = 1727108826179; /** * And two pi, which happens to be odd in its most accurate representation. */ int128 constant REAL_TWO_PI = 6908435304715; /** * What's the sign bit? */ int128 constant SIGN_MASK = int128(1) << 127; function getMinInt64() internal pure returns (int64) { return MIN_INT64; } function getMaxInt64() internal pure returns (int64) { return MAX_INT64; } function isUInt256ValidIn64(uint256 val) internal pure returns (bool) { return val >= 0 && val <= uint256(getMaxInt64()); } function isInt256ValidIn64(int256 val) internal pure returns (bool) { return val >= int256(getMinInt64()) && val <= int256(getMaxInt64()); } function isUInt64ValidIn64(uint64 val) internal pure returns (bool) { return val >= 0 && val <= uint64(getMaxInt64()); } function isInt128ValidIn64(int128 val) internal pure returns (bool) { return val >= int128(getMinInt64()) && val <= int128(getMaxInt64()); } /** * Convert an integer to a real. Preserves sign. */ function toReal(int64 ipart) internal pure returns (int128) { return int128(ipart) * REAL_ONE; } /** * Convert a real to an integer. Preserves sign. */ function fromReal(int128 real_value) internal pure returns (int64) { int128 intVal = real_value / REAL_ONE; require(isInt128ValidIn64(intVal)); return int64(intVal); } /** * Get the absolute value of a real. Just the same as abs on a normal int128. */ function abs(int128 real_value) internal pure returns (int128) { if (real_value > 0) { return real_value; } else { return -real_value; } } /** * Get the fractional part of a real, as a real. Ignores sign (so fpart(-0.5) is 0.5). */ function fpart(int128 real_value) internal pure returns (int128) { // This gets the fractional part but strips the sign return abs(real_value) % REAL_ONE; } /** * Get the fractional part of a real, as a real. Respects sign (so fpartSigned(-0.5) is -0.5). */ function fpartSigned(int128 real_value) internal pure returns (int128) { // This gets the fractional part but strips the sign int128 fractional = fpart(real_value); return real_value < 0 ? -fractional : fractional; } /** * Get the integer part of a fixed point value. */ function ipart(int128 real_value) internal pure returns (int128) { // Subtract out the fractional part to get the real part. return real_value - fpartSigned(real_value); } /** * Multiply one real by another. Truncates overflows. */ function mul(int128 real_a, int128 real_b) internal pure returns (int128) { // When multiplying fixed point in x.y and z.w formats we get (x+z).(y+w) format. // So we just have to clip off the extra REAL_FBITS fractional bits. return int128((int256(real_a) * int256(real_b)) >> REAL_FBITS); } /** * Divide one real by another real. Truncates overflows. */ function div(int128 real_numerator, int128 real_denominator) internal pure returns (int128) { // We use the reverse of the multiplication trick: convert numerator from // x.y to (x+z).(y+w) fixed point, then divide by denom in z.w fixed point. return int128((int256(real_numerator) * REAL_ONE) / int256(real_denominator)); } /** * Create a real from a rational fraction. */ function fraction(int64 numerator, int64 denominator) internal pure returns (int128) { return div(toReal(numerator), toReal(denominator)); } // Now we have some fancy math things (like pow and trig stuff). This isn't // in the RealMath that was deployed with the original Macroverse // deployment, so it needs to be linked into your contract statically. /** * Raise a number to a positive integer power in O(log power) time. * See <https://stackoverflow.com/a/101613> */ function ipow(int128 real_base, int64 exponent) internal pure returns (int128) { if (exponent < 0) { // Negative powers are not allowed here. revert(); } // Start with the 0th power int128 real_result = REAL_ONE; while (exponent != 0) { // While there are still bits set if ((exponent & 0x1) == 0x1) { // If the low bit is set, multiply in the (many-times-squared) base real_result = mul(real_result, real_base); } // Shift off the low bit exponent = exponent >> 1; // Do the squaring real_base = mul(real_base, real_base); } // Return the final result. return real_result; } /** * Zero all but the highest set bit of a number. * See <https://stackoverflow.com/a/53184> */ function hibit(uint256 val) internal pure returns (uint256) { // Set all the bits below the highest set bit val |= (val >> 1); val |= (val >> 2); val |= (val >> 4); val |= (val >> 8); val |= (val >> 16); val |= (val >> 32); val |= (val >> 64); val |= (val >> 128); return val ^ (val >> 1); } /** * Given a number with one bit set, finds the index of that bit. */ function findbit(uint256 val) internal pure returns (uint8 index) { index = 0; // We and the value with alternating bit patters of various pitches to find it. if (val & 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA != 0) { // Picth 1 index |= 1; } if (val & 0xCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC != 0) { // Pitch 2 index |= 2; } if (val & 0xF0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0 != 0) { // Pitch 4 index |= 4; } if (val & 0xFF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00 != 0) { // Pitch 8 index |= 8; } if (val & 0xFFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000 != 0) { // Pitch 16 index |= 16; } if (val & 0xFFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000 != 0) { // Pitch 32 index |= 32; } if (val & 0xFFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF0000000000000000 != 0) { // Pitch 64 index |= 64; } if (val & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000 != 0) { // Pitch 128 index |= 128; } } /** * Shift real_arg left or right until it is between 1 and 2. Return the * rescaled value, and the number of bits of right shift applied. Shift may be negative. * * Expresses real_arg as real_scaled * 2^shift, setting shift to put real_arg between [1 and 2). * * Rejects 0 or negative arguments. */ function rescale(int128 real_arg) internal pure returns (int128 real_scaled, int64 shift) { if (real_arg <= 0) { // Not in domain! revert(); } require(isInt256ValidIn64(REAL_FBITS)); // Find the high bit int64 high_bit = findbit(hibit(uint256(real_arg))); // We'll shift so the high bit is the lowest non-fractional bit. shift = high_bit - int64(REAL_FBITS); if (shift < 0) { // Shift left real_scaled = real_arg << -shift; } else if (shift >= 0) { // Shift right real_scaled = real_arg >> shift; } } /** * Calculate the natural log of a number. Rescales the input value and uses * the algorithm outlined at <https://math.stackexchange.com/a/977836> and * the ipow implementation. * * Lets you artificially limit the number of iterations. * * Note that it is potentially possible to get an un-converged value; lack * of convergence does not throw. */ function lnLimited(int128 real_arg, int max_iterations) internal pure returns (int128) { if (real_arg <= 0) { // Outside of acceptable domain revert(); } if (real_arg == REAL_ONE) { // Handle this case specially because people will want exactly 0 and // not ~2^-39 ish. return 0; } // We know it's positive, so rescale it to be between [1 and 2) int128 real_rescaled; int64 shift; (real_rescaled, shift) = rescale(real_arg); // Compute the argument to iterate on int128 real_series_arg = div(real_rescaled - REAL_ONE, real_rescaled + REAL_ONE); // We will accumulate the result here int128 real_series_result = 0; for (int64 n = 0; n < max_iterations; n++) { // Compute term n of the series int128 real_term = div(ipow(real_series_arg, 2 * n + 1), toReal(2 * n + 1)); // And add it in real_series_result += real_term; if (real_term == 0) { // We must have converged. Next term is too small to represent. break; } // If we somehow never converge I guess we will run out of gas } // Double it to account for the factor of 2 outside the sum real_series_result = mul(real_series_result, REAL_TWO); // Now compute and return the overall result return mul(toReal(shift), REAL_LN_TWO) + real_series_result; } /** * Calculate a natural logarithm with a sensible maximum iteration count to * wait until convergence. Note that it is potentially possible to get an * un-converged value; lack of convergence does not throw. */ function ln(int128 real_arg) internal pure returns (int128) { return lnLimited(real_arg, 100); } /** * Calculate e^x. Uses the series given at * <http://pages.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/exp.html>. * * Lets you artificially limit the number of iterations. * * Note that it is potentially possible to get an un-converged value; lack * of convergence does not throw. */ function expLimited(int128 real_arg, int max_iterations) internal pure returns (int128) { // We will accumulate the result here int128 real_result = 0; // We use this to save work computing terms int128 real_term = REAL_ONE; for (int64 n = 0; n < max_iterations; n++) { // Add in the term real_result += real_term; // Compute the next term real_term = mul(real_term, div(real_arg, toReal(n + 1))); if (real_term == 0) { // We must have converged. Next term is too small to represent. break; } // If we somehow never converge I guess we will run out of gas } // Return the result return real_result; } function expLimited(int128 real_arg, int max_iterations, int k) internal pure returns (int128) { // We will accumulate the result here int128 real_result = 0; // We use this to save work computing terms int128 real_term = REAL_ONE; for (int64 n = 0; n < max_iterations; n++) { // Add in the term real_result += real_term; // Compute the next term real_term = mul(real_term, div(real_arg, toReal(n + 1))); if (real_term == 0) { // We must have converged. Next term is too small to represent. break; } if (n == k) return real_term; // If we somehow never converge I guess we will run out of gas } // Return the result return real_result; } /** * Calculate e^x with a sensible maximum iteration count to wait until * convergence. Note that it is potentially possible to get an un-converged * value; lack of convergence does not throw. */ function exp(int128 real_arg) internal pure returns (int128) { return expLimited(real_arg, 100); } /** * Raise any number to any power, except for negative bases to fractional powers. */ function pow(int128 real_base, int128 real_exponent) internal pure returns (int128) { if (real_exponent == 0) { // Anything to the 0 is 1 return REAL_ONE; } if (real_base == 0) { if (real_exponent < 0) { // Outside of domain! revert(); } // Otherwise it's 0 return 0; } if (fpart(real_exponent) == 0) { // Anything (even a negative base) is super easy to do to an integer power. if (real_exponent > 0) { // Positive integer power is easy return ipow(real_base, fromReal(real_exponent)); } else { // Negative integer power is harder return div(REAL_ONE, ipow(real_base, fromReal(-real_exponent))); } } if (real_base < 0) { // It's a negative base to a non-integer power. // In general pow(-x^y) is undefined, unless y is an int or some // weird rational-number-based relationship holds. revert(); } // If it's not a special case, actually do it. return exp(mul(real_exponent, ln(real_base))); } }
Divide one real by another real. Truncates overflows./ We use the reverse of the multiplication trick: convert numerator from x.y to (x+z).(y+w) fixed point, then divide by denom in z.w fixed point.
function div(int128 real_numerator, int128 real_denominator) internal pure returns (int128) { return int128((int256(real_numerator) * REAL_ONE) / int256(real_denominator)); }
1,321,914
./partial_match/1/0x6D061EBFd8BDF5D574A7029E918341B1736d6F6c/sources/SmolTingPot.sol
view function to calculate the total pending TINGs of address across all pools
function totalPendingTing(address _user) public view returns (uint256) { uint256 total = 0; uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { total = total.add(pendingTing(pid, _user)); } return total; }
3,893,452
./full_match/80001/0x4Eafc934AB85740e7e1CF4DD0656db6567127399/sources/mastercheffinal.sol
Deposit LP tokens to MasterChef for CNT allocation.
function depositFor(uint256 _pid, uint256 _amount , address _user) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; whiteListedHandlers[_user][_user] = true; updatePool(_pid); payOrLockupPendingcnt(_pid,_user); depositInternal(_pid,_amount ,_user); }
5,680,315
/* * Copyright 2021 ConsenSys Software Inc * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ pragma solidity >=0.8; import "../interface/CrosschainVerifier.sol"; import "../../common/BytesUtil.sol"; import "../common/MessagingRegistrar.sol"; import "../../functioncall/sfc/SimpleCrosschainControl.sol"; contract EventRelayVerifier is CrosschainVerifier, BytesUtil { MessagingRegistrar registrar; SimpleCrosschainControl functionCall; // 0x77dab611 bytes32 internal constant CROSS_CALL_EVENT_SIGNATURE = keccak256("CrossCall(bytes32,uint256,address,uint256,address,bytes)"); struct SignedEvents { // The event to be actioned. bytes encodedEvent; // Replay protection is the responsibility of the function call layer. // This variable ensures the signers who submit the event are recorded, even // if it is after the event is actioned. bool actioned; // List of which signers voted. address[] whoVoted; mapping(address => bool) whoVotedMap; } mapping(bytes32 => SignedEvents) private signedEvents; constructor(address _registrar, address _functionCall) { registrar = MessagingRegistrar(_registrar); functionCall = SimpleCrosschainControl(_functionCall); } uint256 constant LEN_OF_LEN = 4; uint256 constant LEN_OF_SIG = 20 + 32 + 32 + 1; /** * For this implementation, the signatures have already been checked in the * relayEvent function below. */ function decodeAndVerifyEvent( uint256 _blockchainId, bytes32, /* _eventSig */ bytes calldata _encodedEvent, bytes calldata /* _signature */ ) external view override { bytes32 eventDigest = keccak256(_encodedEvent); uint256 threshold = registrar.getSigningThreshold(_blockchainId); require( signedEvents[eventDigest].whoVoted.length >= threshold, "Not enough signers" ); } /** * Relay event from one or more relayers. * * Note that replay protection and time outs are handled by the function call layer. */ function relayEvent( uint256 _sourceBlockchainId, address _sourceCbcAddress, bytes calldata _eventData, bytes calldata _signature ) external { // Step 1: Check the signatures of signers. address[] memory signers; bytes32[] memory sigRs; bytes32[] memory sigSs; uint8[] memory sigVs; uint32 len = BytesUtil.bytesToUint32(_signature, 0); { require( _signature.length == LEN_OF_LEN + len * LEN_OF_SIG, "Signature incorrect length" ); signers = new address[](len); sigRs = new bytes32[](len); sigSs = new bytes32[](len); sigVs = new uint8[](len); uint256 offset = LEN_OF_LEN; for (uint256 i = 0; i < len; i++) { signers[i] = BytesUtil.bytesToAddress2(_signature, offset); offset += 20; sigRs[i] = BytesUtil.bytesToBytes32(_signature, offset); offset += 32; sigSs[i] = BytesUtil.bytesToBytes32(_signature, offset); offset += 32; sigVs[i] = BytesUtil.bytesToUint8(_signature, offset); offset += 1; } } bytes memory encodedEvent = abi.encodePacked( _sourceBlockchainId, _sourceCbcAddress, CROSS_CALL_EVENT_SIGNATURE, _eventData ); registrar.verify( _sourceBlockchainId, signers, sigRs, sigSs, sigVs, encodedEvent ); // Step 2: Record who signed the event. bytes32 eventDigest = keccak256(encodedEvent); for (uint256 i = 0; i < len; i++) { if (signedEvents[eventDigest].whoVotedMap[signers[i]]) { // Ignore relayers inadvertently signing a second time. continue; } signedEvents[eventDigest].whoVotedMap[signers[i]] = true; signedEvents[eventDigest].whoVoted.push(signers[i]); } // Action the event if enough relayers have signed. if (signedEvents[eventDigest].actioned) { // There is no more to do. The signers have been recorded. This could // be important for determining who to pay. return; } uint256 threshold = registrar.getSigningThreshold(_sourceBlockchainId); if (signedEvents[eventDigest].whoVoted.length >= threshold) { signedEvents[eventDigest].actioned = true; // NOTE: In the call below, the _signature parameter isn't used. Could be cheaper to pass bytes("") functionCall.crossCallHandler( _sourceBlockchainId, _sourceCbcAddress, _eventData, _signature ); } } }
For this implementation, the signatures have already been checked in the relayEvent function below./
function decodeAndVerifyEvent( uint256 _blockchainId, bytes32, /* _eventSig */ bytes calldata _encodedEvent, bytes calldata /* _signature */ ) external view override { bytes32 eventDigest = keccak256(_encodedEvent); uint256 threshold = registrar.getSigningThreshold(_blockchainId); require( signedEvents[eventDigest].whoVoted.length >= threshold, "Not enough signers" ); }
5,365,726
./partial_match/1/0x45D117011da1D49bA86aF6CEd94126488084186f/sources/contracts/VotingEscrow.sol
Calculate total voting power at some point in the past _block Block to calculate the total voting power at return Total voting power at `_block`
function totalSupplyAt(uint256 _block) external view returns (uint256) { require(_block <= block.number); uint256 _epoch = epoch; uint256 target_epoch = _find_block_epoch(_block, _epoch); Point memory point = point_history[target_epoch]; uint256 dt = 0; if (target_epoch < _epoch) { Point memory point_next = point_history[target_epoch + 1]; if (point.blk != point_next.blk) { dt = ((_block - point.blk) * (point_next.ts - point.ts)) / (point_next.blk - point.blk); } if (point.blk != block.number) { dt = ((_block - point.blk) * (block.timestamp - point.ts)) / (block.number - point.blk); } } }
4,042,280
./full_match/1/0xe0767bED7527dcb36B29c42dE670f70877240Be5/sources/browser/HarvestUSDT.sol
========== Harvest wrapper ========== / function withdraw(uint256 amount) external; unstake
interface IHarvest { function getReward() external; function balanceOf(address account) external view returns (uint256); }
4,824,459
./full_match/1/0x07a24CA74a7592C16827d186b802E004cec33Bb3/sources/contracts/CLPCProxy.sol
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); }
17,152,951
./full_match/97/0xd1390fa4eeBD96b5fd4AEeCa60671e8dF6cDbA50/sources/AiGameWithStructurePlayer.sol
Check if the player has enough stamina to enter the dungeon Deduct 1 stamina from the player Generate a random number to determine if the player wins the fight and a random number to determine the amount of gold as loot The player wins the fight Add the loot to the player's gold balance Call the generateRandomLoot function to add a random loot item to the player's inventory The player loses the fight and doesn't get any loot
function enterDungeon(address player) public { Player storage playerData = players[player]; require(playerData.stamina >= 1, "Not enough stamina to enter the dungeon"); playerData.stamina = playerData.stamina - 1; uint randomNumber = uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, player))) % 2; uint randomNumberGold = (uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, player))) % 100) + 1; if (randomNumber == 0) { uint loot = randomNumberGold; playerData.gold = playerData.gold + loot; generateRandomLoot(player); } }
5,020,308
//SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "./interface/IiToken.sol"; import "./interface/IRewardDistributorV3.sol"; import "./interface/IPriceOracle.sol"; import "./library/Initializable.sol"; import "./library/Ownable.sol"; import "./library/SafeRatioMath.sol"; import "./Controller.sol"; /** * @title dForce's lending reward distributor Contract * @author dForce */ contract RewardDistributorV3 is Initializable, Ownable, IRewardDistributorV3 { using SafeRatioMath for uint256; using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; /// @notice the controller Controller public controller; /// @notice the global Reward distribution speed uint256 public globalDistributionSpeed; /// @notice the Reward distribution speed of each iToken mapping(address => uint256) public distributionSpeed; /// @notice the Reward distribution factor of each iToken, 1.0 by default. stored as a mantissa mapping(address => uint256) public distributionFactorMantissa; struct DistributionState { // Token's last updated index, stored as a mantissa uint256 index; // The block number the index was last updated at uint256 block; } /// @notice the Reward distribution supply state of each iToken mapping(address => DistributionState) public distributionSupplyState; /// @notice the Reward distribution borrow state of each iToken mapping(address => DistributionState) public distributionBorrowState; /// @notice the Reward distribution state of each account of each iToken mapping(address => mapping(address => uint256)) public distributionSupplierIndex; /// @notice the Reward distribution state of each account of each iToken mapping(address => mapping(address => uint256)) public distributionBorrowerIndex; /// @notice the Reward distributed into each account mapping(address => uint256) public reward; /// @notice the Reward token address address public rewardToken; /// @notice whether the reward distribution is paused bool public paused; /// @notice the Reward distribution speed supply side of each iToken mapping(address => uint256) public distributionSupplySpeed; /// @notice the global Reward distribution speed for supply uint256 public globalDistributionSupplySpeed; /** * @dev Throws if called by any account other than the controller. */ modifier onlyController() { require( address(controller) == msg.sender, "onlyController: caller is not the controller" ); _; } /** * @notice Initializes the contract. */ function initialize(Controller _controller) external initializer { require( address(_controller) != address(0), "initialize: controller address should not be zero address!" ); __Ownable_init(); controller = _controller; paused = true; } /** * @notice set reward token address * @dev Admin function, only owner can call this * @param _newRewardToken the address of reward token */ function _setRewardToken(address _newRewardToken) external override onlyOwner { address _oldRewardToken = rewardToken; require( _newRewardToken != address(0) && _newRewardToken != _oldRewardToken, "Reward token address invalid" ); rewardToken = _newRewardToken; emit NewRewardToken(_oldRewardToken, _newRewardToken); } /** * @notice Add the iToken as receipient * @dev Admin function, only controller can call this * @param _iToken the iToken to add as recipient * @param _distributionFactor the distribution factor of the recipient */ function _addRecipient(address _iToken, uint256 _distributionFactor) external override onlyController { distributionFactorMantissa[_iToken] = _distributionFactor; distributionSupplyState[_iToken] = DistributionState({ index: 0, block: block.number }); distributionBorrowState[_iToken] = DistributionState({ index: 0, block: block.number }); emit NewRecipient(_iToken, _distributionFactor); } /** * @notice Pause the reward distribution * @dev Admin function, pause will set global speed to 0 to stop the accumulation */ function _pause() external override onlyOwner { // Set the global distribution speed to 0 to stop accumulation address[] memory _iTokens = controller.getAlliTokens(); uint256 _len = _iTokens.length; for (uint256 i = 0; i < _len; i++) { _setDistributionBorrowSpeed(_iTokens[i], 0); _setDistributionSupplySpeed(_iTokens[i], 0); } _refreshGlobalDistributionSpeeds(); _setPaused(true); } /** * @notice Unpause and set distribution speeds * @dev Admin function * @param _borrowiTokens The borrow asset array * @param _borrowSpeeds The borrow speed array * @param _supplyiTokens The supply asset array * @param _supplySpeeds The supply speed array */ function _unpause( address[] calldata _borrowiTokens, uint256[] calldata _borrowSpeeds, address[] calldata _supplyiTokens, uint256[] calldata _supplySpeeds ) external override onlyOwner { _setPaused(false); _setDistributionSpeedsInternal( _borrowiTokens, _borrowSpeeds, _supplyiTokens, _supplySpeeds ); _refreshGlobalDistributionSpeeds(); } /** * @notice Pause/Unpause the reward distribution * @dev Admin function * @param _paused whether to pause/unpause the distribution */ function _setPaused(bool _paused) internal { paused = _paused; emit Paused(_paused); } /** * @notice Set distribution speeds * @dev Admin function, will fail when paused * @param _borrowiTokens The borrow asset array * @param _borrowSpeeds The borrow speed array * @param _supplyiTokens The supply asset array * @param _supplySpeeds The supply speed array */ function _setDistributionSpeeds( address[] calldata _borrowiTokens, uint256[] calldata _borrowSpeeds, address[] calldata _supplyiTokens, uint256[] calldata _supplySpeeds ) external onlyOwner { require(!paused, "Can not change speeds when paused"); _setDistributionSpeedsInternal( _borrowiTokens, _borrowSpeeds, _supplyiTokens, _supplySpeeds ); _refreshGlobalDistributionSpeeds(); } function _setDistributionSpeedsInternal( address[] memory _borrowiTokens, uint256[] memory _borrowSpeeds, address[] memory _supplyiTokens, uint256[] memory _supplySpeeds ) internal { _setDistributionBorrowSpeedsInternal(_borrowiTokens, _borrowSpeeds); _setDistributionSupplySpeedsInternal(_supplyiTokens, _supplySpeeds); } /** * @notice Set borrow distribution speeds * @dev Admin function, will fail when paused * @param _iTokens The borrow asset array * @param _borrowSpeeds The borrow speed array */ function _setDistributionBorrowSpeeds( address[] calldata _iTokens, uint256[] calldata _borrowSpeeds ) external onlyOwner { require(!paused, "Can not change borrow speeds when paused"); _setDistributionBorrowSpeedsInternal(_iTokens, _borrowSpeeds); _refreshGlobalDistributionSpeeds(); } /** * @notice Set supply distribution speeds * @dev Admin function, will fail when paused * @param _iTokens The supply asset array * @param _supplySpeeds The supply speed array */ function _setDistributionSupplySpeeds( address[] calldata _iTokens, uint256[] calldata _supplySpeeds ) external onlyOwner { require(!paused, "Can not change supply speeds when paused"); _setDistributionSupplySpeedsInternal(_iTokens, _supplySpeeds); _refreshGlobalDistributionSpeeds(); } function _refreshGlobalDistributionSpeeds() internal { address[] memory _iTokens = controller.getAlliTokens(); uint256 _len = _iTokens.length; uint256 _borrowSpeed; uint256 _supplySpeed; for (uint256 i = 0; i < _len; i++) { _borrowSpeed = _borrowSpeed.add(distributionSpeed[_iTokens[i]]); _supplySpeed = _supplySpeed.add( distributionSupplySpeed[_iTokens[i]] ); } globalDistributionSpeed = _borrowSpeed; globalDistributionSupplySpeed = _supplySpeed; emit GlobalDistributionSpeedsUpdated(_borrowSpeed, _supplySpeed); } function _setDistributionBorrowSpeedsInternal( address[] memory _iTokens, uint256[] memory _borrowSpeeds ) internal { require( _iTokens.length == _borrowSpeeds.length, "Length of _iTokens and _borrowSpeeds mismatch" ); uint256 _len = _iTokens.length; for (uint256 i = 0; i < _len; i++) { _setDistributionBorrowSpeed(_iTokens[i], _borrowSpeeds[i]); } } function _setDistributionSupplySpeedsInternal( address[] memory _iTokens, uint256[] memory _supplySpeeds ) internal { require( _iTokens.length == _supplySpeeds.length, "Length of _iTokens and _supplySpeeds mismatch" ); uint256 _len = _iTokens.length; for (uint256 i = 0; i < _len; i++) { _setDistributionSupplySpeed(_iTokens[i], _supplySpeeds[i]); } } function _setDistributionBorrowSpeed(address _iToken, uint256 _borrowSpeed) internal { // iToken must have been listed require(controller.hasiToken(_iToken), "Token has not been listed"); // Update borrow state before updating new speed _updateDistributionState(_iToken, true); distributionSpeed[_iToken] = _borrowSpeed; emit DistributionBorrowSpeedUpdated(_iToken, _borrowSpeed); } function _setDistributionSupplySpeed(address _iToken, uint256 _supplySpeed) internal { // iToken must have been listed require(controller.hasiToken(_iToken), "Token has not been listed"); // Update supply state before updating new speed _updateDistributionState(_iToken, false); distributionSupplySpeed[_iToken] = _supplySpeed; emit DistributionSupplySpeedUpdated(_iToken, _supplySpeed); } /** * @notice Update the iToken's Reward distribution state * @dev Will be called every time when the iToken's supply/borrow changes * @param _iToken The iToken to be updated * @param _isBorrow whether to update the borrow state */ function updateDistributionState(address _iToken, bool _isBorrow) external override { // Skip all updates if it is paused if (paused) { return; } _updateDistributionState(_iToken, _isBorrow); } function _updateDistributionState(address _iToken, bool _isBorrow) internal { require(controller.hasiToken(_iToken), "Token has not been listed"); DistributionState storage state = _isBorrow ? distributionBorrowState[_iToken] : distributionSupplyState[_iToken]; uint256 _speed = _isBorrow ? distributionSpeed[_iToken] : distributionSupplySpeed[_iToken]; uint256 _blockNumber = block.number; uint256 _deltaBlocks = _blockNumber.sub(state.block); if (_deltaBlocks > 0 && _speed > 0) { uint256 _totalToken = _isBorrow ? IiToken(_iToken).totalBorrows().rdiv( IiToken(_iToken).borrowIndex() ) : IERC20Upgradeable(_iToken).totalSupply(); uint256 _totalDistributed = _speed.mul(_deltaBlocks); // Reward distributed per token since last time uint256 _distributedPerToken = _totalToken > 0 ? _totalDistributed.rdiv(_totalToken) : 0; state.index = state.index.add(_distributedPerToken); } state.block = _blockNumber; } /** * @notice Update the account's Reward distribution state * @dev Will be called every time when the account's supply/borrow changes * @param _iToken The iToken to be updated * @param _account The account to be updated * @param _isBorrow whether to update the borrow state */ function updateReward( address _iToken, address _account, bool _isBorrow ) external override { _updateReward(_iToken, _account, _isBorrow); } function _updateReward( address _iToken, address _account, bool _isBorrow ) internal { require(_account != address(0), "Invalid account address!"); require(controller.hasiToken(_iToken), "Token has not been listed"); uint256 _iTokenIndex; uint256 _accountIndex; uint256 _accountBalance; if (_isBorrow) { _iTokenIndex = distributionBorrowState[_iToken].index; _accountIndex = distributionBorrowerIndex[_iToken][_account]; _accountBalance = IiToken(_iToken) .borrowBalanceStored(_account) .rdiv(IiToken(_iToken).borrowIndex()); // Update the account state to date distributionBorrowerIndex[_iToken][_account] = _iTokenIndex; } else { _iTokenIndex = distributionSupplyState[_iToken].index; _accountIndex = distributionSupplierIndex[_iToken][_account]; _accountBalance = IERC20Upgradeable(_iToken).balanceOf(_account); // Update the account state to date distributionSupplierIndex[_iToken][_account] = _iTokenIndex; } uint256 _deltaIndex = _iTokenIndex.sub(_accountIndex); uint256 _amount = _accountBalance.rmul(_deltaIndex); if (_amount > 0) { reward[_account] = reward[_account].add(_amount); emit RewardDistributed(_iToken, _account, _amount, _accountIndex); } } /** * @notice Update reward accrued in iTokens by the holders regardless of paused or not * @param _holders The account to update * @param _iTokens The _iTokens to update */ function updateRewardBatch( address[] memory _holders, address[] memory _iTokens ) public override { // Update rewards for all _iTokens for holders for (uint256 i = 0; i < _iTokens.length; i++) { address _iToken = _iTokens[i]; _updateDistributionState(_iToken, false); _updateDistributionState(_iToken, true); for (uint256 j = 0; j < _holders.length; j++) { _updateReward(_iToken, _holders[j], false); _updateReward(_iToken, _holders[j], true); } } } /** * @notice Update reward accrued in iTokens by the holders regardless of paused or not * @param _holders The account to update * @param _iTokens The _iTokens to update * @param _isBorrow whether to update the borrow state */ function _updateRewards( address[] memory _holders, address[] memory _iTokens, bool _isBorrow ) internal { // Update rewards for all _iTokens for holders for (uint256 i = 0; i < _iTokens.length; i++) { address _iToken = _iTokens[i]; _updateDistributionState(_iToken, _isBorrow); for (uint256 j = 0; j < _holders.length; j++) { _updateReward(_iToken, _holders[j], _isBorrow); } } } /** * @notice Claim reward accrued in iTokens by the holders * @param _holders The account to claim for * @param _iTokens The _iTokens to claim from */ function claimReward(address[] memory _holders, address[] memory _iTokens) public override { updateRewardBatch(_holders, _iTokens); // Withdraw all reward for all holders for (uint256 j = 0; j < _holders.length; j++) { address _account = _holders[j]; uint256 _reward = reward[_account]; if (_reward > 0) { reward[_account] = 0; IERC20Upgradeable(rewardToken).safeTransfer(_account, _reward); } } } /** * @notice Claim reward accrued in iTokens by the holders * @param _holders The account to claim for * @param _suppliediTokens The _suppliediTokens to claim from * @param _borrowediTokens The _borrowediTokens to claim from */ function claimRewards( address[] memory _holders, address[] memory _suppliediTokens, address[] memory _borrowediTokens ) external override { _updateRewards(_holders, _suppliediTokens, false); _updateRewards(_holders, _borrowediTokens, true); // Withdraw all reward for all holders for (uint256 j = 0; j < _holders.length; j++) { address _account = _holders[j]; uint256 _reward = reward[_account]; if (_reward > 0) { reward[_account] = 0; IERC20Upgradeable(rewardToken).safeTransfer(_account, _reward); } } } /** * @notice Claim reward accrued in all iTokens by the holders * @param _holders The account to claim for */ function claimAllReward(address[] memory _holders) external override { claimReward(_holders, controller.getAlliTokens()); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./IInterestRateModelInterface.sol"; import "./IControllerInterface.sol"; interface IiToken { function isSupported() external returns (bool); function isiToken() external returns (bool); //---------------------------------- //********* User Interface ********* //---------------------------------- function mint(address recipient, uint256 mintAmount) external; function mintAndEnterMarket(address recipient, uint256 mintAmount) external; function redeem(address from, uint256 redeemTokens) external; function redeemUnderlying(address from, uint256 redeemAmount) external; function borrow(uint256 borrowAmount) external; function repayBorrow(uint256 repayAmount) external; function repayBorrowBehalf(address borrower, uint256 repayAmount) external; function liquidateBorrow( address borrower, uint256 repayAmount, address iTokenCollateral ) external; function flashloan( address recipient, uint256 loanAmount, bytes memory data ) external; function seize( address _liquidator, address _borrower, uint256 _seizeTokens ) external; function updateInterest() external returns (bool); function controller() external view returns (address); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function totalBorrows() external view returns (uint256); function borrowBalanceCurrent(address _user) external returns (uint256); function borrowBalanceStored(address _user) external view returns (uint256); function borrowIndex() external view returns (uint256); function getAccountSnapshot(address _account) external view returns ( uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function getCash() external view returns (uint256); //---------------------------------- //********* Owner Actions ********** //---------------------------------- function _setNewReserveRatio(uint256 _newReserveRatio) external; function _setNewFlashloanFeeRatio(uint256 _newFlashloanFeeRatio) external; function _setNewProtocolFeeRatio(uint256 _newProtocolFeeRatio) external; function _setController(IControllerInterface _newController) external; function _setInterestRateModel( IInterestRateModelInterface _newInterestRateModel ) external; function _withdrawReserves(uint256 _withdrawAmount) external; } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IRewardDistributorV3 { function _setRewardToken(address newRewardToken) external; /// @notice Emitted reward token address is changed by admin event NewRewardToken(address oldRewardToken, address newRewardToken); function _addRecipient(address _iToken, uint256 _distributionFactor) external; event NewRecipient(address iToken, uint256 distributionFactor); /// @notice Emitted when mint is paused/unpaused by admin event Paused(bool paused); function _pause() external; function _unpause( address[] calldata _borrowiTokens, uint256[] calldata _borrowSpeeds, address[] calldata _supplyiTokens, uint256[] calldata _supplySpeeds ) external; /// @notice Emitted when Global Distribution speed for both supply and borrow are updated event GlobalDistributionSpeedsUpdated( uint256 borrowSpeed, uint256 supplySpeed ); /// @notice Emitted when iToken's Distribution borrow speed is updated event DistributionBorrowSpeedUpdated(address iToken, uint256 borrowSpeed); /// @notice Emitted when iToken's Distribution supply speed is updated event DistributionSupplySpeedUpdated(address iToken, uint256 supplySpeed); /// @notice Emitted when iToken's Distribution factor is changed by admin event NewDistributionFactor( address iToken, uint256 oldDistributionFactorMantissa, uint256 newDistributionFactorMantissa ); function updateDistributionState(address _iToken, bool _isBorrow) external; function updateReward( address _iToken, address _account, bool _isBorrow ) external; function updateRewardBatch( address[] memory _holders, address[] memory _iTokens ) external; function claimReward(address[] memory _holders, address[] memory _iTokens) external; function claimAllReward(address[] memory _holders) external; function claimRewards(address[] memory _holders, address[] memory _suppliediTokens, address[] memory _borrowediTokens) external; /// @notice Emitted when reward of amount is distributed into account event RewardDistributed( address iToken, address account, uint256 amount, uint256 accountIndex ); } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./IiToken.sol"; interface IPriceOracle { /** * @notice Get the underlying price of a iToken asset * @param _iToken The iToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(address _iToken) external view returns (uint256); /** * @notice Get the price of a underlying asset * @param _iToken The iToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable and whether the price is valid. */ function getUnderlyingPriceAndStatus(address _iToken) external view returns (uint256, bool); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require( !_initialized, "Initializable: contract is already initialized" ); _; _initialized = true; } } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {_setPendingOwner} and {_acceptOwner}. */ contract Ownable { /** * @dev Returns the address of the current owner. */ address payable public owner; /** * @dev Returns the address of the current pending owner. */ address payable public pendingOwner; event NewOwner(address indexed previousOwner, address indexed newOwner); event NewPendingOwner( address indexed oldPendingOwner, address indexed newPendingOwner ); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner == msg.sender, "onlyOwner: caller is not the owner"); _; } /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal { owner = msg.sender; emit NewOwner(address(0), msg.sender); } /** * @notice Base on the inputing parameter `newPendingOwner` to check the exact error reason. * @dev Transfer contract control to a new owner. The newPendingOwner must call `_acceptOwner` to finish the transfer. * @param newPendingOwner New pending owner. */ function _setPendingOwner(address payable newPendingOwner) external onlyOwner { require( newPendingOwner != address(0) && newPendingOwner != pendingOwner, "_setPendingOwner: New owenr can not be zero address and owner has been set!" ); // Gets current owner. address oldPendingOwner = pendingOwner; // Sets new pending owner. pendingOwner = newPendingOwner; emit NewPendingOwner(oldPendingOwner, newPendingOwner); } /** * @dev Accepts the admin rights, but only for pendingOwenr. */ function _acceptOwner() external { require( msg.sender == pendingOwner, "_acceptOwner: Only for pending owner!" ); // Gets current values for events. address oldOwner = owner; address oldPendingOwner = pendingOwner; // Set the new contract owner. owner = pendingOwner; // Clear the pendingOwner. pendingOwner = address(0); emit NewOwner(oldOwner, owner); emit NewPendingOwner(oldPendingOwner, pendingOwner); } uint256[50] private __gap; } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; library SafeRatioMath { using SafeMathUpgradeable for uint256; uint256 private constant BASE = 10**18; uint256 private constant DOUBLE = 10**36; function divup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.add(y.sub(1)).div(y); } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(y).div(BASE); } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(BASE).div(y); } function rdivup(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x.mul(BASE).add(y.sub(1)).div(y); } function tmul( uint256 x, uint256 y, uint256 z ) internal pure returns (uint256 result) { result = x.mul(y).mul(z).div(DOUBLE); } function rpow( uint256 x, uint256 n, uint256 base ) internal pure returns (uint256 z) { assembly { switch x case 0 { switch n case 0 { z := base } default { z := 0 } } default { switch mod(n, 2) case 0 { z := base } default { z := x } let half := div(base, 2) // for rounding. for { n := div(n, 2) } n { n := div(n, 2) } { let xx := mul(x, x) if iszero(eq(div(xx, x), x)) { revert(0, 0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0, 0) } x := div(xxRound, base) if mod(n, 2) { let zx := mul(z, x) if and( iszero(iszero(x)), iszero(eq(div(zx, x), z)) ) { revert(0, 0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0, 0) } z := div(zxRound, base) } } } } } } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol"; import "./interface/IControllerInterface.sol"; import "./interface/IPriceOracle.sol"; import "./interface/IiToken.sol"; import "./interface/IRewardDistributor.sol"; import "./library/Initializable.sol"; import "./library/Ownable.sol"; import "./library/SafeRatioMath.sol"; /** * @title dForce's lending controller Contract * @author dForce */ contract Controller is Initializable, Ownable, IControllerInterface { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using SafeRatioMath for uint256; using SafeMathUpgradeable for uint256; using SafeERC20Upgradeable for IERC20Upgradeable; /// @dev EnumerableSet of all iTokens EnumerableSetUpgradeable.AddressSet internal iTokens; struct Market { /* * Multiplier representing the most one can borrow against their collateral in this market. * For instance, 0.9 to allow borrowing 90% of collateral value. * Must be in [0, 0.9], and stored as a mantissa. */ uint256 collateralFactorMantissa; /* * Multiplier representing the most one can borrow the asset. * For instance, 0.5 to allow borrowing this asset 50% * collateral value * collateralFactor. * When calculating equity, 0.5 with 100 borrow balance will produce 200 borrow value * Must be between (0, 1], and stored as a mantissa. */ uint256 borrowFactorMantissa; /* * The borrow capacity of the asset, will be checked in beforeBorrow() * -1 means there is no limit on the capacity * 0 means the asset can not be borrowed any more */ uint256 borrowCapacity; /* * The supply capacity of the asset, will be checked in beforeMint() * -1 means there is no limit on the capacity * 0 means the asset can not be supplied any more */ uint256 supplyCapacity; // Whether market's mint is paused bool mintPaused; // Whether market's redeem is paused bool redeemPaused; // Whether market's borrow is paused bool borrowPaused; } /// @notice Mapping of iTokens to corresponding markets mapping(address => Market) public markets; struct AccountData { // Account's collateral assets EnumerableSetUpgradeable.AddressSet collaterals; // Account's borrowed assets EnumerableSetUpgradeable.AddressSet borrowed; } /// @dev Mapping of accounts' data, including collateral and borrowed assets mapping(address => AccountData) internal accountsData; /** * @notice Oracle to query the price of a given asset */ address public priceOracle; /** * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow */ uint256 public closeFactorMantissa; // closeFactorMantissa must be strictly greater than this value uint256 internal constant closeFactorMinMantissa = 0.05e18; // 0.05 // closeFactorMantissa must not exceed this value uint256 internal constant closeFactorMaxMantissa = 0.9e18; // 0.9 /** * @notice Multiplier representing the discount on collateral that a liquidator receives */ uint256 public liquidationIncentiveMantissa; // liquidationIncentiveMantissa must be no less than this value uint256 internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0 // liquidationIncentiveMantissa must be no greater than this value uint256 internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5 // collateralFactorMantissa must not exceed this value uint256 internal constant collateralFactorMaxMantissa = 1e18; // 1.0 // borrowFactorMantissa must not exceed this value uint256 internal constant borrowFactorMaxMantissa = 1e18; // 1.0 /** * @notice Guardian who can pause mint/borrow/liquidate/transfer in case of emergency */ address public pauseGuardian; /// @notice whether global transfer is paused bool public transferPaused; /// @notice whether global seize is paused bool public seizePaused; /** * @notice the address of reward distributor */ address public rewardDistributor; /** * @dev Check if called by owner or pauseGuardian, and only owner can unpause */ modifier checkPauser(bool _paused) { require( msg.sender == owner || (msg.sender == pauseGuardian && _paused), "Only owner and guardian can pause and only owner can unpause" ); _; } /** * @notice Initializes the contract. */ function initialize() external initializer { __Ownable_init(); } /*********************************/ /******** Security Check *********/ /*********************************/ /** * @notice Ensure this is a Controller contract. */ function isController() external view override returns (bool) { return true; } /*********************************/ /******** Admin Operations *******/ /*********************************/ /** * @notice Admin function to add iToken into supported markets * Checks if the iToken already exsits * Will `revert()` if any check fails * @param _iToken The _iToken to add * @param _collateralFactor The _collateralFactor of _iToken * @param _borrowFactor The _borrowFactor of _iToken * @param _supplyCapacity The _supplyCapacity of _iToken * @param _distributionFactor The _distributionFactor of _iToken */ function _addMarket( address _iToken, uint256 _collateralFactor, uint256 _borrowFactor, uint256 _supplyCapacity, uint256 _borrowCapacity, uint256 _distributionFactor ) external override onlyOwner { require(IiToken(_iToken).isSupported(), "Token is not supported"); // Market must not have been listed, EnumerableSet.add() will return false if it exsits require(iTokens.add(_iToken), "Token has already been listed"); require( _collateralFactor <= collateralFactorMaxMantissa, "Collateral factor invalid" ); require( _borrowFactor > 0 && _borrowFactor <= borrowFactorMaxMantissa, "Borrow factor invalid" ); // Its value will be taken into account when calculate account equity // Check if the price is available for the calculation require( IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0, "Underlying price is unavailable" ); markets[_iToken] = Market({ collateralFactorMantissa: _collateralFactor, borrowFactorMantissa: _borrowFactor, borrowCapacity: _borrowCapacity, supplyCapacity: _supplyCapacity, mintPaused: false, redeemPaused: false, borrowPaused: false }); IRewardDistributor(rewardDistributor)._addRecipient( _iToken, _distributionFactor ); emit MarketAdded( _iToken, _collateralFactor, _borrowFactor, _supplyCapacity, _borrowCapacity, _distributionFactor ); } /** * @notice Sets price oracle * @dev Admin function to set price oracle * @param _newOracle New oracle contract */ function _setPriceOracle(address _newOracle) external override onlyOwner { address _oldOracle = priceOracle; require( _newOracle != address(0) && _newOracle != _oldOracle, "Oracle address invalid" ); priceOracle = _newOracle; emit NewPriceOracle(_oldOracle, _newOracle); } /** * @notice Sets the closeFactor used when liquidating borrows * @dev Admin function to set closeFactor * @param _newCloseFactorMantissa New close factor, scaled by 1e18 */ function _setCloseFactor(uint256 _newCloseFactorMantissa) external override onlyOwner { require( _newCloseFactorMantissa >= closeFactorMinMantissa && _newCloseFactorMantissa <= closeFactorMaxMantissa, "Close factor invalid" ); uint256 _oldCloseFactorMantissa = closeFactorMantissa; closeFactorMantissa = _newCloseFactorMantissa; emit NewCloseFactor(_oldCloseFactorMantissa, _newCloseFactorMantissa); } /** * @notice Sets liquidationIncentive * @dev Admin function to set liquidationIncentive * @param _newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18 */ function _setLiquidationIncentive(uint256 _newLiquidationIncentiveMantissa) external override onlyOwner { require( _newLiquidationIncentiveMantissa >= liquidationIncentiveMinMantissa && _newLiquidationIncentiveMantissa <= liquidationIncentiveMaxMantissa, "Liquidation incentive invalid" ); uint256 _oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa; liquidationIncentiveMantissa = _newLiquidationIncentiveMantissa; emit NewLiquidationIncentive( _oldLiquidationIncentiveMantissa, _newLiquidationIncentiveMantissa ); } /** * @notice Sets the collateralFactor for a iToken * @dev Admin function to set collateralFactor for a iToken * @param _iToken The token to set the factor on * @param _newCollateralFactorMantissa The new collateral factor, scaled by 1e18 */ function _setCollateralFactor( address _iToken, uint256 _newCollateralFactorMantissa ) external override onlyOwner { _checkiTokenListed(_iToken); require( _newCollateralFactorMantissa <= collateralFactorMaxMantissa, "Collateral factor invalid" ); // Its value will be taken into account when calculate account equity // Check if the price is available for the calculation require( IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0, "Failed to set collateral factor, underlying price is unavailable" ); Market storage _market = markets[_iToken]; uint256 _oldCollateralFactorMantissa = _market.collateralFactorMantissa; _market.collateralFactorMantissa = _newCollateralFactorMantissa; emit NewCollateralFactor( _iToken, _oldCollateralFactorMantissa, _newCollateralFactorMantissa ); } /** * @notice Sets the borrowFactor for a iToken * @dev Admin function to set borrowFactor for a iToken * @param _iToken The token to set the factor on * @param _newBorrowFactorMantissa The new borrow factor, scaled by 1e18 */ function _setBorrowFactor(address _iToken, uint256 _newBorrowFactorMantissa) external override onlyOwner { _checkiTokenListed(_iToken); require( _newBorrowFactorMantissa > 0 && _newBorrowFactorMantissa <= borrowFactorMaxMantissa, "Borrow factor invalid" ); // Its value will be taken into account when calculate account equity // Check if the price is available for the calculation require( IPriceOracle(priceOracle).getUnderlyingPrice(_iToken) != 0, "Failed to set borrow factor, underlying price is unavailable" ); Market storage _market = markets[_iToken]; uint256 _oldBorrowFactorMantissa = _market.borrowFactorMantissa; _market.borrowFactorMantissa = _newBorrowFactorMantissa; emit NewBorrowFactor( _iToken, _oldBorrowFactorMantissa, _newBorrowFactorMantissa ); } /** * @notice Sets the borrowCapacity for a iToken * @dev Admin function to set borrowCapacity for a iToken * @param _iToken The token to set the capacity on * @param _newBorrowCapacity The new borrow capacity */ function _setBorrowCapacity(address _iToken, uint256 _newBorrowCapacity) external override onlyOwner { _checkiTokenListed(_iToken); Market storage _market = markets[_iToken]; uint256 oldBorrowCapacity = _market.borrowCapacity; _market.borrowCapacity = _newBorrowCapacity; emit NewBorrowCapacity(_iToken, oldBorrowCapacity, _newBorrowCapacity); } /** * @notice Sets the supplyCapacity for a iToken * @dev Admin function to set supplyCapacity for a iToken * @param _iToken The token to set the capacity on * @param _newSupplyCapacity The new supply capacity */ function _setSupplyCapacity(address _iToken, uint256 _newSupplyCapacity) external override onlyOwner { _checkiTokenListed(_iToken); Market storage _market = markets[_iToken]; uint256 oldSupplyCapacity = _market.supplyCapacity; _market.supplyCapacity = _newSupplyCapacity; emit NewSupplyCapacity(_iToken, oldSupplyCapacity, _newSupplyCapacity); } /** * @notice Sets the pauseGuardian * @dev Admin function to set pauseGuardian * @param _newPauseGuardian The new pause guardian */ function _setPauseGuardian(address _newPauseGuardian) external override onlyOwner { address _oldPauseGuardian = pauseGuardian; require( _newPauseGuardian != address(0) && _newPauseGuardian != _oldPauseGuardian, "Pause guardian address invalid" ); pauseGuardian = _newPauseGuardian; emit NewPauseGuardian(_oldPauseGuardian, _newPauseGuardian); } /** * @notice pause/unpause mint() for all iTokens * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setAllMintPaused(bool _paused) external override checkPauser(_paused) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); for (uint256 i = 0; i < _len; i++) { _setMintPausedInternal(_iTokens.at(i), _paused); } } /** * @notice pause/unpause mint() for the iToken * @dev Admin function, only owner and pauseGuardian can call this * @param _iToken The iToken to pause/unpause * @param _paused whether to pause or unpause */ function _setMintPaused(address _iToken, bool _paused) external override checkPauser(_paused) { _checkiTokenListed(_iToken); _setMintPausedInternal(_iToken, _paused); } function _setMintPausedInternal(address _iToken, bool _paused) internal { markets[_iToken].mintPaused = _paused; emit MintPaused(_iToken, _paused); } /** * @notice pause/unpause redeem() for all iTokens * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setAllRedeemPaused(bool _paused) external override checkPauser(_paused) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); for (uint256 i = 0; i < _len; i++) { _setRedeemPausedInternal(_iTokens.at(i), _paused); } } /** * @notice pause/unpause redeem() for the iToken * @dev Admin function, only owner and pauseGuardian can call this * @param _iToken The iToken to pause/unpause * @param _paused whether to pause or unpause */ function _setRedeemPaused(address _iToken, bool _paused) external override checkPauser(_paused) { _checkiTokenListed(_iToken); _setRedeemPausedInternal(_iToken, _paused); } function _setRedeemPausedInternal(address _iToken, bool _paused) internal { markets[_iToken].redeemPaused = _paused; emit RedeemPaused(_iToken, _paused); } /** * @notice pause/unpause borrow() for all iTokens * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setAllBorrowPaused(bool _paused) external override checkPauser(_paused) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); for (uint256 i = 0; i < _len; i++) { _setBorrowPausedInternal(_iTokens.at(i), _paused); } } /** * @notice pause/unpause borrow() for the iToken * @dev Admin function, only owner and pauseGuardian can call this * @param _iToken The iToken to pause/unpause * @param _paused whether to pause or unpause */ function _setBorrowPaused(address _iToken, bool _paused) external override checkPauser(_paused) { _checkiTokenListed(_iToken); _setBorrowPausedInternal(_iToken, _paused); } function _setBorrowPausedInternal(address _iToken, bool _paused) internal { markets[_iToken].borrowPaused = _paused; emit BorrowPaused(_iToken, _paused); } /** * @notice pause/unpause global transfer() * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setTransferPaused(bool _paused) external override checkPauser(_paused) { _setTransferPausedInternal(_paused); } function _setTransferPausedInternal(bool _paused) internal { transferPaused = _paused; emit TransferPaused(_paused); } /** * @notice pause/unpause global seize() * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setSeizePaused(bool _paused) external override checkPauser(_paused) { _setSeizePausedInternal(_paused); } function _setSeizePausedInternal(bool _paused) internal { seizePaused = _paused; emit SeizePaused(_paused); } /** * @notice pause/unpause all actions iToken, including mint/redeem/borrow * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setiTokenPaused(address _iToken, bool _paused) external override checkPauser(_paused) { _checkiTokenListed(_iToken); _setiTokenPausedInternal(_iToken, _paused); } function _setiTokenPausedInternal(address _iToken, bool _paused) internal { Market storage _market = markets[_iToken]; _market.mintPaused = _paused; emit MintPaused(_iToken, _paused); _market.redeemPaused = _paused; emit RedeemPaused(_iToken, _paused); _market.borrowPaused = _paused; emit BorrowPaused(_iToken, _paused); } /** * @notice pause/unpause entire protocol, including mint/redeem/borrow/seize/transfer * @dev Admin function, only owner and pauseGuardian can call this * @param _paused whether to pause or unpause */ function _setProtocolPaused(bool _paused) external override checkPauser(_paused) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); for (uint256 i = 0; i < _len; i++) { address _iToken = _iTokens.at(i); _setiTokenPausedInternal(_iToken, _paused); } _setTransferPausedInternal(_paused); _setSeizePausedInternal(_paused); } /** * @notice Sets Reward Distributor * @dev Admin function to set reward distributor * @param _newRewardDistributor new reward distributor */ function _setRewardDistributor(address _newRewardDistributor) external override onlyOwner { address _oldRewardDistributor = rewardDistributor; require( _newRewardDistributor != address(0) && _newRewardDistributor != _oldRewardDistributor, "Reward Distributor address invalid" ); rewardDistributor = _newRewardDistributor; emit NewRewardDistributor(_oldRewardDistributor, _newRewardDistributor); } /*********************************/ /******** Poclicy Hooks **********/ /*********************************/ /** * @notice Hook function before iToken `mint()` * Checks if the account should be allowed to mint the given iToken * Will `revert()` if any check fails * @param _iToken The iToken to check the mint against * @param _minter The account which would get the minted tokens * @param _mintAmount The amount of underlying being minted to iToken */ function beforeMint( address _iToken, address _minter, uint256 _mintAmount ) external override { _checkiTokenListed(_iToken); Market storage _market = markets[_iToken]; require(!_market.mintPaused, "Token mint has been paused"); // Check the iToken's supply capacity, -1 means no limit uint256 _totalSupplyUnderlying = IERC20Upgradeable(_iToken).totalSupply().rmul( IiToken(_iToken).exchangeRateStored() ); require( _totalSupplyUnderlying.add(_mintAmount) <= _market.supplyCapacity, "Token supply capacity reached" ); // Update the Reward Distribution Supply state and distribute reward to suppplier IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, false ); IRewardDistributor(rewardDistributor).updateReward( _iToken, _minter, false ); } /** * @notice Hook function after iToken `mint()` * Will `revert()` if any operation fails * @param _iToken The iToken being minted * @param _minter The account which would get the minted tokens * @param _mintAmount The amount of underlying being minted to iToken * @param _mintedAmount The amount of iToken being minted */ function afterMint( address _iToken, address _minter, uint256 _mintAmount, uint256 _mintedAmount ) external override { _iToken; _minter; _mintAmount; _mintedAmount; } /** * @notice Hook function before iToken `redeem()` * Checks if the account should be allowed to redeem the given iToken * Will `revert()` if any check fails * @param _iToken The iToken to check the redeem against * @param _redeemer The account which would redeem iToken * @param _redeemAmount The amount of iToken to redeem */ function beforeRedeem( address _iToken, address _redeemer, uint256 _redeemAmount ) external override { // _redeemAllowed below will check whether _iToken is listed require(!markets[_iToken].redeemPaused, "Token redeem has been paused"); _redeemAllowed(_iToken, _redeemer, _redeemAmount); // Update the Reward Distribution Supply state and distribute reward to suppplier IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, false ); IRewardDistributor(rewardDistributor).updateReward( _iToken, _redeemer, false ); } /** * @notice Hook function after iToken `redeem()` * Will `revert()` if any operation fails * @param _iToken The iToken being redeemed * @param _redeemer The account which redeemed iToken * @param _redeemAmount The amount of iToken being redeemed * @param _redeemedUnderlying The amount of underlying being redeemed */ function afterRedeem( address _iToken, address _redeemer, uint256 _redeemAmount, uint256 _redeemedUnderlying ) external override { _iToken; _redeemer; _redeemAmount; _redeemedUnderlying; } /** * @notice Hook function before iToken `borrow()` * Checks if the account should be allowed to borrow the given iToken * Will `revert()` if any check fails * @param _iToken The iToken to check the borrow against * @param _borrower The account which would borrow iToken * @param _borrowAmount The amount of underlying to borrow */ function beforeBorrow( address _iToken, address _borrower, uint256 _borrowAmount ) external override { _checkiTokenListed(_iToken); Market storage _market = markets[_iToken]; require(!_market.borrowPaused, "Token borrow has been paused"); if (!hasBorrowed(_borrower, _iToken)) { // Unlike collaterals, borrowed asset can only be added by iToken, // rather than enabled by user directly. require(msg.sender == _iToken, "sender must be iToken"); // Have checked _iToken is listed, just add it _addToBorrowed(_borrower, _iToken); } // Check borrower's equity (, uint256 _shortfall, , ) = calcAccountEquityWithEffect(_borrower, _iToken, 0, _borrowAmount); require(_shortfall == 0, "Account has some shortfall"); // Check the iToken's borrow capacity, -1 means no limit uint256 _totalBorrows = IiToken(_iToken).totalBorrows(); require( _totalBorrows.add(_borrowAmount) <= _market.borrowCapacity, "Token borrow capacity reached" ); // Update the Reward Distribution Borrow state and distribute reward to borrower IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, true ); IRewardDistributor(rewardDistributor).updateReward( _iToken, _borrower, true ); } /** * @notice Hook function after iToken `borrow()` * Will `revert()` if any operation fails * @param _iToken The iToken being borrewd * @param _borrower The account which borrowed iToken * @param _borrowedAmount The amount of underlying being borrowed */ function afterBorrow( address _iToken, address _borrower, uint256 _borrowedAmount ) external override { _iToken; _borrower; _borrowedAmount; } /** * @notice Hook function before iToken `repayBorrow()` * Checks if the account should be allowed to repay the given iToken * for the borrower. Will `revert()` if any check fails * @param _iToken The iToken to verify the repay against * @param _payer The account which would repay iToken * @param _borrower The account which has borrowed * @param _repayAmount The amount of underlying to repay */ function beforeRepayBorrow( address _iToken, address _payer, address _borrower, uint256 _repayAmount ) external override { _checkiTokenListed(_iToken); // Update the Reward Distribution Borrow state and distribute reward to borrower IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, true ); IRewardDistributor(rewardDistributor).updateReward( _iToken, _borrower, true ); _payer; _repayAmount; } /** * @notice Hook function after iToken `repayBorrow()` * Will `revert()` if any operation fails * @param _iToken The iToken being repaid * @param _payer The account which would repay * @param _borrower The account which has borrowed * @param _repayAmount The amount of underlying being repaied */ function afterRepayBorrow( address _iToken, address _payer, address _borrower, uint256 _repayAmount ) external override { _checkiTokenListed(_iToken); // Remove _iToken from borrowed list if new borrow balance is 0 if (IiToken(_iToken).borrowBalanceStored(_borrower) == 0) { // Only allow called by iToken as we are going to remove this token from borrower's borrowed list require(msg.sender == _iToken, "sender must be iToken"); // Have checked _iToken is listed, just remove it _removeFromBorrowed(_borrower, _iToken); } _payer; _repayAmount; } /** * @notice Hook function before iToken `liquidateBorrow()` * Checks if the account should be allowed to liquidate the given iToken * for the borrower. Will `revert()` if any check fails * @param _iTokenBorrowed The iToken was borrowed * @param _iTokenCollateral The collateral iToken to be liqudate with * @param _liquidator The account which would repay the borrowed iToken * @param _borrower The account which has borrowed * @param _repayAmount The amount of underlying to repay */ function beforeLiquidateBorrow( address _iTokenBorrowed, address _iTokenCollateral, address _liquidator, address _borrower, uint256 _repayAmount ) external override { // Tokens must have been listed require( iTokens.contains(_iTokenBorrowed) && iTokens.contains(_iTokenCollateral), "Tokens have not been listed" ); (, uint256 _shortfall, , ) = calcAccountEquity(_borrower); require(_shortfall > 0, "Account does not have shortfall"); // Only allowed to repay the borrow balance's close factor uint256 _borrowBalance = IiToken(_iTokenBorrowed).borrowBalanceStored(_borrower); uint256 _maxRepay = _borrowBalance.rmul(closeFactorMantissa); require(_repayAmount <= _maxRepay, "Repay exceeds max repay allowed"); _liquidator; } /** * @notice Hook function after iToken `liquidateBorrow()` * Will `revert()` if any operation fails * @param _iTokenBorrowed The iToken was borrowed * @param _iTokenCollateral The collateral iToken to be seized * @param _liquidator The account which would repay and seize * @param _borrower The account which has borrowed * @param _repaidAmount The amount of underlying being repaied * @param _seizedAmount The amount of collateral being seized */ function afterLiquidateBorrow( address _iTokenBorrowed, address _iTokenCollateral, address _liquidator, address _borrower, uint256 _repaidAmount, uint256 _seizedAmount ) external override { _iTokenBorrowed; _iTokenCollateral; _liquidator; _borrower; _repaidAmount; _seizedAmount; // Unlike repayBorrow, liquidateBorrow does not allow to repay all borrow balance // No need to check whether should remove from borrowed asset list } /** * @notice Hook function before iToken `seize()` * Checks if the liquidator should be allowed to seize the collateral iToken * Will `revert()` if any check fails * @param _iTokenCollateral The collateral iToken to be seize * @param _iTokenBorrowed The iToken was borrowed * @param _liquidator The account which has repaid the borrowed iToken * @param _borrower The account which has borrowed * @param _seizeAmount The amount of collateral iToken to seize */ function beforeSeize( address _iTokenCollateral, address _iTokenBorrowed, address _liquidator, address _borrower, uint256 _seizeAmount ) external override { require(!seizePaused, "Seize has been paused"); // Markets must have been listed require( iTokens.contains(_iTokenBorrowed) && iTokens.contains(_iTokenCollateral), "Tokens have not been listed" ); // Sanity Check the controllers require( IiToken(_iTokenBorrowed).controller() == IiToken(_iTokenCollateral).controller(), "Controller mismatch between Borrowed and Collateral" ); // Update the Reward Distribution Supply state on collateral IRewardDistributor(rewardDistributor).updateDistributionState( _iTokenCollateral, false ); // Update reward of liquidator and borrower on collateral IRewardDistributor(rewardDistributor).updateReward( _iTokenCollateral, _liquidator, false ); IRewardDistributor(rewardDistributor).updateReward( _iTokenCollateral, _borrower, false ); _seizeAmount; } /** * @notice Hook function after iToken `seize()` * Will `revert()` if any operation fails * @param _iTokenCollateral The collateral iToken to be seized * @param _iTokenBorrowed The iToken was borrowed * @param _liquidator The account which has repaid and seized * @param _borrower The account which has borrowed * @param _seizedAmount The amount of collateral being seized */ function afterSeize( address _iTokenCollateral, address _iTokenBorrowed, address _liquidator, address _borrower, uint256 _seizedAmount ) external override { _iTokenBorrowed; _iTokenCollateral; _liquidator; _borrower; _seizedAmount; } /** * @notice Hook function before iToken `transfer()` * Checks if the transfer should be allowed * Will `revert()` if any check fails * @param _iToken The iToken to be transfered * @param _from The account to be transfered from * @param _to The account to be transfered to * @param _amount The amount to be transfered */ function beforeTransfer( address _iToken, address _from, address _to, uint256 _amount ) external override { // _redeemAllowed below will check whether _iToken is listed require(!transferPaused, "Transfer has been paused"); // Check account equity with this amount to decide whether the transfer is allowed _redeemAllowed(_iToken, _from, _amount); // Update the Reward Distribution supply state IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, false ); // Update reward of from and to IRewardDistributor(rewardDistributor).updateReward( _iToken, _from, false ); IRewardDistributor(rewardDistributor).updateReward(_iToken, _to, false); } /** * @notice Hook function after iToken `transfer()` * Will `revert()` if any operation fails * @param _iToken The iToken was transfered * @param _from The account was transfer from * @param _to The account was transfer to * @param _amount The amount was transfered */ function afterTransfer( address _iToken, address _from, address _to, uint256 _amount ) external override { _iToken; _from; _to; _amount; } /** * @notice Hook function before iToken `flashloan()` * Checks if the flashloan should be allowed * Will `revert()` if any check fails * @param _iToken The iToken to be flashloaned * @param _to The account flashloaned transfer to * @param _amount The amount to be flashloaned */ function beforeFlashloan( address _iToken, address _to, uint256 _amount ) external override { // Flashloan share the same pause state with borrow require(!markets[_iToken].borrowPaused, "Token borrow has been paused"); _checkiTokenListed(_iToken); _to; _amount; // Update the Reward Distribution Borrow state IRewardDistributor(rewardDistributor).updateDistributionState( _iToken, true ); } /** * @notice Hook function after iToken `flashloan()` * Will `revert()` if any operation fails * @param _iToken The iToken was flashloaned * @param _to The account flashloan transfer to * @param _amount The amount was flashloaned */ function afterFlashloan( address _iToken, address _to, uint256 _amount ) external override { _iToken; _to; _amount; } /*********************************/ /***** Internal Functions *******/ /*********************************/ function _redeemAllowed( address _iToken, address _redeemer, uint256 _amount ) private view { _checkiTokenListed(_iToken); // No need to check liquidity if _redeemer has not used _iToken as collateral if (!accountsData[_redeemer].collaterals.contains(_iToken)) { return; } (, uint256 _shortfall, , ) = calcAccountEquityWithEffect(_redeemer, _iToken, _amount, 0); require(_shortfall == 0, "Account has some shortfall"); } /** * @dev Check if _iToken is listed */ function _checkiTokenListed(address _iToken) private view { require(iTokens.contains(_iToken), "Token has not been listed"); } /*********************************/ /** Account equity calculation ***/ /*********************************/ /** * @notice Calculates current account equity * @param _account The account to query equity of * @return account equity, shortfall, collateral value, borrowed value. */ function calcAccountEquity(address _account) public view override returns ( uint256, uint256, uint256, uint256 ) { return calcAccountEquityWithEffect(_account, address(0), 0, 0); } /** * @dev Local vars for avoiding stack-depth limits in calculating account liquidity. * Note that `iTokenBalance` is the number of iTokens the account owns in the collateral, * whereas `borrowBalance` is the amount of underlying that the account has borrowed. */ struct AccountEquityLocalVars { uint256 sumCollateral; uint256 sumBorrowed; uint256 iTokenBalance; uint256 borrowBalance; uint256 exchangeRateMantissa; uint256 underlyingPrice; uint256 collateralValue; uint256 borrowValue; } /** * @notice Calculates current account equity plus some token and amount to effect * @param _account The account to query equity of * @param _tokenToEffect The token address to add some additional redeeem/borrow * @param _redeemAmount The additional amount to redeem * @param _borrowAmount The additional amount to borrow * @return account euqity, shortfall, collateral value, borrowed value plus the effect. */ function calcAccountEquityWithEffect( address _account, address _tokenToEffect, uint256 _redeemAmount, uint256 _borrowAmount ) internal view virtual returns ( uint256, uint256, uint256, uint256 ) { AccountEquityLocalVars memory _local; AccountData storage _accountData = accountsData[_account]; // Calculate value of all collaterals // collateralValuePerToken = underlyingPrice * exchangeRate * collateralFactor // collateralValue = balance * collateralValuePerToken // sumCollateral += collateralValue uint256 _len = _accountData.collaterals.length(); for (uint256 i = 0; i < _len; i++) { IiToken _token = IiToken(_accountData.collaterals.at(i)); _local.iTokenBalance = IERC20Upgradeable(address(_token)).balanceOf( _account ); _local.exchangeRateMantissa = _token.exchangeRateStored(); if (_tokenToEffect == address(_token) && _redeemAmount > 0) { _local.iTokenBalance = _local.iTokenBalance.sub(_redeemAmount); } _local.underlyingPrice = IPriceOracle(priceOracle) .getUnderlyingPrice(address(_token)); require( _local.underlyingPrice != 0, "Invalid price to calculate account equity" ); _local.collateralValue = _local .iTokenBalance .mul(_local.underlyingPrice) .rmul(_local.exchangeRateMantissa) .rmul(markets[address(_token)].collateralFactorMantissa); _local.sumCollateral = _local.sumCollateral.add( _local.collateralValue ); } // Calculate all borrowed value // borrowValue = underlyingPrice * underlyingBorrowed / borrowFactor // sumBorrowed += borrowValue _len = _accountData.borrowed.length(); for (uint256 i = 0; i < _len; i++) { IiToken _token = IiToken(_accountData.borrowed.at(i)); _local.borrowBalance = _token.borrowBalanceStored(_account); if (_tokenToEffect == address(_token) && _borrowAmount > 0) { _local.borrowBalance = _local.borrowBalance.add(_borrowAmount); } _local.underlyingPrice = IPriceOracle(priceOracle) .getUnderlyingPrice(address(_token)); require( _local.underlyingPrice != 0, "Invalid price to calculate account equity" ); // borrowFactorMantissa can not be set to 0 _local.borrowValue = _local .borrowBalance .mul(_local.underlyingPrice) .rdiv(markets[address(_token)].borrowFactorMantissa); _local.sumBorrowed = _local.sumBorrowed.add(_local.borrowValue); } // Should never underflow return _local.sumCollateral > _local.sumBorrowed ? ( _local.sumCollateral - _local.sumBorrowed, uint256(0), _local.sumCollateral, _local.sumBorrowed ) : ( uint256(0), _local.sumBorrowed - _local.sumCollateral, _local.sumCollateral, _local.sumBorrowed ); } /** * @notice Calculate amount of collateral iToken to seize after repaying an underlying amount * @dev Used in liquidation * @param _iTokenBorrowed The iToken was borrowed * @param _iTokenCollateral The collateral iToken to be seized * @param _actualRepayAmount The amount of underlying token liquidator has repaied * @return _seizedTokenCollateral amount of iTokenCollateral tokens to be seized */ function liquidateCalculateSeizeTokens( address _iTokenBorrowed, address _iTokenCollateral, uint256 _actualRepayAmount ) external view virtual override returns (uint256 _seizedTokenCollateral) { /* Read oracle prices for borrowed and collateral assets */ uint256 _priceBorrowed = IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenBorrowed); uint256 _priceCollateral = IPriceOracle(priceOracle).getUnderlyingPrice(_iTokenCollateral); require( _priceBorrowed != 0 && _priceCollateral != 0, "Borrowed or Collateral asset price is invalid" ); uint256 _valueRepayPlusIncentive = _actualRepayAmount.mul(_priceBorrowed).rmul( liquidationIncentiveMantissa ); // Use stored value here as it is view function uint256 _exchangeRateMantissa = IiToken(_iTokenCollateral).exchangeRateStored(); // seizedTokenCollateral = valueRepayPlusIncentive / valuePerTokenCollateral // valuePerTokenCollateral = exchangeRateMantissa * priceCollateral _seizedTokenCollateral = _valueRepayPlusIncentive .rdiv(_exchangeRateMantissa) .div(_priceCollateral); } /*********************************/ /*** Account Markets Operation ***/ /*********************************/ /** * @notice Returns the markets list the account has entered * @param _account The address of the account to query * @return _accountCollaterals The markets list the account has entered */ function getEnteredMarkets(address _account) external view override returns (address[] memory _accountCollaterals) { AccountData storage _accountData = accountsData[_account]; uint256 _len = _accountData.collaterals.length(); _accountCollaterals = new address[](_len); for (uint256 i = 0; i < _len; i++) { _accountCollaterals[i] = _accountData.collaterals.at(i); } } /** * @notice Add markets to `msg.sender`'s markets list for liquidity calculations * @param _iTokens The list of addresses of the iToken markets to be entered * @return _results Success indicator for whether each corresponding market was entered */ function enterMarkets(address[] calldata _iTokens) external override returns (bool[] memory _results) { uint256 _len = _iTokens.length; _results = new bool[](_len); for (uint256 i = 0; i < _len; i++) { _results[i] = _enterMarket(_iTokens[i], msg.sender); } } /** * @notice Only expect to be called by iToken contract. * @dev Add the market to the account's markets list for liquidity calculations * @param _account The address of the account to modify */ function enterMarketFromiToken(address _account) external override { require( _enterMarket(msg.sender, _account), "enterMarketFromiToken: Only can be called by a supported iToken!" ); } /** * @notice Add the market to the account's markets list for liquidity calculations * @param _iToken The market to enter * @param _account The address of the account to modify * @return True if entered successfully, false for non-listed market or other errors */ function _enterMarket(address _iToken, address _account) internal returns (bool) { // Market not listed, skip it if (!iTokens.contains(_iToken)) { return false; } // add() will return false if iToken is in account's market list if (accountsData[_account].collaterals.add(_iToken)) { emit MarketEntered(_iToken, _account); } return true; } /** * @notice Returns whether the given account has entered the market * @param _account The address of the account to check * @param _iToken The iToken to check against * @return True if the account has entered the market, otherwise false. */ function hasEnteredMarket(address _account, address _iToken) external view override returns (bool) { return accountsData[_account].collaterals.contains(_iToken); } /** * @notice Remove markets from `msg.sender`'s collaterals for liquidity calculations * @param _iTokens The list of addresses of the iToken to exit * @return _results Success indicators for whether each corresponding market was exited */ function exitMarkets(address[] calldata _iTokens) external override returns (bool[] memory _results) { uint256 _len = _iTokens.length; _results = new bool[](_len); for (uint256 i = 0; i < _len; i++) { _results[i] = _exitMarket(_iTokens[i], msg.sender); } } /** * @notice Remove the market to the account's markets list for liquidity calculations * @param _iToken The market to exit * @param _account The address of the account to modify * @return True if exit successfully, false for non-listed market or other errors */ function _exitMarket(address _iToken, address _account) internal returns (bool) { // Market not listed, skip it if (!iTokens.contains(_iToken)) { return true; } // Account has not entered this market, skip it if (!accountsData[_account].collaterals.contains(_iToken)) { return true; } // Get the iToken balance uint256 _balance = IERC20Upgradeable(_iToken).balanceOf(_account); // Check account's equity if all balance are redeemed // which means iToken can be removed from collaterals _redeemAllowed(_iToken, _account, _balance); // Have checked account has entered market before accountsData[_account].collaterals.remove(_iToken); emit MarketExited(_iToken, _account); return true; } /** * @notice Returns the asset list the account has borrowed * @param _account The address of the account to query * @return _borrowedAssets The asset list the account has borrowed */ function getBorrowedAssets(address _account) external view override returns (address[] memory _borrowedAssets) { AccountData storage _accountData = accountsData[_account]; uint256 _len = _accountData.borrowed.length(); _borrowedAssets = new address[](_len); for (uint256 i = 0; i < _len; i++) { _borrowedAssets[i] = _accountData.borrowed.at(i); } } /** * @notice Add the market to the account's borrowed list for equity calculations * @param _iToken The iToken of underlying to borrow * @param _account The address of the account to modify */ function _addToBorrowed(address _account, address _iToken) internal { // add() will return false if iToken is in account's market list if (accountsData[_account].borrowed.add(_iToken)) { emit BorrowedAdded(_iToken, _account); } } /** * @notice Returns whether the given account has borrowed the given iToken * @param _account The address of the account to check * @param _iToken The iToken to check against * @return True if the account has borrowed the iToken, otherwise false. */ function hasBorrowed(address _account, address _iToken) public view override returns (bool) { return accountsData[_account].borrowed.contains(_iToken); } /** * @notice Remove the iToken from the account's borrowed list * @param _iToken The iToken to remove * @param _account The address of the account to modify */ function _removeFromBorrowed(address _account, address _iToken) internal { // remove() will return false if iToken does not exist in account's borrowed list if (accountsData[_account].borrowed.remove(_iToken)) { emit BorrowedRemoved(_iToken, _account); } } /*********************************/ /****** General Information ******/ /*********************************/ /** * @notice Return all of the iTokens * @return _alliTokens The list of iToken addresses */ function getAlliTokens() public view override returns (address[] memory _alliTokens) { EnumerableSetUpgradeable.AddressSet storage _iTokens = iTokens; uint256 _len = _iTokens.length(); _alliTokens = new address[](_len); for (uint256 i = 0; i < _len; i++) { _alliTokens[i] = _iTokens.at(i); } } /** * @notice Check whether a iToken is listed in controller * @param _iToken The iToken to check for * @return true if the iToken is listed otherwise false */ function hasiToken(address _iToken) public view override returns (bool) { return iTokens.contains(_iToken); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @title dForce Lending Protocol's InterestRateModel Interface. * @author dForce Team. */ interface IInterestRateModelInterface { function isInterestRateModel() external view returns (bool); /** * @dev Calculates the current borrow interest rate per block. * @param cash The total amount of cash the market has. * @param borrows The total amount of borrows the market has. * @param reserves The total amnount of reserves the market has. * @return The borrow rate per block (as a percentage, and scaled by 1e18). */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256); /** * @dev Calculates the current supply interest rate per block. * @param cash The total amount of cash the market has. * @param borrows The total amount of borrows the market has. * @param reserves The total amnount of reserves the market has. * @param reserveRatio The current reserve factor the market has. * @return The supply rate per block (as a percentage, and scaled by 1e18). */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveRatio ) external view returns (uint256); } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IControllerAdminInterface { /// @notice Emitted when an admin supports a market event MarketAdded( address iToken, uint256 collateralFactor, uint256 borrowFactor, uint256 supplyCapacity, uint256 borrowCapacity, uint256 distributionFactor ); function _addMarket( address _iToken, uint256 _collateralFactor, uint256 _borrowFactor, uint256 _supplyCapacity, uint256 _borrowCapacity, uint256 _distributionFactor ) external; /// @notice Emitted when new price oracle is set event NewPriceOracle(address oldPriceOracle, address newPriceOracle); function _setPriceOracle(address newOracle) external; /// @notice Emitted when close factor is changed by admin event NewCloseFactor( uint256 oldCloseFactorMantissa, uint256 newCloseFactorMantissa ); function _setCloseFactor(uint256 newCloseFactorMantissa) external; /// @notice Emitted when liquidation incentive is changed by admin event NewLiquidationIncentive( uint256 oldLiquidationIncentiveMantissa, uint256 newLiquidationIncentiveMantissa ); function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa) external; /// @notice Emitted when iToken's collateral factor is changed by admin event NewCollateralFactor( address iToken, uint256 oldCollateralFactorMantissa, uint256 newCollateralFactorMantissa ); function _setCollateralFactor( address iToken, uint256 newCollateralFactorMantissa ) external; /// @notice Emitted when iToken's borrow factor is changed by admin event NewBorrowFactor( address iToken, uint256 oldBorrowFactorMantissa, uint256 newBorrowFactorMantissa ); function _setBorrowFactor(address iToken, uint256 newBorrowFactorMantissa) external; /// @notice Emitted when iToken's borrow capacity is changed by admin event NewBorrowCapacity( address iToken, uint256 oldBorrowCapacity, uint256 newBorrowCapacity ); function _setBorrowCapacity(address iToken, uint256 newBorrowCapacity) external; /// @notice Emitted when iToken's supply capacity is changed by admin event NewSupplyCapacity( address iToken, uint256 oldSupplyCapacity, uint256 newSupplyCapacity ); function _setSupplyCapacity(address iToken, uint256 newSupplyCapacity) external; /// @notice Emitted when pause guardian is changed by admin event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian); function _setPauseGuardian(address newPauseGuardian) external; /// @notice Emitted when mint is paused/unpaused by admin or pause guardian event MintPaused(address iToken, bool paused); function _setMintPaused(address iToken, bool paused) external; function _setAllMintPaused(bool paused) external; /// @notice Emitted when redeem is paused/unpaused by admin or pause guardian event RedeemPaused(address iToken, bool paused); function _setRedeemPaused(address iToken, bool paused) external; function _setAllRedeemPaused(bool paused) external; /// @notice Emitted when borrow is paused/unpaused by admin or pause guardian event BorrowPaused(address iToken, bool paused); function _setBorrowPaused(address iToken, bool paused) external; function _setAllBorrowPaused(bool paused) external; /// @notice Emitted when transfer is paused/unpaused by admin or pause guardian event TransferPaused(bool paused); function _setTransferPaused(bool paused) external; /// @notice Emitted when seize is paused/unpaused by admin or pause guardian event SeizePaused(bool paused); function _setSeizePaused(bool paused) external; function _setiTokenPaused(address iToken, bool paused) external; function _setProtocolPaused(bool paused) external; event NewRewardDistributor( address oldRewardDistributor, address _newRewardDistributor ); function _setRewardDistributor(address _newRewardDistributor) external; } interface IControllerPolicyInterface { function beforeMint( address iToken, address account, uint256 mintAmount ) external; function afterMint( address iToken, address minter, uint256 mintAmount, uint256 mintedAmount ) external; function beforeRedeem( address iToken, address redeemer, uint256 redeemAmount ) external; function afterRedeem( address iToken, address redeemer, uint256 redeemAmount, uint256 redeemedAmount ) external; function beforeBorrow( address iToken, address borrower, uint256 borrowAmount ) external; function afterBorrow( address iToken, address borrower, uint256 borrowedAmount ) external; function beforeRepayBorrow( address iToken, address payer, address borrower, uint256 repayAmount ) external; function afterRepayBorrow( address iToken, address payer, address borrower, uint256 repayAmount ) external; function beforeLiquidateBorrow( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external; function afterLiquidateBorrow( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 repaidAmount, uint256 seizedAmount ) external; function beforeSeize( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 seizeAmount ) external; function afterSeize( address iTokenBorrowed, address iTokenCollateral, address liquidator, address borrower, uint256 seizedAmount ) external; function beforeTransfer( address iToken, address from, address to, uint256 amount ) external; function afterTransfer( address iToken, address from, address to, uint256 amount ) external; function beforeFlashloan( address iToken, address to, uint256 amount ) external; function afterFlashloan( address iToken, address to, uint256 amount ) external; } interface IControllerAccountEquityInterface { function calcAccountEquity(address account) external view returns ( uint256, uint256, uint256, uint256 ); function liquidateCalculateSeizeTokens( address iTokenBorrowed, address iTokenCollateral, uint256 actualRepayAmount ) external view returns (uint256); } interface IControllerAccountInterface { function hasEnteredMarket(address account, address iToken) external view returns (bool); function getEnteredMarkets(address account) external view returns (address[] memory); /// @notice Emitted when an account enters a market event MarketEntered(address iToken, address account); function enterMarkets(address[] calldata iTokens) external returns (bool[] memory); function enterMarketFromiToken(address _account) external; /// @notice Emitted when an account exits a market event MarketExited(address iToken, address account); function exitMarkets(address[] calldata iTokens) external returns (bool[] memory); /// @notice Emitted when an account add a borrow asset event BorrowedAdded(address iToken, address account); /// @notice Emitted when an account remove a borrow asset event BorrowedRemoved(address iToken, address account); function hasBorrowed(address account, address iToken) external view returns (bool); function getBorrowedAssets(address account) external view returns (address[] memory); } interface IControllerInterface is IControllerAdminInterface, IControllerPolicyInterface, IControllerAccountEquityInterface, IControllerAccountInterface { /** * @notice Security checks when updating the comptroller of a market, always expect to return true. */ function isController() external view returns (bool); /** * @notice Return all of the iTokens * @return The list of iToken addresses */ function getAlliTokens() external view returns (address[] memory); /** * @notice Check whether a iToken is listed in controller * @param _iToken The iToken to check for * @return true if the iToken is listed otherwise false */ function hasiToken(address _iToken) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } //SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IRewardDistributor { function _setRewardToken(address newRewardToken) external; /// @notice Emitted reward token address is changed by admin event NewRewardToken(address oldRewardToken, address newRewardToken); function _addRecipient(address _iToken, uint256 _distributionFactor) external; event NewRecipient(address iToken, uint256 distributionFactor); /// @notice Emitted when mint is paused/unpaused by admin event Paused(bool paused); function _pause() external; function _unpause(uint256 _borrowSpeed, uint256 _supplySpeed) external; /// @notice Emitted when Global Distribution speed for both supply and borrow are updated event GlobalDistributionSpeedsUpdated( uint256 borrowSpeed, uint256 supplySpeed ); function _setGlobalDistributionSpeeds( uint256 borrowSpeed, uint256 supplySpeed ) external; /// @notice Emitted when iToken's Distribution speed is updated event DistributionSpeedsUpdated( address iToken, uint256 borrowSpeed, uint256 supplySpeed ); function updateDistributionSpeed() external; /// @notice Emitted when iToken's Distribution factor is changed by admin event NewDistributionFactor( address iToken, uint256 oldDistributionFactorMantissa, uint256 newDistributionFactorMantissa ); function _setDistributionFactors( address[] calldata iToken, uint256[] calldata distributionFactors ) external; function updateDistributionState(address _iToken, bool _isBorrow) external; function updateReward( address _iToken, address _account, bool _isBorrow ) external; function updateRewardBatch( address[] memory _holders, address[] memory _iTokens ) external; function claimReward(address[] memory _holders, address[] memory _iTokens) external; function claimAllReward(address[] memory _holders) external; /// @notice Emitted when reward of amount is distributed into account event RewardDistributed( address iToken, address account, uint256 amount, uint256 accountIndex ); }
Add the iToken as receipient Admin function, only controller can call this _iToken the iToken to add as recipient _distributionFactor the distribution factor of the recipient/
function _addRecipient(address _iToken, uint256 _distributionFactor) external override onlyController { distributionFactorMantissa[_iToken] = _distributionFactor; distributionSupplyState[_iToken] = DistributionState({ index: 0, block: block.number }); distributionBorrowState[_iToken] = DistributionState({ index: 0, block: block.number }); emit NewRecipient(_iToken, _distributionFactor); }
1,317,987
./full_match/11155111/0x455d83fa7D8320147B80130861Df030A1f050097/sources/contracts/Predictor.sol
had faced issues while fetchings api from chainlink functions which is in closed beta. untill, hardcoded the contests and events. Emit an event when contest is created
function createContest() private { uint256 randNum = randomNum(1000000); ContestsId.push( Game(randNum, "India", "Australia", matchStatus.Yet_to_Start) ); emit Ongoing_Contests(randNum, "India", "Australia", "Yet_to_Start"); ContestsId.push( Game(randNum + 1, "Newzealand", "England", matchStatus.Yet_to_Start) ); emit Ongoing_Contests( randNum + 1, "Newzealand", "England", "Yet_to_Start" ); ContestsId.push( Game( randNum + 2, "SouthAfrica", "Srilanka", matchStatus.Yet_to_Start ) ); emit Ongoing_Contests( randNum + 2, "SouthAfrica", "Srilanka", "Yet_to_Start" ); }
3,811,696
./partial_match/1/0x14132D979fDdA62a56d9f552C9aa477b9c94851e/sources/@yield-protocol/yieldspace-tv/src/Exp64x64.sol
Calculate 2 raised into given power. x power to raise 2 into, multiplied by 2^121 return 2 raised into given power
function pow_2(uint128 x) internal pure returns (uint128) { unchecked { uint256 r = 0x80000000000000000000000000000000; if (x & 0x1000000000000000000000000000000 > 0) r = (r * 0xb504f333f9de6484597d89b3754abe9f) >> 127; if (x & 0x800000000000000000000000000000 > 0) r = (r * 0x9837f0518db8a96f46ad23182e42f6f6) >> 127; if (x & 0x400000000000000000000000000000 > 0) r = (r * 0x8b95c1e3ea8bd6e6fbe4628758a53c90) >> 127; if (x & 0x200000000000000000000000000000 > 0) r = (r * 0x85aac367cc487b14c5c95b8c2154c1b2) >> 127; if (x & 0x100000000000000000000000000000 > 0) r = (r * 0x82cd8698ac2ba1d73e2a475b46520bff) >> 127; if (x & 0x80000000000000000000000000000 > 0) r = (r * 0x8164d1f3bc0307737be56527bd14def4) >> 127; if (x & 0x40000000000000000000000000000 > 0) r = (r * 0x80b1ed4fd999ab6c25335719b6e6fd20) >> 127; if (x & 0x20000000000000000000000000000 > 0) r = (r * 0x8058d7d2d5e5f6b094d589f608ee4aa2) >> 127; if (x & 0x10000000000000000000000000000 > 0) r = (r * 0x802c6436d0e04f50ff8ce94a6797b3ce) >> 127; if (x & 0x8000000000000000000000000000 > 0) r = (r * 0x8016302f174676283690dfe44d11d008) >> 127; if (x & 0x4000000000000000000000000000 > 0) r = (r * 0x800b179c82028fd0945e54e2ae18f2f0) >> 127; if (x & 0x2000000000000000000000000000 > 0) r = (r * 0x80058baf7fee3b5d1c718b38e549cb93) >> 127; if (x & 0x1000000000000000000000000000 > 0) r = (r * 0x8002c5d00fdcfcb6b6566a58c048be1f) >> 127; if (x & 0x800000000000000000000000000 > 0) r = (r * 0x800162e61bed4a48e84c2e1a463473d9) >> 127; if (x & 0x400000000000000000000000000 > 0) r = (r * 0x8000b17292f702a3aa22beacca949013) >> 127; if (x & 0x200000000000000000000000000 > 0) r = (r * 0x800058b92abbae02030c5fa5256f41fe) >> 127; if (x & 0x100000000000000000000000000 > 0) r = (r * 0x80002c5c8dade4d71776c0f4dbea67d6) >> 127; if (x & 0x80000000000000000000000000 > 0) r = (r * 0x8000162e44eaf636526be456600bdbe4) >> 127; if (x & 0x40000000000000000000000000 > 0) r = (r * 0x80000b1721fa7c188307016c1cd4e8b6) >> 127; if (x & 0x20000000000000000000000000 > 0) r = (r * 0x8000058b90de7e4cecfc487503488bb1) >> 127; if (x & 0x10000000000000000000000000 > 0) r = (r * 0x800002c5c8678f36cbfce50a6de60b14) >> 127; if (x & 0x8000000000000000000000000 > 0) r = (r * 0x80000162e431db9f80b2347b5d62e516) >> 127; if (x & 0x4000000000000000000000000 > 0) r = (r * 0x800000b1721872d0c7b08cf1e0114152) >> 127; if (x & 0x2000000000000000000000000 > 0) r = (r * 0x80000058b90c1aa8a5c3736cb77e8dff) >> 127; if (x & 0x1000000000000000000000000 > 0) r = (r * 0x8000002c5c8605a4635f2efc2362d978) >> 127; if (x & 0x800000000000000000000000 > 0) r = (r * 0x800000162e4300e635cf4a109e3939bd) >> 127; if (x & 0x400000000000000000000000 > 0) r = (r * 0x8000000b17217ff81bef9c551590cf83) >> 127; if (x & 0x200000000000000000000000 > 0) r = (r * 0x800000058b90bfdd4e39cd52c0cfa27c) >> 127; if (x & 0x100000000000000000000000 > 0) r = (r * 0x80000002c5c85fe6f72d669e0e76e411) >> 127; if (x & 0x80000000000000000000000 > 0) r = (r * 0x8000000162e42ff18f9ad35186d0df28) >> 127; if (x & 0x40000000000000000000000 > 0) r = (r * 0x80000000b17217f84cce71aa0dcfffe7) >> 127; if (x & 0x20000000000000000000000 > 0) r = (r * 0x8000000058b90bfc07a77ad56ed22aaa) >> 127; if (x & 0x10000000000000000000000 > 0) r = (r * 0x800000002c5c85fdfc23cdead40da8d6) >> 127; if (x & 0x8000000000000000000000 > 0) r = (r * 0x80000000162e42fefc25eb1571853a66) >> 127; if (x & 0x4000000000000000000000 > 0) r = (r * 0x800000000b17217f7d97f692baacded5) >> 127; if (x & 0x2000000000000000000000 > 0) r = (r * 0x80000000058b90bfbead3b8b5dd254d7) >> 127; if (x & 0x1000000000000000000000 > 0) r = (r * 0x8000000002c5c85fdf4eedd62f084e67) >> 127; if (x & 0x800000000000000000000 > 0) r = (r * 0x800000000162e42fefa58aef378bf586) >> 127; if (x & 0x400000000000000000000 > 0) r = (r * 0x8000000000b17217f7d24a78a3c7ef02) >> 127; if (x & 0x200000000000000000000 > 0) r = (r * 0x800000000058b90bfbe9067c93e474a6) >> 127; if (x & 0x100000000000000000000 > 0) r = (r * 0x80000000002c5c85fdf47b8e5a72599f) >> 127; if (x & 0x80000000000000000000 > 0) r = (r * 0x8000000000162e42fefa3bdb315934a2) >> 127; if (x & 0x40000000000000000000 > 0) r = (r * 0x80000000000b17217f7d1d7299b49c46) >> 127; if (x & 0x20000000000000000000 > 0) r = (r * 0x8000000000058b90bfbe8e9a8d1c4ea0) >> 127; if (x & 0x10000000000000000000 > 0) r = (r * 0x800000000002c5c85fdf4745969ea76f) >> 127; if (x & 0x8000000000000000000 > 0) r = (r * 0x80000000000162e42fefa3a0df5373bf) >> 127; if (x & 0x4000000000000000000 > 0) r = (r * 0x800000000000b17217f7d1cff4aac1e1) >> 127; if (x & 0x2000000000000000000 > 0) r = (r * 0x80000000000058b90bfbe8e7db95a2f1) >> 127; if (x & 0x1000000000000000000 > 0) r = (r * 0x8000000000002c5c85fdf473e61ae1f8) >> 127; if (x & 0x800000000000000000 > 0) r = (r * 0x800000000000162e42fefa39f121751c) >> 127; if (x & 0x400000000000000000 > 0) r = (r * 0x8000000000000b17217f7d1cf815bb96) >> 127; if (x & 0x200000000000000000 > 0) r = (r * 0x800000000000058b90bfbe8e7bec1e0d) >> 127; if (x & 0x100000000000000000 > 0) r = (r * 0x80000000000002c5c85fdf473dee5f17) >> 127; if (x & 0x80000000000000000 > 0) r = (r * 0x8000000000000162e42fefa39ef5438f) >> 127; if (x & 0x40000000000000000 > 0) r = (r * 0x80000000000000b17217f7d1cf7a26c8) >> 127; if (x & 0x20000000000000000 > 0) r = (r * 0x8000000000000058b90bfbe8e7bcf4a4) >> 127; if (x & 0x10000000000000000 > 0) r = (r * 0x800000000000002c5c85fdf473de72a2) >> 127; /* if(x & 0x8000000000000000 > 0) r = r * 0x80000000000000162e42fefa39ef3765 >> 127; if(x & 0x4000000000000000 > 0) r = r * 0x800000000000000b17217f7d1cf79b37 >> 127; if(x & 0x2000000000000000 > 0) r = r * 0x80000000000000058b90bfbe8e7bcd7d >> 127; if(x & 0x1000000000000000 > 0) r = r * 0x8000000000000002c5c85fdf473de6b6 >> 127; if(x & 0x800000000000000 > 0) r = r * 0x800000000000000162e42fefa39ef359 >> 127; if(x & 0x400000000000000 > 0) r = r * 0x8000000000000000b17217f7d1cf79ac >> 127; if(x & 0x200000000000000 > 0) r = r * 0x800000000000000058b90bfbe8e7bcd6 >> 127; if(x & 0x100000000000000 > 0) r = r * 0x80000000000000002c5c85fdf473de6a >> 127; if(x & 0x80000000000000 > 0) r = r * 0x8000000000000000162e42fefa39ef35 >> 127; if(x & 0x40000000000000 > 0) r = r * 0x80000000000000000b17217f7d1cf79a >> 127; if(x & 0x20000000000000 > 0) r = r * 0x8000000000000000058b90bfbe8e7bcd >> 127; if(x & 0x10000000000000 > 0) r = r * 0x800000000000000002c5c85fdf473de6 >> 127; if(x & 0x8000000000000 > 0) r = r * 0x80000000000000000162e42fefa39ef3 >> 127; if(x & 0x4000000000000 > 0) r = r * 0x800000000000000000b17217f7d1cf79 >> 127; if(x & 0x2000000000000 > 0) r = r * 0x80000000000000000058b90bfbe8e7bc >> 127; if(x & 0x1000000000000 > 0) r = r * 0x8000000000000000002c5c85fdf473de >> 127; if(x & 0x800000000000 > 0) r = r * 0x800000000000000000162e42fefa39ef >> 127; if(x & 0x400000000000 > 0) r = r * 0x8000000000000000000b17217f7d1cf7 >> 127; if(x & 0x200000000000 > 0) r = r * 0x800000000000000000058b90bfbe8e7b >> 127; if(x & 0x100000000000 > 0) r = r * 0x80000000000000000002c5c85fdf473d >> 127; if(x & 0x80000000000 > 0) r = r * 0x8000000000000000000162e42fefa39e >> 127; if(x & 0x40000000000 > 0) r = r * 0x80000000000000000000b17217f7d1cf >> 127; if(x & 0x20000000000 > 0) r = r * 0x8000000000000000000058b90bfbe8e7 >> 127; if(x & 0x10000000000 > 0) r = r * 0x800000000000000000002c5c85fdf473 >> 127; if(x & 0x8000000000 > 0) r = r * 0x80000000000000000000162e42fefa39 >> 127; if(x & 0x4000000000 > 0) r = r * 0x800000000000000000000b17217f7d1c >> 127; if(x & 0x2000000000 > 0) r = r * 0x80000000000000000000058b90bfbe8e >> 127; if(x & 0x1000000000 > 0) r = r * 0x8000000000000000000002c5c85fdf47 >> 127; if(x & 0x800000000 > 0) r = r * 0x800000000000000000000162e42fefa3 >> 127; if(x & 0x400000000 > 0) r = r * 0x8000000000000000000000b17217f7d1 >> 127; if(x & 0x200000000 > 0) r = r * 0x800000000000000000000058b90bfbe8 >> 127; if(x & 0x100000000 > 0) r = r * 0x80000000000000000000002c5c85fdf4 >> 127; if(x & 0x80000000 > 0) r = r * 0x8000000000000000000000162e42fefa >> 127; if(x & 0x40000000 > 0) r = r * 0x80000000000000000000000b17217f7d >> 127; if(x & 0x20000000 > 0) r = r * 0x8000000000000000000000058b90bfbe >> 127; if(x & 0x10000000 > 0) r = r * 0x800000000000000000000002c5c85fdf >> 127; if(x & 0x8000000 > 0) r = r * 0x80000000000000000000000162e42fef >> 127; if(x & 0x4000000 > 0) r = r * 0x800000000000000000000000b17217f7 >> 127; if(x & 0x2000000 > 0) r = r * 0x80000000000000000000000058b90bfb >> 127; if(x & 0x1000000 > 0) r = r * 0x8000000000000000000000002c5c85fd >> 127; if(x & 0x800000 > 0) r = r * 0x800000000000000000000000162e42fe >> 127; if(x & 0x400000 > 0) r = r * 0x8000000000000000000000000b17217f >> 127; if(x & 0x200000 > 0) r = r * 0x800000000000000000000000058b90bf >> 127; if(x & 0x100000 > 0) r = r * 0x80000000000000000000000002c5c85f >> 127; if(x & 0x80000 > 0) r = r * 0x8000000000000000000000000162e42f >> 127; if(x & 0x40000 > 0) r = r * 0x80000000000000000000000000b17217 >> 127; if(x & 0x20000 > 0) r = r * 0x8000000000000000000000000058b90b >> 127; if(x & 0x10000 > 0) r = r * 0x800000000000000000000000002c5c85 >> 127; if(x & 0x8000 > 0) r = r * 0x80000000000000000000000000162e42 >> 127; if(x & 0x4000 > 0) r = r * 0x800000000000000000000000000b1721 >> 127; if(x & 0x2000 > 0) r = r * 0x80000000000000000000000000058b90 >> 127; if(x & 0x1000 > 0) r = r * 0x8000000000000000000000000002c5c8 >> 127; if(x & 0x800 > 0) r = r * 0x800000000000000000000000000162e4 >> 127; if(x & 0x400 > 0) r = r * 0x8000000000000000000000000000b172 >> 127; if(x & 0x200 > 0) r = r * 0x800000000000000000000000000058b9 >> 127; if(x & 0x100 > 0) r = r * 0x80000000000000000000000000002c5c >> 127; if(x & 0x80 > 0) r = r * 0x8000000000000000000000000000162e >> 127; if(x & 0x40 > 0) r = r * 0x80000000000000000000000000000b17 >> 127; if(x & 0x20 > 0) r = r * 0x8000000000000000000000000000058b >> 127; if(x & 0x10 > 0) r = r * 0x800000000000000000000000000002c5 >> 127; if(x & 0x8 > 0) r = r * 0x80000000000000000000000000000162 >> 127; if(x & 0x4 > 0) r = r * 0x800000000000000000000000000000b1 >> 127; if(x & 0x2 > 0) r = r * 0x80000000000000000000000000000058 >> 127; if(x & 0x1 > 0) r = r * 0x8000000000000000000000000000002c >> 127; */ r >>= 127 - (x >> 121); return uint128(r); } }
15,663,230