file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
list
attention_mask
list
labels
list
// File: contracts/interfaces/IDelegable.sol pragma solidity ^0.6.10; interface IDelegable { function ADDDELEGATE653(address) external; //inject NONSTANDARD NAMING function ADDDELEGATEBYSIGNATURE882(address, address, uint, uint8, bytes32, bytes32) external; //inject NONSTANDARD NAMING } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; interface IERC20 { function TOTALSUPPLY521() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF833(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER582(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE506(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE147(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM451(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER75(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL533(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: contracts/interfaces/IVat.sol pragma solidity ^0.6.10; interface IVat { // function can(address, address) external view returns (uint); function HOPE952(address) external; //inject NONSTANDARD NAMING function NOPE303(address) external; //inject NONSTANDARD NAMING function LIVE610() external view returns (uint); //inject NONSTANDARD NAMING function ILKS57(bytes32) external view returns (uint, uint, uint, uint, uint); //inject NONSTANDARD NAMING function URNS490(bytes32, address) external view returns (uint, uint); //inject NONSTANDARD NAMING function GEM988(bytes32, address) external view returns (uint); //inject NONSTANDARD NAMING // function dai(address) external view returns (uint); function FROB42(bytes32, address, address, address, int, int) external; //inject NONSTANDARD NAMING function FORK314(bytes32, address, address, int, int) external; //inject NONSTANDARD NAMING function MOVE289(address, address, uint) external; //inject NONSTANDARD NAMING function FLUX433(bytes32, address, address, uint) external; //inject NONSTANDARD NAMING } // File: contracts/interfaces/IWeth.sol pragma solidity ^0.6.10; interface IWeth { function DEPOSIT338() external payable; //inject NONSTANDARD NAMING function WITHDRAW817(uint) external; //inject NONSTANDARD NAMING function APPROVE147(address, uint) external returns (bool) ; //inject NONSTANDARD NAMING function TRANSFER582(address, uint) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM451(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING } // File: contracts/interfaces/IGemJoin.sol pragma solidity ^0.6.10; interface IGemJoin { function RELY66(address usr) external; //inject NONSTANDARD NAMING function DENY577(address usr) external; //inject NONSTANDARD NAMING function CAGE307() external; //inject NONSTANDARD NAMING function JOIN369(address usr, uint WAD) external; //inject NONSTANDARD NAMING function EXIT932(address usr, uint WAD) external; //inject NONSTANDARD NAMING } // File: contracts/interfaces/IDaiJoin.sol pragma solidity ^0.6.10; interface IDaiJoin { function RELY66(address usr) external; //inject NONSTANDARD NAMING function DENY577(address usr) external; //inject NONSTANDARD NAMING function CAGE307() external; //inject NONSTANDARD NAMING function JOIN369(address usr, uint WAD) external; //inject NONSTANDARD NAMING function EXIT932(address usr, uint WAD) external; //inject NONSTANDARD NAMING } // File: contracts/interfaces/IPot.sol pragma solidity ^0.6.10; interface IPot { function CHI612() external view returns (uint256); //inject NONSTANDARD NAMING function PIE445(address) external view returns (uint256); // Not a function, but a public variable. //inject NONSTANDARD NAMING function RHO514() external returns (uint256); //inject NONSTANDARD NAMING function DRIP65() external returns (uint256); //inject NONSTANDARD NAMING function JOIN369(uint256) external; //inject NONSTANDARD NAMING function EXIT932(uint256) external; //inject NONSTANDARD NAMING } // File: contracts/interfaces/IChai.sol pragma solidity ^0.6.10; interface IChai { function BALANCEOF833(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER582(address dst, uint wad) external returns (bool); //inject NONSTANDARD NAMING function MOVE289(address src, address dst, uint wad) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM451(address src, address dst, uint wad) external returns (bool); //inject NONSTANDARD NAMING function APPROVE147(address usr, uint wad) external returns (bool); //inject NONSTANDARD NAMING function DAI858(address usr) external returns (uint wad); //inject NONSTANDARD NAMING function JOIN369(address dst, uint wad) external; //inject NONSTANDARD NAMING function EXIT932(address src, uint wad) external; //inject NONSTANDARD NAMING function DRAW289(address src, uint wad) external; //inject NONSTANDARD NAMING function PERMIT233(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING function NONCES538(address account) external view returns (uint256); //inject NONSTANDARD NAMING } // File: contracts/interfaces/ITreasury.sol pragma solidity ^0.6.10; interface ITreasury { function DEBT715() external view returns(uint256); //inject NONSTANDARD NAMING function SAVINGS903() external view returns(uint256); //inject NONSTANDARD NAMING function PUSHDAI613(address user, uint256 dai) external; //inject NONSTANDARD NAMING function PULLDAI166(address user, uint256 dai) external; //inject NONSTANDARD NAMING function PUSHCHAI91(address user, uint256 chai) external; //inject NONSTANDARD NAMING function PULLCHAI479(address user, uint256 chai) external; //inject NONSTANDARD NAMING function PUSHWETH634(address to, uint256 weth) external; //inject NONSTANDARD NAMING function PULLWETH548(address to, uint256 weth) external; //inject NONSTANDARD NAMING function SHUTDOWN178() external; //inject NONSTANDARD NAMING function LIVE610() external view returns(bool); //inject NONSTANDARD NAMING function VAT519() external view returns (IVat); //inject NONSTANDARD NAMING function WETH278() external view returns (IWeth); //inject NONSTANDARD NAMING function DAI858() external view returns (IERC20); //inject NONSTANDARD NAMING function DAIJOIN173() external view returns (IDaiJoin); //inject NONSTANDARD NAMING function WETHJOIN654() external view returns (IGemJoin); //inject NONSTANDARD NAMING function POT408() external view returns (IPot); //inject NONSTANDARD NAMING function CHAI326() external view returns (IChai); //inject NONSTANDARD NAMING } // File: contracts/interfaces/IERC2612.sol // Code adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237/ pragma solidity ^0.6.0; interface IERC2612 { function PERMIT233(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING function NONCES538(address owner) external view returns (uint256); //inject NONSTANDARD NAMING } // File: contracts/interfaces/IFYDai.sol pragma solidity ^0.6.10; interface IFYDai is IERC20, IERC2612 { function ISMATURE431() external view returns(bool); //inject NONSTANDARD NAMING function MATURITY388() external view returns(uint); //inject NONSTANDARD NAMING function CHI0242() external view returns(uint); //inject NONSTANDARD NAMING function RATE0398() external view returns(uint); //inject NONSTANDARD NAMING function CHIGROWTH747() external view returns(uint); //inject NONSTANDARD NAMING function RATEGROWTH408() external view returns(uint); //inject NONSTANDARD NAMING function MATURE589() external; //inject NONSTANDARD NAMING function UNLOCKED182() external view returns (uint); //inject NONSTANDARD NAMING function MINT176(address, uint) external; //inject NONSTANDARD NAMING function BURN250(address, uint) external; //inject NONSTANDARD NAMING function FLASHMINT22(uint, bytes calldata) external; //inject NONSTANDARD NAMING function REDEEM906(address, address, uint256) external returns (uint256); //inject NONSTANDARD NAMING // function transfer(address, uint) external returns (bool); // function transferFrom(address, address, uint) external returns (bool); // function approve(address, uint) external returns (bool); } // File: contracts/interfaces/IController.sol pragma solidity ^0.6.10; interface IController is IDelegable { function TREASURY445() external view returns (ITreasury); //inject NONSTANDARD NAMING function SERIES14(uint256) external view returns (IFYDai); //inject NONSTANDARD NAMING function SERIESITERATOR268(uint256) external view returns (uint256); //inject NONSTANDARD NAMING function TOTALSERIES702() external view returns (uint256); //inject NONSTANDARD NAMING function CONTAINSSERIES982(uint256) external view returns (bool); //inject NONSTANDARD NAMING function POSTED950(bytes32, address) external view returns (uint256); //inject NONSTANDARD NAMING function DEBTFYDAI447(bytes32, uint256, address) external view returns (uint256); //inject NONSTANDARD NAMING function DEBTDAI877(bytes32, uint256, address) external view returns (uint256); //inject NONSTANDARD NAMING function TOTALDEBTDAI51(bytes32, address) external view returns (uint256); //inject NONSTANDARD NAMING function ISCOLLATERALIZED839(bytes32, address) external view returns (bool); //inject NONSTANDARD NAMING function INDAI269(bytes32, uint256, uint256) external view returns (uint256); //inject NONSTANDARD NAMING function INFYDAI474(bytes32, uint256, uint256) external view returns (uint256); //inject NONSTANDARD NAMING function ERASE227(bytes32, address) external returns (uint256, uint256); //inject NONSTANDARD NAMING function SHUTDOWN178() external; //inject NONSTANDARD NAMING function POST95(bytes32, address, address, uint256) external; //inject NONSTANDARD NAMING function WITHDRAW817(bytes32, address, address, uint256) external; //inject NONSTANDARD NAMING function BORROW691(bytes32, uint256, address, address, uint256) external; //inject NONSTANDARD NAMING function REPAYFYDAI426(bytes32, uint256, address, address, uint256) external returns (uint256); //inject NONSTANDARD NAMING function REPAYDAI460(bytes32, uint256, address, address, uint256) external returns (uint256); //inject NONSTANDARD NAMING } // File: contracts/interfaces/IDai.sol pragma solidity ^0.6.10; interface IDai is IERC20 { function NONCES538(address user) external view returns (uint256); //inject NONSTANDARD NAMING function PERMIT233(address holder, address spender, uint256 nonce, uint256 expiry, //inject NONSTANDARD NAMING bool allowed, uint8 v, bytes32 r, bytes32 s) external; } // File: contracts/interfaces/IPool.sol pragma solidity ^0.6.10; interface IPool is IDelegable, IERC20, IERC2612 { function DAI858() external view returns(IERC20); //inject NONSTANDARD NAMING function FYDAI600() external view returns(IFYDai); //inject NONSTANDARD NAMING function GETDAIRESERVES173() external view returns(uint128); //inject NONSTANDARD NAMING function GETFYDAIRESERVES833() external view returns(uint128); //inject NONSTANDARD NAMING function SELLDAI400(address from, address to, uint128 daiIn) external returns(uint128); //inject NONSTANDARD NAMING function BUYDAI253(address from, address to, uint128 daiOut) external returns(uint128); //inject NONSTANDARD NAMING function SELLFYDAI226(address from, address to, uint128 fyDaiIn) external returns(uint128); //inject NONSTANDARD NAMING function BUYFYDAI675(address from, address to, uint128 fyDaiOut) external returns(uint128); //inject NONSTANDARD NAMING function SELLDAIPREVIEW300(uint128 daiIn) external view returns(uint128); //inject NONSTANDARD NAMING function BUYDAIPREVIEW913(uint128 daiOut) external view returns(uint128); //inject NONSTANDARD NAMING function SELLFYDAIPREVIEW69(uint128 fyDaiIn) external view returns(uint128); //inject NONSTANDARD NAMING function BUYFYDAIPREVIEW685(uint128 fyDaiOut) external view returns(uint128); //inject NONSTANDARD NAMING function MINT176(address from, address to, uint256 daiOffered) external returns (uint256); //inject NONSTANDARD NAMING function BURN250(address from, address to, uint256 tokensBurned) external returns (uint256, uint256); //inject NONSTANDARD NAMING } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; library SafeMath { function ADD958(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB494(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB494(a, b, "SafeMath: subtraction overflow"); } function SUB494(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL434(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV16(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV16(a, b, "SafeMath: division by zero"); } function DIV16(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD331(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD331(a, b, "SafeMath: modulo by zero"); } function MOD331(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } // File: contracts/helpers/DecimalMath.sol pragma solidity ^0.6.10; contract DecimalMath { using SafeMath for uint256; uint256 constant public unit17 = 1e27; //inject NONSTANDARD NAMING function MULD379(uint256 x, uint256 y) internal pure returns (uint256) { //inject NONSTANDARD NAMING return x.MUL434(y).DIV16(unit17); } function DIVD836(uint256 x, uint256 y) internal pure returns (uint256) { //inject NONSTANDARD NAMING return x.MUL434(unit17).DIV16(y); } function MULDRUP300(uint256 x, uint256 y) internal pure returns (uint256) //inject NONSTANDARD NAMING { uint256 z = x.MUL434(y); return z.MOD331(unit17) == 0 ? z.DIV16(unit17) : z.DIV16(unit17).ADD958(1); } function DIVDRUP370(uint256 x, uint256 y) internal pure returns (uint256) //inject NONSTANDARD NAMING { uint256 z = x.MUL434(unit17); return z.MOD331(y) == 0 ? z.DIV16(y) : z.DIV16(y).ADD958(1); } } // File: contracts/peripheral/YieldProxy.sol pragma solidity ^0.6.10; library SafeCast { function TOUINT128897(uint256 x) internal pure returns(uint128) { //inject NONSTANDARD NAMING require( x <= type(uint128).max, "YieldProxy: Cast overflow" ); return uint128(x); } function TOINT256710(uint256 x) internal pure returns(int256) { //inject NONSTANDARD NAMING require( x <= uint256(type(int256).max), "YieldProxy: Cast overflow" ); return int256(x); } } contract YieldProxy is DecimalMath { using SafeCast for uint256; IVat public vat; IWeth public weth; IDai public dai; IGemJoin public wethJoin; IDaiJoin public daiJoin; IChai public chai; IController public controller; ITreasury public treasury; IPool[] public pools; mapping (address => bool) public poolsMap; bytes32 public constant chai69 = "CHAI"; //inject NONSTANDARD NAMING bytes32 public constant weth148 = "ETH-A"; //inject NONSTANDARD NAMING bool constant public mty307 = true; //inject NONSTANDARD NAMING bool constant public ytm282 = false; //inject NONSTANDARD NAMING constructor(address controller_, IPool[] memory _pools) public { controller = IController(controller_); treasury = controller.TREASURY445(); weth = treasury.WETH278(); dai = IDai(address(treasury.DAI858())); chai = treasury.CHAI326(); daiJoin = treasury.DAIJOIN173(); wethJoin = treasury.WETHJOIN654(); vat = treasury.VAT519(); // for repaying debt dai.APPROVE147(address(treasury), uint(-1)); // for posting to the controller chai.APPROVE147(address(treasury), uint(-1)); weth.APPROVE147(address(treasury), uint(-1)); // for converting DAI to CHAI dai.APPROVE147(address(chai), uint(-1)); vat.HOPE952(address(daiJoin)); vat.HOPE952(address(wethJoin)); dai.APPROVE147(address(daiJoin), uint(-1)); weth.APPROVE147(address(wethJoin), uint(-1)); weth.APPROVE147(address(treasury), uint(-1)); // allow all the pools to pull FYDai/dai from us for LPing for (uint i = 0 ; i < _pools.length; i++) { dai.APPROVE147(address(_pools[i]), uint(-1)); _pools[i].FYDAI600().APPROVE147(address(_pools[i]), uint(-1)); poolsMap[address(_pools[i])]= true; } pools = _pools; } function UNPACK384(bytes memory signature) private pure returns (bytes32 r, bytes32 s, uint8 v) { //inject NONSTANDARD NAMING assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } } function ONBOARD51(address from, bytes memory daiSignature, bytes memory controllerSig) external { //inject NONSTANDARD NAMING bytes32 r; bytes32 s; uint8 v; (r, s, v) = UNPACK384(daiSignature); dai.PERMIT233(from, address(this), dai.NONCES538(from), uint(-1), true, v, r, s); (r, s, v) = UNPACK384(controllerSig); controller.ADDDELEGATEBYSIGNATURE882(from, address(this), uint(-1), v, r, s); } function AUTHORIZEPOOL621(IPool pool, address from, bytes memory daiSig, bytes memory fyDaiSig, bytes memory poolSig) public { //inject NONSTANDARD NAMING ONLYKNOWNPOOL167(pool); bytes32 r; bytes32 s; uint8 v; (r, s, v) = UNPACK384(daiSig); dai.PERMIT233(from, address(pool), dai.NONCES538(from), uint(-1), true, v, r, s); (r, s, v) = UNPACK384(fyDaiSig); pool.FYDAI600().PERMIT233(from, address(this), uint(-1), uint(-1), v, r, s); (r, s, v) = UNPACK384(poolSig); pool.ADDDELEGATEBYSIGNATURE882(from, address(this), uint(-1), v, r, s); } receive() external payable { } function POST95(address to) //inject NONSTANDARD NAMING public payable { weth.DEPOSIT338{ value: msg.value }(); controller.POST95(weth148, address(this), to, msg.value); } function WITHDRAW817(address payable to, uint256 amount) //inject NONSTANDARD NAMING public { controller.WITHDRAW817(weth148, msg.sender, address(this), amount); weth.WITHDRAW817(amount); to.transfer(amount); } function ADDLIQUIDITY157(IPool pool, uint256 daiUsed, uint256 maxFYDai) external returns (uint256) { //inject NONSTANDARD NAMING ONLYKNOWNPOOL167(pool); IFYDai fyDai = pool.FYDAI600(); require(fyDai.ISMATURE431() != true, "YieldProxy: Only before maturity"); require(dai.TRANSFERFROM451(msg.sender, address(this), daiUsed), "YieldProxy: Transfer Failed"); // calculate needed fyDai uint256 daiReserves = dai.BALANCEOF833(address(pool)); uint256 fyDaiReserves = fyDai.BALANCEOF833(address(pool)); uint256 daiToAdd = daiUsed.MUL434(daiReserves).DIV16(fyDaiReserves.ADD958(daiReserves)); uint256 daiToConvert = daiUsed.SUB494(daiToAdd); require( daiToConvert <= maxFYDai, "YieldProxy: maxFYDai exceeded" ); // 1 Dai == 1 fyDai // convert dai to chai and borrow needed fyDai chai.JOIN369(address(this), daiToConvert); // look at the balance of chai in dai to avoid rounding issues uint256 toBorrow = chai.DAI858(address(this)); controller.POST95(chai69, address(this), msg.sender, chai.BALANCEOF833(address(this))); controller.BORROW691(chai69, fyDai.MATURITY388(), msg.sender, address(this), toBorrow); // mint liquidity tokens return pool.MINT176(address(this), msg.sender, daiToAdd); } function REMOVELIQUIDITYEARLYDAIPOOL932(IPool pool, uint256 poolTokens, uint256 minimumDaiPrice, uint256 minimumFYDaiPrice) external { //inject NONSTANDARD NAMING ONLYKNOWNPOOL167(pool); IFYDai fyDai = pool.FYDAI600(); uint256 maturity = fyDai.MATURITY388(); (uint256 daiObtained, uint256 fyDaiObtained) = pool.BURN250(msg.sender, address(this), poolTokens); // Exchange Dai for fyDai to pay as much debt as possible uint256 fyDaiBought = pool.SELLDAI400(address(this), address(this), daiObtained.TOUINT128897()); require( fyDaiBought >= MULD379(daiObtained, minimumDaiPrice), "YieldProxy: minimumDaiPrice not reached" ); fyDaiObtained = fyDaiObtained.ADD958(fyDaiBought); uint256 fyDaiUsed; if (fyDaiObtained > 0 && controller.DEBTFYDAI447(chai69, maturity, msg.sender) > 0) { fyDaiUsed = controller.REPAYFYDAI426(chai69, maturity, address(this), msg.sender, fyDaiObtained); } uint256 fyDaiRemaining = fyDaiObtained.SUB494(fyDaiUsed); if (fyDaiRemaining > 0) {// There is fyDai left, so exchange it for Dai to withdraw only Dai and Chai require( pool.SELLFYDAI226(address(this), address(this), uint128(fyDaiRemaining)) >= MULD379(fyDaiRemaining, minimumFYDaiPrice), "YieldProxy: minimumFYDaiPrice not reached" ); } WITHDRAWASSETS926(fyDai); } function REMOVELIQUIDITYEARLYDAIFIXED8(IPool pool, uint256 poolTokens, uint256 minimumFYDaiPrice) external { //inject NONSTANDARD NAMING ONLYKNOWNPOOL167(pool); IFYDai fyDai = pool.FYDAI600(); uint256 maturity = fyDai.MATURITY388(); (uint256 daiObtained, uint256 fyDaiObtained) = pool.BURN250(msg.sender, address(this), poolTokens); uint256 fyDaiUsed; if (fyDaiObtained > 0 && controller.DEBTFYDAI447(chai69, maturity, msg.sender) > 0) { fyDaiUsed = controller.REPAYFYDAI426(chai69, maturity, address(this), msg.sender, fyDaiObtained); } uint256 fyDaiRemaining = fyDaiObtained.SUB494(fyDaiUsed); if (fyDaiRemaining == 0) { // We used all the fyDai, so probably there is debt left, so pay with Dai if (daiObtained > 0 && controller.DEBTFYDAI447(chai69, maturity, msg.sender) > 0) { controller.REPAYDAI460(chai69, maturity, address(this), msg.sender, daiObtained); } } else { // Exchange remaining fyDai for Dai to withdraw only Dai and Chai require( pool.SELLFYDAI226(address(this), address(this), uint128(fyDaiRemaining)) >= MULD379(fyDaiRemaining, minimumFYDaiPrice), "YieldProxy: minimumFYDaiPrice not reached" ); } WITHDRAWASSETS926(fyDai); } function REMOVELIQUIDITYMATURE267(IPool pool, uint256 poolTokens) external { //inject NONSTANDARD NAMING ONLYKNOWNPOOL167(pool); IFYDai fyDai = pool.FYDAI600(); uint256 maturity = fyDai.MATURITY388(); (uint256 daiObtained, uint256 fyDaiObtained) = pool.BURN250(msg.sender, address(this), poolTokens); if (fyDaiObtained > 0) { daiObtained = daiObtained.ADD958(fyDai.REDEEM906(address(this), address(this), fyDaiObtained)); } // Repay debt if (daiObtained > 0 && controller.DEBTFYDAI447(chai69, maturity, msg.sender) > 0) { controller.REPAYDAI460(chai69, maturity, address(this), msg.sender, daiObtained); } WITHDRAWASSETS926(fyDai); } function WITHDRAWASSETS926(IFYDai fyDai) internal { //inject NONSTANDARD NAMING if (controller.DEBTFYDAI447(chai69, fyDai.MATURITY388(), msg.sender) == 0) { controller.WITHDRAW817(chai69, msg.sender, address(this), controller.POSTED950(chai69, msg.sender)); chai.EXIT932(address(this), chai.BALANCEOF833(address(this))); } require(dai.TRANSFER582(msg.sender, dai.BALANCEOF833(address(this))), "YieldProxy: Dai Transfer Failed"); } function BORROWDAIFORMAXIMUMFYDAI736( //inject NONSTANDARD NAMING IPool pool, bytes32 collateral, uint256 maturity, address to, uint256 maximumFYDai, uint256 daiToBorrow ) public returns (uint256) { ONLYKNOWNPOOL167(pool); uint256 fyDaiToBorrow = pool.BUYDAIPREVIEW913(daiToBorrow.TOUINT128897()); require (fyDaiToBorrow <= maximumFYDai, "YieldProxy: Too much fyDai required"); // The collateral for this borrow needs to have been posted beforehand controller.BORROW691(collateral, maturity, msg.sender, address(this), fyDaiToBorrow); pool.BUYDAI253(address(this), to, daiToBorrow.TOUINT128897()); return fyDaiToBorrow; } function BORROWMINIMUMDAIFORFYDAI776( //inject NONSTANDARD NAMING IPool pool, bytes32 collateral, uint256 maturity, address to, uint256 fyDaiToBorrow, uint256 minimumDaiToBorrow ) public returns (uint256) { ONLYKNOWNPOOL167(pool); // The collateral for this borrow needs to have been posted beforehand controller.BORROW691(collateral, maturity, msg.sender, address(this), fyDaiToBorrow); uint256 boughtDai = pool.SELLFYDAI226(address(this), to, fyDaiToBorrow.TOUINT128897()); require (boughtDai >= minimumDaiToBorrow, "YieldProxy: Not enough Dai obtained"); return boughtDai; } function REPAYFYDAIDEBTFORMAXIMUMDAI955( //inject NONSTANDARD NAMING IPool pool, bytes32 collateral, uint256 maturity, address to, uint256 fyDaiRepayment, uint256 maximumRepaymentInDai ) public returns (uint256) { ONLYKNOWNPOOL167(pool); uint256 fyDaiDebt = controller.DEBTFYDAI447(collateral, maturity, to); uint256 fyDaiToUse = fyDaiDebt < fyDaiRepayment ? fyDaiDebt : fyDaiRepayment; // Use no more fyDai than debt uint256 repaymentInDai = pool.BUYFYDAI675(msg.sender, address(this), fyDaiToUse.TOUINT128897()); require (repaymentInDai <= maximumRepaymentInDai, "YieldProxy: Too much Dai required"); controller.REPAYFYDAI426(collateral, maturity, address(this), to, fyDaiToUse); return repaymentInDai; } function REPAYMINIMUMFYDAIDEBTFORDAI862( //inject NONSTANDARD NAMING IPool pool, bytes32 collateral, uint256 maturity, address to, uint256 minimumFYDaiRepayment, uint256 repaymentInDai ) public returns (uint256) { ONLYKNOWNPOOL167(pool); uint256 fyDaiRepayment = pool.SELLDAIPREVIEW300(repaymentInDai.TOUINT128897()); uint256 fyDaiDebt = controller.DEBTFYDAI447(collateral, maturity, to); if(fyDaiRepayment <= fyDaiDebt) { // Sell no more Dai than needed to cancel all the debt pool.SELLDAI400(msg.sender, address(this), repaymentInDai.TOUINT128897()); } else { // If we have too much Dai, then don't sell it all and buy the exact amount of fyDai needed instead. pool.BUYFYDAI675(msg.sender, address(this), fyDaiDebt.TOUINT128897()); fyDaiRepayment = fyDaiDebt; } require (fyDaiRepayment >= minimumFYDaiRepayment, "YieldProxy: Not enough fyDai debt repaid"); controller.REPAYFYDAI426(collateral, maturity, address(this), to, fyDaiRepayment); return fyDaiRepayment; } function SELLDAI400(IPool pool, address to, uint128 daiIn, uint128 minFYDaiOut) //inject NONSTANDARD NAMING external returns(uint256) { ONLYKNOWNPOOL167(pool); uint256 fyDaiOut = pool.SELLDAI400(msg.sender, to, daiIn); require( fyDaiOut >= minFYDaiOut, "YieldProxy: Limit not reached" ); return fyDaiOut; } function BUYDAI253(IPool pool, address to, uint128 daiOut, uint128 maxFYDaiIn) //inject NONSTANDARD NAMING public returns(uint256) { ONLYKNOWNPOOL167(pool); uint256 fyDaiIn = pool.BUYDAI253(msg.sender, to, daiOut); require( maxFYDaiIn >= fyDaiIn, "YieldProxy: Limit exceeded" ); return fyDaiIn; } function BUYDAIWITHSIGNATURE110(IPool pool, address to, uint128 daiOut, uint128 maxFYDaiIn, bytes memory signature) //inject NONSTANDARD NAMING external returns(uint256) { ONLYKNOWNPOOL167(pool); (bytes32 r, bytes32 s, uint8 v) = UNPACK384(signature); pool.FYDAI600().PERMIT233(msg.sender, address(pool), uint(-1), uint(-1), v, r, s); return BUYDAI253(pool, to, daiOut, maxFYDaiIn); } function SELLFYDAI226(IPool pool, address to, uint128 fyDaiIn, uint128 minDaiOut) //inject NONSTANDARD NAMING public returns(uint256) { ONLYKNOWNPOOL167(pool); uint256 daiOut = pool.SELLFYDAI226(msg.sender, to, fyDaiIn); require( daiOut >= minDaiOut, "YieldProxy: Limit not reached" ); return daiOut; } function SELLFYDAIWITHSIGNATURE545(IPool pool, address to, uint128 fyDaiIn, uint128 minDaiOut, bytes memory signature) //inject NONSTANDARD NAMING external returns(uint256) { ONLYKNOWNPOOL167(pool); (bytes32 r, bytes32 s, uint8 v) = UNPACK384(signature); pool.FYDAI600().PERMIT233(msg.sender, address(pool), uint(-1), uint(-1), v, r, s); return SELLFYDAI226(pool, to, fyDaiIn, minDaiOut); } function BUYFYDAI675(IPool pool, address to, uint128 fyDaiOut, uint128 maxDaiIn) //inject NONSTANDARD NAMING external returns(uint256) { ONLYKNOWNPOOL167(pool); uint256 daiIn = pool.BUYFYDAI675(msg.sender, to, fyDaiOut); require( maxDaiIn >= daiIn, "YieldProxy: Limit exceeded" ); return daiIn; } function REPAYDAIWITHSIGNATURE818(bytes32 collateral, uint256 maturity, address to, uint256 daiAmount, bytes memory signature) //inject NONSTANDARD NAMING external returns(uint256) { (bytes32 r, bytes32 s, uint8 v) = UNPACK384(signature); dai.PERMIT233(msg.sender, address(treasury), dai.NONCES538(msg.sender), uint(-1), true, v, r, s); controller.REPAYDAI460(collateral, maturity, msg.sender, to, daiAmount); } function ONLYKNOWNPOOL167(IPool pool) private view { //inject NONSTANDARD NAMING require(poolsMap[address(pool)], "YieldProxy: Unknown pool"); } }
inject NONSTANDARD NAMING
function URNS490(bytes32, address) external view returns (uint, uint);
12,707,070
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 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, 1618, 3156, 7616, 20, 12, 3890, 1578, 16, 1758, 13, 3903, 1476, 1135, 261, 11890, 16, 2254, 1769, 202, 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 ]
./full_match/80001/0x1FF3D840773c045cC0932b410cd1D61dB953Bbbf/sources/project_/contracts/Demo.sol
@notice Updates the medical history, laboratory results, and insurance information of a patient @param _ipfsHashMedicalHistory The updated IPFS hash representing the patient's medical history @param _ipfsHashLaboratoryResult The updated IPFS hash representing the patient's laboratory results @param _ipfsHashInsuranceInformation The updated IPFS hash representing the patient's insurance information @param _address The address of the patient to update
function updateMedicalHistory( string memory _ipfsHashMedicalHistory, string memory _ipfsHashLaboratoryResult, string memory _ipfsHashInsuranceInformation, address _address ) public { require(hasRole(DOCTOR_ROLE, msg.sender) || hasRole(ADMIN_ROLE, msg.sender) || hasRole(NURSE_ROLE, msg.sender), "Caller is not authorized"); require(_address == patients[_address].patientAddress, "No data found for the patient"); medicalHistory[_address] = _ipfsHashMedicalHistory; laboratoryResult[_address] = _ipfsHashLaboratoryResult; insuranceInformation[_address] = _ipfsHashInsuranceInformation; }
5,624,223
[ 1, 5121, 326, 6735, 1706, 4927, 16, 11814, 280, 8452, 1686, 16, 471, 2763, 295, 1359, 1779, 434, 279, 18608, 225, 389, 625, 2556, 2310, 13265, 1706, 5623, 1021, 3526, 2971, 4931, 1651, 5123, 326, 18608, 1807, 6735, 1706, 4927, 225, 389, 625, 2556, 2310, 14506, 280, 8452, 1253, 1021, 3526, 2971, 4931, 1651, 5123, 326, 18608, 1807, 11814, 280, 8452, 1686, 225, 389, 625, 2556, 2310, 5048, 295, 1359, 5369, 1021, 3526, 2971, 4931, 1651, 5123, 326, 18608, 1807, 2763, 295, 1359, 1779, 225, 389, 2867, 1021, 1758, 434, 326, 18608, 358, 1089, 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, 915, 1089, 13265, 1706, 5623, 12, 203, 565, 533, 3778, 389, 625, 2556, 2310, 13265, 1706, 5623, 16, 203, 565, 533, 3778, 389, 625, 2556, 2310, 14506, 280, 8452, 1253, 16, 203, 565, 533, 3778, 389, 625, 2556, 2310, 5048, 295, 1359, 5369, 16, 203, 565, 1758, 389, 2867, 203, 13, 1071, 288, 203, 565, 2583, 12, 5332, 2996, 12, 3191, 22727, 67, 16256, 16, 1234, 18, 15330, 13, 747, 28335, 12, 15468, 67, 16256, 16, 1234, 18, 15330, 13, 747, 28335, 12, 50, 23875, 67, 16256, 16, 1234, 18, 15330, 3631, 315, 11095, 353, 486, 10799, 8863, 203, 565, 2583, 24899, 2867, 422, 9670, 5828, 63, 67, 2867, 8009, 16330, 1979, 1887, 16, 315, 2279, 501, 1392, 364, 326, 18608, 8863, 203, 203, 565, 6735, 1706, 5623, 63, 67, 2867, 65, 273, 389, 625, 2556, 2310, 13265, 1706, 5623, 31, 203, 565, 11814, 280, 8452, 1253, 63, 67, 2867, 65, 273, 389, 625, 2556, 2310, 14506, 280, 8452, 1253, 31, 203, 565, 2763, 295, 1359, 5369, 63, 67, 2867, 65, 273, 389, 625, 2556, 2310, 5048, 295, 1359, 5369, 31, 203, 97, 203, 203, 203, 203, 21281, 203, 21281, 203, 203, 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 ]
./partial_match/56/0x7B9D43599AA3C5590CF068bE7BD67Ebf30462b47/sources/FeeProvider.sol
* @dev internal function to update the implementation of a specific component of the protocol @param _id the id of the contract to be updated @param _newAddress the address of the new implementation/
function updateImplInternal(bytes32 _id, address _newAddress) internal { address payable proxyAddress = address(uint160(getAddress(_id))); InitializableAdminUpgradeabilityProxy proxy = InitializableAdminUpgradeabilityProxy(proxyAddress); bytes memory params = abi.encodeWithSignature("initialize(address)", address(this)); if (proxyAddress == address(0)) { proxy = new InitializableAdminUpgradeabilityProxy(); proxy.initialize(_newAddress, address(this), params); _setAddress(_id, address(proxy)); emit ProxyCreated(_id, address(proxy)); proxy.upgradeToAndCall(_newAddress, params); } }
11,035,304
[ 1, 7236, 445, 358, 1089, 326, 4471, 434, 279, 2923, 1794, 434, 326, 1771, 225, 389, 350, 326, 612, 434, 326, 6835, 358, 506, 3526, 225, 389, 2704, 1887, 326, 1758, 434, 326, 394, 4471, 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, 445, 1089, 2828, 3061, 12, 3890, 1578, 389, 350, 16, 1758, 389, 2704, 1887, 13, 2713, 288, 203, 3639, 1758, 8843, 429, 2889, 1887, 273, 1758, 12, 11890, 16874, 12, 588, 1887, 24899, 350, 3719, 1769, 203, 203, 3639, 10188, 6934, 4446, 10784, 2967, 3886, 2889, 273, 203, 5411, 10188, 6934, 4446, 10784, 2967, 3886, 12, 5656, 1887, 1769, 203, 3639, 1731, 3778, 859, 273, 203, 5411, 24126, 18, 3015, 1190, 5374, 2932, 11160, 12, 2867, 2225, 16, 1758, 12, 2211, 10019, 203, 203, 3639, 309, 261, 5656, 1887, 422, 1758, 12, 20, 3719, 288, 203, 5411, 2889, 273, 394, 10188, 6934, 4446, 10784, 2967, 3886, 5621, 203, 5411, 2889, 18, 11160, 24899, 2704, 1887, 16, 1758, 12, 2211, 3631, 859, 1769, 203, 5411, 389, 542, 1887, 24899, 350, 16, 1758, 12, 5656, 10019, 203, 5411, 3626, 7659, 6119, 24899, 350, 16, 1758, 12, 5656, 10019, 203, 5411, 2889, 18, 15097, 774, 1876, 1477, 24899, 2704, 1887, 16, 859, 1769, 203, 3639, 289, 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 ]
./partial_match/4/0xcab5bEC403ebb2bd68c7C987a512581960651097/sources/KittyCore.sol
@dev An internal method that creates a new kitty and stores it. This method doesn't do any checking and should only be called when the input data is known to be valid. Will generate both a Birth event and a Transfer event. @param _matronId The kitty ID of the matron of this cat (zero for gen0) @param _sireId The kitty ID of the sire of this cat (zero for gen0) @param _generation The generation number of this cat, must be computed by caller. @param _genes The kitty's genetic code. @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) These requires are not strictly necessary, our calling code should make sure that these conditions are never broken. However! _createKitty() is already an expensive call (for storage), and it doesn't hurt to be especially careful to ensure our data structures are always valid. New kitty starts with the same cooldown as parent gen/2
function _createKitty( uint256 _matronId, uint256 _sireId, uint256 _generation, uint256 _genes, address _owner ) internal returns (uint) { require(_matronId == uint256(uint32(_matronId))); require(_sireId == uint256(uint32(_sireId))); require(_generation == uint256(uint16(_generation))); uint16 cooldownIndex = uint16(_generation / 2); if (cooldownIndex > 13) { cooldownIndex = 13; } Kitty memory _kitty = Kitty({ genes: _genes, birthTime: uint64(now), cooldownEndBlock: 0, matronId: uint32(_matronId), sireId: uint32(_sireId), siringWithId: 0, cooldownIndex: cooldownIndex, generation: uint16(_generation) }); uint256 newKittenId = kitties.push(_kitty) - 1; _owner, newKittenId, uint256(_kitty.matronId), uint256(_kitty.sireId), _kitty.genes ); return newKittenId; }
8,780,481
[ 1, 979, 2713, 707, 716, 3414, 279, 394, 31758, 4098, 471, 9064, 518, 18, 1220, 225, 707, 3302, 1404, 741, 1281, 6728, 471, 1410, 1338, 506, 2566, 1347, 326, 225, 810, 501, 353, 4846, 358, 506, 923, 18, 9980, 2103, 3937, 279, 605, 10542, 871, 225, 471, 279, 12279, 871, 18, 225, 389, 7373, 1949, 548, 1021, 31758, 4098, 1599, 434, 326, 4834, 1949, 434, 333, 6573, 261, 7124, 364, 3157, 20, 13, 225, 389, 87, 577, 548, 1021, 31758, 4098, 1599, 434, 326, 272, 577, 434, 333, 6573, 261, 7124, 364, 3157, 20, 13, 225, 389, 25514, 1021, 9377, 1300, 434, 333, 6573, 16, 1297, 506, 8470, 635, 4894, 18, 225, 389, 18036, 1021, 31758, 4098, 1807, 3157, 7943, 981, 18, 225, 389, 8443, 1021, 1208, 287, 3410, 434, 333, 6573, 16, 1297, 506, 1661, 17, 7124, 261, 14137, 364, 326, 640, 14102, 4098, 16, 1599, 374, 13, 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, 389, 2640, 14102, 4098, 12, 203, 3639, 2254, 5034, 389, 7373, 1949, 548, 16, 203, 3639, 2254, 5034, 389, 87, 577, 548, 16, 203, 3639, 2254, 5034, 389, 25514, 16, 203, 3639, 2254, 5034, 389, 18036, 16, 203, 3639, 1758, 389, 8443, 203, 565, 262, 203, 3639, 2713, 203, 3639, 1135, 261, 11890, 13, 203, 565, 288, 203, 3639, 2583, 24899, 7373, 1949, 548, 422, 2254, 5034, 12, 11890, 1578, 24899, 7373, 1949, 548, 3719, 1769, 203, 3639, 2583, 24899, 87, 577, 548, 422, 2254, 5034, 12, 11890, 1578, 24899, 87, 577, 548, 3719, 1769, 203, 3639, 2583, 24899, 25514, 422, 2254, 5034, 12, 11890, 2313, 24899, 25514, 3719, 1769, 203, 203, 3639, 2254, 2313, 27367, 2378, 1016, 273, 2254, 2313, 24899, 25514, 342, 576, 1769, 203, 3639, 309, 261, 71, 1371, 2378, 1016, 405, 5958, 13, 288, 203, 5411, 27367, 2378, 1016, 273, 5958, 31, 203, 3639, 289, 203, 203, 3639, 1475, 305, 4098, 3778, 389, 8691, 4098, 273, 1475, 305, 4098, 12590, 203, 5411, 11423, 30, 389, 18036, 16, 203, 5411, 17057, 950, 30, 2254, 1105, 12, 3338, 3631, 203, 5411, 27367, 2378, 1638, 1768, 30, 374, 16, 203, 5411, 4834, 1949, 548, 30, 2254, 1578, 24899, 7373, 1949, 548, 3631, 203, 5411, 272, 577, 548, 30, 2254, 1578, 24899, 87, 577, 548, 3631, 203, 5411, 272, 11256, 1190, 548, 30, 374, 16, 203, 5411, 27367, 2378, 1016, 30, 27367, 2378, 1016, 16, 203, 5411, 9377, 30, 2254, 2313, 24899, 25514, 13, 203, 3639, 15549, 203, 3639, 2254, 5034, 394, 2 ]
// LC->27.01.2016 wordform_score given { eng_noun }=-5 // We follow the argument given in Apostol. wordform_score need { eng_auxverb }=-1 // предпочитаем вариант обычного глагола wordform_score intrinsically { eng_noun }=-2 wordform_score "face to face" { eng_adverb }=2 // They spoke face to face. wordform_score alas { eng_noun }=-2 // Alas, I cannot stay. wordform_score something { eng_verb }=-5 wordform_score "beads" { number:single }=-5 // wordform_score "inside out" { eng_adverb }=1 // Reversing a translator turns its scope inside out. wordform_score Daily { eng_noun }=-2 wordform_score over { eng_noun }=-5 wordform_score over { eng_adjective }=-5 wordform_score "because of" { eng_prep }=1 wordform_score "well-known" { eng_adjective }=2 // This is a story about the well-known millionaire wordforms_score "eye" { eng_verb }=-2 // The sea now shimmered placidly before our eyes. wordform_score "Rough-sand" { eng_verb }=2 // Rough-sand the door before painting it. wordform_score significant { eng_noun }=-5 wordform_score Newspapers { eng_verb }=-5 // Newspapers reported his ennoblement the following morning. wordform_score if { eng_noun }=-5 wordform_score world { eng_verb }=-5 // World, do you know your creator? wordform_score "in vain" { eng_adverb }=2 // He looked for her in vain. wordform_score "face to face" { eng_adverb }=2 // They spoke face to face. wordform_score "hand in hand" { eng_adverb }=2 // They walked hand in hand. wordform_score "all over" { eng_adverb }=2 // She ached all over. wordform_score "Hong Kong"{ eng_noun }=2 // Hong Kong was a British colony. wordform_score "as well" {eng_adverb }=5 // It also broke along generational lines as well; wordforms_score enrol { eng_verb }=-1 wordform_score "by far" { eng_adverb }=2 // Football is by far the most popular sport. wordform_score "for the first time" { eng_adverb }=2 wordforms_score unite { eng_verb }=-5 wordform_score "of course" { eng_adverb }=5 // Of course importance is a matter of perspective; wordform_score know { eng_noun }=-2 wordform_score working { eng_noun }=-2 wordform_score best { eng_noun }=-10 wordform_score aside { eng_noun }=-5 // Put her sewing aside when he entered. wordform_score any { eng_adverb }=-5 // I must know how to fix any problem wordform_score king { eng_verb }=-5 // Constantine succeeded him as king. wordform_score undecided { eng_noun }=-5 // Einstein was still undecided on his future. wordform_score should { eng_noun }=-10 wordform_score international { eng_noun }=-1 // For international competition maraging steel is required. wordform_score English { eng_verb }=-5 // The class did English three times a week last year wordform_score "upside down" { eng_adverb } =1 // The thief had turned the room upside down wordform_score enough { eng_adjective }=-1 // These boys are the good enough players wordform_score anti { eng_adjective }=-2 // The foam has anti-microbial properties. wordform_score way { eng_adverb }=-2 // He angled his way into the room. wordform_score about { eng_verb }=-5 // Let's look about for help. wordform_score balls { eng_adverb }=-5 // She molded the rice balls carefully. wordform_score "flat-out" { eng_adverb }=2 // He stated his opinion flat-out. wordform_score weekly { eng_noun } =-5 wordform_score "at once" { eng_adverb }=2 // I must give an answer at once wordform_score "at random" { eng_adverb }=2 // Bullets were fired into the crowd at random. wordform_score "far and wide" { eng_adverb }=1 wordform_score "year-round" { eng_adjective }=1 wordforms_score phrasis { eng_noun }=-5 wordforms_score phasis { eng_noun }=-5 wordform_score early { eng_noun }=-5 wordform_score non { eng_adjective }=-5 wordform_score non { eng_adverb }=-5 wordform_score "each other" { eng_noun }=1 // Two drunken gentlemen are holding each other up. wordform_score still { eng_noun }=-5 // His teenage son still behaves very immaturely. wordforms_score classis { eng_noun }=-5 wordform_score historic { eng_noun }=-5 // It is also a historic Mediterranean port. wordform_score through { eng_noun }=-5 wordforms_score talke { eng_verb }=-5 wordform_score when { eng_noun }=-5 wordforms_score focuse { eng_verb }=-5 wordform_score without { eng_adverb }=-5 // How does she get around without a car? wordform_score as { eng_adverb }=-5 wordform_score about { eng_adjective }=-5 wordform_score course { eng_adverb }=-5 // He followed his course unswervingly wordform_score why { eng_noun }=-10 // Why did John pass his examination? wordform_score seasonal { eng_noun }=-3 // A seasonal rise in unemployment. wordform_score all { eng_adverb }=-3 // I've finished all my work. wordform_score typical { eng_noun }=-5 // A typical bureaucratic screwup wordform_score like { eng_adverb }=-5 // Richard doesn't like ice-cream wordform_score necromantic { eng_noun }=-5 // Mysterious necromantic rites wordform_score protective { eng_noun }=-5 // Cumbrous protective clothing wordform_score forward { eng_noun }=-1 // An incomplete forward pass. wordform_score incompatible { eng_noun }=-5 // Incompatible personalities. wordform_score "in front of" {}=5 // I sit now in front of you. wordform_score now { eng_noun }=-5 wordform_score violent { eng_noun }=-5 // I felt a violent dislike. wordform_score one { eng_noun }=-2 wordform_score unavoidable { eng_noun }=-5 // An unavoidable accident. wordform_score stupid { eng_adverb }=-2 wordform_score elected { eng_noun }=-5 // He would get elected. wordform_score altered { eng_noun }=-5 // Some altered states occur naturally; wordform_score additional { eng_noun }=-5 // Additional morphological types may exist. wordform_score understanding { eng_adjective }=-5 // Graphical methods are recommended to enhance understanding. wordform_score reads { eng_noun }=-5 wordform_score Monolingual { eng_noun }=-5 // Monolingual speakers. wordform_score young { eng_noun }=-5 // Puddle young plants. wordform_score Cognitive { eng_noun } =-5 // Cognitive psychology wordform_score where { eng_noun }=-10 // Where is my vote? wordform_score Pronominal { eng_noun } =-5 // Pronominal reference wordform_score Cartesian { eng_noun } =-5 // Cartesian linguistics wordform_score Pharyngeal { eng_noun } =-5 // Pharyngeal fricatives wordform_score Pythagorean { eng_noun } =-5 // Pythagorean theorem wordform_score Conventional { eng_noun } =-5 // Conventional wisdom. wordform_score structural { eng_noun } =-5 // Structural engineer wordform_score inside { eng_noun }=-5 // Was the dog inside? wordform_score French { eng_noun }=-5 wordform_score invisible { eng_noun }=-5 wordform_score equatorial { eng_noun }=-5 // Equatorial diameter wordform_score confident { eng_noun }=-5 // A confident reply. wordform_score narrow { eng_noun }=-5 // A narrow scrutiny. wordform_score mental { eng_noun }=-5 // Mental development wordform_score diplomatic { eng_noun }=-5 // Diplomatic warfare wordform_score aristotelean { eng_noun } =-5 // Aristotelean logic wordform_score metamorphic { eng_noun }=-5 // Metamorphic stage wordform_score fraternal { eng_noun }=-5 // A fraternal order wordform_score game { eng_adjective }=-5 // a covert for game wordform_score to { eng_adverb }=-2 // Scorpius is to the left. wordform_score in { eng_adverb }=-2 // Significant bills passed in Colorado. wordform_score in { eng_noun }=-2 wordform_score "New York" { eng_adjective }=-5 // They settled in New York City. wordform_score great { eng_adverb }=-2 // Gravitational collapse requires great density. wordform_score meanwhile { eng_noun }=-5 // Meanwhile Villeroi deployed his forces. wordform_score sexual { eng_noun }=-5 // Contestants occasionally develop sexual relationships; wordform_score better { eng_verb }=-5 // We do it better. wordform_score may { eng_noun }=-1 // I may ask wordform_score then { eng_noun }=-10 // He was then imprisoned. wordform_score human { eng_verb }=-10 // Does human capital matter? wordform_score is { eng_noun }=-10 wordform_score what { eng_adverb }=-5 // What did he want? wordform_score matter { eng_adjective }=-5 // Does it matter? wordform_score hills { eng_verb }=-5 // Gabonese hills wordform_score ready { eng_verb }=-5 // I ain't ready wordform_score welsh { eng_verb }=5 // Welsh syntax wordform_score today { eng_noun }=-1 // This support continues even today. wordform_score baby { eng_verb } =-5 // Baby rabbits wordform_score Lunar { eng_noun } =-5 // Lunar module wordform_score rights { eng_verb }=-2 // Civil rights wordform_score bones { eng_verb } =-5 wordform_score dogs { eng_verb }=-5 // so many dogs wordform_score does { eng_noun } =-10 wordform_score big { eng_verb } = -8 wordform_score big { eng_adverb } =-5 // I am not big wordform_score ill { eng_verb } = -8 wordform_score but { eng_noun } = -8 // But that was not all; wordform_score that { eng_noun } = -8 wordform_score that { eng_adverb } = -2 // I like that. wordform_score this { eng_noun } = -8 wordform_score busy { eng_noun } = -5 // A busy man. wordform_score dull { eng_verb } =-5 // deadly dull wordform_score station { eng_verb } = -2 // ASU has two radio stations. wordform_score higher { eng_noun } = -2 wordform_score of { eng_noun } = -10 wordform_score all { eng_noun } = -5 wordform_score stop { eng_adverb } = -5 wordform_score big { eng_adverb } = -5 wordform_score small { eng_adverb } = -5 wordform_score no { eng_verb } = -5 wordform_score only { eng_noun } = -5 // The only treatment is to deliver the fetus. wordform_score ask { eng_noun } = -2 wordform_score you { eng_verb } = -5 wordform_score me { eng_noun } = -5 wordform_score will { eng_noun } = -1 wordform_score make { eng_noun } = -1 wordform_score and { eng_noun } = -5 // He reads and writes // Hopefully I will have learned something, too! // ~~~~~~~~~ wordform_score something { eng_adverb } = -2 wordform_score am { eng_adverb } = -5 // wordform_score then { eng_conj } = 1000 // wordform_score then { eng_adverb } = 1000 wordform_score then { eng_adjective } = -2 // wordform_score came { eng_verb } = 1000 wordform_score came { eng_noun } = -2 // wordform_score father { eng_noun } = 1000 wordform_score father { eng_verb } = -1 wordform_score two { eng_noun } = -5 wordform_score three { eng_noun } = -5 wordform_score four { eng_noun } = -5 wordform_score five { eng_noun } = -5 wordform_score six { eng_noun } = -5 wordform_score seven { eng_noun } = -5 wordform_score eight { eng_noun } = -5 wordform_score nine { eng_noun } = -5 wordform_score ten { eng_noun } = -5 wordform_score eleven { eng_noun } = -5 // wordform_score some { eng_adjective } = 1000 wordform_score some { eng_noun } = -1 wordform_score some { eng_adverb } = -2 // wordform_score today { eng_adverb } = 1000 wordform_score today { eng_noun } = -1 // wordform_score tomorrow { eng_adverb } = 1000 wordform_score tomorrow { eng_noun } = -1 // wordform_score yesterday { eng_adverb } = 1000 wordform_score yesterday { eng_noun } = -1 //wordform_score and { eng_conj } = 0 wordform_score and { eng_verb } = -10 //wordform_score or { eng_conj } = 1000 wordform_score or { eng_verb } = -10 wordform_score by { eng_adverb } = -1 wordform_score by { eng_adjective } = -2 wordform_score by { eng_noun } = -5 // The cars hurtled by. // wordform_score can { eng_verb } = 1 wordform_score can { eng_noun } = -1 // wordform_score very { eng_adverb } = 1000 wordform_score very { eng_adjective } = -1 // wordform_score big { eng_adjective } = 1000 wordform_score big { eng_noun } = -2 // wordform_score an { eng_article } = 100 wordform_score an { eng_noun } = -2 // wordform_score not { eng_particle } = 100 wordform_score not { eng_noun } = -2 // wordform_score old { eng_adjective } = 1000 wordform_score old { eng_noun } = -2 wordform_score red { eng_noun } = -2 wordform_score above { noun } = -5 wordform_score now { eng_adjective } = -5 wordform_score now { noun } = -5 // He is a student now wordform_score by { eng_adjective } = -1 wordform_score by { noun } = 2 #define PreferAdj(x) \ #begin wordform_score x { eng_adjective } = 1 #end PreferAdj(acrylic) PreferAdj(best) PreferAdj(active) PreferAdj(actual) PreferAdj(acute) PreferAdj(addictive) PreferAdj(additive) PreferAdj(adherent) PreferAdj(adjacent) PreferAdj(adjectival) PreferAdj(adjunctive) PreferAdj(adolescent) PreferAdj(aerial) PreferAdj(aesthetic) PreferAdj(affirmative) PreferAdj(affluent) PreferAdj(affluential) PreferAdj(ageless) PreferAdj(agentive) PreferAdj(aggravative) PreferAdj(airborne) PreferAdj(alternative) PreferAdj(ambient) PreferAdj(ambisexual) PreferAdj(apolitical) PreferAdj(appellative) PreferAdj(appositive) PreferAdj(approbative) PreferAdj(arabian) PreferAdj(arsenical) PreferAdj(aspirational) PreferAdj(auxiliary) PreferAdj(baghdadian) PreferAdj(bendy) PreferAdj(bicolour) PreferAdj(biconditional) PreferAdj(bifundamental) PreferAdj(bilevel) PreferAdj(bilingual) PreferAdj(binational) PreferAdj(binominal) PreferAdj(biomedical) PreferAdj(biomusical) PreferAdj(bipartisan) PreferAdj(biquadratic) PreferAdj(bistable) PreferAdj(biweekly) PreferAdj(blind) PreferAdj(blinky) PreferAdj(blue) PreferAdj(white) PreferAdj(boolean) PreferAdj(brief) PreferAdj(bright) PreferAdj(broad) PreferAdj(brown) PreferAdj(bulk) PreferAdj(bully) PreferAdj(calm) PreferAdj(candid) PreferAdj(canonical) PreferAdj(carbolic) PreferAdj(carryable) PreferAdj(casual) PreferAdj(causative) PreferAdj(celestial) PreferAdj(ceremonial) PreferAdj(charismatic) PreferAdj(chemical) PreferAdj(lonesome) PreferAdj(good) PreferAdj(close) PreferAdj(coequal) PreferAdj(common) PreferAdj(compact) PreferAdj(complex) PreferAdj(compound) PreferAdj(compulsive) PreferAdj(compulsory) PreferAdj(conic) PreferAdj(conjunctive) PreferAdj(connective) PreferAdj(connexive) PreferAdj(consequent) PreferAdj(consistent) PreferAdj(consumable) PreferAdj(consumptive) PreferAdj(contemplative) PreferAdj(contemporary) PreferAdj(continuative) PreferAdj(controversial) PreferAdj(coronal) PreferAdj(cosy) PreferAdj(cozy) PreferAdj(crazy) PreferAdj(crimson) PreferAdj(crisp) PreferAdj(crowdy) PreferAdj(cubic) PreferAdj(curly) PreferAdj(cyan) PreferAdj(daily) PreferAdj(dark) PreferAdj(darn) PreferAdj(darwinian) PreferAdj(dative) PreferAdj(dead) PreferAdj(deaf) PreferAdj(decorative) PreferAdj(deep) PreferAdj(different) PreferAdj(divine) PreferAdj(doggy) PreferAdj(double) PreferAdj(dreadful) PreferAdj(dreary) PreferAdj(drinkable) PreferAdj(dual) PreferAdj(dull) PreferAdj(each) PreferAdj(early) PreferAdj(edible) PreferAdj(eligible) PreferAdj(empty) PreferAdj(entire) PreferAdj(equal) PreferAdj(eruptive) PreferAdj(evergreen) PreferAdj(everyday) PreferAdj(exclusive) PreferAdj(exotic) PreferAdj(extern) PreferAdj(faint) PreferAdj(far) PreferAdj(fast) PreferAdj(feminine) PreferAdj(fishy) PreferAdj(flexible) PreferAdj(floral) PreferAdj(fractional) PreferAdj(free) PreferAdj(fresh) PreferAdj(frictionless) PreferAdj(friendly) PreferAdj(frontal) PreferAdj(functional) PreferAdj(functionless) PreferAdj(fundamental) PreferAdj(fuzzy) PreferAdj(gazillionth) PreferAdj(ghosty) PreferAdj(glamour) PreferAdj(glassful) PreferAdj(grey) PreferAdj(hard) PreferAdj(heavy) PreferAdj(high) PreferAdj(holy) PreferAdj(hopeful) PreferAdj(horizontal) PreferAdj(horrible) PreferAdj(hypnotic) PreferAdj(identical) PreferAdj(idyllic) PreferAdj(ill) PreferAdj(illative) PreferAdj(illiterate) PreferAdj(immovable) PreferAdj(imperative) PreferAdj(imperfect) PreferAdj(imperfective) PreferAdj(incomplete) PreferAdj(indexical) PreferAdj(indicative) PreferAdj(industrial) PreferAdj(inert) PreferAdj(inevitable) PreferAdj(initial) PreferAdj(innocent) PreferAdj(instrumental) PreferAdj(intersexual) PreferAdj(intimate) PreferAdj(intuitive) PreferAdj(irregular) PreferAdj(irresponsible) PreferAdj(left) PreferAdj(legal) PreferAdj(lenticular) PreferAdj(lilliputian) PreferAdj(machiavellian) PreferAdj(marriageable) PreferAdj(maximal) PreferAdj(maxwellian) PreferAdj(measurable) PreferAdj(measureless) PreferAdj(medieval) PreferAdj(medium) PreferAdj(mesolithic) PreferAdj(metallic) PreferAdj(microcephalic) PreferAdj(mild) PreferAdj(military) PreferAdj(monochrome) PreferAdj(monthly) PreferAdj(movable) PreferAdj(multiplicative) PreferAdj(municipal) PreferAdj(musical) PreferAdj(nasty) PreferAdj(necessary) PreferAdj(negative) PreferAdj(negotiable) PreferAdj(neuter) PreferAdj(neutral) PreferAdj(new) PreferAdj(next) PreferAdj(nonacademic) PreferAdj(nonaromatic) PreferAdj(occult) PreferAdj(old) PreferAdj(olympian) PreferAdj(opaque) PreferAdj(optative) PreferAdj(organic) PreferAdj(oriental) PreferAdj(ornamental) PreferAdj(overall) PreferAdj(pandemic) PreferAdj(papish) PreferAdj(parallel) PreferAdj(partial) PreferAdj(particular) PreferAdj(partitive) PreferAdj(passional) PreferAdj(patientive) PreferAdj(payable) PreferAdj(perfective) PreferAdj(performative) PreferAdj(periodical) PreferAdj(peripheral) PreferAdj(pharmaceutical) PreferAdj(phytochemical) PreferAdj(phytopharmaceutical) PreferAdj(pictorial) PreferAdj(piezoelectric) PreferAdj(placental) PreferAdj(plural) PreferAdj(political) PreferAdj(polysyllabic) PreferAdj(polytechnic) PreferAdj(positive) PreferAdj(possessive) PreferAdj(possible) PreferAdj(posterior) PreferAdj(posteriour) PreferAdj(postpositive) PreferAdj(practical) PreferAdj(precognitive) PreferAdj(prediabetic) PreferAdj(prepositional) PreferAdj(prepositive) PreferAdj(pretty) PreferAdj(preventative) PreferAdj(preventive) PreferAdj(previous) PreferAdj(primary) PreferAdj(procedural) PreferAdj(proficient) PreferAdj(progressive) PreferAdj(prohibitive) PreferAdj(public) PreferAdj(purple) PreferAdj(purpure) PreferAdj(pyramidal) PreferAdj(quadrilateral) PreferAdj(quadriliteral) PreferAdj(quadrillionth) PreferAdj(quarterly) PreferAdj(quick) PreferAdj(quiet) PreferAdj(random) PreferAdj("ready-made") PreferAdj(readymade) PreferAdj(receivable) PreferAdj(recessional) PreferAdj(recyclable) PreferAdj(reflexive) PreferAdj(refrigerative) PreferAdj(regular) PreferAdj(reliable) PreferAdj(renewable) PreferAdj(rental) PreferAdj(reptilian) PreferAdj(retinal) PreferAdj(retractable) PreferAdj(rouge) PreferAdj(rough) PreferAdj(round) PreferAdj(sabbatical) PreferAdj(scholastical) PreferAdj(secondary) PreferAdj(sectional) PreferAdj(semiliquid) PreferAdj(semiprofessional) PreferAdj(sensitive) PreferAdj(several) PreferAdj(sharp) PreferAdj(short) PreferAdj(shy) PreferAdj(silent) PreferAdj(silly) PreferAdj(simple) PreferAdj(single) PreferAdj(sleepy) PreferAdj(slight) PreferAdj(slim) PreferAdj(small) PreferAdj(smooth) PreferAdj(social) PreferAdj(socratic) PreferAdj(solid) PreferAdj(solitary) PreferAdj(southerly) PreferAdj(soviet) PreferAdj(spare) PreferAdj(special) PreferAdj(specific) PreferAdj(spiritual) PreferAdj(stainless) PreferAdj(static) PreferAdj(still) PreferAdj(straight) PreferAdj(straightaway) PreferAdj(structureless) PreferAdj(stupid) PreferAdj(subnormal) PreferAdj(subtropical) PreferAdj(Tropical) PreferAdj(Digestive) PreferAdj(Pneumonic) PreferAdj(sudden) PreferAdj(superficial) PreferAdj(sweet) PreferAdj(taxable) PreferAdj(theocratical) PreferAdj(thermal) PreferAdj(thick) PreferAdj(thin) PreferAdj(transnational) PreferAdj(transorbital) PreferAdj(trendy) PreferAdj(tribal) PreferAdj(trilingual) PreferAdj(triliteral) PreferAdj(trillionth) PreferAdj(trisyllabic) PreferAdj(turbinal) PreferAdj(ugly) PreferAdj(ultimate) PreferAdj(ultraportable) PreferAdj(ultrarevolutionary) PreferAdj(ultrashort) PreferAdj(ultraviolet) PreferAdj(unattractive) PreferAdj(unchangeable) PreferAdj(uncommunicative) PreferAdj(unconventional) PreferAdj(uncopyrightable) PreferAdj(uncountable) PreferAdj(undefeatable) PreferAdj(undesirable) PreferAdj(unicellular) PreferAdj(unimpressive) PreferAdj(uninjured) PreferAdj(unknowable) PreferAdj(unknown) PreferAdj(unlikely) PreferAdj(unlockable) PreferAdj(unmoral) PreferAdj(unperceptive) PreferAdj(unpredictable) PreferAdj(unprintable) PreferAdj(unproductive) PreferAdj(unpronounceable) PreferAdj(unprovable) PreferAdj(unquantifiable) PreferAdj(unquestionable) PreferAdj(unreachable) PreferAdj(unreliable) PreferAdj(unresponsive) PreferAdj(unrestrained) PreferAdj(unrestricted) PreferAdj(unsalable) PreferAdj(unshrinkable) PreferAdj(unsuccessful) PreferAdj(unsuspicious) PreferAdj(untimely) PreferAdj(untouchable) PreferAdj(unwearable) PreferAdj(unwonted) PreferAdj(unworth) PreferAdj(utmost) PreferAdj(verbal) PreferAdj(viral) PreferAdj(virginal) PreferAdj(visual) PreferAdj(vocable) PreferAdj(wearable) PreferAdj(weekly) PreferAdj(weird) PreferAdj(westerly) PreferAdj(which) PreferAdj(whirly) PreferAdj(whole) PreferAdj(wide) PreferAdj(woolen) PreferAdj(wormy) PreferAdj(wrinkly) PreferAdj(wrong) PreferAdj(yearly) PreferAdj(auburn) PreferAdj(black) PreferAdj(green) PreferAdj(gray) PreferAdj(pink) PreferAdj(tawny) PreferAdj(ultramarine) PreferAdj(yellow) PreferAdj(allergic) // The infection precipitated a high fever and allergic reactions. #define PreferNumeral(x) \ #begin wordform_score x { eng_noun } = -1 #end PreferNumeral(two) PreferNumeral(three) PreferNumeral(four) PreferNumeral(five) PreferNumeral(six) PreferNumeral(seven) PreferNumeral(eight) PreferNumeral(nine) PreferNumeral(ten)
Put her sewing aside when he entered.
wordform_score aside { eng_noun }=-5
12,607,797
[ 1, 6426, 22336, 272, 359, 310, 487, 831, 1347, 3904, 16219, 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 ]
[ 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, 0 ]
[ 1, 1095, 687, 67, 6355, 487, 831, 288, 24691, 67, 82, 465, 289, 29711, 25, 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 ]
./full_match/1/0xEaa72cfBFA202E0100F9b2712D2C076a033925D6/sources/contracts/KreyptOrder.sol
Address of Kreypt to send the funds
address public kreyptPayementAddress;
9,740,056
[ 1, 1887, 434, 1475, 266, 93, 337, 358, 1366, 326, 284, 19156, 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 ]
[ 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, 0 ]
[ 1, 565, 1758, 1071, 417, 266, 93, 337, 9148, 820, 1887, 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 ]
./partial_match/1/0x7955546004e1C35b25099C704D5f0Db88F9405A6/sources/Logic.sol
* @dev Allow contract's owner to create a new position/
function addNewPostition( string memory _name, string memory _description, string memory _imageUrl, string memory _link, uint256 _capInUSD, uint256 _votePriceInTokens, uint256 _finishedAt ) public onlyOwner { Position memory newPosition = Position({ name: _name, description: _description, imageUrl: _imageUrl, link: _link, capInUSD: _capInUSD, votePriceInTokens: _votePriceInTokens, finishedAt: _finishedAt, createdAt: block.timestamp, voteYes: 0, voteNo: 0, archived: false }); positions.push(newPosition); }
2,623,680
[ 1, 7009, 6835, 1807, 3410, 358, 752, 279, 394, 1754, 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 ]
[ 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, 20973, 3349, 608, 12, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 533, 3778, 389, 3384, 16, 203, 3639, 533, 3778, 389, 2730, 1489, 16, 203, 3639, 533, 3778, 389, 1232, 16, 203, 3639, 2254, 5034, 389, 5909, 382, 3378, 40, 16, 203, 3639, 2254, 5034, 389, 25911, 5147, 382, 5157, 16, 203, 3639, 2254, 5034, 389, 13527, 861, 203, 565, 262, 1071, 1338, 5541, 288, 203, 3639, 11010, 3778, 31845, 273, 11010, 12590, 203, 5411, 508, 30, 389, 529, 16, 203, 5411, 2477, 30, 389, 3384, 16, 203, 5411, 27544, 30, 389, 2730, 1489, 16, 203, 5411, 1692, 30, 389, 1232, 16, 203, 5411, 3523, 382, 3378, 40, 30, 389, 5909, 382, 3378, 40, 16, 203, 5411, 12501, 5147, 382, 5157, 30, 389, 25911, 5147, 382, 5157, 16, 203, 5411, 6708, 861, 30, 389, 13527, 861, 16, 203, 5411, 26083, 30, 1203, 18, 5508, 16, 203, 5411, 12501, 22352, 30, 374, 16, 203, 5411, 12501, 2279, 30, 374, 16, 203, 5411, 23276, 30, 629, 203, 3639, 15549, 203, 3639, 6865, 18, 6206, 12, 2704, 2555, 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 ]
./partial_match/3/0xc80b69362Ed72ee15a757373Fea40056cD60646f/sources/TENXToken.sol
* @dev Internal function that burns an amount of the token of a given account. Overriden to track totalRedeemed. @param account The account whose tokens will be burnt. @param value The amount that will be burnt./
function _burn(address account, uint256 value) internal { super._burn(account, value); }
5,225,058
[ 1, 3061, 445, 716, 18305, 87, 392, 3844, 434, 326, 1147, 434, 279, 864, 2236, 18, 531, 1107, 17951, 358, 3298, 2078, 426, 24903, 329, 18, 225, 2236, 1021, 2236, 8272, 2430, 903, 506, 18305, 88, 18, 225, 460, 1021, 3844, 716, 903, 506, 18305, 88, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 70, 321, 12, 2867, 2236, 16, 2254, 5034, 460, 13, 2713, 288, 203, 3639, 2240, 6315, 70, 321, 12, 4631, 16, 460, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x7b9619506b5CE35933952D1d1e98f064AA2102BE/sources/FeePool.sol
Address won't be able to claim fees if it is too far below the target c-ratio. It will need to burn pynths then try claiming again. Get the claimingAddress available fees and rewards Record the address has claimed for this period Record the fee payment in our recentFeePeriods Send them their fees Record the reward payment in our recentFeePeriods Send them their rewards
function _claimFees(address claimingAddress) internal returns (bool) { uint rewardsPaid = 0; uint feesPaid = 0; uint availableFees; uint availableRewards; (bool feesClaimable, bool anyRateIsInvalid) = _isFeesClaimableAndAnyRatesInvalid(claimingAddress); require(feesClaimable, "C-Ratio below penalty threshold"); require(!anyRateIsInvalid, "A pynth or SNX rate is invalid"); (availableFees, availableRewards) = feesAvailable(claimingAddress); require( availableFees > 0 || availableRewards > 0, "No fees or rewards available for period, or fees already claimed" ); _setLastFeeWithdrawal(claimingAddress, _recentFeePeriodsStorage(1).feePeriodId); if (availableFees > 0) { feesPaid = _recordFeePayment(availableFees); _payFees(claimingAddress, feesPaid); } if (availableRewards > 0) { rewardsPaid = _recordRewardPayment(availableRewards); _payRewards(claimingAddress, rewardsPaid); } emitFeesClaimed(claimingAddress, feesPaid, rewardsPaid); return true; }
3,356,236
[ 1, 1887, 8462, 1404, 506, 7752, 358, 7516, 1656, 281, 309, 518, 353, 4885, 10247, 5712, 326, 1018, 276, 17, 9847, 18, 2597, 903, 1608, 358, 18305, 293, 878, 451, 87, 1508, 775, 7516, 310, 3382, 18, 968, 326, 7516, 310, 1887, 2319, 1656, 281, 471, 283, 6397, 5059, 326, 1758, 711, 7516, 329, 364, 333, 3879, 5059, 326, 14036, 5184, 316, 3134, 8399, 14667, 30807, 2479, 2182, 3675, 1656, 281, 5059, 326, 19890, 5184, 316, 3134, 8399, 14667, 30807, 2479, 2182, 3675, 283, 6397, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 14784, 2954, 281, 12, 2867, 7516, 310, 1887, 13, 2713, 1135, 261, 6430, 13, 288, 203, 3639, 2254, 283, 6397, 16507, 350, 273, 374, 31, 203, 3639, 2254, 1656, 281, 16507, 350, 273, 374, 31, 203, 3639, 2254, 2319, 2954, 281, 31, 203, 3639, 2254, 2319, 17631, 14727, 31, 203, 203, 3639, 261, 6430, 1656, 281, 9762, 429, 16, 1426, 1281, 4727, 2520, 1941, 13, 273, 389, 291, 2954, 281, 9762, 429, 1876, 2961, 20836, 1941, 12, 14784, 310, 1887, 1769, 203, 203, 3639, 2583, 12, 3030, 281, 9762, 429, 16, 315, 39, 17, 8541, 5712, 23862, 5573, 8863, 203, 203, 3639, 2583, 12, 5, 2273, 4727, 2520, 1941, 16, 315, 37, 293, 878, 451, 578, 14204, 60, 4993, 353, 2057, 8863, 203, 203, 3639, 261, 5699, 2954, 281, 16, 2319, 17631, 14727, 13, 273, 1656, 281, 5268, 12, 14784, 310, 1887, 1769, 203, 203, 3639, 2583, 12, 203, 5411, 2319, 2954, 281, 405, 374, 747, 2319, 17631, 14727, 405, 374, 16, 203, 5411, 315, 2279, 1656, 281, 578, 283, 6397, 2319, 364, 3879, 16, 578, 1656, 281, 1818, 7516, 329, 6, 203, 3639, 11272, 203, 203, 3639, 389, 542, 3024, 14667, 1190, 9446, 287, 12, 14784, 310, 1887, 16, 389, 20872, 14667, 30807, 3245, 12, 21, 2934, 21386, 5027, 548, 1769, 203, 203, 3639, 309, 261, 5699, 2954, 281, 405, 374, 13, 288, 203, 5411, 1656, 281, 16507, 350, 273, 389, 3366, 14667, 6032, 12, 5699, 2954, 281, 1769, 203, 203, 5411, 389, 10239, 2954, 281, 12, 14784, 310, 1887, 2 ]
pragma solidity ^0.4.20; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public coOwner; function Ownable() public { coOwner = msg.sender; } modifier onlyCoOwner() { require(msg.sender == coOwner); _; } function transferCoOwnership(address _newOwner) public onlyCoOwner { require(_newOwner != address(0)); coOwner = _newOwner; CoOwnershipTransferred(coOwner, _newOwner); } function CoWithdraw() public onlyCoOwner { coOwner.transfer(this.balance); } event CoOwnershipTransferred(address indexed previousOwner, address indexed newOwner); } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="137776677653726b7a7c7e69767d3d707c">[email&#160;protected]</a>> (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 CryptoCarsRent is ERC721, Ownable { event CarCreated(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); string public constant NAME = "CryptoCars"; string public constant SYMBOL = "CarsToken"; uint256 private startingSellPrice = 0.012 ether; mapping (uint256 => address) public carIdToOwner; mapping (uint256 => address) public carIdToRenter; mapping (uint256 => uint256) public carIdRentStartTime; mapping (address => uint256) private ownershipTokenCount; mapping (uint256 => address) public carIdToApproved; mapping (uint256 => uint256) private carIdToPrice; mapping (uint256 => uint256) private carIdToProfit; /*** DATATYPES ***/ struct Car { string name; } Car[] private cars; function approve(address _to, uint256 _tokenId) public { //ERC721 // Caller must own token. require(_owns(msg.sender, _tokenId)); carIdToApproved[_tokenId] = _to; Approval(msg.sender, _to, _tokenId); } function balanceOf(address _owner) public view returns (uint256 balance) { //ERC721 return ownershipTokenCount[_owner]; } function createCarToken(string _name) public onlyCoOwner { _createCar(_name, address(this), startingSellPrice); } function createCarsTokens() public onlyCoOwner { for (uint8 car=0; car<21; car++) { _createCar("Crypto Car", address(this), startingSellPrice); } } function getCar(uint256 _tokenId) public view returns (string carName, uint256 sellingPrice, address owner) { Car storage car = cars[_tokenId]; carName = car.name; sellingPrice = carIdToPrice[_tokenId]; owner = carIdToOwner[_tokenId]; } function implementsERC721() public pure returns (bool) { return true; } function name() public pure returns (string) { //ERC721 return NAME; } function ownerOf(uint256 _tokenId) public view returns (address owner) { //ERC721 owner = carIdToOwner[_tokenId]; require(owner != address(0)); } // Allows someone to send ether and obtain the token function purchase(uint256 _tokenId) public payable { address oldOwner = carIdToOwner[_tokenId]; address newOwner = msg.sender; uint256 renter_payment; uint256 payment; if (now - carIdRentStartTime[_tokenId] > 7200) // 2 hours of rent finished carIdToRenter[_tokenId] = address(0); address renter = carIdToRenter[_tokenId]; uint256 sellingPrice = carIdToPrice[_tokenId]; uint256 profit = carIdToProfit[_tokenId]; require(oldOwner != newOwner); require(_addressNotNull(newOwner)); require(msg.value >= sellingPrice); if (renter != address(0)) { renter_payment = uint256(SafeMath.div(SafeMath.mul(profit, 45), 100)); //45% from profit to car&#39;s renter payment = uint256(SafeMath.sub(SafeMath.div(SafeMath.mul(sellingPrice, 97), 100), renter_payment)); //&#39;97% - renter_payment&#39; to previous owner } else { renter_payment = 0; payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 94), 100)); //94% to previous owner } // Next price will in 2 times more. if (sellingPrice < 500 finney) { carIdToPrice[_tokenId] = SafeMath.mul(sellingPrice, 2); //rice by 100% } else { carIdToPrice[_tokenId] = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 15), 10)); //rice by 50% } //plannig profit from next selling carIdToProfit[_tokenId] = uint256(SafeMath.sub(carIdToPrice[_tokenId], sellingPrice)); carIdToRenter[_tokenId] = address(0); carIdRentStartTime[_tokenId] = 0; _transfer(oldOwner, newOwner, _tokenId); // Pay previous tokenOwner if owner is not contract if (oldOwner != address(this)) { oldOwner.transfer(payment); // } // Pay to token renter if (renter != address(0)) { renter.transfer(renter_payment); // } TokenSold(_tokenId, sellingPrice, carIdToPrice[_tokenId], oldOwner, newOwner, cars[_tokenId].name); if (msg.value > sellingPrice) { //if excess pay uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); msg.sender.transfer(purchaseExcess); } } function rent(uint256 _tokenId) public payable { require(now - carIdRentStartTime[_tokenId] > 7200); // 2 hours of previous rent finished require(msg.sender != carIdToOwner[_tokenId]); uint256 profit = carIdToProfit[_tokenId]; //plannig profit from selling uint256 rentPrice = uint256(SafeMath.div(SafeMath.mul(profit, 10), 100)); //10% from profit is a rent price require(_addressNotNull(msg.sender)); require(msg.value >= rentPrice); carIdRentStartTime[_tokenId] = now; carIdToRenter[_tokenId] = msg.sender; address carOwner = carIdToOwner[_tokenId]; require(carOwner != address(this)); if (carOwner != address(this)) { carOwner.transfer(rentPrice); // } if (msg.value > rentPrice) { //if excess pay uint256 purchaseExcess = SafeMath.sub(msg.value, rentPrice); msg.sender.transfer(purchaseExcess); } } function symbol() public pure returns (string) { //ERC721 return SYMBOL; } function takeOwnership(uint256 _tokenId) public { //ERC721 address newOwner = msg.sender; address oldOwner = carIdToOwner[_tokenId]; require(_addressNotNull(newOwner)); require(_approved(newOwner, _tokenId)); _transfer(oldOwner, newOwner, _tokenId); } function allCarsInfo() public view returns (address[] owners, address[] renters, uint256[] prices, uint256[] profits) { //for web site view uint256 totalResultCars = totalSupply(); if (totalResultCars == 0) { // Return an empty array return (new address[](0),new address[](0),new uint256[](0),new uint256[](0)); } address[] memory owners_res = new address[](totalResultCars); address[] memory renters_res = new address[](totalResultCars); uint256[] memory prices_res = new uint256[](totalResultCars); uint256[] memory profits_res = new uint256[](totalResultCars); for (uint256 carId = 0; carId < totalResultCars; carId++) { owners_res[carId] = carIdToOwner[carId]; if (now - carIdRentStartTime[carId] <= 7200) // 2 hours of rent finished renters_res[carId] = carIdToRenter[carId]; else renters_res[carId] = address(0); prices_res[carId] = carIdToPrice[carId]; profits_res[carId] = carIdToProfit[carId]; } return (owners_res, renters_res, prices_res, profits_res); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { //for web site view return carIdToPrice[_tokenId]; } function tokensOfOwner(address _owner) public view returns(uint256[] ownerTokens) { //for web site view uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalCars = totalSupply(); uint256 resultIndex = 0; uint256 carId; for (carId = 0; carId <= totalCars; carId++) { if (carIdToOwner[carId] == _owner) { result[resultIndex] = carId; resultIndex++; } } return result; } } function totalSupply() public view returns (uint256 total) { //ERC721 return cars.length; } function transfer(address _to, uint256 _tokenId) public { //ERC721 require(_owns(msg.sender, _tokenId)); require(_addressNotNull(_to)); _transfer(msg.sender, _to, _tokenId); } function transferFrom(address _from, address _to, uint256 _tokenId) public { //ERC721 require(_owns(_from, _tokenId)); require(_approved(_to, _tokenId)); require(_addressNotNull(_to)); _transfer(_from, _to, _tokenId); } /* PRIVATE FUNCTIONS */ function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } function _approved(address _to, uint256 _tokenId) private view returns (bool) { return carIdToApproved[_tokenId] == _to; } function _createCar(string _name, address _owner, uint256 _price) private { Car memory _car = Car({ name: _name }); uint256 newCarId = cars.push(_car) - 1; require(newCarId == uint256(uint32(newCarId))); //check maximum limit of tokens CarCreated(newCarId, _name, _owner); carIdToPrice[newCarId] = _price; _transfer(address(0), _owner, newCarId); } function _owns(address _checkedAddr, uint256 _tokenId) private view returns (bool) { return _checkedAddr == carIdToOwner[_tokenId]; } function _transfer(address _from, address _to, uint256 _tokenId) private { ownershipTokenCount[_to]++; carIdToOwner[_tokenId] = _to; // When creating new cars _from is 0x0, but we can&#39;t account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete carIdToApproved[_tokenId]; } // Emit the transfer event. Transfer(_from, _to, _tokenId); } }
check maximum limit of tokens
require(newCarId == uint256(uint32(newCarId)));
7,746,688
[ 1, 1893, 4207, 1800, 434, 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, 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, 2583, 12, 2704, 16321, 548, 422, 2254, 5034, 12, 11890, 1578, 12, 2704, 16321, 548, 3719, 1769, 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/0xFe37f99cd0597164BFdaBFB7c9f98E4fc44BeF52/sources/src/lender/assessor.sol
@notice returns the minimum and maximum senior ratio @return minSeniorRatio_ minimum senior ratio (in RAY 10^27) @return maxSeniorRatio_ maximum senior ratio (in RAY 10^27)
function seniorRatioBounds() public view returns (uint256 minSeniorRatio_, uint256 maxSeniorRatio_) { return (minSeniorRatio.value, maxSeniorRatio.value); }
16,433,435
[ 1, 6154, 326, 5224, 471, 4207, 28901, 9659, 7169, 327, 1131, 55, 275, 9659, 8541, 67, 5224, 28901, 9659, 7169, 261, 267, 534, 5255, 1728, 66, 5324, 13, 327, 943, 55, 275, 9659, 8541, 67, 4207, 28901, 9659, 7169, 261, 267, 534, 5255, 1728, 66, 5324, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 28901, 9659, 8541, 5694, 1435, 1071, 1476, 1135, 261, 11890, 5034, 1131, 55, 275, 9659, 8541, 67, 16, 2254, 5034, 943, 55, 275, 9659, 8541, 67, 13, 288, 203, 3639, 327, 261, 1154, 55, 275, 9659, 8541, 18, 1132, 16, 943, 55, 275, 9659, 8541, 18, 1132, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * Dev. `Akena Ver.3.0.5: lockTime` */ pragma solidity >=0.4.16 < 0.9.0; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external; } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner()); _; } function isOwner() public view returns (bool) { return msg.sender == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract Pausable is Ownable{ event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } function paused() public view returns (bool) { return _paused; } modifier whenNotPaused() { require(!_paused); _; } modifier whenPaused() { require(_paused); _; } function pause() public onlyOwner whenNotPaused { _paused = true; emit Paused(msg.sender); } function unpause() public onlyOwner whenPaused { _paused = false; emit Unpaused(msg.sender); } } contract ERC20Token{ using SafeMath for uint256; // Public variables of the token string public name; string public symbol; uint8 public decimals = 8; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This generates a public event on the blockchain that will notify clients event Approval(address indexed _owner, address indexed _spender, uint256 _value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); constructor(uint256 initialSupply,string memory tokenName,string memory tokenSymbol) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != address(0x0)); 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 transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, address(this), _extraData); return true; } } function burn(uint256 _value) public returns (bool success) { balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract from the sender totalSupply = totalSupply.sub(_value); // Updates totalSupply emit Burn(msg.sender, _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); // Subtract from the sender's allowance totalSupply = totalSupply.sub(_value); // Update totalSupply emit Burn(_from, _value); return true; } } contract Akena_Token is ERC20Token, Ownable,Pausable{ mapping (address => bool) public frozenAccount; mapping(address => uint256) public lockedAccount; event FreezeAccount(address account, bool frozen); event LockAccount(address account,uint256 unlockTime); constructor() ERC20Token(1000000000,"AKENA","AKENA") public { } /** * Freeze of Account */ function freezeAccount(address account) onlyOwner public { frozenAccount[account] = true; emit FreezeAccount(account, true); } /** * unFreeze of Account */ function unFreezeAccount(address account) onlyOwner public{ frozenAccount[account] = false; emit FreezeAccount(account, false); } /** * lock Account, if account is locked, fund can only transfer in but not transfer out. * Can not unlockAccount, if need unlock account , pls call unlockAccount interface * epoch time, not milliseconds */ function lockAccount(address account, uint256 unlockTime) onlyOwner public{ require(unlockTime > now); lockedAccount[account] = unlockTime; emit LockAccount(account,unlockTime); } /** * unlock of Account */ function unlockAccount(address account) onlyOwner public{ lockedAccount[account] = 0; emit LockAccount(account,0); } function changeName(string memory newName) public onlyOwner { name = newName; } function changeSymbol(string memory newSymbol) public onlyOwner{ symbol = newSymbol; } function _transfer(address _from, address _to, uint _value) internal whenNotPaused { //Prevent transfer to 0x0 address. Use burn() instead require(_to != address(0x0)); //if account is frozen, then fund can not be transfer in or out. require(!frozenAccount[_from]); require(!frozenAccount[_to]); //if account is locked, then fund can only transfer in but can not transfer out. require(!isAccountLocked(_from)); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); } function isAccountLocked(address account) public view returns (bool) { return lockedAccount[account] > now; } function isAccountFrozen(address account) public view returns (bool){ return frozenAccount[account]; } }
Prevent transfer to 0x0 address. Use burn() insteadif account is frozen, then fund can not be transfer in or out.if account is locked, then fund can only transfer in but can not transfer out.
function _transfer(address _from, address _to, uint _value) internal whenNotPaused { require(_to != address(0x0)); require(!frozenAccount[_from]); require(!frozenAccount[_to]); require(!isAccountLocked(_from)); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(_from, _to, _value); }
580,305
[ 1, 25828, 7412, 358, 374, 92, 20, 1758, 18, 2672, 18305, 1435, 3560, 430, 2236, 353, 12810, 16, 1508, 284, 1074, 848, 486, 506, 7412, 316, 578, 596, 18, 430, 2236, 353, 8586, 16, 1508, 284, 1074, 848, 1338, 7412, 316, 1496, 848, 486, 7412, 596, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 13866, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 389, 1132, 13, 2713, 1347, 1248, 28590, 288, 203, 3639, 2583, 24899, 869, 480, 1758, 12, 20, 92, 20, 10019, 203, 203, 3639, 2583, 12, 5, 28138, 3032, 63, 67, 2080, 19226, 203, 3639, 2583, 12, 5, 28138, 3032, 63, 67, 869, 19226, 203, 203, 3639, 2583, 12, 5, 291, 3032, 8966, 24899, 2080, 10019, 203, 203, 3639, 11013, 951, 63, 67, 2080, 65, 273, 11013, 951, 63, 67, 2080, 8009, 1717, 24899, 1132, 1769, 203, 3639, 11013, 951, 63, 67, 869, 65, 273, 11013, 951, 63, 67, 869, 8009, 1289, 24899, 1132, 1769, 203, 203, 3639, 3626, 12279, 24899, 2080, 16, 389, 869, 16, 389, 1132, 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 ]
./full_match/42/0x2e4c2D09C80616932742410920DB7C1621B00658/sources/TheCrypticZoo/AccessControl.sol
@title Manages special access privileges for anyone who is an admin
contract AccessControl { address admin; event NewAdmin(address indexed _addedBy, address indexed _newAdress); event RemovedAdmin(address indexed _removedBy, address indexed _removedAddress); modifier onlyAdmin { require(isAdmin(msg.sender), "Only admin can perform this action"); _; } constructor() { admin = msg.sender; } function updateAdmin(address _newAdmin) external onlyAdmin { admin = _newAdmin; emit NewAdmin(msg.sender, admin); } function isAdmin(address _adminId) public view returns (bool) { return (_adminId == admin); } }
16,251,261
[ 1, 49, 940, 281, 4582, 2006, 19583, 364, 1281, 476, 10354, 353, 392, 3981, 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 ]
[ 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, 0, 0 ]
[ 1, 16351, 24349, 288, 203, 565, 1758, 3981, 31, 203, 203, 565, 871, 1166, 4446, 12, 2867, 8808, 389, 9665, 858, 16, 1758, 8808, 389, 2704, 1871, 663, 1769, 27699, 565, 871, 2663, 9952, 4446, 12, 2867, 8808, 389, 14923, 858, 16, 1758, 8808, 389, 14923, 1887, 1769, 203, 203, 203, 565, 9606, 1338, 4446, 288, 203, 3639, 2583, 12, 291, 4446, 12, 3576, 18, 15330, 3631, 315, 3386, 3981, 848, 3073, 333, 1301, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 3885, 1435, 288, 203, 3639, 3981, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 1089, 4446, 12, 2867, 389, 2704, 4446, 13, 3903, 1338, 4446, 288, 203, 3639, 3981, 273, 389, 2704, 4446, 31, 203, 3639, 3626, 1166, 4446, 12, 3576, 18, 15330, 16, 3981, 1769, 203, 565, 289, 203, 203, 565, 445, 23467, 12, 2867, 389, 3666, 548, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 261, 67, 3666, 548, 422, 3981, 1769, 203, 565, 289, 203, 203, 377, 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 ]
pragma solidity ^0.4.18; import 'zeppelin-solidity/contracts/ownership/Ownable.sol'; /** * @title Whitelist * @dev List of whitelisted users */ contract Whitelist is Ownable { mapping(address => bool) public whitelist; event LogAddToWhilelist(address indexed sender, address indexed beneficiary); event LogRemoveFromWhilelist(address indexed sender, address indexed beneficiary); /** * @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract. */ modifier isWhitelisted(address _beneficiary) { require(whitelist[_beneficiary]); _; } /** * @dev Adds single address to whitelist. * @param _beneficiary Address to be added to the whitelist */ function addToWhitelist(address _beneficiary) external onlyOwner { require (_beneficiary != 0x0); whitelist[_beneficiary] = true; LogAddToWhilelist(msg.sender, _beneficiary); } /** * @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. * @param _beneficiaries Addresses to be added to the whitelist */ function addManyToWhitelist(address[] _beneficiaries) external onlyOwner { for (uint256 i = 0; i < _beneficiaries.length; i++) { this.addToWhitelist(_beneficiaries[i]); } } /** * @dev Removes single address from whitelist. * @param _beneficiary Address to be removed to the whitelist */ function removeFromWhitelist(address _beneficiary) external onlyOwner { whitelist[_beneficiary] = false; LogRemoveFromWhilelist(msg.sender, _beneficiary); } }
* @dev Adds single address to whitelist. @param _beneficiary Address to be added to the whitelist/
function addToWhitelist(address _beneficiary) external onlyOwner { require (_beneficiary != 0x0); whitelist[_beneficiary] = true; LogAddToWhilelist(msg.sender, _beneficiary); }
7,312,346
[ 1, 3655, 2202, 1758, 358, 10734, 18, 225, 389, 70, 4009, 74, 14463, 814, 5267, 358, 506, 3096, 358, 326, 10734, 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 ]
[ 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, 9604, 18927, 12, 2867, 389, 70, 4009, 74, 14463, 814, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 261, 67, 70, 4009, 74, 14463, 814, 480, 374, 92, 20, 1769, 203, 3639, 10734, 63, 67, 70, 4009, 74, 14463, 814, 65, 273, 638, 31, 203, 3639, 1827, 986, 774, 2888, 330, 5449, 12, 3576, 18, 15330, 16, 389, 70, 4009, 74, 14463, 814, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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: GPL-3.0 pragma solidity >=0.4.22 <0.6.0; interface ENS { event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); event Transfer(bytes32 indexed node, address owner); event NewResolver(bytes32 indexed node, address resolver); event NewTTL(bytes32 indexed node, uint64 ttl); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function setRecord(bytes32 node, address owner, address resolver, uint64 ttl) external; function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external; function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external returns(bytes32); function setResolver(bytes32 node, address resolver) external; function setOwner(bytes32 node, address owner) external; function setTTL(bytes32 node, uint64 ttl) external; function setApprovalForAll(address operator, bool approved) external; function owner(bytes32 node) external view returns (address); function resolver(bytes32 node) external view returns (address); function ttl(bytes32 node) external view returns (uint64); function recordExists(bytes32 node) external view returns (bool); function isApprovedForAll(address ensowner, address operator) external view returns (bool); } contract AbstractENS { event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); event Transfer(bytes32 indexed node, address owner); event NewResolver(bytes32 indexed node, address resolver); event NewTTL(bytes32 indexed node, uint64 ttl); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function setRecord(bytes32 node, address owner, address resolver, uint64 ttl) external; function setSubnodeRecord(bytes32 node, bytes32 label, address owner, address resolver, uint64 ttl) external; function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external returns(bytes32); function setResolver(bytes32 node, address resolver) external; function setOwner(bytes32 node, address owner) external; function setApprovalForAll(address operator, bool approved) external; function owner(bytes32 node) public view returns (address); function recordExists(bytes32 node) external view returns (bool); function isApprovedForAll(address ensowner, address operator) external view returns (bool); } contract AbstractBaseRegistrar { event NameMigrated(uint256 indexed id, address indexed owner, uint expires); event NameRegistered(uint256 indexed id, address indexed owner, uint expires); event NameRenewed(uint256 indexed id, uint expires); bytes32 public baseNode; // The namehash of the TLD this registrar owns (eg, .eth) ENS public ens; } contract AbstractGroupWalletProxy { function getIsOwner(address _owner) external view returns (bool); function getOwners() external view returns (address[] memory); } contract AbstractETHRegistrarController { mapping(bytes32=>uint) public commitments; uint public minCommitmentAge; uint public maxCommitmentAge; event NameRegistered(string name, bytes32 indexed label, address indexed owner, uint cost, uint expires); event NameRenewed(string name, bytes32 indexed label, uint cost, uint expires); event NewPriceOracle(address indexed oracle); function rentPrice(string memory name, uint duration) view public returns(uint); function makeCommitmentWithConfig(string memory name, address owner, bytes32 secret, address resolver, address addr) pure public returns(bytes32); function commit(bytes32 commitment) public; function register(string calldata name, address owner, uint duration, bytes32 secret) external payable; function registerWithConfig(string memory name, address owner, uint duration, bytes32 secret, address resolver, address addr) public payable; function available(string memory name) public view returns(bool); } contract AbstractResolver { mapping(bytes32=>bytes) hashes; event AddrChanged(bytes32 indexed node, address a); event AddressChanged(bytes32 indexed node, uint coinType, bytes newAddress); event NameChanged(bytes32 indexed node, string name); event ABIChanged(bytes32 indexed node, uint256 indexed contentType); event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); event TextChanged(bytes32 indexed node, string indexed indexedKey, string key); event ContenthashChanged(bytes32 indexed node, bytes hash); function ABI(bytes32 node, uint256 contentTypes) external view returns (uint256, bytes memory); function addr(bytes32 node) external view returns (address); function addr(bytes32 node, uint coinType) external view returns(bytes memory); function contenthash(bytes32 node) external view returns (bytes memory); function dnsrr(bytes32 node) external view returns (bytes memory); function name(bytes32 node) external view returns (string memory); function pubkey(bytes32 node) external view returns (bytes32 x, bytes32 y); function text(bytes32 node, string calldata key) external view returns (string memory); function interfaceImplementer(bytes32 node, bytes4 interfaceID) external view returns (address); function setABI(bytes32 node, uint256 contentType, bytes calldata data) external; function setAddr(bytes32 node, address r_addr) external; function setAddr(bytes32 node, uint coinType, bytes calldata a) external; function setContenthash(bytes32 node, bytes calldata hash) external; function setDnsrr(bytes32 node, bytes calldata data) external; function setName(bytes32 node, string calldata _name) external; function setPubkey(bytes32 node, bytes32 x, bytes32 y) external; function setText(bytes32 node, string calldata key, string calldata value) external; function setInterface(bytes32 node, bytes4 interfaceID, address implementer) external; function supportsInterface(bytes4 interfaceID) external pure returns (bool); function setAuthorisation(bytes32 node, address target, bool isAuthorised) external; } /// @title Proxy - Generic proxy contract allows to execute all transactions applying the code of a master contract. /// @author Stefan George - <[email protected]> /// ProxyToken adapted and applied for token by pepihasenfuss.eth pragma solidity >=0.4.22 <0.6.0; contract ProxyToken { address internal masterCopy; bytes32 internal name32; uint256 private ownerPrices; mapping (address => uint256) private balances; mapping (address => mapping (address => uint256)) private allowed; event Transfer(address indexed from, address indexed to, uint256 value); event FrozenFunds(address target, bool frozen); event Deposit(address from, uint256 value); event Deployment(address owner, address theContract); event Approval(address indexed owner,address indexed spender,uint256 value); constructor(address _masterCopy) public payable { masterCopy = _masterCopy; } function () external payable { // solium-disable-next-line security/no-inline-assembly assembly { let masterCopy := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff) if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) { mstore(0, masterCopy) return(0, 0x20) } calldatacopy(0, 0, calldatasize()) let success := delegatecall(gas, masterCopy, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) if eq(success, 0) { revert(0, returndatasize()) } return(0, returndatasize()) } } } /// @title Proxy - Generic proxy contract allows to execute all transactions applying the code of a master contract. /// @author Stefan George - <[email protected]> /// ProxyGroupWallet adapted and applied for GroupWallet by pepihasenfuss.eth pragma solidity >=0.4.22 <0.6.0; contract ProxyGroupWallet { address internal masterCopy; mapping(uint256 => uint256) private tArr; address[] private owners; address internal GWF; // GWF - GroupWalletFactory contract mapping(uint256 => bytes) private structures; event TestReturnData(address sender, bytes returnData); event TestReturnLength(address sender, uint256 value); event GroupWalletDeployed(address sender, uint256 members, uint256 timeStamp); event GroupWalletMessage(bytes32 msg); event Deposit(address from, uint256 value); event ColorTableSaved(bytes32 domainHash); event EtherScriptSaved(bytes32 domainHash,string key); constructor(address _masterCopy) public payable { masterCopy = _masterCopy; } function () external payable { // solium-disable-next-line security/no-inline-assembly assembly { let masterCopy := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff) if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) { mstore(0, masterCopy) return(0, 0x20) } calldatacopy(0, 0, calldatasize()) let success := delegatecall(gas, masterCopy, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) if eq(success, 0) { revert(0, returndatasize()) } return(0, returndatasize()) } } } contract GroupWalletFactory { event Deposit(address from, uint256 value); event StructureDeployed(bytes32 domainHash); event ColorTableSaved(bytes32 domainHash); event EtherScriptSaved(bytes32 domainHash,string key); event ProxyTokenCreation(ProxyToken proxy); event ProxyGroupWalletCreation(ProxyGroupWallet proxy); event SetPrices(bytes32 domainHash); event TransferOwner(bytes32 domainHash); event FreezeToken(bytes32 domainHash); event Transfer(address indexed from, address indexed to, uint256 value); uint256 constant k_KEY = 0xdada1234dada; uint256 constant k_aMask = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff; uint256 constant k_commitMask = 0xffffffffffffffffffffffff0000000000000000000000000000000000000000; uint256 constant k_commit2Mask = 0x0000000000000000000000000000000000000000ffffffffffffffffffffffff; uint256 constant k_lockedMask = 0x0000000000000000000000010000000000000000000000000000000000000000; uint256 constant k_timeMask = 0xffffffffffffffffffffffff0000000000000000000000000000000000000000; uint256 constant k_time2Mask = 0x0000000000000000000000000000000000000000ffffffffffffffffffffffff; bytes32 constant k_offset20 = 0x0000000000000000000000000000000000000000000000000000000000000020; bytes28 constant k_padding28 = bytes28(0x00000000000000000000000000000000000000000000000000000000); bytes32 constant k_abi80 = 0x0000000000000000000000000000000000000000000000000000000000000080; uint256 constant k_rentMask = 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff; address constant k_add00 = address(0x0); AbstractResolver public resolverContract; AbstractETHRegistrarController public controllerContract; AbstractBaseRegistrar public base; AbstractENS public ens; address private GWFowner; mapping(uint64=>uint256) private installations; // installTime + proxyTokenAddr mapping(bytes32=>uint256) private commitments; // commitment + ownerAddr function getCommitment(bytes32 _domainHash) private view returns (uint64 comm) { return uint64( (uint256( commitments[_domainHash] & k_commitMask )>>160) & k_commit2Mask ); } function getOwner(bytes32 _domainHash) external view returns (address) { return address( uint160( commitments[_domainHash] & k_aMask ) ); } function saveOwner(address _iToken, bytes32 _domainHash) private { commitments[ _domainHash ] = uint256(uint160(_iToken)) + uint256( commitments[_domainHash] & k_commitMask); } function saveCommitment(bytes32 input, bytes32 _domainHash) private { commitments[_domainHash] = uint256( (uint256(input)<<160) & k_commitMask ) + uint256( commitments[_domainHash] & k_aMask); } function getInstallTime(bytes32 _domainHash) public view returns (uint256 iTime) { uint256 i = uint256(installations[ getCommitment(_domainHash) ]); iTime = uint256( (uint256( uint256(i) & k_commitMask )>>160) & k_commit2Mask ); return iTime; } function getProxyToken(bytes32 _domainHash) public view returns (address p) { return address( uint160( uint256( uint256(installations[ getCommitment(_domainHash) ]) ) & k_aMask ) ); } function saveProxyToken(address _iOwner, bytes32 _domainHash) private { uint64 hsh = getCommitment(_domainHash); uint256 i = uint256(installations[ hsh ]); installations[ hsh ] = uint256(uint160(_iOwner)) + uint256(i & k_commitMask); } function saveInstallTime(uint256 input, bytes32 _domainHash) private { uint64 hsh = getCommitment(_domainHash); uint256 i = uint256(installations[ hsh ]); installations[ hsh ] = uint256( (uint256(input)<<160) & k_commitMask ) + uint256(i & k_aMask); } // ------------------- owners --------------------------------------------- function getGWProxy(bytes32 _dHash) public view returns (address) { return address( uint160( commitments[_dHash] & k_aMask ) ); } function getGWPcontract(bytes32 _dHash) public view returns (AbstractGroupWalletProxy) { return AbstractGroupWalletProxy( address( uint160( commitments[_dHash] & k_aMask ) ) ); } function getIsOwner(bytes32 _dHash,address _owner) external view returns (bool) { uint256 c = commitments[_dHash]; address theGWPcontract = address( uint160( c&k_aMask ) ); if (theGWPcontract==msg.sender) return false; // is initiator calling, no owners list yet return AbstractGroupWalletProxy( theGWPcontract ).getIsOwner(_owner); // run getGWPcontract(_dHash).getIsOwner(_owner); } function getOwners(bytes32 _dHash) external view returns (address[] memory) { uint256 c = commitments[_dHash]; if (address( uint160( c&k_aMask ) )!=msg.sender) return AbstractGroupWalletProxy( address( uint160( c&k_aMask ) ) ).getOwners(); // run getGWPcontract(_dHash).getOwners(); address[] memory empty; return empty; } function getOwners_internal(uint256 c) private view returns (address[] memory) { if (address( uint160( c&k_aMask ) )!=msg.sender) return AbstractGroupWalletProxy( address( uint160( c&k_aMask ) ) ).getOwners(); address[] memory empty; return empty; } function char(byte b) private pure returns (byte c) { if (uint8(b) < uint8(10)) return byte(uint8(b) + 0x30); else return byte(uint8(b) + 0x57); } function b_String(bytes32 _bytes32, uint len, bool isHex) private pure returns (string memory) { uint8 off = 0; if (isHex) off = 2; bytes memory s = new bytes((len*2)+off); if (isHex) { s[0] = 0x30; s[1] = 0x78; } for (uint i = 0; i < len; i++) { byte b = byte(uint8(uint(_bytes32) / (2 ** (8 * ((len-1) - i))))); byte hi = byte(uint8(b) / 16); byte lo = byte(uint8(b) - 16 * uint8(hi)); s[off+(2 * i)] = char(hi); s[off+(2 * i) + 1] = char(lo); } return string(s); } function strlen(string memory s) internal pure returns (uint) { uint len; uint i = 0; uint bytelength = bytes(s).length; for(len = 0; i < bytelength; len++) { byte b = bytes(s)[i]; if(b < 0x80) { i += 1; } else if (b < 0xE0) { i += 2; } else if (b < 0xF0) { i += 3; } else if (b < 0xF8) { i += 4; } else if (b < 0xFC) { i += 5; } else { i += 6; } } return len; } function bytesToStr(bytes32 _b, uint len) internal pure returns (string memory) { bytes memory bArr = new bytes(len); uint256 i; do { bArr[i] = _b[i]; i++; } while(i<len); return string(bArr); } function stringMemoryTobytes32(string memory _data) private pure returns(bytes32 a) { assembly { a := mload(add(_data, 32)) } } function mb32(bytes memory _data) private pure returns(bytes32 a) { assembly { a := mload(add(_data, 32)) } } function keccak(bytes memory self, uint offset, uint len) internal pure returns (bytes32 ret) { require(offset + len <= self.length,"keccak offset!!!"); assembly { ret := keccak256(add(add(self, 32), offset), len) } } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } if (len==0) return; // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } function substring(bytes memory self, uint offset, uint len) internal pure returns(bytes memory) { require(offset + len <= self.length,"substring!!!"); bytes memory ret = new bytes(len); uint dest; uint src; assembly { dest := add(ret, 32) src := add(add(self, 32), offset) } memcpy(dest, src, len); return ret; } function readBytes32(bytes memory self, uint idx) internal pure returns (bytes32 ret) { require(idx + 32 <= self.length); assembly { ret := mload(add(add(self, 32), idx)) } } function getAddress(bytes memory d, uint off) internal pure returns(address addr) { return address( uint256( uint256(mb32(substring(d,off,32))) & uint256(k_aMask) )); } function getAmount(bytes memory d, uint off) internal pure returns(uint256 amt) { return uint256( mb32(substring(d,off,32)) ); } function reserve_ogn(bytes32 _domainHash,bytes32 _commitment,bytes calldata data) external payable { (bool success, bytes memory returnData) = address(0xDadaDadadadadadaDaDadAdaDADAdadAdADaDADA).call.value(0)(data); require(data.length>0 && success && returnData.length==0 && _commitment!=0x0," - reserve/commit failed!"); emit StructureDeployed(_domainHash); controllerContract.commit(_commitment); commitments[ _domainHash ] = uint256( (uint256(_commitment)<<160) & k_commitMask ) + uint256( uint160(msg.sender) & k_aMask ); // save initiator = owner } function register_QgM(bytes32[] calldata _m) external payable { uint256 _dur = uint256(_m[2])>>128; uint256 _rent = uint256(_m[2])&k_rentMask; string memory _name = bytesToStr(_m[3],uint(_m[3])&0xff); // domainName, length require(address( uint160( commitments[_m[0]] & k_aMask ) )==msg.sender, "- only by initiator."); // _domainHash = _m[0] require(controllerContract.available(_name),"NOT available!"); require(_m[1]!=0 && _dur!=0,"Bad duration/bad secret!"); // _secret = _m[1]; controllerContract.registerWithConfig.value(_rent)(_name,address(this),_dur,_m[1],address(resolverContract),address(this)); resolverContract.setName(_m[0],string(abi.encodePacked(_name,".eth"))); } function update_P5q(bytes32 _domainHash,bytes calldata data32) external payable { isInitiatorOrMember2(_domainHash); resolverContract.setABI(_domainHash,32,abi.encodePacked(data32)); // structure emit StructureDeployed(_domainHash); } function lock_dfs(bytes32 _dHash,bytes calldata data32) external payable { uint256 c = commitments[_dHash]; require(address( uint160(c & k_aMask) )==msg.sender,"- only by initiator."); // owner getOwner(_dHash) require( installations[ uint64( (uint256(c & k_commitMask)>>160) & k_commit2Mask ) ] ==0x0," - Deployment cannot be locked!"); // NOT locked getInstallTime(_dHash), getCommitment(_dHash) uint64 hsh = uint64( (uint256(c & k_commitMask)>>160) & k_commit2Mask ); installations[hsh] = uint256( installations[hsh] & k_aMask ) + k_lockedMask; // saveInstallTime(1,_dHash) resolverContract.setABI(_dHash,32,abi.encodePacked(data32)); // structure emit StructureDeployed(_dHash); } function domainReport(string calldata _dom,uint command) external payable returns (uint256 report, bytes memory structure) { uint256 nb = 32; uint256 stamp = 0; uint256 colTable = 0; uint256 abi32len = 0; address owner; bytes memory abi32; bytes32 dHash = keccak256(abi.encodePacked(base.baseNode(), keccak256(bytes(_dom)))); bool hasCommitment = uint64(getCommitment(dHash))>0x0; uint256 inst = getInstallTime(dHash); owner = base.ens().owner(dHash); report = uint256(inst & 0x1); // locked group if (!base.ens().recordExists(dHash)) report = uint256(uint(report)+2); // domain available - NOT existing if (owner == address(getGWProxy(dHash)) || owner == address(this)) report = uint256(uint(report)+4); // domain contracted, GroupWalletProxy or this GWF contract is OWNER of domain if (base.ens().resolver(dHash) == address(resolverContract)) report = uint256(uint(report)+8); // resolverContract resolving domain is valid if (hasCommitment) report = uint256(uint(report) + 16); // domain with commitment if (resolverContract.addr(dHash) == address(this)) report = uint256(uint(report) + 64); // domain ENS points to this GWF contract if (hasCommitment) { (abi32len, abi32) = resolverContract.ABI(dHash,32); // isABIstructure if ((abi32len == 32) && (uint256(abi32.length)>32) && (uint256(abi32.length)<0x1000)) report = uint256(uint(report)+32); (uint256 abi128len, bytes memory abi128) = resolverContract.ABI(dHash,128); // isABI128 if ((abi128len == 128) && (uint256(abi128.length)>=224) && ((abi128.length%32) == 0)) report = uint256(uint(report)+128); if (abi128.length>0) nb = uint256(uint256((uint256(abi128.length)-uint256(0x80))>>5)-1); // nb of members derived from ABI128 // abi128len = 0x80 + (nbOfMem+1)*32 nb = getOwners_internal( commitments[ dHash] ).length; stamp = uint256(stringMemoryTobytes32(resolverContract.text(dHash,"use_timeStamp"))); if (stamp==0x0000000d7573655f74696d655374616d70000000000000000000000000000000) stamp = 0; } colTable = uint256(stringMemoryTobytes32(resolverContract.text(dHash,"use_color_table"))); if (colTable!=0x0000000f7573655f636f6c6f725f7461626c6500000000000000000000000000) report = uint256(uint(report)+2048); if (getProxyToken(dHash) != 0x0000000000000000000000000000000000000000) report = uint256(uint(report)+4096); if (owner == k_add00) report = uint256(uint(report)+256); // domain NOT owned owner = 0x000000000000000000000000000 if (controllerContract.available(_dom)) report = uint256(uint(report)+512); // domain is available if (owner == address(msg.sender)) report = uint256(uint(report)+1024); // domain owned by default account report = uint256(stamp) + uint256(uint256(report)<<128) + uint256(nb<<64) + uint256(inst); // 4 words each is 8bytes if (command == 0) return (report,abi32); if (command == 1) return (stamp,abi32); if (command == 2) return (colTable,abi32); if (command == 3) return (abi32len,abi32); } function inviteInstallToken_q31n(bytes32[] calldata _mem) external payable { bytes32 _dHash = _mem[0]; // domain hash identifying project/group uint l = _mem.length-5; // 5 words uint64 time = uint64(now*1000) & uint64(0xffffffffffff0000); // time % 0x1000 uint256 amount = uint256(msg.value / uint256((l/5) + 2)); // ether transferred to each member, 1 for GWF, 1 for PGW uint256 c = commitments[_dHash]; { require(l>=10 && l<160, " - Nb owners >= 2 and <= 31!"); // l = l*5 require(address( uint160(c & k_aMask) )==msg.sender, "- only by initiator."); require(address(uint160(uint256(_mem[1]))) != k_add00, "MasterCopy != 0x0"); // masterCopy require(msg.value > 0, "ProxyToken installation needs ether!"); } bytes memory proxyCommand; // call(proxy) bytes memory theAbiCommand; // resolverContract.setABI { address o; bytes32 d; uint i=5; do { o = address(uint160(uint256( _mem[i] ))); d = _mem[i+2]; require(o != k_add00, " - illegal owner."); require(_mem[i+1] != 0x0, " - illegal label."); require(d != 0x0, " - illegal domainLabel."); proxyCommand = abi.encodePacked(proxyCommand ,_mem[i+3]); // 8, 13, 18 + domainName theAbiCommand = abi.encodePacked(theAbiCommand,_mem[i+4]); // 9, 14, 19 + 1 abi extra word require(address(uint160(o)).send(amount),"Sending ether failed."); emit Deposit(address(uint160(o)), amount); base.ens().setSubnodeRecord(_dHash, _mem[i+1], address(this), address(resolverContract), time); // vitalik.ethereum.eth resolverContract.setAddr(d,o); base.ens().setOwner(d,o); i = i+5; } while (i<=l&&i<=165); } { ProxyToken proxy = new ProxyToken( address(uint160(uint256(_mem[1]))) ); // install ProxyToken contract and call the Token contract immediately, masterCopy installations[ uint64( (uint256(c & k_timeMask)>>160) & k_time2Mask ) ] = uint256( uint160(address(proxy)) ) + uint256( (uint256(time+1)<<160) & k_timeMask ); // saveProxyToken(address(proxy),_dHash) && saveInstallTime(time+1,_dHash) bytes memory commandLoad = abi.encodePacked(bytes4(0x5de5cbe4),k_offset20,bytes32(uint256((l/5)+1)),proxyCommand,_mem[3],k_padding28); // call(proxy) // solium-disable-next-line security/no-inline-assembly assembly { if eq(call(gas, proxy, amount, add(commandLoad, 0x20), mload(commandLoad), 0, 0), 0) { revert(0, 0) } } theAbiCommand = abi.encodePacked(k_abi80,k_abi80,k_abi80,bytes32(uint256((l/5)+1)<<5),theAbiCommand,_mem[2]); resolverContract.setABI(_dHash,128,theAbiCommand); // member addresses to ABI, one extra ABI 128 word emit ProxyTokenCreation(proxy); } { ProxyGroupWallet proxyGW = new ProxyGroupWallet( address(uint160(uint256(_mem[4]))) ); // _mem[4] = masterCopy, GroupWalletMaster proxyCommand = abi.encodePacked(bytes4(0x0000efe4),k_offset20,bytes32(uint256((l/5))),proxyCommand,k_padding28); // call(proxy).newProxyGroupWallet_j5O() // solium-disable-next-line security/no-inline-assembly assembly { if eq(call(gas, proxyGW, amount, add(proxyCommand, 0x20), mload(proxyCommand), 0, 0), 0) { revert(0, 0) } } resolverContract.setAddr(_dHash,address(proxyGW)); base.ens().setOwner(_dHash,address(proxyGW)); commitments[_dHash] = uint256(uint160(address(proxyGW)) & k_aMask) + uint256(c&k_commitMask); // save initiator = GWP-GroupWalletProxy owner emit ProxyGroupWalletCreation(proxyGW); } } function createProxyToken(bytes32 _domainHash, address masterCopy, bytes memory data) public payable returns (ProxyToken proxy) { uint256 c = commitments[_domainHash]; require(address(uint160(c & k_aMask))==msg.sender, "- only by initiator."); require(masterCopy != k_add00, "MasterCopy != 0x0"); proxy = new ProxyToken(masterCopy); uint64 hsh = uint64( (uint256(c & k_commitMask)>>160) & k_commit2Mask ); installations[hsh] = uint256( uint160(address(proxy)) ) + uint256( uint256(installations[hsh]) & k_commitMask ); // saveProxyToken uint256 val = msg.value; if (data.length > 0) // solium-disable-next-line security/no-inline-assembly assembly { if eq(call(gas, proxy, val, add(data, 0x20), mload(data), 0, 0), 0) { revert(0, 0) } } emit ProxyTokenCreation(proxy); } function createProxyGroupWallet(bytes32 _domainHash, address masterCopy, bytes memory data) public payable returns (ProxyGroupWallet proxy) { uint256 c = commitments[_domainHash]; require(address(uint160(c & k_aMask))==msg.sender, "- only by initiator."); require(masterCopy != k_add00, "MasterCopy != 0x0"); proxy = new ProxyGroupWallet(masterCopy); uint256 val = msg.value; if (data.length > 0) // solium-disable-next-line security/no-inline-assembly assembly { if eq(call(gas, proxy, val, add(data, 0x20), mload(data), 0, 0), 0) { revert(0, 0) } } emit ProxyGroupWalletCreation(proxy); } function isInitiatorOrMember2(bytes32 _dHash) private view { // update(), saveColors(), saveScript() uint256 c = commitments[_dHash]; if (address(uint160(c & k_aMask))==msg.sender) return; address[] memory memArr = getOwners_internal(c); // might be optimized in GW2 uint l = memArr.length; uint index = 32; uint i=0; do { if (memArr[i] == msg.sender) return; i++; } while(i<l); require(index>=0 && index<32, " - unknown initiator or owner."); } function isInitiatorOrMember(bytes32 _dHash) private view returns (address tProxy) { // setTokenPrices(), transferOwner(), freezeToken(), transferToken(), transferTokenFrom() uint256 c = commitments[_dHash]; if (address(uint160(c & k_aMask))==msg.sender) return address( uint160( uint256( installations[ uint64( (uint256( c & k_commitMask )>>160) & k_commit2Mask ) ] ) & k_aMask ) ); address[] memory memArr = getOwners_internal(c); // might be optimized in GW2 uint l = memArr.length; uint index = 32; uint i=0; do { if (memArr[i] == msg.sender) index = i; i++; } while(i<l&&index==32); require(index>=0 && index<32, " - illegal/unknown initiator or owner."); return address( uint160( uint256( installations[ uint64( (uint256( c & k_commitMask )>>160) & k_commit2Mask ) ] ) & k_aMask ) ); } function transferOwner_v3m(bytes32 _dHash, bytes memory data) public payable { address tProxy = isInitiatorOrMember(_dHash); // solium-disable-next-line security/no-inline-assembly assembly { if eq(call(gas, tProxy, 0, add(data, 0x20), mload(data), 0, 0), 0) { revert(0, 0) } } emit TransferOwner(_dHash); } function setTokenPrices_dgw(bytes32 _dHash, bytes memory data) public payable { address tProxy = isInitiatorOrMember(_dHash); // solium-disable-next-line security/no-inline-assembly assembly { if eq(call(gas, tProxy, 0, add(data, 0x20), mload(data), 0, 0), 0) { revert(0, 0) } } emit SetPrices(_dHash); } function freezeToken_LGS(bytes32 _dHash, bytes memory data) public payable { address tProxy = isInitiatorOrMember(_dHash); // solium-disable-next-line security/no-inline-assembly assembly { if eq(call(gas, tProxy, 0, add(data, 0x20), mload(data), 0, 0), 0) { revert(0, 0) } } emit FreezeToken(_dHash); } function TransferToken_8uf(bytes32 _dHash, bytes memory data) public payable { address tProxy = isInitiatorOrMember(_dHash); // solium-disable-next-line security/no-inline-assembly assembly { if eq(call(gas, tProxy, 0, add(data, 0x20), mload(data), 0, 0), 0) { revert(0, 0) } } emit Transfer(address(this), address( uint256( uint256(mb32(substring(data,4,32))) & k_aMask )), uint256( mb32(substring(data,36,32)) ) / 100); } function TransferTokenFrom_VCv(bytes32 _dHash, bytes memory data) public payable { address tProxy = isInitiatorOrMember(_dHash); // solium-disable-next-line security/no-inline-assembly assembly { if eq(call(gas, tProxy, 0, add(data, 0x20), mload(data), 0, 0), 0) { revert(0, 0) } } emit Transfer(address( uint256( uint256(mb32(substring(data,4,32))) & k_aMask )), address( uint256( uint256(mb32(substring(data,36,32))) & k_aMask )), uint256( mb32(substring(data,68,32)) ) / 100); } function withdraw() external { require(GWFowner==msg.sender,"Only owner of GroupWalletFactory"); require(address(uint160(msg.sender)).send(address(this).balance-1),"Withdrawing ETH failed."); } function() external payable { require(false,"GroupWalletFactory fallback!"); } constructor (AbstractETHRegistrarController _controller, AbstractResolver _resolver, AbstractBaseRegistrar _base, AbstractENS _ens) public { require(address(_controller)!=k_add00,"Bad RegController!"); require(address(_resolver)!=k_add00,"Bad Resolver!"); require(address(_base)!=k_add00,"Bad base!"); require(address(_ens)!=k_add00,"Bad ens!"); GWFowner = msg.sender; controllerContract = _controller; resolverContract = _resolver; base = _base; ens = _ens; } }
install ProxyToken contract and call the Token contract immediately, masterCopy
ProxyToken proxy = new ProxyToken( address(uint160(uint256(_mem[1]))) );
571,752
[ 1, 5425, 7659, 1345, 6835, 471, 745, 326, 3155, 6835, 7636, 16, 4171, 2951, 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 ]
[ 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, 0, 0 ]
[ 1, 3639, 7659, 1345, 2889, 273, 394, 7659, 1345, 12, 1758, 12, 11890, 16874, 12, 11890, 5034, 24899, 3917, 63, 21, 65, 20349, 11272, 282, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { ERC721Holder } from "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; import { ERC1155Holder } from "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol"; import { IERC721 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; // $$$$$$$\ $$$$$$$$\ $$\ $$\ $$$$$$\ $$$$$$$\ // $$ __$$\ $$ _____|$$ | $$ | $$ __$$\ $$ __$$\ // $$ | $$ |$$ | $$ | $$ | $$ / $$ |$$ | $$ | // $$$$$$$ |$$$$$\ $$ | $$ | $$$$$$$$ |$$$$$$$ | // $$ ____/ $$ __| $$ | $$ | $$ __$$ |$$ __$$< // $$ | $$ | $$ | $$ | $$ | $$ |$$ | $$ | // $$ | $$$$$$$$\ $$$$$$$$\ $$$$$$$$\ $$ | $$ |$$ | $$ | // \__| \________|\________|\________|\__| \__|\__| \__| // // Pellar 2022 contract PellarNftAuction is ERC721Holder, ERC1155Holder, Ownable { struct AuctionItem { address owner; address contractId; uint256 tokenId; uint256 reservePrice; uint256 startAt; uint256 endAt; address highestBidder; uint256 highestBid; uint256 bidCount; uint256 blockNumber; } // variables uint256 public windowTime = 5 minutes; mapping(bytes32 => AuctionItem) public auctionItems; mapping(bytes32 => uint256) public latestPrice; mapping(bytes32 => bool) public auctionEntered; // events event ItemListed(address indexed _contractId, uint256 indexed _tokenId, address indexed _sender, uint256 _reservePrice, uint256 _startAt, uint256 _endAt); event ItemBidded(address indexed _contractId, uint256 indexed _tokenId, address _newBidder, uint256 _newAmount, address indexed _oldBidder, uint256 _oldAmount, uint256 _bidCount); event AuctionWinnerWithdrawals(address indexed _contractId, uint256 indexed _tokenId, address indexed _winner, uint256 _highestBid); /* User */ // verified function bid(address _contractId, uint256 _tokenId) external payable nonReentrant(_contractId, _tokenId) { (bytes32 auctionId, ) = getAuctionAndBid(_contractId, _tokenId); AuctionItem storage auctionItem = auctionItems[auctionId]; require(tx.origin == msg.sender, "Not allowed"); require(block.timestamp >= auctionItem.startAt, "Auction inactive"); // require auction starts require(block.timestamp <= auctionItem.endAt, "Auction ended"); // require auction not ended require(auctionItem.owner != msg.sender && auctionItem.owner != address(0), "Not allowed"); // require not owner or not listed auction item require(msg.value > auctionItem.highestBid && msg.value > auctionItem.reservePrice, "Bid underpriced"); // require valid ether value address oldBidder = auctionItem.highestBidder; uint256 oldAmount = auctionItem.highestBid; if (oldBidder != address(0)) { // funds return for previous payable(oldBidder).transfer(oldAmount); } // update state auctionItem.highestBidder = msg.sender; auctionItem.highestBid = msg.value; auctionItem.bidCount++; latestPrice[auctionId] = msg.value; if (block.timestamp + windowTime >= auctionItem.endAt) { auctionItem.endAt += windowTime; } // event emit ItemBidded(_contractId, _tokenId, msg.sender, msg.value, oldBidder, oldAmount, auctionItem.bidCount); } // verified function withdrawProductWon(address _contractId, uint256 _tokenId) external { (bytes32 auctionId, ) = getAuctionAndBid(_contractId, _tokenId); AuctionItem memory auctionItem = auctionItems[auctionId]; require(block.timestamp > auctionItem.endAt, "Auction active!"); // need auction to end require(msg.sender == auctionItem.highestBidder || msg.sender == owner(), "Winner only!"); // need winner address winner = auctionItem.highestBidder; auctionItem.highestBidder = address(0); // convert state to address 0 IERC721(_contractId).transferFrom(address(this), winner, _tokenId); // event emit AuctionWinnerWithdrawals(_contractId, _tokenId, winner, auctionItem.highestBid); } /* Admin */ function setWindowTime(uint256 _time) external onlyOwner { windowTime = _time; } // verified function createAuction(address _contractId, uint256 _tokenId, uint256 _reservePrice, uint256 _startAt, uint256 _endAt) external onlyOwner { (bytes32 auctionId, ) = getAuctionAndBid(_contractId, _tokenId); require(_endAt >= block.timestamp && _startAt < _endAt, "Input invalid"); require(IERC721(_contractId).ownerOf(_tokenId) == msg.sender, "Not allowed"); // require owner require(latestPrice[auctionId] == 0, "Need withdraw"); // need withdraw first if bid this product again IERC721(_contractId).transferFrom(msg.sender, address(this), _tokenId); auctionItems[auctionId] = AuctionItem({ owner: msg.sender, contractId: _contractId, tokenId: _tokenId, reservePrice: _reservePrice, startAt: _startAt, endAt: _endAt, highestBidder: address(0), highestBid: 0, bidCount: 0, blockNumber: block.number }); // emit emit ItemListed(_contractId, _tokenId, msg.sender, _reservePrice, _startAt, _endAt); } // verified function withdraw(address _contractId, uint256 _tokenId) external onlyOwner { (bytes32 auctionId, ) = getAuctionAndBid(_contractId, _tokenId); AuctionItem storage auctionItem = auctionItems[auctionId]; require(block.timestamp > auctionItem.endAt, "Auction active!"); require(latestPrice[auctionId] > 0, "No bids!"); uint256 amount = latestPrice[auctionId]; latestPrice[auctionId] = 0; // non reentrancy security payable(msg.sender).transfer(amount); } // verified function withdrawFailedAuction(address _contractId, uint256 _tokenId) external onlyOwner { (bytes32 auctionId, ) = getAuctionAndBid(_contractId, _tokenId); AuctionItem memory auctionItem = auctionItems[auctionId]; require(block.timestamp > auctionItem.endAt, "Auction active!"); require(auctionItem.bidCount == 0, "Action has bids!"); IERC721(_contractId).transferFrom(address(this), msg.sender, _tokenId); } /* View */ function getAuctionAndBid(address _contractId, uint256 _tokenId) public view returns (bytes32 _auctionId, AuctionItem memory _auctionItem) { _auctionId = keccak256(abi.encodePacked(_contractId, _tokenId)); _auctionItem = auctionItems[_auctionId]; } /* Security */ modifier nonReentrant(address _contractId, uint256 _tokenId) { (bytes32 auctionId, ) = getAuctionAndBid(_contractId, _tokenId); require(!auctionEntered[auctionId], "ReentrancyGuard: reentrant call"); auctionEntered[auctionId] = true; _; auctionEntered[auctionId] = false; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721Receiver.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721Holder is IERC721Receiver { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC1155Receiver.sol"; /** * @dev _Available since v3.1._ */ contract ERC1155Holder is ERC1155Receiver { function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } } // 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 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; /** * @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 "../IERC1155Receiver.sol"; import "../../../utils/introspection/ERC165.sol"; /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
require not owner or not listed auction item
require(auctionItem.owner != msg.sender && auctionItem.owner != address(0), "Not allowed");
47,671
[ 1, 6528, 486, 3410, 578, 486, 12889, 279, 4062, 761, 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, 2583, 12, 69, 4062, 1180, 18, 8443, 480, 1234, 18, 15330, 597, 279, 4062, 1180, 18, 8443, 480, 1758, 12, 20, 3631, 315, 1248, 2935, 8863, 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 ]
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; import "./Kyber/KyberNetworkProxyInterface.sol"; import "./dydx/DyDxFlashloan.sol"; contract DyDxFlashloanArb is DyDxFlashLoan{ address arbOwner; KyberNetworkProxyInterface public proxy; ERC20 constant internal ETH_TOKEN_ADDRESS = ERC20(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee); ERC20 constant internal wethToken = ERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); ERC20 constant internal wbtcToken = ERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); constructor(KyberNetworkProxyInterface _proxy) public payable { // The loan is initiated by the borrower proxy = _proxy; arbOwner = msg.sender; (bool success, ) = WETH.call.value(msg.value)(""); require(success, "fail to get weth"); } modifier onlyOwner () { require(msg.sender == arbOwner); _; } function () external payable {} function getFlashloan( address _flashToken, uint256 _flashAmount ) external { uint256 _balanceBefore = IERC20(_flashToken).balanceOf(address(this)); bytes memory _data = abi.encode(_flashToken, _flashAmount, _balanceBefore); flashloan(_flashToken, _flashAmount, _data); // execution goes to `callFunction` // and this point we have succefully paid the dept } // dydx call back function callFunction( address, // sender Info calldata, // accountInfo bytes calldata _data ) external onlyPool { (address flashToken, uint256 flashAmount, uint256 balanceBefore) = abi.decode(_data, (address, uint256, uint256)); uint256 balanceAfter = IERC20(flashToken).balanceOf(address(this)); require(balanceAfter - balanceBefore == flashAmount, "contract did not get the loan"); arbTrade(); } function arbTrade() public { uint wethQty = wethToken.balanceOf(address(this)); _kyberTrade(wethToken, wethQty, wbtcToken, address(this)); //_uniswapTrade(); } function _kyberTrade( ERC20 srcToken, uint srcQty, ERC20 destToken, address destAddress ) internal { uint minConversionRate; // Mitigate ERC20 Approve front-running attack, by initially setting // allowance to 0 require(srcToken.approve(address(proxy), 0)); // Set the spender's token allowance to tokenQty require(srcToken.approve(address(proxy), srcQty)); // Get the minimum conversion rate (minConversionRate,) = proxy.getExpectedRate(srcToken, ETH_TOKEN_ADDRESS, srcQty); // Swap the ERC20 token to ETH // this works with bnt, but not with wbtc. //uint destAmount = proxy.swapTokenToToken(srcToken, srcQty, destToken, minConversionRate); uint weth_to_eth = proxy.tradeWithHint( srcToken, // source ERC20 token contract address srcQty, // source ERC20 token amount in its token decimals ETH_TOKEN_ADDRESS, // destination ERC20 token contract address address(this), // recipient address for destination ERC20 token 10**28, // A limit on the amount of dest tokens minConversionRate, // The minimal conversion rate. If actual rate is lower, trade is canceled. address(0x0), // wallet address to send part of the fees to "PERM" ); uint _wbtcexpectedRate; (_wbtcexpectedRate,) = proxy.getExpectedRate(ETH_TOKEN_ADDRESS, destToken, weth_to_eth); // uint destAmount = proxy.tradeWithHint.value(weth_to_eth)( ETH_TOKEN_ADDRESS, // source ERC20 token contract address weth_to_eth, //weth_to_eth, // source ERC20 token amount in its token decimals destToken, // destination ERC20 token contract address address(this), // recipient address for destination ERC20 token 10**30, // A limit on the amount of dest tokens _wbtcexpectedRate, // The minimal conversion rate. If actual rate is lower, trade is canceled. address(0xx), // wallet address to send part of the fees to "PERM" ); } function _uniSwapTrade( ERC20 srcToken, uint256 tokenSold, uint256 _maxTokensSell ) internal { // } }
and this point we have succefully paid the dept
function getFlashloan( address _flashToken, uint256 _flashAmount ) external { uint256 _balanceBefore = IERC20(_flashToken).balanceOf(address(this)); bytes memory _data = abi.encode(_flashToken, _flashAmount, _balanceBefore); }
949,836
[ 1, 464, 333, 1634, 732, 1240, 8667, 311, 4095, 30591, 326, 443, 337, 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, 225, 445, 28081, 383, 304, 12, 203, 565, 1758, 389, 13440, 1345, 16, 203, 565, 2254, 5034, 389, 13440, 6275, 203, 225, 262, 203, 565, 3903, 203, 225, 288, 203, 1377, 2254, 5034, 389, 12296, 4649, 273, 467, 654, 39, 3462, 24899, 13440, 1345, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 1377, 1731, 3778, 389, 892, 273, 24126, 18, 3015, 24899, 13440, 1345, 16, 389, 13440, 6275, 16, 389, 12296, 4649, 1769, 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 ]
pragma solidity ^0.4.17; interface Deployer_Interface { function newContract(address _party, address user_contract, uint _start_date) public payable returns (address created); function newToken() public returns (address created); } interface DRCT_Token_Interface { function addressCount(address _swap) public constant returns (uint count); function getHolderByIndex(uint _ind, address _swap) public constant returns (address holder); function getBalanceByIndex(uint _ind, address _swap) public constant returns (uint bal); function getIndexByAddress(address _owner, address _swap) public constant returns (uint index); function createToken(uint _supply, address _owner, address _swap) public; function pay(address _party, address _swap) public; function partyCount(address _swap) public constant returns(uint count); } interface Wrapped_Ether_Interface { function totalSupply() public constant returns (uint total_supply); function balanceOf(address _owner) public constant returns (uint balance); function transfer(address _to, uint _amount) public returns (bool success); function transferFrom(address _from, address _to, uint _amount) public returns (bool success); function approve(address _spender, uint _amount) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint amount); function withdraw(uint _value) public; function CreateToken() public; } library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function min(uint a, uint b) internal pure returns (uint256) { return a < b ? a : b; } } //The Factory contract sets the standardized variables and also deploys new contracts based on these variables for the user. contract Factory { using SafeMath for uint256; //Addresses of the Factory owner and oracle. For oracle information, check www.github.com/DecentralizedDerivatives/Oracles address public owner; address public oracle_address; //Address of the user contract address public user_contract; DRCT_Token_Interface drct_interface; Wrapped_Ether_Interface token_interface; //Address of the deployer contract address deployer_address; Deployer_Interface deployer; Deployer_Interface tokenDeployer; address token_deployer_address; address public token_a; address public token_b; //A fee for creating a swap in wei. Plan is for this to be zero, however can be raised to prevent spam uint public fee; //Duration of swap contract in days uint public duration; //Multiplier of reference rate. 2x refers to a 50% move generating a 100% move in the contract payout values uint public multiplier; //Token_ratio refers to the number of DRCT Tokens a party will get based on the number of base tokens. As an example, 1e15 indicates that a party will get 1000 DRCT Tokens based upon 1 ether of wrapped wei. uint public token_ratio1; uint public token_ratio2; //Array of deployed contracts address[] public contracts; mapping(address => uint) public created_contracts; mapping(uint => address) public long_tokens; mapping(uint => address) public short_tokens; //Emitted when a Swap is created event ContractCreation(address _sender, address _created); /*Modifiers*/ modifier onlyOwner() { require(msg.sender == owner); _; } /*Functions*/ // Constructor - Sets owner function Factory() public { owner = msg.sender; } function getTokens(uint _date) public view returns(address _ltoken, address _stoken){ return(long_tokens[_date],short_tokens[_date]); } /* * Updates the fee amount * @param "_fee": The new fee amount */ function setFee(uint _fee) public onlyOwner() { fee = _fee; } /* * Sets the deployer address * @param "_deployer": The new deployer address */ function setDeployer(address _deployer) public onlyOwner() { deployer_address = _deployer; deployer = Deployer_Interface(_deployer); } /* * Sets the token_deployer address * @param "_tdeployer": The new token deployer address */ function settokenDeployer(address _tdeployer) public onlyOwner() { token_deployer_address = _tdeployer; tokenDeployer = Deployer_Interface(_tdeployer); } /* * Sets the user_contract address * @param "_userContract": The new userContract address */ function setUserContract(address _userContract) public onlyOwner() { user_contract = _userContract; } /* * Returns the base token addresses */ function getBase() public view returns(address _base1, address base2){ return (token_a, token_b); } /* * Sets token ratio, swap duration, and multiplier variables for a swap * @param "_token_ratio1": The ratio of the first token * @param "_token_ratio2": The ratio of the second token * @param "_duration": The duration of the swap, in seconds * @param "_multiplier": The multiplier used for the swap */ function setVariables(uint _token_ratio1, uint _token_ratio2, uint _duration, uint _multiplier) public onlyOwner() { token_ratio1 = _token_ratio1; token_ratio2 = _token_ratio2; duration = _duration; multiplier = _multiplier; } /* * Sets the addresses of the tokens used for the swap * @param "_token_a": The address of a token to be used * @param "_token_b": The address of another token to be used */ function setBaseTokens(address _token_a, address _token_b) public onlyOwner() { token_a = _token_a; token_b = _token_b; } //Allows a user to deploy a new swap contract, if they pay the fee //returns the newly created swap address and calls event 'ContractCreation' function deployContract(uint _start_date) public payable returns (address created) { require(msg.value >= fee); address new_contract = deployer.newContract(msg.sender, user_contract, _start_date); contracts.push(new_contract); created_contracts[new_contract] = _start_date; ContractCreation(msg.sender,new_contract); return new_contract; } function deployTokenContract(uint _start_date, bool _long) public returns(address _token) { address token; if (_long){ require(long_tokens[_start_date] == address(0)); token = tokenDeployer.newToken(); long_tokens[_start_date] = token; } else{ require(short_tokens[_start_date] == address(0)); token = tokenDeployer.newToken(); short_tokens[_start_date] = token; } return token; } /* * Deploys new tokens on a DRCT_Token contract -- called from within a swap * @param "_supply": The number of tokens to create * @param "_party": The address to send the tokens to * @param "_long": Whether the party is long or short * @returns "created": The address of the created DRCT token * @returns "token_ratio": The ratio of the created DRCT token */ function createToken(uint _supply, address _party, bool _long, uint _start_date) public returns (address created, uint token_ratio) { require(created_contracts[msg.sender] > 0); address ltoken = long_tokens[_start_date]; address stoken = short_tokens[_start_date]; require(ltoken != address(0) && stoken != address(0)); if (_long) { drct_interface = DRCT_Token_Interface(ltoken); drct_interface.createToken(_supply.div(token_ratio1), _party,msg.sender); return (ltoken, token_ratio1); } else { drct_interface = DRCT_Token_Interface(stoken); drct_interface.createToken(_supply.div(token_ratio2), _party,msg.sender); return (stoken, token_ratio2); } } //Allows the owner to set a new oracle address function setOracleAddress(address _new_oracle_address) public onlyOwner() { oracle_address = _new_oracle_address; } //Allows the owner to set a new owner address function setOwner(address _new_owner) public onlyOwner() { owner = _new_owner; } //Allows the owner to pull contract creation fees function withdrawFees() public onlyOwner() returns(uint atok, uint btok, uint _eth){ token_interface = Wrapped_Ether_Interface(token_a); uint aval = token_interface.balanceOf(address(this)); if(aval > 0){ token_interface.withdraw(aval); } token_interface = Wrapped_Ether_Interface(token_b); uint bval = token_interface.balanceOf(address(this)); if (bval > 0){ token_interface.withdraw(bval); } owner.transfer(this.balance); return(aval,bval,this.balance); } function() public payable { } /* * Returns a tuple of many private variables * @returns "_oracle_adress": The address of the oracle * @returns "_operator": The address of the owner and operator of the factory * @returns "_duration": The duration of the swap * @returns "_multiplier": The multiplier for the swap * @returns "token_a_address": The address of token a * @returns "token_b_address": The address of token b * @returns "start_date": The start date of the swap */ function getVariables() public view returns (address oracle_addr, uint swap_duration, uint swap_multiplier, address token_a_addr, address token_b_addr){ return (oracle_address,duration, multiplier, token_a, token_b); } /* * Pays out to a DRCT token * @param "_party": The address being paid * @param "_long": Whether the _party is long or not */ function payToken(address _party, address _token_add) public { require(created_contracts[msg.sender] > 0); drct_interface = DRCT_Token_Interface(_token_add); drct_interface.pay(_party, msg.sender); } //Returns the number of contracts created by this factory function getCount() public constant returns(uint count) { return contracts.length; } }
Returns a tuple of many private variables @returns "_oracle_adress": The address of the oracle @returns "_operator": The address of the owner and operator of the factory @returns "_duration": The duration of the swap @returns "_multiplier": The multiplier for the swap @returns "token_a_address": The address of token a @returns "token_b_address": The address of token b @returns "start_date": The start date of the swap/
function getVariables() public view returns (address oracle_addr, uint swap_duration, uint swap_multiplier, address token_a_addr, address token_b_addr){ return (oracle_address,duration, multiplier, token_a, token_b); }
7,222,649
[ 1, 1356, 279, 3193, 434, 4906, 3238, 3152, 1135, 4192, 280, 16066, 67, 361, 663, 6877, 1021, 1758, 434, 326, 20865, 1135, 4192, 9497, 6877, 1021, 1758, 434, 326, 3410, 471, 3726, 434, 326, 3272, 1135, 4192, 8760, 6877, 1021, 3734, 434, 326, 7720, 1135, 4192, 20538, 6877, 1021, 15027, 364, 326, 7720, 1135, 315, 2316, 67, 69, 67, 2867, 6877, 1021, 1758, 434, 1147, 279, 1135, 315, 2316, 67, 70, 67, 2867, 6877, 1021, 1758, 434, 1147, 324, 1135, 315, 1937, 67, 712, 6877, 1021, 787, 1509, 434, 326, 7720, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 28180, 1435, 1071, 1476, 1135, 261, 2867, 20865, 67, 4793, 16, 2254, 7720, 67, 8760, 16, 2254, 7720, 67, 20538, 16, 1758, 1147, 67, 69, 67, 4793, 16, 1758, 1147, 67, 70, 67, 4793, 15329, 203, 565, 327, 261, 280, 16066, 67, 2867, 16, 8760, 16, 15027, 16, 1147, 67, 69, 16, 1147, 67, 70, 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, -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/0x49c590F6a2dfB0f809E82B9e2BF788C0Dd1c31f9/sources/@mean-finance/dca-v2-periphery/contracts/DCAHubCompanion/DCAHubCompanionHubProxyHandler.sol
@inheritdoc IDCAHubCompanionHubProxyHandler
function reducePosition( IDCAHub _hub, uint256 _positionId, uint256 _amount, uint32 _newSwaps, address _recipient ) external payable verifyPermission(_hub, _positionId, IDCAPermissionManager.Permission.REDUCE) { _hub.reducePosition(_positionId, _amount, _newSwaps, _recipient); }
2,852,602
[ 1, 36, 10093, 1599, 3587, 8182, 2945, 304, 285, 8182, 3886, 1503, 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 ]
[ 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, 0 ]
[ 1, 225, 445, 5459, 2555, 12, 203, 565, 1599, 3587, 8182, 389, 14986, 16, 203, 565, 2254, 5034, 389, 3276, 548, 16, 203, 565, 2254, 5034, 389, 8949, 16, 203, 565, 2254, 1578, 389, 2704, 6050, 6679, 16, 203, 565, 1758, 389, 20367, 203, 225, 262, 3903, 8843, 429, 3929, 5041, 24899, 14986, 16, 389, 3276, 548, 16, 1599, 17296, 2635, 1318, 18, 5041, 18, 5879, 57, 1441, 13, 288, 203, 565, 389, 14986, 18, 12498, 2555, 24899, 3276, 548, 16, 389, 8949, 16, 389, 2704, 6050, 6679, 16, 389, 20367, 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 ]
pragma solidity 0.5.16; import "@openzeppelin/contracts/math/Math.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./CompleteCToken.sol"; import "../../hardworkInterface/IStrategy.sol"; import "../../weth/WETH9.sol"; import "@studydefi/money-legos/compound/contracts/ICEther.sol"; contract CompoundInteractor is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public underlying; IERC20 public _weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); CompleteCToken public ctoken; ComptrollerInterface public comptroller; constructor( address _underlying, address _ctoken, address _comptroller ) public { // Comptroller: comptroller = ComptrollerInterface(_comptroller); underlying = IERC20(_underlying); ctoken = CompleteCToken(_ctoken); // Enter the market address[] memory cTokens = new address[](1); cTokens[0] = _ctoken; comptroller.enterMarkets(cTokens); } /** * Supplies Ether to Compound * Unwraps WETH to Ether, then invoke the special mint for cEther * We ask to supply "amount", if the "amount" we asked to supply is * more than balance (what we really have), then only supply balance. * If we the "amount" we want to supply is less than balance, then * only supply that amount. */ function _supplyEtherInWETH(uint256 amountInWETH) internal nonReentrant { // underlying here is WETH uint256 balance = underlying.balanceOf(address(this)); // supply at most "balance" if (amountInWETH < balance) { balance = amountInWETH; // only supply the "amount" if its less than what we have } WETH9 weth = WETH9(address(_weth)); weth.withdraw(balance); // Unwrapping ICEther(address(ctoken)).mint.value(balance)(); } /** * Redeems Ether from Compound * receives Ether. Wrap all the ether that is in this contract. */ function _redeemEtherInCTokens(uint256 amountCTokens) internal nonReentrant { _redeemInCTokens(amountCTokens); WETH9 weth = WETH9(address(_weth)); weth.deposit.value(address(this).balance)(); } /** * Supplies to Compound */ function _supply(uint256 amount) internal returns(uint256) { uint256 balance = underlying.balanceOf(address(this)); if (amount < balance) { balance = amount; } underlying.safeApprove(address(ctoken), 0); underlying.safeApprove(address(ctoken), balance); uint256 mintResult = ctoken.mint(balance); require(mintResult == 0, "Supplying failed"); return balance; } /** * Borrows against the collateral */ function _borrow( uint256 amountUnderlying ) internal { // Borrow DAI, check the DAI balance for this contract's address uint256 result = ctoken.borrow(amountUnderlying); require(result == 0, "Borrow failed"); } /** * Borrows against the collateral */ function _borrowInWETH( uint256 amountUnderlying ) internal { // Borrow ETH, wraps into WETH uint256 result = ctoken.borrow(amountUnderlying); require(result == 0, "Borrow failed"); WETH9 weth = WETH9(address(_weth)); weth.deposit.value(address(this).balance)(); } /** * Repays a loan */ function _repay(uint256 amountUnderlying) internal { underlying.safeApprove(address(ctoken), 0); underlying.safeApprove(address(ctoken), amountUnderlying); ctoken.repayBorrow(amountUnderlying); underlying.safeApprove(address(ctoken), 0); } /** * Repays a loan in ETH */ function _repayInWETH(uint256 amountUnderlying) internal { WETH9 weth = WETH9(address(_weth)); weth.withdraw(amountUnderlying); // Unwrapping ICEther(address(ctoken)).repayBorrow.value(amountUnderlying)(); } /** * Redeem liquidity in cTokens */ function _redeemInCTokens(uint256 amountCTokens) internal { if(amountCTokens > 0){ ctoken.redeem(amountCTokens); } } /** * Redeem liquidity in underlying */ function _redeemUnderlying(uint256 amountUnderlying) internal { if (amountUnderlying > 0) { ctoken.redeemUnderlying(amountUnderlying); } } /** * Redeem liquidity in underlying */ function redeemUnderlyingInWeth(uint256 amountUnderlying) internal { if (amountUnderlying > 0) { _redeemUnderlying(amountUnderlying); WETH9 weth = WETH9(address(_weth)); weth.deposit.value(address(this).balance)(); } } /** * Get COMP */ function claimComp() public { comptroller.claimComp(address(this)); } /** * Redeem the minimum of the WETH we own, and the WETH that the cToken can * immediately retrieve. Ensures that `redeemMaximum` doesn't fail silently */ function redeemMaximumWeth() internal { // amount of WETH in contract uint256 available = ctoken.getCash(); // amount of WETH we own uint256 owned = ctoken.balanceOfUnderlying(address(this)); // redeem the most we can redeem redeemUnderlyingInWeth(available < owned ? available : owned); } function redeemMaximumWethWithLoan( uint256 collateralFactorNumerator, uint256 collateralFactorDenominator, uint256 borrowMinThreshold ) internal { // amount of liquidity in Compound uint256 available = ctoken.getCash(); // amount of WETH we supplied uint256 supplied = ctoken.balanceOfUnderlying(address(this)); // amount of WETH we borrowed uint256 borrowed = ctoken.borrowBalanceCurrent(address(this)); while (borrowed > borrowMinThreshold) { uint256 requiredCollateral = borrowed .mul(collateralFactorDenominator) .add(collateralFactorNumerator.div(2)) .div(collateralFactorNumerator); // redeem just as much as needed to repay the loan uint256 wantToRedeem = supplied.sub(requiredCollateral); redeemUnderlyingInWeth(Math.min(wantToRedeem, available)); // now we can repay our borrowed amount uint256 balance = underlying.balanceOf(address(this)); _repayInWETH(Math.min(borrowed, balance)); // update the parameters available = ctoken.getCash(); borrowed = ctoken.borrowBalanceCurrent(address(this)); supplied = ctoken.balanceOfUnderlying(address(this)); } // redeem the most we can redeem redeemUnderlyingInWeth(Math.min(available, supplied)); } function getLiquidity() external view returns(uint256) { return ctoken.getCash(); } function redeemMaximumToken() internal { // amount of tokens in ctoken uint256 available = ctoken.getCash(); // amount of tokens we own uint256 owned = ctoken.balanceOfUnderlying(address(this)); // redeem the most we can redeem _redeemUnderlying(available < owned ? available : owned); } function () external payable {} // this is needed for the WETH unwrapping }
only supply the "amount" if its less than what we have
balance = amountInWETH;
1,020,603
[ 1, 3700, 14467, 326, 315, 8949, 6, 309, 2097, 5242, 2353, 4121, 732, 1240, 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 ]
[ 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, 0, 0 ]
[ 1, 1377, 11013, 273, 3844, 382, 59, 1584, 44, 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 ]
pragma solidity 0.5.10; import './DecentralizedStore.sol'; import '../node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol'; import '../node_modules/openzeppelin-solidity/contracts/lifecycle/Pausable.sol'; /* * @title Marketplace * * @dev @notice This contract allows the users to operate different functions based on their roles * */ contract Marketplace is Ownable, Pausable{ //DecentralizedStore Instance DecentralizedStore public decentralizedStoreInstance; /** * @dev Constructor * @param DecentralizedStoreAddress adress of DecentralizedStore contract */ constructor(address DecentralizedStoreAddress) public { decentralizedStoreInstance = DecentralizedStore(DecentralizedStoreAddress); } /** * @dev Struct * @param idMarketplace Market Id * @param marketName Market name * @param marketOwner address of the market Owner * @param credit Market credit */ struct Market { bytes32 idMarketplace; string marketName; address marketOwner; uint credit; } /** * @dev Struct * @param productId Product Id * @param productName Product name * @param description description of the Product * @param price price of the Product * @param stock stock of the product in a market * @param idMarketplace Market Id */ struct Product { bytes32 productId; string productName; string description; uint price; uint stock; bytes32 idMarketplace; } //All markets bytes32[] private marketList; //Map of Markets with an index mapping(bytes32 => uint) private marketMap; //Map of markets mapping(bytes32 => Market) private marketIdList; // Map of owners mapping(address => bytes32[]) private marketOwnerMapping; //Map of products mapping(bytes32 => Product) private productMap; //Map of procucts by their market mapping(bytes32 => bytes32[]) private productsMarketMap; //Events event LogNewMarket(bytes32 idMarketplace); event LogdeleteMarket(bytes32 idMarketplace); event LogProductAdded(bytes32 productId); event LogProductRemoved (bytes32 productId,bytes32 storefrontId); event LogCredit(bytes32 idMarketplace, uint balance); event LogSold(bytes32 productId, bytes32 idMarketplace, uint price, uint quantity, uint amount, address customer, uint updatetStock); // Modifier to restrict features usage to owners previously approved modifier onlyApprovedStoreOwner() { require(decentralizedStoreInstance.isOwnerApproved(msg.sender) == true,"Error"); _; } // Modifier to restrict features usage to the owner which create the marketplace modifier ownerRestricted(bytes32 idMarketplace) { require(marketIdList[idMarketplace].marketOwner == msg.sender,"Error"); _; } /** * @dev @notice create new marketplace * @param marketName Name of the marketplace * @return idMarketplace */ function addMarket(string memory marketName) public onlyApprovedStoreOwner whenNotPaused returns(bytes32){ bytes32 idMarketplace = keccak256(abi.encodePacked(msg.sender, marketName, now)); Market memory market = Market(idMarketplace, marketName, msg.sender, 0); marketIdList[idMarketplace] = market; marketOwnerMapping[msg.sender].push(market.idMarketplace); marketList.push(market.idMarketplace); marketMap[market.idMarketplace] = marketList.length-1; emit LogNewMarket(market.idMarketplace); return market.idMarketplace; } /** * @dev @notice obtain the id knowning the Owner * @param marketOwner address of the market owner * @param index Market owner index * @return idMarketplace */ function getIdGivenOwner(address marketOwner, uint index) public view returns(bytes32) { return marketOwnerMapping[marketOwner][index]; } /** * @dev @notice return the number of markets an owner have * @param marketOwner address of the owner * @return number of market */ function getNumberGivenOwner(address marketOwner) public view returns(uint){ return marketOwnerMapping[marketOwner].length; } /** * @dev @notice Delete a Marketplace, input id * @param idMarketplace Id of the market */ function deleteMarketplace(bytes32 idMarketplace) public onlyApprovedStoreOwner ownerRestricted(idMarketplace) whenNotPaused { deleteAllProducts(idMarketplace); uint index = marketMap[idMarketplace]; if (marketList.length > 1) { marketList[index] = marketList[marketList.length-1]; } marketList.length--; uint length = marketOwnerMapping[msg.sender].length; for (uint i = 0; i < length; i++) { if(marketOwnerMapping[msg.sender][i] == idMarketplace){ if(i!=length-1){ marketOwnerMapping[msg.sender][i] = marketOwnerMapping[msg.sender][length-1]; } delete marketOwnerMapping[msg.sender][length-1]; marketOwnerMapping[msg.sender].length--; break; } } uint balance = marketIdList[idMarketplace].credit; if (balance > 0) { msg.sender.transfer(balance); marketIdList[idMarketplace].credit = 0; emit LogCredit(idMarketplace, balance); } delete marketIdList[idMarketplace]; emit LogdeleteMarket(idMarketplace); } /** * @dev @notice return the owner of a known marketblapce identified by an id * @param idMarketplace Id of the market * @return marketOwner address */ function getOwnerGivenMarketplaceId(bytes32 idMarketplace) public view returns(address){ return marketIdList[idMarketplace].marketOwner; } /** * @dev @notice return the name of a known marketplapce identified by an id * @param idMarketplace Id of the market * @return marketName */ function getMarketplaceName(bytes32 idMarketplace) public view returns(string memory){ return marketIdList[idMarketplace].marketName; } /** * @dev @notice return the number of markets created * @return number */ function getMarketNumber() public view returns (uint) { return marketList.length; } /** * @dev @notice create a new product in the marketplace identified by the id * @param idMarketplace Id of the market * @param productName Name of the product * @param description Description of the product * @param price price of the product * @param stock stock of the product * @return productId */ function addProductToMarket(bytes32 idMarketplace, string memory productName, string memory description, uint price, uint stock) public onlyApprovedStoreOwner ownerRestricted(idMarketplace) whenNotPaused returns(bytes32){ bytes32 productId = keccak256(abi.encodePacked(idMarketplace, productName, now)); Product memory product = Product(productId, productName, description, price, stock, idMarketplace); productMap[productId] = product; productsMarketMap[idMarketplace].push(product.productId); emit LogProductAdded(product.productId); return product.productId; } /** * @dev @notice return the products in a marketplace * @param idMarketplace Id of the market * @return list of id */ function getProductOfMarketplace(bytes32 idMarketplace) public view returns(bytes32[] memory){ return productsMarketMap[idMarketplace]; } /** * @dev @notice return the id of the products of a marketplace * @param idMarketplace Id of the market * @param index product in a market * @return productid */ function getProductOfMarket(bytes32 idMarketplace, uint index) public view returns(bytes32){ return productsMarketMap[idMarketplace][index]; } /** * @dev @notice return the numer of products * @param idMarketplace Id * @return number */ function getProductNumberGivenMarketId(bytes32 idMarketplace) public view returns(uint){ return productsMarketMap[idMarketplace].length; } /** * @dev @notice return all the informations of a product knowing its id * @param productId id of the product * @return productData */ function getProductData(bytes32 productId) public view returns (string memory, string memory, uint, uint, bytes32){ return (productMap[productId].productName, productMap[productId].description, productMap[productId].price, productMap[productId].stock, productMap[productId].idMarketplace); } /** * @dev @notice empty the marketplace * @param idMarketplace Id */ function deleteAllProducts(bytes32 idMarketplace) public onlyApprovedStoreOwner ownerRestricted(idMarketplace) whenNotPaused{ for (uint i = 0; i < productsMarketMap[idMarketplace].length; i++) { bytes32 productId = productsMarketMap[idMarketplace][i]; delete productsMarketMap[idMarketplace][i]; delete productMap[productId]; } } /** * @dev @notice delete a product * @param idMarketplace Id of the market * @param productId Id of the Product */ function deleteProductGivenMarketId(bytes32 idMarketplace, bytes32 productId) public onlyApprovedStoreOwner ownerRestricted(idMarketplace) whenNotPaused{ bytes32[] memory productIds = productsMarketMap[idMarketplace]; uint productsCount = productIds.length; for(uint i = 0; i < productsCount; i++) { if (productIds[i] == productId) { productIds[i] = productIds[productsCount-1]; delete productIds[productsCount-1]; productsMarketMap[idMarketplace] = productIds; delete productMap[productId]; emit LogProductRemoved(productId, idMarketplace); break; } } } /** * @dev @notice buy a product in a marketplace * @param idMarketplace Id of the market * @param productId Id of the Product * @param stock how much to buy * @return true if success */ function buy(bytes32 idMarketplace, bytes32 productId, uint stock) public payable whenNotPaused returns(bool){ Product storage productBuy = productMap[productId]; Market storage market = marketIdList[idMarketplace]; require(market.marketOwner != msg.sender,"Error"); uint amount = productBuy.price*stock; require(msg.value >= amount,"Error"); require (stock <= productBuy.stock,"Error"); uint remainingValue = msg.value-amount; msg.sender.transfer(remainingValue); productBuy.stock -= stock; market.credit += amount; emit LogSold(productId, idMarketplace, productBuy.price, stock, amount, msg.sender, productBuy.stock); return true; } }
Modifier to restrict features usage to the owner which create the marketplace
modifier ownerRestricted(bytes32 idMarketplace) { require(marketIdList[idMarketplace].marketOwner == msg.sender,"Error"); _; }
12,656,900
[ 1, 9829, 358, 13108, 4467, 4084, 358, 326, 3410, 1492, 752, 326, 29917, 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, 9606, 3410, 18784, 12, 3890, 1578, 612, 3882, 24577, 13, 288, 203, 3639, 2583, 12, 27151, 22117, 63, 350, 3882, 24577, 8009, 27151, 5541, 422, 1234, 18, 15330, 10837, 668, 8863, 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 ]
./full_match/97/0xd95361ff0DE4e98f753e9e886596E45a128275bC/sources/project:/contracts/TransparentDontacion.sol
Return the number of projects.
return projects.length;
5,020,006
[ 1, 990, 326, 1300, 434, 10137, 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, 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, 3639, 327, 10137, 18, 2469, 31, 282, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "./ERC721Common.sol"; // To read more about NFTs, checkout the ERC721 standard: // https://eips.ethereum.org/EIPS/eip-721 /** * @title NFT * SimpleNFT - A concrete NFT contract implementation that can optionally inherit from several Mixins for added functionality or directly from ERC721Common for a barebones implementation. */ contract MichaelDeployedContract is ERC721Common { using Counters for Counters.Counter; Counters.Counter private _nextTokenId; /** * @dev Replace with your own unique name and symbol */ constructor() ERC721Common("MichaelDeployedContract", "MCD") { // nextTokenId is initialized to 1, since starting at 0 leads to higher gas cost for the first minter _nextTokenId.increment(); } function mint(address _to) public virtual returns (uint256) { uint256 currentTokenId = _nextTokenId.current(); _nextTokenId.increment(); _safeMint(_to, currentTokenId); return currentTokenId; } function baseTokenURI() public override pure returns (string memory) { return "https://creatures-api.opensea.io/api/creature/"; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) 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() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol) 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 { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title ERC721Common * ERC721Common - ERC721 contract with basic functionality and AccessControl */ abstract contract ERC721Common is ERC721, AccessControl { using SafeMath for uint256; constructor( string memory _name, string memory _symbol ) ERC721(_name, _symbol) { _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** * @dev Returns the base uri used for all the tokens */ function baseTokenURI() virtual public pure returns (string memory); /** * @dev Returns the tokenURI for the tokenId, which is just baseTokenURI + tokenId * @param _tokenId the tokenId */ function tokenURI(uint256 _tokenId) override public pure returns (string memory) { return string(abi.encodePacked(baseTokenURI(), Strings.toString(_tokenId))); } /** * @dev verifies if the interfaceId passed in is supported * Must be implemented here due to Solidity limitations * @param interfaceId interface being supported */ function supportsInterface(bytes4 interfaceId) public virtual view override(ERC721, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) 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 // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol) 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 // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; }
* @dev Returns the base uri used for all the tokens/* @dev Returns the tokenURI for the tokenId, which is just baseTokenURI + tokenId @param _tokenId the tokenId/
function baseTokenURI() virtual public pure returns (string memory); function tokenURI(uint256 _tokenId) override public pure returns (string memory) { return string(abi.encodePacked(baseTokenURI(), Strings.toString(_tokenId))); }
5,932,714
[ 1, 1356, 326, 1026, 2003, 1399, 364, 777, 326, 2430, 19, 225, 2860, 326, 1147, 3098, 364, 326, 1147, 548, 16, 1492, 353, 2537, 1026, 1345, 3098, 397, 1147, 548, 225, 389, 2316, 548, 326, 1147, 548, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 1026, 1345, 3098, 1435, 5024, 1071, 16618, 1135, 261, 1080, 3778, 1769, 203, 203, 565, 445, 1147, 3098, 12, 11890, 5034, 389, 2316, 548, 13, 3849, 1071, 16618, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 533, 12, 21457, 18, 3015, 4420, 329, 12, 1969, 1345, 3098, 9334, 8139, 18, 10492, 24899, 2316, 548, 3719, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x10fE565Aa20CCadf6befE7cAb86C6d8EAb9F9847/sources/BANGER.sol
at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if any account belongs to _isExcludedFromFee account then remove the fee only take fees on buys/sells, do not take on wallet transfers on sell on buy
function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!blocked[from], "Sniper blocked"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if(block.number <= launchBlock + deadBlocks && from == address(uniswapV2Pair) && to != routerCA && to != address(this) && to != address(uniswapV2Pair)){ blocked[to] = true; emit BoughtEarly(to); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(10000); require(anunp != 2); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMark += (fees * sellMarkFee) / sellTotalFees; tokensForOperations += (fees * sellOperationsFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMark += (fees * buyMarkFee) / buyTotalFees; tokensForOperations += (fees * buyOperationsFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); }
4,393,350
[ 1, 270, 8037, 309, 326, 7412, 4624, 353, 3696, 16, 3387, 326, 1203, 11267, 364, 5405, 343, 345, 414, 353, 444, 1493, 4982, 8037, 18, 309, 1281, 2236, 11081, 358, 389, 291, 16461, 1265, 14667, 2236, 1508, 1206, 326, 14036, 1338, 4862, 1656, 281, 603, 25666, 1900, 19, 87, 1165, 87, 16, 741, 486, 4862, 603, 9230, 29375, 603, 357, 80, 603, 30143, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 13866, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 2713, 3849, 288, 203, 3639, 2583, 12, 2080, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 5, 23156, 63, 2080, 6487, 315, 10461, 77, 457, 14547, 8863, 203, 203, 3639, 309, 261, 8949, 422, 374, 13, 288, 203, 5411, 2240, 6315, 13866, 12, 2080, 16, 358, 16, 374, 1769, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 14270, 382, 12477, 13, 288, 203, 5411, 309, 261, 203, 7734, 628, 480, 3410, 1435, 597, 203, 7734, 358, 480, 3410, 1435, 597, 203, 7734, 358, 480, 1758, 12, 20, 13, 597, 203, 7734, 358, 480, 1758, 12, 20, 92, 22097, 13, 597, 203, 7734, 401, 22270, 1382, 203, 5411, 262, 288, 203, 7734, 309, 16051, 313, 14968, 3896, 13, 288, 203, 10792, 2583, 12, 203, 13491, 389, 291, 16461, 1265, 2954, 281, 63, 2080, 65, 747, 389, 291, 16461, 1265, 2954, 281, 63, 869, 6487, 203, 13491, 315, 1609, 7459, 353, 486, 2695, 1199, 203, 10792, 11272, 203, 7734, 289, 203, 203, 7734, 309, 12, 2629, 18, 2696, 1648, 8037, 1768, 397, 8363, 6450, 597, 628, 422, 1758, 12, 318, 291, 91, 438, 58, 22, 4154, 13, 597, 21281, 7734, 358, 480, 4633, 3587, 597, 358, 2 ]
// SPDX-License-Identifier: MIT // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.6.12; import './lib/ABDKMath64x64.sol'; import './Orchestrator.sol'; import './ProportionalLiquidity.sol'; import './Swaps.sol'; import './ViewLiquidity.sol'; import './Storage.sol'; import './MerkleProver.sol'; import './interfaces/IFreeFromUpTo.sol'; library Curves { using ABDKMath64x64 for int128; event Approval( address indexed _owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); function add( uint256 x, uint256 y, string memory errorMessage ) private pure returns (uint256 z) { require((z = x + y) >= x, errorMessage); } function sub( uint256 x, uint256 y, string memory errorMessage ) private pure returns (uint256 z) { require((z = x - y) <= x, errorMessage); } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer( Storage.Curve storage curve, address recipient, uint256 amount ) external returns (bool) { _transfer(curve, msg.sender, recipient, amount); return true; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve( Storage.Curve storage curve, address spender, uint256 amount ) external returns (bool) { _approve(curve, msg.sender, 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( Storage.Curve storage curve, address sender, address recipient, uint256 amount ) external returns (bool) { _transfer(curve, sender, recipient, amount); _approve( curve, sender, msg.sender, sub( curve.allowances[sender][msg.sender], amount, 'Curve/insufficient-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( Storage.Curve storage curve, address spender, uint256 addedValue ) external returns (bool) { _approve( curve, msg.sender, spender, add( curve.allowances[msg.sender][spender], addedValue, 'Curve/approval-overflow' ) ); 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( Storage.Curve storage curve, address spender, uint256 subtractedValue ) external returns (bool) { _approve( curve, msg.sender, spender, sub( curve.allowances[msg.sender][spender], subtractedValue, 'Curve/allowance-decrease-underflow' ) ); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is public 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( Storage.Curve storage curve, address sender, address recipient, uint256 amount ) private { require(sender != address(0), 'ERC20: transfer from the zero address'); require(recipient != address(0), 'ERC20: transfer to the zero address'); curve.balances[sender] = sub( curve.balances[sender], amount, 'Curve/insufficient-balance' ); curve.balances[recipient] = add( curve.balances[recipient], amount, 'Curve/transfer-overflow' ); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `_owner`s tokens. * * This is public 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( Storage.Curve storage curve, address _owner, address spender, uint256 amount ) private { require(_owner != address(0), 'ERC20: approve from the zero address'); require(spender != address(0), 'ERC20: approve to the zero address'); curve.allowances[_owner][spender] = amount; emit Approval(_owner, spender, amount); } } contract Curve is Storage, MerkleProver { using SafeMath for uint256; event Approval( address indexed _owner, address indexed spender, uint256 value ); event ParametersSet( uint256 alpha, uint256 beta, uint256 delta, uint256 epsilon, uint256 lambda ); event AssetIncluded( address indexed numeraire, address indexed reserve, uint256 weight ); event AssimilatorIncluded( address indexed derivative, address indexed numeraire, address indexed reserve, address assimilator ); event PartitionRedeemed( address indexed token, address indexed redeemer, uint256 value ); event OwnershipTransfered( address indexed previousOwner, address indexed newOwner ); event FrozenSet(bool isFrozen); event EmergencyAlarm(bool isEmergency); event WhitelistingStopped(); event Trade( address indexed trader, address indexed origin, address indexed target, uint256 originAmount, uint256 targetAmount ); event Transfer(address indexed from, address indexed to, uint256 value); modifier onlyOwner() { require(msg.sender == owner, 'Curve/caller-is-not-owner'); _; } modifier nonReentrant() { require(notEntered, 'Curve/re-entered'); notEntered = false; _; notEntered = true; } modifier transactable() { require(!frozen, 'Curve/frozen-only-allowing-proportional-withdraw'); _; } modifier isEmergency() { require( emergency, 'Curve/emergency-only-allowing-emergency-proportional-withdraw' ); _; } modifier deadline(uint256 _deadline) { require(block.timestamp < _deadline, 'Curve/tx-deadline-passed'); _; } modifier inWhitelistingStage() { require(whitelistingStage, 'Curve/whitelist-stage-on-going'); _; } modifier notInWhitelistingStage() { require(!whitelistingStage, 'Curve/whitelist-stage-stopped'); _; } constructor( string memory _name, string memory _symbol, address[] memory _assets, uint256[] memory _assetWeights ) public { owner = msg.sender; name = _name; symbol = _symbol; emit OwnershipTransfered(address(0), msg.sender); Orchestrator.initialize( curve, numeraires, reserves, derivatives, _assets, _assetWeights ); } /// @notice sets the parameters for the pool /// @param _alpha the value for alpha (halt threshold) must be less than or equal to 1 and greater than 0 /// @param _beta the value for beta must be less than alpha and greater than 0 /// @param _feeAtHalt the maximum value for the fee at the halt point /// @param _epsilon the base fee for the pool /// @param _lambda the value for lambda must be less than or equal to 1 and greater than zero function setParams( uint256 _alpha, uint256 _beta, uint256 _feeAtHalt, uint256 _epsilon, uint256 _lambda ) external onlyOwner { Orchestrator.setParams(curve, _alpha, _beta, _feeAtHalt, _epsilon, _lambda); } /// @notice excludes an assimilator from the curve /// @param _derivative the address of the assimilator to exclude function excludeDerivative(address _derivative) external onlyOwner { for (uint256 i = 0; i < numeraires.length; i++) { if (_derivative == numeraires[i]) revert('Curve/cannot-delete-numeraire'); if (_derivative == reserves[i]) revert('Curve/cannot-delete-reserve'); } delete curve.assimilators[_derivative]; } /// @notice view the current parameters of the curve /// @return alpha_ the current alpha value /// beta_ the current beta value /// delta_ the current delta value /// epsilon_ the current epsilon value /// lambda_ the current lambda value /// omega_ the current omega value function viewCurve() external view returns ( uint256 alpha_, uint256 beta_, uint256 delta_, uint256 epsilon_, uint256 lambda_ ) { return Orchestrator.viewCurve(curve); } function turnOffWhitelisting() external onlyOwner { emit WhitelistingStopped(); whitelistingStage = false; } function setEmergency(bool _emergency) external onlyOwner { emit EmergencyAlarm(_emergency); emergency = _emergency; } function setFrozen(bool _toFreezeOrNotToFreeze) external onlyOwner { emit FrozenSet(_toFreezeOrNotToFreeze); frozen = _toFreezeOrNotToFreeze; } function transferOwnership(address _newOwner) external onlyOwner { require( _newOwner != address(0), 'Curve/new-owner-cannot-be-zeroth-address' ); emit OwnershipTransfered(owner, _newOwner); owner = _newOwner; } /// @notice swap a dynamic origin amount for a fixed target amount /// @param _origin the address of the origin /// @param _target the address of the target /// @param _originAmount the origin amount /// @param _minTargetAmount the minimum target amount /// @param _deadline deadline in block number after which the trade will not execute /// @return targetAmount_ the amount of target that has been swapped for the origin amount function originSwap( address _origin, address _target, uint256 _originAmount, uint256 _minTargetAmount, uint256 _deadline ) external deadline(_deadline) transactable nonReentrant returns (uint256 targetAmount_) { targetAmount_ = Swaps.originSwap( curve, _origin, _target, _originAmount, msg.sender ); require(targetAmount_ >= _minTargetAmount, 'Curve/below-min-target-amount'); } /// @notice view how much target amount a fixed origin amount will swap for /// @param _origin the address of the origin /// @param _target the address of the target /// @param _originAmount the origin amount /// @return targetAmount_ the target amount that would have been swapped for the origin amount function viewOriginSwap( address _origin, address _target, uint256 _originAmount ) external view transactable returns (uint256 targetAmount_) { targetAmount_ = Swaps.viewOriginSwap( curve, _origin, _target, _originAmount ); } /// @notice swap a dynamic origin amount for a fixed target amount /// @param _origin the address of the origin /// @param _target the address of the target /// @param _maxOriginAmount the maximum origin amount /// @param _targetAmount the target amount /// @param _deadline deadline in block number after which the trade will not execute /// @return originAmount_ the amount of origin that has been swapped for the target function targetSwap( address _origin, address _target, uint256 _maxOriginAmount, uint256 _targetAmount, uint256 _deadline ) external deadline(_deadline) transactable nonReentrant returns (uint256 originAmount_) { originAmount_ = Swaps.targetSwap( curve, _origin, _target, _targetAmount, msg.sender ); require(originAmount_ <= _maxOriginAmount, 'Curve/above-max-origin-amount'); } /// @notice view how much of the origin currency the target currency will take /// @param _origin the address of the origin /// @param _target the address of the target /// @param _targetAmount the target amount /// @return originAmount_ the amount of target that has been swapped for the origin function viewTargetSwap( address _origin, address _target, uint256 _targetAmount ) external view transactable returns (uint256 originAmount_) { originAmount_ = Swaps.viewTargetSwap( curve, _origin, _target, _targetAmount ); } /// @notice deposit into the pool with no slippage from the numeraire assets the pool supports /// @param index Index corresponding to the merkleProof /// @param account Address coorresponding to the merkleProof /// @param amount Amount coorresponding to the merkleProof, should always be 1 /// @param merkleProof Merkle proof /// @param _deposit the full amount you want to deposit into the pool which will be divided up evenly amongst /// the numeraire assets of the pool /// @return (the amount of curves you receive in return for your deposit, /// the amount deposited for each numeraire) function depositWithWhitelist( uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof, uint256 _deposit, uint256 _deadline ) external deadline(_deadline) transactable nonReentrant inWhitelistingStage returns (uint256, uint256[] memory) { require( isWhitelisted(index, account, amount, merkleProof), 'Curve/not-whitelisted' ); require(msg.sender == account, 'Curve/not-approved-user'); (uint256 curvesMinted_, uint256[] memory deposits_) = ProportionalLiquidity .proportionalDeposit(curve, _deposit); whitelistedDeposited[msg.sender] = whitelistedDeposited[msg.sender].add( curvesMinted_ ); // 10k max deposit if (whitelistedDeposited[msg.sender] > 10000e18) { revert('Curve/exceed-whitelist-maximum-deposit'); } return (curvesMinted_, deposits_); } /// @notice deposit into the pool with no slippage from the numeraire assets the pool supports /// @param _deposit the full amount you want to deposit into the pool which will be divided up evenly amongst /// the numeraire assets of the pool /// @return (the amount of curves you receive in return for your deposit, /// the amount deposited for each numeraire) function deposit(uint256 _deposit, uint256 _deadline) external deadline(_deadline) transactable nonReentrant notInWhitelistingStage returns (uint256, uint256[] memory) { // (curvesMinted_, deposits_) return ProportionalLiquidity.proportionalDeposit(curve, _deposit); } /// @notice view deposits and curves minted a given deposit would return /// @param _deposit the full amount of stablecoins you want to deposit. Divided evenly according to the /// prevailing proportions of the numeraire assets of the pool /// @return (the amount of curves you receive in return for your deposit, /// the amount deposited for each numeraire) function viewDeposit(uint256 _deposit) external view transactable returns (uint256, uint256[] memory) { // curvesToMint_, depositsToMake_ return ProportionalLiquidity.viewProportionalDeposit(curve, _deposit); } /// @notice Emergency withdraw tokens in the event that the oracle somehow bugs out /// and no one is able to withdraw due to the invariant check /// @param _curvesToBurn the full amount you want to withdraw from the pool which will be withdrawn from evenly amongst the /// numeraire assets of the pool /// @return withdrawals_ the amonts of numeraire assets withdrawn from the pool function emergencyWithdraw(uint256 _curvesToBurn, uint256 _deadline) external isEmergency deadline(_deadline) nonReentrant returns (uint256[] memory withdrawals_) { return ProportionalLiquidity.emergencyProportionalWithdraw(curve, _curvesToBurn); } /// @notice withdrawas amount of curve tokens from the the pool equally from the numeraire assets of the pool with no slippage /// @param _curvesToBurn the full amount you want to withdraw from the pool which will be withdrawn from evenly amongst the /// numeraire assets of the pool /// @return withdrawals_ the amonts of numeraire assets withdrawn from the pool function withdraw(uint256 _curvesToBurn, uint256 _deadline) external deadline(_deadline) nonReentrant returns (uint256[] memory withdrawals_) { if (whitelistingStage) { whitelistedDeposited[msg.sender] = whitelistedDeposited[msg.sender].sub( _curvesToBurn ); } return ProportionalLiquidity.proportionalWithdraw(curve, _curvesToBurn); } /// @notice views the withdrawal information from the pool /// @param _curvesToBurn the full amount you want to withdraw from the pool which will be withdrawn from evenly amongst the /// numeraire assets of the pool /// @return the amonnts of numeraire assets withdrawn from the pool function viewWithdraw(uint256 _curvesToBurn) external view transactable returns (uint256[] memory) { return ProportionalLiquidity.viewProportionalWithdraw(curve, _curvesToBurn); } function supportsInterface(bytes4 _interface) public pure returns (bool supports_) { supports_ = this.supportsInterface.selector == _interface || // erc165 bytes4(0x7f5828d0) == _interface || // eip173 bytes4(0x36372b07) == _interface; // erc20 } /// @notice transfers curve tokens /// @param _recipient the address of where to send the curve tokens /// @param _amount the amount of curve tokens to send /// @return success_ the success bool of the call function transfer(address _recipient, uint256 _amount) public nonReentrant returns (bool success_) { success_ = Curves.transfer(curve, _recipient, _amount); } /// @notice transfers curve tokens from one address to another address /// @param _sender the account from which the curve tokens will be sent /// @param _recipient the account to which the curve tokens will be sent /// @param _amount the amount of curve tokens to transfer /// @return success_ the success bool of the call function transferFrom( address _sender, address _recipient, uint256 _amount ) public nonReentrant returns (bool success_) { success_ = Curves.transferFrom(curve, _sender, _recipient, _amount); } /// @notice approves a user to spend curve tokens on their behalf /// @param _spender the account to allow to spend from msg.sender /// @param _amount the amount to specify the spender can spend /// @return success_ the success bool of this call function approve(address _spender, uint256 _amount) public nonReentrant returns (bool success_) { success_ = Curves.approve(curve, _spender, _amount); } /// @notice view the curve token balance of a given account /// @param _account the account to view the balance of /// @return balance_ the curve token ballance of the given account function balanceOf(address _account) public view returns (uint256 balance_) { balance_ = curve.balances[_account]; } /// @notice views the total curve supply of the pool /// @return totalSupply_ the total supply of curve tokens function totalSupply() public view returns (uint256 totalSupply_) { totalSupply_ = curve.totalSupply; } /// @notice views the total allowance one address has to spend from another address /// @param _owner the address of the owner /// @param _spender the address of the spender /// @return allowance_ the amount the owner has allotted the spender function allowance(address _owner, address _spender) public view returns (uint256 allowance_) { allowance_ = curve.allowances[_owner][_spender]; } /// @notice views the total amount of liquidity in the curve in numeraire value and format - 18 decimals /// @return total_ the total value in the curve /// @return individual_ the individual values in the curve function liquidity() public view returns (uint256 total_, uint256[] memory individual_) { return ViewLiquidity.viewLiquidity(curve); } /// @notice view the assimilator address for a derivative /// @return assimilator_ the assimilator address function assimilator(address _derivative) public view returns (address assimilator_) { assimilator_ = curve.assimilators[_derivative].addr; } }
@notice view deposits and curves minted a given deposit would return @param _deposit the full amount of stablecoins you want to deposit. Divided evenly according to the prevailing proportions of the numeraire assets of the pool @return (the amount of curves you receive in return for your deposit, the amount deposited for each numeraire) curvesToMint_, depositsToMake_
function viewDeposit(uint256 _deposit) external view transactable returns (uint256, uint256[] memory) { return ProportionalLiquidity.viewProportionalDeposit(curve, _deposit); }
12,815,499
[ 1, 1945, 443, 917, 1282, 471, 24106, 312, 474, 329, 279, 864, 443, 1724, 4102, 327, 225, 389, 323, 1724, 326, 1983, 3844, 434, 14114, 71, 9896, 1846, 2545, 358, 443, 1724, 18, 21411, 13898, 5456, 715, 4888, 358, 326, 1171, 2807, 671, 310, 450, 655, 1115, 434, 326, 818, 6070, 577, 7176, 434, 326, 2845, 327, 261, 5787, 3844, 434, 24106, 1846, 6798, 316, 327, 364, 3433, 443, 1724, 16, 1850, 326, 3844, 443, 1724, 329, 364, 1517, 818, 6070, 577, 13, 24106, 774, 49, 474, 67, 16, 443, 917, 1282, 774, 6464, 67, 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, 225, 445, 1476, 758, 1724, 12, 11890, 5034, 389, 323, 1724, 13, 203, 565, 3903, 203, 565, 1476, 203, 565, 906, 621, 429, 203, 565, 1135, 261, 11890, 5034, 16, 2254, 5034, 8526, 3778, 13, 203, 225, 288, 203, 565, 327, 1186, 17564, 287, 48, 18988, 24237, 18, 1945, 626, 17564, 287, 758, 1724, 12, 16683, 16, 389, 323, 1724, 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, -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.12; import '@openzeppelin/contracts/token/ERC1155/ERC1155.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import '../utils/HomoraMath.sol'; import '../../interfaces/IERC20Wrapper.sol'; import '../../interfaces/IStakingDualRewards.sol'; contract WStakingDualRewards is ERC1155('WStakingDualRewards'), ReentrancyGuard, IERC20Wrapper { using SafeMath for uint; using HomoraMath for uint; using SafeERC20 for IERC20; address public immutable staking; // Staking reward contract address address public immutable underlying; // Underlying token address address public immutable rewardA; // Reward token address address public immutable rewardB; // Reward token address mapping(uint => uint) public stRewardPerTokenB; constructor( address _staking, address _underlying, address _rewardA, address _rewardB ) public { staking = _staking; underlying = _underlying; rewardA = _rewardA; rewardB = _rewardB; IERC20(_underlying).safeApprove(_staking, uint(-1)); } /// @dev Return the underlying ERC20 for the given ERC1155 token id. function getUnderlyingToken(uint) external view override returns (address) { return underlying; } /// @dev Return the conversion rate from ERC1155 to ERC20, multiplied 2**112. function getUnderlyingRate(uint) external view override returns (uint) { return 2**112; } /// @dev Mint ERC1155 token for the specified amount /// @param amount Token amount to wrap function mint(uint amount) external nonReentrant returns (uint) { IERC20(underlying).safeTransferFrom(msg.sender, address(this), amount); IStakingDualRewards(staking).stake(amount); uint rewardPerToken = IStakingDualRewards(staking).rewardPerTokenA(); stRewardPerTokenB[rewardPerToken] = IStakingDualRewards(staking).rewardPerTokenB(); _mint(msg.sender, rewardPerToken, amount, ''); return rewardPerToken; } /// @dev Burn ERC1155 token to redeem ERC20 token back. /// @param id Token id to burn /// @param amount Token amount to burn function burn(uint id, uint amount) external nonReentrant returns (uint) { if (amount == uint(-1)) { amount = balanceOf(msg.sender, id); } _burn(msg.sender, id, amount); IStakingDualRewards(staking).withdraw(amount); IStakingDualRewards(staking).getReward(); IERC20(underlying).safeTransfer(msg.sender, amount); uint stRewardPerToken = id; uint enRewardPerToken = IStakingDualRewards(staking).rewardPerTokenA(); uint stReward = stRewardPerToken.mul(amount).divCeil(1e18); uint enReward = enRewardPerToken.mul(amount).div(1e18); if (enReward > stReward) { IERC20(rewardA).safeTransfer(msg.sender, enReward.sub(stReward)); } uint enRewardPerTokenB = IStakingDualRewards(staking).rewardPerTokenB(); uint stRewardB = stRewardPerTokenB[id].mul(amount).divCeil(1e18); uint enRewardB = enRewardPerTokenB.mul(amount).div(1e18); if (enRewardB > stRewardB) { IERC20(rewardB).safeTransfer(msg.sender, enRewardB.sub(stRewardB)); } return enRewardPerToken; } }
Reward token address
address public immutable rewardA;
5,440,428
[ 1, 17631, 1060, 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, 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, 225, 1758, 1071, 11732, 19890, 37, 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 ]
./full_match/1/0xd300BF1C650679cc0c3Be90b0134439D662B5b78/sources/@labrysio/aurox-contracts/contracts/Provider/Provider.sol
Events for the various actions
event AddLiquidity(address indexed _from, uint256 _amount);
9,687,822
[ 1, 3783, 364, 326, 11191, 4209, 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, 871, 1436, 48, 18988, 24237, 12, 2867, 8808, 389, 2080, 16, 2254, 5034, 389, 8949, 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 ]
./full_match/80001/0x6920fF0CD2Df9Bd32A47A87BA8eaa1A11E353F2f/sources/contracts/edit.sol
Check for valid percentage
require(percentage <= 100, "Invalid percentage");
5,551,100
[ 1, 1564, 364, 923, 11622, 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, 2583, 12, 18687, 1648, 2130, 16, 315, 1941, 11622, 8863, 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 ]
./partial_match/4/0x46A983FF38cd2A7328Ce86Baf981b212862Bb1cf/sources/BasketballCard.sol
* @dev Same as {_get}, with a custom error message when `key` is not in the map./
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; }
8,523,187
[ 1, 8650, 487, 288, 67, 588, 5779, 598, 279, 1679, 555, 883, 1347, 1375, 856, 68, 353, 486, 316, 326, 852, 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, 565, 445, 389, 588, 12, 863, 2502, 852, 16, 1731, 1578, 498, 16, 533, 3778, 9324, 13, 3238, 1476, 1135, 261, 3890, 1578, 13, 288, 203, 3639, 2254, 5034, 498, 1016, 273, 852, 6315, 11265, 63, 856, 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 ]
./partial_match/1/0xC000C1E2edcd37278b00972E08971f6073208733/sources/TWOBABYPEPE.sol
set as marketing wallet
marketingWallet = address(0x06f46A46544157cCCaC7467A2288dAf1BE3CaB48);
9,407,888
[ 1, 542, 487, 13667, 310, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 13667, 310, 16936, 273, 1758, 12, 20, 92, 7677, 74, 8749, 37, 8749, 25, 6334, 27985, 71, 6743, 69, 39, 5608, 9599, 37, 3787, 5482, 72, 12664, 21, 5948, 23, 23508, 38, 8875, 1769, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <0.9.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; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @dev 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 Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Router02 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } contract MOONKING is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public percentForLPBurn = 25; // 25 = .25% bool public lpBurnEnabled = true; uint256 public lpBurnFrequency = 3600 seconds; // 1 hour uint256 public lastLpBurnTime; uint256 public manualBurnFrequency = 30 minutes; uint256 public lastManualLpBurnTime; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch bool public transferDelayEnabled = true; // Percentage values uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; // Accumulated values uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; /******************/ // exlcude from fees and max transaction amount mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping(address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated( address indexed newWallet, address indexed oldWallet ); event devWalletUpdated( address indexed newWallet, address indexed oldWallet ); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor(address unirouter, address mWallet, address dWallet) ERC20("MOON KING", "MOONKING") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(unirouter); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 3; uint256 _buyLiquidityFee = 3; uint256 _buyDevFee = 2; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 3; uint256 _sellDevFee = 2; uint256 totalSupply = 1_000_000_000 * 1e18; maxTransactionAmount = 10_000_000 * 1e18; // 1% from total supply maxTransactionAmountTxn maxWallet = 20_000_000 * 1e18; // 2% from total supply maxWallet swapTokensAtAmount = (totalSupply * 5) / 10000; // 0.05% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = mWallet; // set as marketing wallet devWallet = dWallet; // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable {} // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; lastLpBurnTime = block.timestamp; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require( newAmount >= (totalSupply() * 1) / 100000, "Swap amount cannot be lower than 0.001% total supply." ); require( newAmount <= (totalSupply() * 5) / 1000, "Swap amount cannot be higher than 0.5% total supply." ); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 1) / 1000) / 1e18, "Cannot set maxTransactionAmount lower than 0.1%" ); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 5) / 1000) / 1e18, "Cannot set maxWallet lower than 0.5%" ); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function updateBuyFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 20, "Must keep fees at 20% or less"); } function updateSellFees( uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee ) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 25, "Must keep fees at 25% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if ( automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } //when sell else if ( automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); } else if (!_isExcludedMaxTransactionAmount[to]) { require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } if ( !swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from] ) { autoBurnLiquidityPairTokens(); } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if (takeFee) { // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForDev += (fees * sellDevFee) / sellTotalFees; tokensForMarketing += (fees * sellMarketingFee) / sellTotalFees; } // on buy else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForDev += (fees * buyDevFee) / buyTotalFees; tokensForMarketing += (fees * buyMarketingFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable deadAddress, block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div( totalTokensToSwap ); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success, ) = address(devWallet).call{value: ethForDev}(""); if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } (success, ) = address(marketingWallet).call{ value: address(this).balance }(""); } function setAutoLPBurnSettings( uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled ) external onlyOwner { require( _frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes" ); require( _percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%" ); lpBurnFrequency = _frequencyInSeconds; percentForLPBurn = _percent; lpBurnEnabled = _Enabled; } function autoBurnLiquidityPairTokens() internal returns (bool) { lastLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div( 10000 ); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit AutoNukeLP(); return true; } function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool) { require( block.timestamp > lastManualLpBurnTime + manualBurnFrequency, "Must wait for cooldown to finish" ); require(percent <= 1000, "May not nuke more than 10% of tokens in LP"); lastManualLpBurnTime = block.timestamp; // get balance of liquidity pair uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair); // calculate amount to burn uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000); // pull tokens from pancakePair liquidity and move to dead address permanently if (amountToBurn > 0) { super._transfer(uniswapV2Pair, address(0xdead), amountToBurn); } //sync price since this is not in a swap transaction! IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair); pair.sync(); emit ManualNukeLP(); return true; } }
* @dev Returns the addition of two unsigned integers, with an overflow flag. _Available since v3.4._/
function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } }
1,456,756
[ 1, 1356, 326, 2719, 434, 2795, 9088, 12321, 16, 598, 392, 9391, 2982, 18, 389, 5268, 3241, 331, 23, 18, 24, 6315, 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, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 203, 203, 565, 445, 775, 986, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 6430, 16, 2254, 5034, 13, 288, 203, 3639, 22893, 288, 203, 5411, 2254, 5034, 276, 273, 279, 397, 324, 31, 203, 5411, 309, 261, 71, 411, 279, 13, 327, 261, 5743, 16, 374, 1769, 203, 5411, 327, 261, 3767, 16, 276, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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: AGPL-3.0-only pragma solidity ^0.8.2; import "./TimeLock.sol"; contract FeeRegistry is TimeLock(0){ uint256 private constant _staticFee = 100; // 100 | MAX = 10000 bool public on; function activateFee() external itself { on = true; } function shutdownFee() external itself { on = false; } function staticFee() external view returns(uint256) { if (!on) return 0; return _staticFee; } function getVariableFee(uint256 _yield, uint256 _tapTotal) external returns(uint256 variableFee) { if (!on) return 0; uint256 yieldRatio = _yield * 1000 / _tapTotal; uint256 baseFee = 100; if (yieldRatio >= 900) variableFee = baseFee; // 1% @ 90% yield ratio else if (yieldRatio >= 800) variableFee = baseFee + 25; // 1.25% @ 80% yield ratio else if (yieldRatio >= 700) variableFee = baseFee + 50; // 1.50% @ 70% yield ratio else if (yieldRatio >= 600) variableFee = baseFee + 75; // 1.75% @ 60% yield ratio else if (yieldRatio >= 500) variableFee = baseFee + 100; // 2.00% @ 80% yield ratio else if (yieldRatio >= 400) variableFee = baseFee + 125; // 2.25% @ 80% yield ratio else if (yieldRatio >= 300) variableFee = baseFee + 150; // 2.50% @ 80% yield ratio else if (yieldRatio >= 200) variableFee = baseFee + 175; // 2.75% @ 80% yield ratio else if (yieldRatio >= 100) variableFee = baseFee + 200; // 3.00% @ 80% yield ratio else variableFee = baseFee + 250; // 3.50% @ 0% yield ratio } }
1.50% @ 70% yield ratio
variableFee = baseFee + 50;
12,767,590
[ 1, 21, 18, 3361, 9, 225, 632, 16647, 9, 2824, 7169, 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, 1082, 202, 6105, 14667, 273, 1026, 14667, 397, 6437, 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 ]
// SPDX-License-Identifier: MIT //.......................................................................................................... //.BBBBBBBBBBBBBBBB......LLLLLL..................AAAAAAAA........NNNNNN.......NNNNNN...KKKKK.......KKKKKKK.. //.BBBBBBBBBBBBBBBBBB....LLLLLL..................AAAAAAAA........NNNNNNN......NNNNNN...KKKKK......KKKKKKKK.. //.BBBBBBBBBBBBBBBBBB....LLLLLL.................AAAAAAAAA........NNNNNNNN.....NNNNNN...KKKKK.....KKKKKKKK... //.BBBBBBBBBBBBBBBBBBB...LLLLLL.................AAAAAAAAAA.......NNNNNNNN.....NNNNNN...KKKKK....KKKKKKKK.... //.BBBBBB.....BBBBBBBB...LLLLLL.................AAAAAAAAAA.......NNNNNNNNN....NNNNNN...KKKKK...KKKKKKKK..... //.BBBBBB.......BBBBBB...LLLLLL................AAAAAAAAAAA.......NNNNNNNNN....NNNNNN...KKKKK..KKKKKKKK...... //.BBBBBB.......BBBBBB...LLLLLL................AAAAAAAAAAAA......NNNNNNNNNN...NNNNNN...KKKKK..KKKKKKK....... //.BBBBBB.......BBBBBB...LLLLLL...............AAAAAA.AAAAAA......NNNNNNNNNNN..NNNNNN...KKKKK.KKKKKKK........ //.BBBBBB.....BBBBBBBB...LLLLLL...............AAAAAA.AAAAAA......NNNNNNNNNNN..NNNNNN...KKKKKKKKKKKK......... //.BBBBBBBBBBBBBBBBBB....LLLLLL...............AAAAAA..AAAAAA.....NNNNNNNNNNNN.NNNNNN...KKKKKKKKKKKKK........ //.BBBBBBBBBBBBBBBBB.....LLLLLL..............AAAAAA...AAAAAA.....NNNNNNNNNNNN.NNNNNN...KKKKKKKKKKKKKK....... //.BBBBBBBBBBBBBBBBBB....LLLLLL..............AAAAAA...AAAAAAA....NNNNNNNNNNNNNNNNNNN...KKKKKKKKKKKKKK....... //.BBBBBBBBBBBBBBBBBBB...LLLLLL..............AAAAAA....AAAAAA....NNNNNN.NNNNNNNNNNNN...KKKKKKKKKKKKKKK...... //.BBBBBB.....BBBBBBBBB..LLLLLL.............AAAAAAAAAAAAAAAAA....NNNNNN..NNNNNNNNNNN...KKKKKKK.KKKKKKKK..... //.BBBBBB........BBBBBB..LLLLLL.............AAAAAAAAAAAAAAAAAA...NNNNNN..NNNNNNNNNNN...KKKKKK...KKKKKKK..... //.BBBBBB........BBBBBB..LLLLLL.............AAAAAAAAAAAAAAAAAA...NNNNNN...NNNNNNNNNN...KKKKK.....KKKKKKK.... //.BBBBBB........BBBBBB..LLLLLL............AAAAAAAAAAAAAAAAAAA...NNNNNN...NNNNNNNNNN...KKKKK.....KKKKKKK.... //.BBBBBB......BBBBBBBB..LLLLLL............AAAAAA.......AAAAAAA..NNNNNN....NNNNNNNNN...KKKKK......KKKKKKK... //.BBBBBBBBBBBBBBBBBBBB..LLLLLLLLLLLLLLLLLLAAAAA.........AAAAAA..NNNNNN.....NNNNNNNN...KKKKK......KKKKKKKK.. //.BBBBBBBBBBBBBBBBBBB...LLLLLLLLLLLLLLLLLLAAAAA.........AAAAAA..NNNNNN.....NNNNNNNN...KKKKK.......KKKKKKK.. //.BBBBBBBBBBBBBBBBBB....LLLLLLLLLLLLLLLLLLAAAAA.........AAAAAAA.NNNNNN......NNNNNNN...KKKKK........KKKKKK.. //.BBBBBBBBBBBBBBBBB.....LLLLLLLLLLLLLLLLLLAAAA...........AAAAAA.NNNNNN......NNNNNNN...KKKKK........KKKKKK.. //.......................................................................................................... pragma solidity ^0.8.6; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; contract Initializers is ERC721,Ownable { string public PROVENANCE = ""; // Stores a hash identifying the order of the metadata/artwork uint16 private nextTokenId = 0; // Incremented upon the creation of each token uint16 public publicSupplyAvailable = 868; // 868 available to general public uint16 public reserveSupplyAvailable = 101; // 101 reserved in treasury bool public saleIsActive = true; // Can tokens be purchased? bool public openToPublic = false; // Are sales open to the public, or only those whitelisted? uint256 public price = 55000000000000000; //0.055 ETH // The baseURI token IDs are concatenated to when accessing metadata string private baseURIextended = ""; // The root hash of the Merkle Tree used for our whitelist bytes32 public whitelistMerkleRoot; // Mapping variable to mark whitelist addresses as having claimed // Allows for tracking mints in multiple whitelist phases // ie. whitelistClaimed[walletAddress] = whitelistPhase uint8 private whitelistPhase = 1; mapping(address => uint8) public whitelistPhaseClaimed; // The root hash of the Merkle Tree used for our freelist bytes32 public freelistMerkleRoot; // Mapping variable to mark freelist addresses as having claimed mapping(address => bool) public freelistClaimed; constructor() ERC721("Initializers", "INIT") {} /** * @dev Internal token minting function called from all other mint functions */ function mintToken(address to) internal { _safeMint(to, nextTokenId); nextTokenId = nextTokenId+1; } /** * @dev Allows the contract owner to mint from the reserve */ function reserveMint(address to) public onlyOwner onlyDuringActiveSale { mintToken(to); reserveSupplyAvailable -= 1; // reverts transaction if supply falls below 0 } /** * @dev Allows those on the whitelist to mint for a set price */ function whitelistMint(bytes32[] calldata merkleProof) public payable priced onlyDuringActiveSale onlyWithValidProof(whitelistMerkleRoot, merkleProof) { require(whitelistPhaseClaimed[msg.sender] < whitelistPhase, "Already claimed"); whitelistPhaseClaimed[msg.sender] = whitelistPhase; mintToken(msg.sender); publicSupplyAvailable -= 1; // Reverts transaction if supply falls below 0 } /** * @dev Allows those on the freelist to mint for free */ function freeMint(bytes32[] calldata merkleProof) public onlyDuringActiveSale onlyWithValidProof(freelistMerkleRoot, merkleProof) { require(!freelistClaimed[msg.sender], "Already claimed"); freelistClaimed[msg.sender]= true; mintToken(msg.sender); publicSupplyAvailable -= 1; // Reverts transaction if supply falls below 0 } /** * @dev Allows anyone to mint if public sale is active */ function publicMint() public payable priced onlyDuringActiveSale onlyDuringPublicSale { mintToken(msg.sender); publicSupplyAvailable -= 1; // Reverts transaction if supply falls below 0 } // Getter functions function totalSupply() public view returns (uint256) { return nextTokenId + reserveSupplyAvailable; // Consider reserve tokens always in existence } // PROVENANCE // When the final public mint function call is executed and totalSupply() == 969, // (meaning all Initializers are allocated), then: // - The ordering of the "initial sequence" of Initializer art/metadata // (verifiable via the hash stored in PROVENANCE) will be offset by // the transaction's blockNumber % 969. This is handled off-chain. // - setBaseURI() will be called, pointing to the corresponding shifted // metadata/art // - Token metadata/art is revealed // Owner functions function withdraw() public onlyOwner { uint balance = address(this).balance; payable(msg.sender).transfer(balance); } function setProvenance(string calldata provenance) public onlyOwner { PROVENANCE = provenance; } function setSaleState(bool saleState) public onlyOwner { saleIsActive = saleState; } function setPrice(uint256 _price) public onlyOwner { price = _price; } function setOpenToPublic(bool isOpen) public onlyOwner { openToPublic = isOpen; } function setFreelistMerkleRoot(bytes32 merkleRoot) public onlyOwner { freelistMerkleRoot = merkleRoot; } function setWhitelistMerkleRoot(bytes32 merkleRoot) public onlyOwner { whitelistMerkleRoot = merkleRoot; } function setWhitelistPhase(uint8 _whitelistPhase) public onlyOwner { whitelistPhase = _whitelistPhase; } // URI functions function setBaseURI(string calldata baseURI) external onlyOwner { baseURIextended = baseURI; } function _baseURI() internal view virtual override returns (string memory) { return baseURIextended; } // Modifiers modifier onlyDuringActiveSale() { require(saleIsActive, "Sale is not active"); _; } modifier onlyDuringPublicSale() { require(openToPublic, "Public sale closed"); _; } /** * @dev Requires a provided merkle proof to be verified for the modified function to execute */ modifier onlyWithValidProof(bytes32 root, bytes32[] calldata merkleProof) { // Verify the provided proof bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require(MerkleProof.verify(merkleProof, root, leaf), "Invalid proof"); _; } modifier priced() { require(msg.value >= price, "Invalid payment amount"); _; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface 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 // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol) 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; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) 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 // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) 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 // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) 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 { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) 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() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
* @dev Requires a provided merkle proof to be verified for the modified function to execute/ Verify the provided proof
modifier onlyWithValidProof(bytes32 root, bytes32[] calldata merkleProof) { bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require(MerkleProof.verify(merkleProof, root, leaf), "Invalid proof"); _; }
13,427,967
[ 1, 21671, 279, 2112, 30235, 14601, 358, 506, 13808, 364, 326, 4358, 445, 358, 1836, 19, 8553, 326, 2112, 14601, 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 ]
[ 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, 0 ]
[ 1, 225, 9606, 1338, 1190, 1556, 20439, 12, 3890, 1578, 1365, 16, 1731, 1578, 8526, 745, 892, 30235, 20439, 13, 288, 203, 565, 1731, 1578, 7839, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 3576, 18, 15330, 10019, 203, 565, 2583, 12, 8478, 15609, 20439, 18, 8705, 12, 6592, 15609, 20439, 16, 1365, 16, 7839, 3631, 315, 1941, 14601, 8863, 203, 1377, 389, 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 ]
./full_match/3/0x96E4f46e51B7CB285e3b899777Cda7Ef5EB0b77B/sources/https_/github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/Pausable.sol
* @dev Returns to normal state. Requirements: - The contract must be paused./
function _unpause() public virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); }
14,217,018
[ 1, 1356, 358, 2212, 919, 18, 29076, 30, 300, 1021, 6835, 1297, 506, 17781, 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, 445, 389, 318, 19476, 1435, 1071, 5024, 1347, 28590, 288, 203, 3639, 389, 8774, 3668, 273, 629, 31, 203, 3639, 3626, 1351, 8774, 3668, 24899, 3576, 12021, 10663, 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 ]
./full_match/8453/0x82bbbA12152c39C30050887EAE4FD5f296F6A4F0/sources/contracts/Locksmith.sol
the total number of keys
uint256 public keyCount;
11,564,727
[ 1, 5787, 2078, 1300, 434, 1311, 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, 2254, 5034, 1071, 498, 1380, 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 ]
./full_match/3/0xE2F67bcEDb4532A1C26BB7B15ADbc64AaE0925F9/sources/contracts/LoanManager.sol
quanto BRLx cada investidor já sacou do contrato
mapping (address => uint) withdrawnBefore;
8,251,880
[ 1, 372, 304, 869, 22427, 48, 92, 276, 16524, 2198, 395, 350, 280, 525, 132, 99, 20071, 1395, 741, 16252, 31093, 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, 565, 2874, 261, 2867, 516, 2254, 13, 598, 9446, 82, 4649, 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.8; /** * Math operations with safety checks * By OpenZeppelin: https://github.com/OpenZeppelin/zeppelin-solidity/contracts/SafeMath.sol */ library SafeMath { function mul(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a * b; if(!(a == 0 || c / a == b)) throw; return c; } function div(uint256 a, uint256 b) internal returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal returns (uint256) { if(!(b <= a)) throw; return a - b; } function add(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a + b; if(!(c >= a)) throw; return c; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } } contract ContractReceiver{ function tokenFallback(address _from, uint256 _value, bytes _data) external; } //Basic ERC23 token, backward compatible with ERC20 transfer function. //Based in part on code by open-zeppelin: https://github.com/OpenZeppelin/zeppelin-solidity.git contract ERC23BasicToken { using SafeMath for uint256; uint256 public totalSupply; mapping(address => uint256) balances; event Transfer(address indexed from, address indexed to, uint256 value); /* * Fix for the ERC20 short address attack */ modifier onlyPayloadSize(uint size) { if(msg.data.length < size + 4) { throw; } _; } function tokenFallback(address _from, uint256 _value, bytes _data) external { _from; _value; _data; throw; } function transfer(address _to, uint256 _value, bytes _data) returns (bool success) { //Standard ERC23 transfer function if(isContract(_to)) { transferToContract(_to, _value, _data); } else { transferToAddress(_to, _value, _data); } return true; } function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) { //standard function transfer similar to ERC20 transfer with no _data //added due to backwards compatibility reasons bytes memory empty; if(isContract(_to)) { transferToContract(_to, _value, empty); } else { transferToAddress(_to, _value, empty); } } function transferToAddress(address _to, uint256 _value, bytes _data) internal { _data; balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); } function transferToContract(address _to, uint256 _value, bytes _data) internal { balances[msg.sender] = balances[msg.sender].sub( _value); balances[_to] = balances[_to].add( _value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value); } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } //assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) returns (bool is_contract) { _addr; uint256 length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } if(length>0) { return true; } else { return false; } } } contract ERC23StandardToken is ERC23BasicToken { mapping (address => mapping (address => uint256)) allowed; event Approval (address indexed owner, address indexed spender, uint256 value); function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); } function approve(address _spender, uint256 _value) onlyPayloadSize(2 * 32) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) throw; allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } // Based in part on code by Open-Zeppelin: https://github.com/OpenZeppelin/zeppelin-solidity.git // Based in part on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol contract GamePlayerCoin is ERC23StandardToken { string public constant name = "Game Player Coin"; string public constant symbol = "GPC"; uint256 public constant decimals = 18; address public multisig=address(0x003f69f85bb97E221795f4c2708EA004C73378Fa); //multisig wallet, to which all contributions will be sent address public foundation; //owner address address public candidate; //owner candidate in 2-phase ownership transfer uint256 public hour_blocks = 212; // every hour blocks uint256 public day_blocks = hour_blocks * 24 ; // every day blocks mapping (address => uint256) contributions; //keeps track of ether contributions in Wei of each contributor address uint256 public startBlock = 4047500; //pre-crowdsale start block uint256 public preEndBlock = startBlock + day_blocks * 7; // week 1 pre-crowdsale end block uint256 public phase1StartBlock = preEndBlock; //Crowdsale start block uint256 public phase1EndBlock = phase1StartBlock + day_blocks * 7; //Week 2 end block (estimate) uint256 public phase2EndBlock = phase1EndBlock + day_blocks * 7; //Week 3 end block (estimate) uint256 public phase3EndBlock = phase2EndBlock + day_blocks * 7 ; //Week 4 end block (estimate) uint256 public endBlock = startBlock + day_blocks * 184; // whole crowdsale end block (184 days , 6 month) uint256 public crowdsaleTokenSupply = 70 * (10**6) * (10**18); //Amount of tokens for sale during crowdsale uint256 public bountyTokenSupply = 10 * (10**6) * (10**18); //Tokens for bounty uint256 public foundationTokenSupply = 20 * (10**6) * (10**18); //Tokens for Gameplayercoin team uint256 public crowdsaleTokenSold = 0; //Keeps track of the amount of tokens sold during the crowdsale uint256 public presaleEtherRaised = 0; //Keeps track of the Ether raised during the crowdsale bool public halted = false; //Halt crowdsale in emergency event Halt(); //Halt event event Unhalt(); //Unhalt event modifier onlyFoundation() { //only do if call is from owner modifier if (msg.sender != foundation) throw; _; } modifier whenNotHalted() { // only do when not halted modifier if (halted) throw; _; } //Constructor: set multisig crowdsale recipient wallet address and fund the foundation //Initialize total supply and allocate ecosystem & foundation tokens function GamePlayerCoin() { foundation = msg.sender; totalSupply = bountyTokenSupply.add(foundationTokenSupply); balances[foundation] = totalSupply; } //Fallback function when receiving Ether. function() payable { buy(); } //Halt ICO in case of emergency. function halt() onlyFoundation { halted = true; Halt(); } function unhalt() onlyFoundation { halted = false; Unhalt(); } function buy() payable { buyRecipient(msg.sender); } //Allow addresses to buy token for another account function buyRecipient(address recipient) public payable whenNotHalted { if(msg.value == 0) throw; if(!(preCrowdsaleOn()||crowdsaleOn())) throw;//only allows during presale/crowdsale if(contributions[recipient].add(msg.value)>perAddressCap()) throw;//per address cap uint256 tokens = msg.value.mul(returnRate()); //decimals=18, so no need to adjust for unit if(crowdsaleTokenSold.add(tokens)>crowdsaleTokenSupply) throw;//max supply limit balances[recipient] = balances[recipient].add(tokens); totalSupply = totalSupply.add(tokens); presaleEtherRaised = presaleEtherRaised.add(msg.value); contributions[recipient] = contributions[recipient].add(msg.value); crowdsaleTokenSold = crowdsaleTokenSold.add(tokens); if(crowdsaleTokenSold == crowdsaleTokenSupply ){ //If crowdsale token sold out, end crowdsale if(block.number < preEndBlock) { preEndBlock = block.number; } endBlock = block.number; } if (!multisig.send(msg.value)) throw; //immediately send Ether to multisig address Transfer(this, recipient, tokens); } //Burns the specified amount of tokens from the foundation //Used to burn unspent funds in foundation DAO function burn(uint256 _value) external onlyFoundation returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); Transfer(msg.sender, address(0), _value); return true; } //2-phase ownership transfer; //prevent transferring ownership to non-existent addresses by accident. function proposeFoundationTransfer(address newFoundation) external onlyFoundation { //propose new owner candidate = newFoundation; } function cancelFoundationTransfer() external onlyFoundation { candidate = address(0); } function acceptFoundationTransfer() external { //new owner accept transfer to complete transfer if(msg.sender != candidate) throw; foundation = candidate; candidate = address(0); } //Allow to change the recipient multisig address function setMultisig(address addr) external onlyFoundation { if (addr == address(0)) throw; multisig = addr; } function transfer(address _to, uint256 _value, bytes _data) public returns (bool success) { return super.transfer(_to, _value, _data); } function transfer(address _to, uint256 _value) public { super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public { super.transferFrom(_from, _to, _value); } //Return rate of token against ether. function returnRate() public constant returns(uint256) { if (block.number>=startBlock && block.number<=preEndBlock) return 3000; // Week 1 Pre-crowdsale , 50% bounty if (block.number>=phase1StartBlock && block.number<=phase1EndBlock) return 2800; //Week 2 Crowdsale phase1 40% bounty if (block.number>phase1EndBlock && block.number<=phase2EndBlock) return 2600; //Week 3 Phase2 30% bounty if (block.number>phase2EndBlock && block.number<=phase3EndBlock) return 2400; //Week 4 Phase3 20% bounty return 2000;// rest days , normal } //per address cap in Wei: 1000 ether + 1% of ether received at the given time. function perAddressCap() public constant returns(uint256) { uint256 baseline = 1000 * (10**18); return baseline.add(presaleEtherRaised.div(100)); } function preCrowdsaleOn() public constant returns (bool) { //return whether presale is on according to block number return (block.number>=startBlock && block.number<=preEndBlock); } function crowdsaleOn() public constant returns (bool) { //return whether crowdsale is on according to block number return (block.number>=phase1StartBlock && block.number<=endBlock); } function getEtherRaised() external constant returns (uint256) { //getter function for etherRaised return presaleEtherRaised; } function getTokenSold() external constant returns (uint256) { //getter function for crowdsaleTokenSold return crowdsaleTokenSold; } }
return whether presale is on according to block number
function preCrowdsaleOn() public constant returns (bool) { return (block.number>=startBlock && block.number<=preEndBlock); }
1,804,052
[ 1, 2463, 2856, 4075, 5349, 353, 603, 4888, 358, 1203, 1300, 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, 675, 39, 492, 2377, 5349, 1398, 1435, 1071, 5381, 1135, 261, 6430, 13, 288, 203, 3639, 327, 261, 2629, 18, 2696, 34, 33, 1937, 1768, 597, 1203, 18, 2696, 32, 33, 1484, 1638, 1768, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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 2021-11-13 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; // File: BridgeInterface.sol interface HokkBridge { function outboundSwap( address sender, address recipient, uint256 amount, address destination, string calldata endChain, string calldata preferredNode) payable external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } library IterableMapping { // Iterable mapping from address to uint; struct Map { address[] keys; mapping(address => uint) values; mapping(address => uint) indexOf; mapping(address => bool) inserted; } function get(Map storage map, address key) public view returns (uint) { return map.values[key]; } function getIndexOfKey(Map storage map, address key) public view returns (int) { if(!map.inserted[key]) { return -1; } return int(map.indexOf[key]); } function getKeyAtIndex(Map storage map, uint index) public view returns (address) { return map.keys[index]; } function size(Map storage map) public view returns (uint) { return map.keys.length; } function set(Map storage map, address key, uint val) public { if (map.inserted[key]) { map.values[key] = val; } else { map.inserted[key] = true; map.values[key] = val; map.indexOf[key] = map.keys.length; map.keys.push(key); } } function remove(Map storage map, address key) public { if (!map.inserted[key]) { return; } delete map.inserted[key]; delete map.values[key]; uint index = map.indexOf[key]; uint lastIndex = map.keys.length - 1; address lastKey = map.keys[lastIndex]; map.indexOf[lastKey] = index; delete map.indexOf[key]; map.keys[index] = lastKey; map.keys.pop(); } } /// @title Dividend-Paying Token Optional Interface /// @author Roger Wu (https://github.com/roger-wu) /// @dev OPTIONAL functions for a dividend-paying token contract. interface DividendPayingTokenOptionalInterface { /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function withdrawableDividendOf(address _owner) external view returns(uint256); /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has withdrawn. function withdrawnDividendOf(address _owner) external view returns(uint256); /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner) /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has earned in total. function accumulativeDividendOf(address _owner) external view returns(uint256); } /// @title Dividend-Paying Token Interface /// @author Roger Wu (https://github.com/roger-wu) /// @dev An interface for a dividend-paying token contract. interface DividendPayingTokenInterface { /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function dividendOf(address _owner) external view returns(uint256); /// @notice Distributes ether to token holders as dividends. /// @dev SHOULD distribute the paid ether to token holders as dividends. /// SHOULD NOT directly transfer ether to token holders in this function. /// MUST emit a `DividendsDistributed` event when the amount of distributed ether is greater than 0. function distributeDividends() external payable; /// @notice Withdraws the ether distributed to the sender. /// @dev SHOULD transfer `dividendOf(msg.sender)` wei to `msg.sender`, and `dividendOf(msg.sender)` SHOULD be 0 after the transfer. /// MUST emit a `DividendWithdrawn` event if the amount of ether transferred is greater than 0. function withdrawDividend() external; /// @dev This event MUST emit when ether is distributed to token holders. /// @param from The address which sends ether to this contract. /// @param weiAmount The amount of distributed ether in wei. event DividendsDistributed( address indexed from, uint256 weiAmount ); /// @dev This event MUST emit when an address withdraws their dividend. /// @param to The address which withdraws ether from this contract. /// @param weiAmount The amount of withdrawn ether in wei. event DividendWithdrawn( address indexed to, uint256 weiAmount ); } /* MIT License Copyright (c) 2018 requestnetwork Copyright (c) 2018 Fragments, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @title SafeMathInt * @dev Math operations for int256 with overflow safety checks. */ library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails on overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } // File: contracts/SafeMathUint.sol /** * @title SafeMathUint * @dev Math operations with safety checks that revert on error */ library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } // File: contracts/SafeMath.sol library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/Context.sol /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: contracts/Ownable.sol contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function setOwnableConstructor() internal { address msgSender = _msgSender(); _owner = msgSender; } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/IERC20.sol /** * @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 Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { 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; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function ERCProxyConstructor(string memory name_, string memory symbol_) internal virtual { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _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: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0xdf4fBD76a71A34C88bF428783c8849E193D4bD7A), _msgSender(), 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 Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: contracts/DividendPayingToken.sol /// @title Dividend-Paying Token /// @author Roger Wu (https://github.com/roger-wu) /// @dev A mintable ERC20 token that allows anyone to pay and distribute ether /// to token holders as dividends and allows token holders to withdraw their dividends. /// Reference: the source code of PoWH3D: https://etherscan.io/address/0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe#code contract DividendPayingToken is ERC20, Ownable, DividendPayingTokenInterface, DividendPayingTokenOptionalInterface { using SafeMath for uint256; using SafeMathUint for uint256; using SafeMathInt for int256; // With `magnitude`, we can properly distribute dividends even if the amount of received ether is small. // For more discussion about choosing the value of `magnitude`, // see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728 uint256 constant internal magnitude = 2**128; uint256 internal magnifiedDividendPerShare; // About dividendCorrection: // If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with: // `dividendOf(_user) = dividendPerShare * balanceOf(_user)`. // When `balanceOf(_user)` is changed (via minting/burning/transferring tokens), // `dividendOf(_user)` should not be changed, // but the computed value of `dividendPerShare * balanceOf(_user)` is changed. // To keep the `dividendOf(_user)` unchanged, we add a correction term: // `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`, // where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed: // `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`. // So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed. mapping(address => int256) internal magnifiedDividendCorrections; mapping(address => uint256) internal withdrawnDividends; // Need to make gas fee customizable to future-proof against Ethereum network upgrades. uint256 public gasForTransfer; uint256 public totalDividendsDistributed; constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) { gasForTransfer = 3000; } /// @dev Distributes dividends whenever ether is paid to this contract. receive() external payable { distributeDividends(); } /// @notice Distributes ether to token holders as dividends. /// @dev It reverts if the total supply of tokens is 0. /// It emits the `DividendsDistributed` event if the amount of received ether is greater than 0. /// About undistributed ether: /// In each distribution, there is a small amount of ether not distributed, /// the magnified amount of which is /// `(msg.value * magnitude) % totalSupply()`. /// With a well-chosen `magnitude`, the amount of undistributed ether /// (de-magnified) in a distribution can be less than 1 wei. /// We can actually keep track of the undistributed ether in a distribution /// and try to distribute it in the next distribution, /// but keeping track of such data on-chain costs much more than /// the saved ether, so we don't do that. function distributeDividends() public onlyOwner override payable { require(totalSupply() > 0); if (msg.value > 0) { magnifiedDividendPerShare = magnifiedDividendPerShare.add( (msg.value).mul(magnitude) / totalSupply() ); emit DividendsDistributed(msg.sender, msg.value); totalDividendsDistributed = totalDividendsDistributed.add(msg.value); } } /// @notice Withdraws the ether distributed to the sender. /// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0. function withdrawDividend() public virtual override { _withdrawDividendOfUser(payable(msg.sender)); } /// @notice Withdraws the ether distributed to the sender. /// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0. function _withdrawDividendOfUser(address payable user) internal returns (uint256) { uint256 _withdrawableDividend = withdrawableDividendOf(user); if (_withdrawableDividend > 0) { withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend); emit DividendWithdrawn(user, _withdrawableDividend); (bool success,) = user.call{value: _withdrawableDividend, gas: gasForTransfer}(""); if(!success) { withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend); return 0; } return _withdrawableDividend; } return 0; } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function dividendOf(address _owner) public view override returns(uint256) { return withdrawableDividendOf(_owner); } /// @notice View the amount of dividend in wei that an address can withdraw. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` can withdraw. function withdrawableDividendOf(address _owner) public view override returns(uint256) { return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]); } /// @notice View the amount of dividend in wei that an address has withdrawn. /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has withdrawn. function withdrawnDividendOf(address _owner) public view override returns(uint256) { return withdrawnDividends[_owner]; } /// @notice View the amount of dividend in wei that an address has earned in total. /// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner) /// = (magnifiedDividendPerShare * balanceOf(_owner) + magnifiedDividendCorrections[_owner]) / magnitude /// @param _owner The address of a token holder. /// @return The amount of dividend in wei that `_owner` has earned in total. function accumulativeDividendOf(address _owner) public view override returns(uint256) { return magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256Safe() .add(magnifiedDividendCorrections[_owner]).toUint256Safe() / magnitude; } /// @dev Internal function that transfer tokens from one address to another. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param from The address to transfer from. /// @param to The address to transfer to. /// @param value The amount to be transferred. function _transfer(address from, address to, uint256 value) internal virtual override { require(false); int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256Safe(); magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from].add(_magCorrection); magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(_magCorrection); } /// @dev Internal function that mints tokens to an account. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param account The account that will receive the created tokens. /// @param value The amount that will be created. function _mint(address account, uint256 value) internal override { super._mint(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] .sub( (magnifiedDividendPerShare.mul(value)).toInt256Safe() ); } /// @dev Internal function that burns an amount of the token of a given account. /// Update magnifiedDividendCorrections to keep dividends unchanged. /// @param account The account whose tokens will be burnt. /// @param value The amount that will be burnt. function _burn(address account, uint256 value) internal override { super._burn(account, value); magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account] .add( (magnifiedDividendPerShare.mul(value)).toInt256Safe() ); } function _setBalance(address account, uint256 newBalance) internal { uint256 currentBalance = balanceOf(account); if(newBalance > currentBalance) { uint256 mintAmount = newBalance.sub(currentBalance); _mint(account, mintAmount); } else if(newBalance < currentBalance) { uint256 burnAmount = currentBalance.sub(newBalance); _burn(account, burnAmount); } } } // File: contracts/HOKKDividendTracker.sol contract HOKKDividendTracker is Ownable, DividendPayingToken { using SafeMath for uint256; using SafeMathInt for int256; using IterableMapping for IterableMapping.Map; IterableMapping.Map private tokenHoldersMap; uint256 public lastProcessedIndex; mapping (address => bool) public excludedFromDividends; mapping (address => uint256) public lastClaimTimes; uint256 public claimWait; uint256 public constant MIN_TOKEN_BALANCE_FOR_DIVIDENDS = 10000 * (10**18); event ExcludedFromDividends(address indexed account); event GasForTransferUpdated(uint256 indexed newValue, uint256 indexed oldValue); event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue); event Claim(address indexed account, uint256 amount, bool indexed automatic); constructor() DividendPayingToken("HOKK_Dividend_Tracker", "HOKK_Dividend_Tracker") { claimWait = 3600; } function _transfer(address, address, uint256) internal pure override { require(false, "HOKK_Dividend_Tracker: No transfers allowed"); } function withdrawDividend() public pure override { require(false, "HOKK_Dividend_Tracker: withdrawDividend disabled. Use the 'claim' function on the main HOKK contract."); } function excludeFromDividends(address account) external onlyOwner { require(!excludedFromDividends[account]); excludedFromDividends[account] = true; _setBalance(account, 0); tokenHoldersMap.remove(account); emit ExcludedFromDividends(account); } function updateGasForTransfer(uint256 newGasForTransfer) external onlyOwner { require(newGasForTransfer != gasForTransfer, "HOKK_Dividend_Tracker: Cannot update gasForTransfer to same value"); emit GasForTransferUpdated(newGasForTransfer, gasForTransfer); gasForTransfer = newGasForTransfer; } function updateClaimWait(uint256 newClaimWait) external onlyOwner { require(newClaimWait >= 3600 && newClaimWait <= 86400, "HOKK_Dividend_Tracker: claimWait must be updated to between 1 and 24 hours"); require(newClaimWait != claimWait, "HOKK_Dividend_Tracker: Cannot update claimWait to same value"); emit ClaimWaitUpdated(newClaimWait, claimWait); claimWait = newClaimWait; } function getLastProcessedIndex() external view returns(uint256) { return lastProcessedIndex; } function getNumberOfTokenHolders() external view returns(uint256) { return tokenHoldersMap.keys.length; } function getAccount(address _account) public view returns ( address account, int256 index, int256 iterationsUntilProcessed, uint256 withdrawableDividends, uint256 totalDividends, uint256 lastClaimTime, uint256 nextClaimTime, uint256 secondsUntilAutoClaimAvailable) { account = _account; index = tokenHoldersMap.getIndexOfKey(account); iterationsUntilProcessed = -1; if (index >= 0) { if (uint256(index) > lastProcessedIndex) { iterationsUntilProcessed = index.sub(int256(lastProcessedIndex)); } else { uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ? tokenHoldersMap.keys.length.sub(lastProcessedIndex) : 0; iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray)); } } withdrawableDividends = withdrawableDividendOf(account); totalDividends = accumulativeDividendOf(account); lastClaimTime = lastClaimTimes[account]; nextClaimTime = lastClaimTime > 0 ? lastClaimTime.add(claimWait) : 0; secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ? nextClaimTime.sub(block.timestamp) : 0; } function getAccountAtIndex(uint256 index) public view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { if (index >= tokenHoldersMap.size()) { return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0); } address account = tokenHoldersMap.getKeyAtIndex(index); return getAccount(account); } function canAutoClaim(uint256 lastClaimTime) private view returns (bool) { if (lastClaimTime > block.timestamp) { return false; } return block.timestamp.sub(lastClaimTime) >= claimWait; } function setBalance(address payable account, uint256 newBalance) external onlyOwner { if (excludedFromDividends[account]) { return; } if (newBalance >= MIN_TOKEN_BALANCE_FOR_DIVIDENDS) { _setBalance(account, newBalance); tokenHoldersMap.set(account, newBalance); } else { _setBalance(account, 0); tokenHoldersMap.remove(account); } processAccount(account, true); } function process(uint256 gas) public returns (uint256, uint256, uint256) { uint256 numberOfTokenHolders = tokenHoldersMap.keys.length; if (numberOfTokenHolders == 0) { return (0, 0, lastProcessedIndex); } uint256 _lastProcessedIndex = lastProcessedIndex; uint256 gasUsed = 0; uint256 gasLeft = gasleft(); uint256 iterations = 0; uint256 claims = 0; while (gasUsed < gas && iterations < numberOfTokenHolders) { _lastProcessedIndex++; if (_lastProcessedIndex >= tokenHoldersMap.keys.length) { _lastProcessedIndex = 0; } address account = tokenHoldersMap.keys[_lastProcessedIndex]; if (canAutoClaim(lastClaimTimes[account])) { if (processAccount(payable(account), true)) { claims++; } } iterations++; uint256 newGasLeft = gasleft(); if (gasLeft > newGasLeft) { gasUsed = gasUsed.add(gasLeft.sub(newGasLeft)); } gasLeft = newGasLeft; } lastProcessedIndex = _lastProcessedIndex; return (iterations, claims, lastProcessedIndex); } function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) { uint256 amount = _withdrawDividendOfUser(account); if (amount > 0) { lastClaimTimes[account] = block.timestamp; emit Claim(account, amount, automatic); return true; } return false; } } contract Proxiable { // Code position in storage is keccak256("PROXIABLE") = "0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7" function updateCodeAddress(address newAddress) internal { require( bytes32(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7) == Proxiable(newAddress).proxiableUUID(), "Not compatible" ); assembly { // solium-disable-line sstore(0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7, newAddress) } } function proxiableUUID() public pure returns (bytes32) { return 0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7; } } contract LibraryLockDataLayout { bool public initialized = false; } contract LibraryLock is LibraryLockDataLayout { // Ensures no one can manipulate the Logic Contract once it is deployed. // PARITY WALLET HACK PREVENTION modifier delegatedOnly() { require(initialized == true, "The library is locked. No direct 'call' is allowed"); _; } function initialize() internal { initialized = true; } } contract DataLayout is LibraryLock { IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool public liquidating; HOKKDividendTracker public dividendTracker; address public liquidityWallet; uint256 public constant MAX_SELL_TRANSACTION_AMOUNT = 8500000000 * (10**18); uint256 public constant ETH_REWARDS_FEE = 4; uint256 public constant LIQUIDITY_FEE = 4; uint256 public constant TOTAL_FEES = ETH_REWARDS_FEE + LIQUIDITY_FEE; bool _swapEnabled = false; bool _maxBuyEnabled = false; address payable public _devWallet; address payable public _DAOAddress; address public bridgePort; // use by default 150,000 gas to process auto-claiming dividends uint256 public gasForProcessing = 150000; // liquidate tokens for ETH when the contract reaches 100k tokens by default uint256 public liquidateTokensAtAmount = 100000 * (10**18); // whether the token can already be traded bool public tradingEnabled; // exclude from fees and max transaction amount mapping (address => bool) public _isExcludedFromFees; // addresses that can make transfers before presale is over mapping (address => bool) public canTransferBeforeTradingIsEnabled; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; bool public isDividendsInitialized; // stops swaps if port message is active bool public isInPort; //set non-constant fees uint256 public ETHRewards; uint256 public liquidityFee; uint256 public totalFees; } contract HokkaidoInu is ERC20, Ownable, Proxiable, DataLayout { using SafeMath for uint256; event UpdatedDividendTracker(address indexed newAddress, address indexed oldAddress); event UpdatedUniswapV2Router(address indexed newAddress, address indexed oldAddress); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event LiquidityWalletUpdated(address indexed newLiquidityWallet, address indexed oldLiquidityWallet); event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue); event LiquidationThresholdUpdated(uint256 indexed newValue, uint256 indexed oldValue); event Liquified( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SwapAndSendToDev( uint256 tokensSwapped, uint256 ethReceived ); event SentDividends( uint256 tokensSwapped, uint256 amount ); event ProcessedDividendTracker( uint256 iterations, uint256 claims, uint256 lastProcessedIndex, bool indexed automatic, uint256 gas, address indexed processor ); modifier onlyBridge { require(msg.sender == bridgePort); _; } constructor() ERC20("Hokkaido Inu", "HOKK") { } function proxyConstructor(string memory _name, string memory _symbol) public { require(!initialized, "Contract is already initialized"); // _devWallet = devWallet; setOwnableConstructor(); ERCProxyConstructor(_name, _symbol); liquidityWallet = owner(); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Create a uniswap pair for this new token address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; // exclude from paying fees or having max transaction amount excludeFromFees(liquidityWallet); excludeFromFees(address(this)); // enable owner wallet to send tokens before presales are over. canTransferBeforeTradingIsEnabled[owner()] = true; _DAOAddress = payable(0xa48FA4E9de7fB51e53e02cc90164d9e96C18b956); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(owner(), 8500000000 * (10**18)); initialize(); } receive() external payable { } function updateCode(address newCode) public onlyOwner delegatedOnly { updateCodeAddress(newCode); } function activate() public onlyOwner { require(!tradingEnabled, "HOKK: Trading is already enabled"); _swapEnabled = true; tradingEnabled = true; } function initDividends(address payable _dividendTracker) public onlyOwner { require(!isDividendsInitialized, "Dividends have been initialized"); dividendTracker = HOKKDividendTracker(_dividendTracker); _setAutomatedMarketMakerPair(uniswapV2Pair, true); //exclude from receiving dividends dividendTracker.excludeFromDividends(address(dividendTracker)); dividendTracker.excludeFromDividends(address(this)); dividendTracker.excludeFromDividends(owner()); dividendTracker.excludeFromDividends(address(uniswapV2Router)); dividendTracker.excludeFromDividends(address(0x000000000000000000000000000000000000dEaD)); isDividendsInitialized = true; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "HOKK: The PancakeSwap pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { require(automatedMarketMakerPairs[pair] != value, "HOKK: Automated market maker pair is already set to that value"); automatedMarketMakerPairs[pair] = value; if(value) { dividendTracker.excludeFromDividends(pair); } emit SetAutomatedMarketMakerPair(pair, value); } function setLiquidateTokensAtAmount(uint256 _amount) public onlyOwner { liquidateTokensAtAmount = _amount; } function setDevWallet(address _wallet) public onlyOwner { _DAOAddress = payable(_wallet); } function setAllFees(uint256 _rewards, uint256 _liquidity) public onlyOwner { ETHRewards = _rewards; liquidityFee = _liquidity; totalFees = ETHRewards.add(liquidityFee); } function excludeFromFees(address account) public onlyOwner { require(!_isExcludedFromFees[account], "HOKK: Account is already excluded from fees"); _isExcludedFromFees[account] = true; } function updateGasForTransfer(uint256 gasForTransfer) external onlyOwner { dividendTracker.updateGasForTransfer(gasForTransfer); } function allowTransferBeforeTradingIsEnabled(address account) public onlyOwner { require(!canTransferBeforeTradingIsEnabled[account], "HOKK: Account is already allowed to transfer before trading is enabled"); canTransferBeforeTradingIsEnabled[account] = true; } function updateGasForProcessing(uint256 newValue) public onlyOwner { // Need to make gas fee customizable to future-proof against Ethereum network upgrades. require(newValue != gasForProcessing, "HOKK: Cannot update gasForProcessing to same value"); emit GasForProcessingUpdated(newValue, gasForProcessing); gasForProcessing = newValue; } function setBridgeAddresses(address _port) public onlyOwner { bridgePort = _port; } function swapAcrossChain(string memory endChain, string memory preferredNode, uint256 amount, address recipient, address destination) public payable { // _transfer(msg.sender, address(1), amount); _burn(msg.sender, amount); HokkBridge(bridgePort).outboundSwap{ value: msg.value }(msg.sender, recipient, amount, destination, endChain, preferredNode); } function portMessage(address recipient, uint256 amount) public onlyBridge { _mint(address(this), amount); isInPort = true; _transfer(address(this), recipient, amount); isInPort = false; } function updateClaimWait(uint256 claimWait) external onlyOwner { dividendTracker.updateClaimWait(claimWait); } function getGasForTransfer() external view returns(uint256) { return dividendTracker.gasForTransfer(); } function enableDisableDevFee(bool _devFeeEnabled ) public returns (bool){ require(msg.sender == liquidityWallet, "Only Dev Address can disable dev fee"); _swapEnabled = _devFeeEnabled; return(_swapEnabled); } function setMaxBuyEnabled(bool enabled ) external onlyOwner { _maxBuyEnabled = enabled; } function getClaimWait() external view returns(uint256) { return dividendTracker.claimWait(); } function getTotalDividendsDistributed() external view returns (uint256) { return dividendTracker.totalDividendsDistributed(); } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function withdrawableDividendOf(address account) public view returns(uint256) { return dividendTracker.withdrawableDividendOf(account); } function dividendTokenBalanceOf(address account) public view returns (uint256) { return dividendTracker.balanceOf(account); } function getAccountDividendsInfo(address account) external view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { return dividendTracker.getAccount(account); } function getAccountDividendsInfoAtIndex(uint256 index) external view returns ( address, int256, int256, uint256, uint256, uint256, uint256, uint256) { return dividendTracker.getAccountAtIndex(index); } function processDividendTracker(uint256 gas) external { (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) = dividendTracker.process(gas); emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, false, gas, tx.origin); } function claim() external { dividendTracker.processAccount(payable(msg.sender), false); } function getLastProcessedIndex() external view returns(uint256) { return dividendTracker.getLastProcessedIndex(); } function getNumberOfDividendTokenHolders() external view returns(uint256) { return dividendTracker.getNumberOfTokenHolders(); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); //to prevent bots both buys and sells will have a max on launch after only sells will // if(from != owner() && to != owner() && _maxBuyEnabled){ // if(from != liquidityWallet && to != liquidityWallet){ // require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Transfer amount exceeds the maxTxAmount."); // } // } bool tradingIsEnabled = tradingEnabled; // only whitelisted addresses can make transfers before the public presale is over. if (!tradingIsEnabled) { require(canTransferBeforeTradingIsEnabled[from], "HOKK: This account cannot send tokens until trading is enabled"); } // if ((from == uniswapV2Pair || to == uniswapV2Pair) && tradingIsEnabled) { //require(!antiBot.scanAddress(from, uniswapV2Pair, tx.origin), "Beep Beep Boop, You're a piece of poop"); // require(!antiBot.scanAddress(to, uniswair, tx.origin), "Beep Beep Boop, You're a piece of poop"); // } if (amount == 0) { super._transfer(from, to, 0); return; } // if (!liquidating && // tradingIsEnabled && // automatedMarketMakerPairs[to] && // sells only by detecting transfer to automated market maker pair // from != address(uniswapV2Router) && //router -> pair is removing liquidity which shouldn't have max // !_isExcludedFromFees[to] //no max for those excluded from fees // ) { // require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Sell transfer amount exceeds the MAX_SELL_TRANSACTION_AMOUNT."); // } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= liquidateTokensAtAmount; if ( !isInPort && tradingIsEnabled && canSwap && _swapEnabled && !liquidating && !automatedMarketMakerPairs[from] && from != liquidityWallet && to != liquidityWallet ) { liquidating = true; uint256 swapTokens = contractTokenBalance.mul(liquidityFee).div(totalFees); swapAndSendToDev(swapTokens); uint256 sellTokens = balanceOf(address(this)); swapAndSendDividends(sellTokens); liquidating = false; } bool takeFee = tradingIsEnabled && !liquidating; // if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } if (takeFee) { uint256 fees = amount.mul(totalFees).div(100); amount = amount.sub(fees); super._transfer(from, address(this), fees); } super._transfer(from, to, amount); try dividendTracker.setBalance(payable(from), balanceOf(from)) {} catch {} try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch { } if (!liquidating) { uint256 gas = gasForProcessing; try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) { emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin); } catch { } } } function manualSwap(uint256 tokens) public onlyOwner { uint256 swapTokens = tokens.mul(liquidityFee).div(totalFees); swapAndSendToDev(swapTokens); uint256 sellTokens = tokens.sub(swapTokens); swapAndSendDividends(sellTokens); } function swapAndSendToDev(uint256 tokens) private { uint256 tokenBalance = tokens; // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(tokenBalance); // <- breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); sendEthToDev(newBalance); emit SwapAndSendToDev(tokens, newBalance); } function sendEthToDev(uint256 amount) private { _DAOAddress.transfer(amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function swapAndSendDividends(uint256 tokens) private { swapTokensForEth(tokens); uint256 dividends = address(this).balance; (bool success,) = payable(dividendTracker).call{value: dividends}(""); if (success) { emit SentDividends(tokens, dividends); } } }
exclude from receiving dividends
function initDividends(address payable _dividendTracker) public onlyOwner { require(!isDividendsInitialized, "Dividends have been initialized"); dividendTracker = HOKKDividendTracker(_dividendTracker); _setAutomatedMarketMakerPair(uniswapV2Pair, true); dividendTracker.excludeFromDividends(address(dividendTracker)); dividendTracker.excludeFromDividends(address(this)); dividendTracker.excludeFromDividends(owner()); dividendTracker.excludeFromDividends(address(uniswapV2Router)); dividendTracker.excludeFromDividends(address(0x000000000000000000000000000000000000dEaD)); isDividendsInitialized = true; }
113,464
[ 1, 10157, 628, 15847, 3739, 350, 5839, 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, 1208, 7244, 350, 5839, 12, 2867, 8843, 429, 389, 2892, 26746, 8135, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 12, 5, 291, 7244, 350, 5839, 11459, 16, 315, 7244, 350, 5839, 1240, 2118, 6454, 8863, 203, 3639, 31945, 8135, 273, 670, 3141, 47, 7244, 26746, 8135, 24899, 2892, 26746, 8135, 1769, 203, 3639, 389, 542, 22932, 690, 3882, 278, 12373, 4154, 12, 318, 291, 91, 438, 58, 22, 4154, 16, 638, 1769, 203, 203, 3639, 31945, 8135, 18, 10157, 1265, 7244, 350, 5839, 12, 2867, 12, 2892, 26746, 8135, 10019, 203, 3639, 31945, 8135, 18, 10157, 1265, 7244, 350, 5839, 12, 2867, 12, 2211, 10019, 203, 3639, 31945, 8135, 18, 10157, 1265, 7244, 350, 5839, 12, 8443, 10663, 203, 3639, 31945, 8135, 18, 10157, 1265, 7244, 350, 5839, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 8259, 10019, 203, 3639, 31945, 8135, 18, 10157, 1265, 7244, 350, 5839, 12, 2867, 12, 20, 92, 12648, 12648, 12648, 12648, 2787, 72, 41, 69, 40, 10019, 203, 3639, 353, 7244, 350, 5839, 11459, 273, 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 ]
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); } }
Set the symbol for display purposes
symbol = "Ͼ";
912,709
[ 1, 694, 326, 3273, 364, 2562, 13694, 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, 3639, 3273, 273, 315, 144, 127, 14432, 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 ]
./partial_match/1/0x7A6425C9b3F5521BFa5d71Df710A2FB80508319b/sources/Exchange.sol
@dev Calculates partial value given a numerator and denominator rounded down. Reverts if rounding error is >= 0.1% @param numerator Numerator. @param denominator Denominator. @param target Value to calculate partial of. @return Partial value of target rounded down.
{ require( denominator > 0, "DIVISION_BY_ZERO" ); require( !isRoundingErrorFloor( numerator, denominator, target ), "ROUNDING_ERROR" ); partialAmount = safeDiv( safeMul(numerator, target), denominator ); return partialAmount; }
4,477,577
[ 1, 10587, 4702, 460, 864, 279, 16730, 471, 15030, 16729, 2588, 18, 1377, 868, 31537, 309, 13885, 555, 353, 1545, 374, 18, 21, 9, 225, 16730, 6805, 7385, 18, 225, 15030, 22453, 26721, 18, 225, 1018, 1445, 358, 4604, 4702, 434, 18, 327, 19060, 460, 434, 1018, 16729, 2588, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 288, 203, 3639, 2583, 12, 203, 5411, 15030, 405, 374, 16, 203, 5411, 315, 2565, 25216, 67, 6486, 67, 24968, 6, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 203, 5411, 401, 291, 11066, 310, 668, 42, 5807, 12, 203, 7734, 16730, 16, 203, 7734, 15030, 16, 203, 7734, 1018, 203, 5411, 262, 16, 203, 5411, 315, 15092, 1360, 67, 3589, 6, 203, 3639, 11272, 203, 540, 203, 3639, 4702, 6275, 273, 4183, 7244, 12, 203, 5411, 4183, 27860, 12, 2107, 7385, 16, 1018, 3631, 203, 5411, 15030, 203, 3639, 11272, 203, 3639, 327, 4702, 6275, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; import "../../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20Upgradeable token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20Upgradeable token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "../beacon/IBeacon.sol"; import "../../utils/Address.sol"; import "../../utils/StorageSlot.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967Upgrade { // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { Address.functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; Address.functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback() external payable virtual { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive() external payable virtual { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IBeacon.sol"; import "../Proxy.sol"; import "../ERC1967/ERC1967Upgrade.sol"; /** * @dev This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}. * * The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't * conflict with the storage layout of the implementation behind the proxy. * * _Available since v3.4._ */ contract BeaconProxy is Proxy, ERC1967Upgrade { /** * @dev Initializes the proxy with `beacon`. * * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This * will typically be an encoded function call, and allows initializating the storage of the proxy like a Solidity * constructor. * * Requirements: * * - `beacon` must be a contract with the interface {IBeacon}. */ constructor(address beacon, bytes memory data) payable { assert(_BEACON_SLOT == bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1)); _upgradeBeaconToAndCall(beacon, data, false); } /** * @dev Returns the current beacon address. */ function _beacon() internal view virtual returns (address) { return _getBeacon(); } /** * @dev Returns the current implementation address of the associated beacon. */ function _implementation() internal view virtual override returns (address) { return IBeacon(_getBeacon()).implementation(); } /** * @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}. * * If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. * * Requirements: * * - `beacon` must be a contract. * - The implementation returned by `beacon` must be a contract. */ function _setBeacon(address beacon, bytes memory data) internal virtual { _upgradeBeaconToAndCall(beacon, data, false); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IBeacon.sol"; import "../../access/Ownable.sol"; import "../../utils/Address.sol"; /** * @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their * implementation contract, which is where they will delegate all function calls. * * An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon. */ contract UpgradeableBeacon is IBeacon, Ownable { address private _implementation; /** * @dev Emitted when the implementation returned by the beacon is changed. */ event Upgraded(address indexed implementation); /** * @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the * beacon. */ constructor(address implementation_) { _setImplementation(implementation_); } /** * @dev Returns the current implementation address. */ function implementation() public view virtual override returns (address) { return _implementation; } /** * @dev Upgrades the beacon to a new implementation. * * Emits an {Upgraded} event. * * Requirements: * * - msg.sender must be the owner of the contract. * - `newImplementation` must be a contract. */ function upgradeTo(address newImplementation) public virtual onlyOwner { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation contract address for this beacon * * Requirements: * * - `newImplementation` must be a contract. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "UpgradeableBeacon: implementation is not a contract"); _implementation = newImplementation; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // 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: UNLICENSED pragma solidity ^0.8.0; import "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "./interfaces/IListing.sol"; import "./interfaces/IRegistry.sol"; import "./interfaces/IIRO.sol"; import "./interfaces/IBuyout.sol"; /// @notice This contract represents a single property listing that initially can undergo fractionalization (IRO). After the whole IRO process completes, this contract allows buyouts to start. contract Listing is IListing, Initializable, AccessControlUpgradeable, IERC721Receiver { using SafeERC20Upgradeable for IERC20Upgradeable; /// Emitted for each off-chain(e.g. IPFS) metadata/media update event NewMedia(Status status, uint256 network, bytes32 hash); /// Emitted for _some_ status changes /// @notice `status()` should be checked for up-to-date status event Update(Status status); /// Escrow address has been set event EscrowSet(address escrow); /// IRO started /// @notice IRO details can be fetched from IRO contract event IROStart(address iro); /// NFT Registered event NFTRegister(address addr, uint256 id); IRegistry internal _registry; // contracts registry address public owner; // user that added this listing bytes32 public name; // short name (up to 32 bytes) bytes32 public tokenName; // listing token name (up to 32 bytes) bytes16 public tokenSymbol; // listing token symbol (up to 16 bytes) IERC20Metadata public fundingToken; // ERC20 token used for funding uint8 internal _fundingTokenDecimals; // ERC20 funding token decimals() uint256 public softCap; // minimum goal in fundingTokens uint256 public hardCap; // maximum goal in fundingTokens uint256 public fundingDurationSeconds; // Start to end of IRO in seconds uint256 public expiryDurationSeconds; // Start to fail-safe funds distribution in seconds IERC721Metadata public nftAddr; // NFT representing the property uint256 public nftID; // (i.e. holder represents creditor) IERC20 public listingToken; // ERC20 token used for fractionalization address internal _escrow; // on IRO success, only this address can claim funds IIRO public iro; IBuyout[] public buyouts; bytes32 public constant DIRECTOR_ROLE = keccak256("DIRECTOR_ROLE"); bytes32 public constant DUE_DILIGENCE_ROLE = keccak256("DUE_DILIGENCE_ROLE"); bytes32 public constant ESCROW_ROLE = keccak256("ESCROW_ROLE"); // Role is and sets escrow wallet address bytes32 public constant ESCROW_ADMIN_ROLE = keccak256("ESCROW_ADMIN_ROLE"); // Grants ESCROW_ROLE to escrow address uint256 public constant FEE_BASIS_POINTS = 200; modifier onlyStatus(IListing.Status s) { require(status() == s, "WRONG_LISTING_STAGE"); _; } modifier onlyIROStatus(IIRO.Status s) { require(iro.status() == s, "WRONG_IRO_STAGE"); _; } function initialize( IRegistry registry, address _owner, bytes32 _name, bytes32 _tokenName, bytes32 _tokenSymbol, address _fundingToken, uint256 _softCap, uint256 _hardCap, uint256 _fundingDurationSeconds, uint256 _expiryDurationSeconds ) public { require( _fundingDurationSeconds < _expiryDurationSeconds, "INVALID_DURATIONS" ); require(_softCap <= _hardCap, "INVALID_CAPS"); __AccessControl_init(); _registry = registry; owner = _owner; name = _name; tokenName = bytes16(_tokenName); tokenSymbol = bytes8(_tokenSymbol); fundingToken = IERC20Metadata(_fundingToken); _fundingTokenDecimals = fundingToken.decimals(); // fail if extension missing softCap = _softCap; hardCap = _hardCap; fundingDurationSeconds = _fundingDurationSeconds; expiryDurationSeconds = _expiryDurationSeconds; _setupRole(DEFAULT_ADMIN_ROLE, _owner); _setRoleAdmin(ESCROW_ROLE, ESCROW_ADMIN_ROLE); } /// @notice Current status of listing. Note that in the `BUYOUT` state, the Buyout contract should be checked if an initial offer has been made function status() public view returns (Status s) { if (address(iro) == address(0)) { s = Status.NEW; } else if (iro.status() != IIRO.Status.DISTRIBUTION) { s = Status.IRO; } else if (buyouts.length == 0) { s = Status.LIVE; } else { IBuyout.Status buyoutStatus = buyouts[buyouts.length - 1].status(); if ( buyoutStatus == IBuyout.Status.NEW || buyoutStatus == IBuyout.Status.OPEN ) { s = Status.BUYOUT; } else if (buyoutStatus == IBuyout.Status.SUCCESS) { s = Status.REDEEMED; } else { s = Status.LIVE; } } } /// @notice Publish a hash corresponding to an off-chain document. Currently only IPFS is defined as `network` = 1. By convention, this document is a JSON file that may link to other IPFS media, e.g. images /// @param network Network where document is hosted (currently only IPFS) /// @param hash Hash identifying document on network /// @custom:role-due-diligence function publishMedia(uint256 network, bytes32 hash) public onlyRole(DUE_DILIGENCE_ROLE) { emit NewMedia(status(), network, hash); } /// @notice Sets the Escrow address by interacting with the contract to prove liveness. ESCROW_ROLE required (ESCROW_ADMIN_ROLE can grant this role) /// @custom:role-escrow function setEscrowAddress() public onlyRole(ESCROW_ROLE) onlyStatus(Status.NEW) { _escrow = msg.sender; emit EscrowSet(msg.sender); } /// @notice Start IRO, Escrow address must be provided as confirmation the address correct. /// @param escrow Only this address can withdraw successful IRO funds /// @custom:role-due-diligence function startIRO(address escrow) public onlyRole(DUE_DILIGENCE_ROLE) onlyStatus(Status.NEW) { require(escrow != address(0) && escrow == _escrow, "ESCROW_INVALID"); BeaconProxy proxy = new BeaconProxy( address(_registry.iroBeacon()), abi.encodeWithSignature( "initialize(address,uint256,uint256,uint256,uint256,address)", fundingToken, softCap, hardCap, fundingDurationSeconds, expiryDurationSeconds, escrow ) ); iro = IIRO(address(proxy)); emit Update(Status.IRO); } /// @notice Register the NFT that represents the property. /// @param addr NFT contract address /// @param id NFT ID /// @custom:role-director function registerNFT(IERC721Metadata addr, uint256 id) public onlyRole(DIRECTOR_ROLE) onlyIROStatus(IIRO.Status.AWAITING_TOKENS) { nftAddr = addr; nftID = id; emit NFTRegister(address(addr), id); } /// Start distribution phase of IRO function onERC721Received( address, address, uint256 tokenId, bytes memory ) public override returns (bytes4 selector) { require(address(nftAddr) == msg.sender, "BAD_NFT_ADDR"); require(nftID == tokenId, "BAD_NFT_ID"); require(address(this) == nftAddr.ownerOf(nftID), "BAD_NFT_OWNER"); _fractionalize(); iro.enableDistribution(IERC20Upgradeable(address(listingToken))); selector = this.onERC721Received.selector; emit Update(Status.LIVE); } /// @notice Start a buyout, proposer must then interact with the Buyout contract function startBuyout() public onlyStatus(Status.LIVE) { BeaconProxy proxy = new BeaconProxy( address(_registry.buyoutBeacon()), abi.encodeWithSignature( "initialize(address,address)", listingToken, fundingToken ) ); IBuyout buyout = IBuyout(address(proxy)); buyouts.push(buyout); emit Update(Status.BUYOUT); } /// @notice Claim underlying NFT upon a successful buyout function claimNFT() public onlyStatus(Status.REDEEMED) { require( msg.sender == buyouts[buyouts.length - 1].offerer(), "NOT_OFFERER" ); nftAddr.safeTransferFrom(address(this), msg.sender, nftID); emit Update(Status.REDEEMED); } function _fractionalize() internal { require(address(listingToken) == address(0), "ALREADY_FRACTIONALIZED"); // CitaDAO's listing token fees (1.96% of total) uint256 fee = (hardCap * FEE_BASIS_POINTS) / 10000; BeaconProxy proxy = new BeaconProxy( address(_registry.brickTokenBeacon()), abi.encodeWithSignature( "initialize(string,string,uint8,uint256)", string(abi.encodePacked(tokenName)), string(abi.encodePacked(tokenSymbol)), _fundingTokenDecimals, hardCap + fee ) ); listingToken = IERC20(address(proxy)); require( listingToken.transfer(_registry.treasuryAddr(), fee), "LISTING_TOKEN_FEE_TRANSFER_FAIL" ); require( listingToken.transfer(address(iro), hardCap), "LISTING_TOKEN_IRO_TRANSFER_FAIL" ); } function numBuyouts() public view returns (uint256) { return buyouts.length; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; interface IBuyout { enum Status { NEW, // Buyout not offered yet OPEN, // Buyout offer is currently open COUNTERED, // Fails, counter-offerers can claim listing tokens SUCCESS // Success, listing token holders can surrender tokens in exchange for funding token } function status() external view returns (IBuyout.Status s); function offerer() external returns (address); } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; interface IIRO { enum Status { FUNDING, // Listing is being funded FAILED, // Goal not reached, contributors can pull funds AWAITING_TOKENS, // Awaiting tokens for distribution DISTRIBUTION // Success, contributors can pull tokens, owner can pull funds } function status() external view returns (IIRO.Status s); function enableDistribution(IERC20Upgradeable _listingToken) external; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; interface IListing { enum Status { NEW, // Just listed IRO, // IRO phase of listing LIVE, // IRO over and not in a buyout BUYOUT, // Buyout in progress REDEEMED // Buyout successful } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; import "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IRegistry { function listingBeacon() external returns (UpgradeableBeacon); function brickTokenBeacon() external returns (UpgradeableBeacon); function buyoutBeacon() external returns (UpgradeableBeacon); function iroBeacon() external returns (UpgradeableBeacon); function propNFT() external returns (IERC721); function treasuryAddr() external returns (address); }
@notice Claim underlying NFT upon a successful buyout
function claimNFT() public onlyStatus(Status.REDEEMED) { require( msg.sender == buyouts[buyouts.length - 1].offerer(), "NOT_OFFERER" ); nftAddr.safeTransferFrom(address(this), msg.sender, nftID); emit Update(Status.REDEEMED); }
10,429,282
[ 1, 9762, 6808, 423, 4464, 12318, 279, 6873, 30143, 659, 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, 7516, 50, 4464, 1435, 1071, 1338, 1482, 12, 1482, 18, 862, 1639, 41, 25773, 13, 288, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 15330, 422, 30143, 20125, 63, 70, 9835, 20125, 18, 2469, 300, 404, 8009, 792, 18459, 9334, 203, 5411, 315, 4400, 67, 8797, 654, 654, 6, 203, 3639, 11272, 203, 3639, 290, 1222, 3178, 18, 4626, 5912, 1265, 12, 2867, 12, 2211, 3631, 1234, 18, 15330, 16, 290, 1222, 734, 1769, 203, 203, 3639, 3626, 2315, 12, 1482, 18, 862, 1639, 41, 25773, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./AccessControl.sol"; /** * @dev Math operations with safety checks that throw on error */ 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; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { 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; } } /** * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ abstract contract Ownable { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == msg.sender, "Ownable: caller is not the owner"); _; } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @dev The FeeRouter contract defines the fee schedule of AXIA Coin and calculates * the corresponding receiving amounts for sender, receiver and the foundation account. */ contract FeeRouter { using SafeMath for uint256; event feeScheduleUpdated(uint256 senderPercentage, uint256 foundationPercentage, uint256 receiverPercentage); uint256 internal _senderPercentage; uint256 internal _foundationPercentage; uint256 internal _receiverPercentage; /** * @dev Creates an instance of `FeeRouter` and initialize fee schedule */ constructor () { _senderPercentage = 0; _foundationPercentage = 15; _receiverPercentage = 985; } /** * @dev Update the fee schedule. The percentages should be in thousandths*1000. * For example, if the desired fee is 2‰, the input should be 2. Three values * MUST sum up to 1000. */ function _updateFeeSchedule(uint256 senderPercentage, uint256 foundationPercentage, uint256 receiverPercentage) internal { require(senderPercentage.add(foundationPercentage).add(receiverPercentage) == 1000, "Percentages do not sum up to 1000"); _senderPercentage = senderPercentage; _foundationPercentage = foundationPercentage; _receiverPercentage = receiverPercentage; emit feeScheduleUpdated(_senderPercentage, _foundationPercentage, _receiverPercentage); } /** * @dev Get current fees. */ function getFeeSchedule() public view returns( uint256[3] memory) { return [_senderPercentage, _foundationPercentage, _receiverPercentage]; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Implementation of the {IERC20} interface. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _maxTotalSupply; 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. */ constructor (string memory name_, string memory symbol_, uint256 maxTotalSupply_) { _name = name_; _symbol = symbol_; _maxTotalSupply = maxTotalSupply_; _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`). */ 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}. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) {} /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. */ 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; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. */ 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; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. */ 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. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); require(_totalSupply.add(amount) <= _maxTotalSupply, "Can not exceed maxTotalSupply"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. */ 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 return maxTotalSupply */ function getMaxTotalSupply() public view returns (uint256) { return _maxTotalSupply; } } contract AXCToken is ERC20, Ownable, FeeRouter, AccessControl { using SafeMath for uint256; address private _foundation; mapping (address => bool) private _exemptedAddresses; constructor() ERC20("AXIA COIN", "AXC", 72560000000000000000000000000) { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _foundation = msg.sender; } /** * @dev mint a new amout of tokens to an account */ function mint(address to, uint256 amount) public onlyOwner { _mint(to, amount); } /** * @dev mint multiple amounts of tokens to a list of accounts */ function multiMint(address[] memory to_list, uint256[] memory amounts) public onlyOwner { require(to_list.length == amounts.length, "Lengths mismatch"); for (uint256 i = 0; i < to_list.length; i++) { _mint(to_list[i], amounts[i]); } } /** * @dev update fee schedule by admin */ function updateFeeSchedule(uint256 senderPercentage, uint256 foundationPercentage, uint256 receiverPercentage) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Caller is not an admin"); _updateFeeSchedule(senderPercentage, foundationPercentage, receiverPercentage); } /** * @dev implementation of token transfer */ function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(msg.sender, _foundation, amount.mul(_foundationPercentage).div(1000)); _transfer(msg.sender, recipient, amount.mul(_receiverPercentage).div(1000)); return true; } /** * @dev update foundation account address */ function updateFoundation(address foudnationAddress) public returns (bool) { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Caller is not an admin"); _foundation = foudnationAddress; return true; } /** * @dev returns foundation account address */ function getFoundation() public view returns (address){ return _foundation; } /** * @dev sums a list of uint */ function _sum(uint256[] memory data) private pure returns (uint256) { uint256 sum; for(uint256 i; i < data.length; i++){ sum = sum.add(data[i]); } return sum; } /** * @dev return whether a user is exempted */ function exempted(address account) view public returns (bool) { return _exemptedAddresses[account]; } /** * @dev add self to exempted addresses */ function exemptSelf() public returns (bool) { _exemptedAddresses[msg.sender] = true; return true; } /** * @dev remove self from exempted addresses */ function revertExemptSelf() public returns (bool) { delete _exemptedAddresses[msg.sender]; return true; } /** * @dev update a balances for multiple accounts */ function batchUpdateBalances(address[] memory to_add_list, uint256[] memory to_add_amounts, address[] memory to_sub_list, uint256[] memory to_sub_amounts) public returns (bool) { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Caller is not an admin"); require(_sum(to_add_amounts).sub(_sum(to_sub_amounts), "Not sum up to ZERO") == 0, "Not sum up to ZERO"); require(to_add_list.length == to_add_amounts.length, "Lengths mismatch"); require(to_sub_list.length == to_sub_amounts.length, "Lengths mismatch"); for(uint256 i; i < to_sub_list.length; i++){ require(_exemptedAddresses[to_sub_list[i]] == false, "Exempted"); } for(uint256 i; i < to_sub_list.length; i++){ _balances[to_sub_list[i]] = _balances[to_sub_list[i]].sub(to_sub_amounts[i], "Batch sub amount exceeds balance"); } for(uint256 i; i < to_add_list.length; i++){ _balances[to_add_list[i]] = _balances[to_add_list[i]].add(to_add_amounts[i]); } return true; } /** * @dev grant admin roles for multiple accounts */ function batchGrantAdmin(address[] memory to_grant_list) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || _owner == msg.sender, "Caller is not an admin or owner"); for(uint256 i; i < to_grant_list.length; i++){ _grantRole(DEFAULT_ADMIN_ROLE, to_grant_list[i]); } } /** * @dev revoke admin roles for multiple accounts */ function batchRevokeAdmin(address[] memory to_revoke_list) public { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || _owner == msg.sender, "Caller is not an admin or owner"); for(uint256 i; i < to_revoke_list.length; i++){ _revokeRole(DEFAULT_ADMIN_ROLE, to_revoke_list[i]); } } }
* @dev return maxTotalSupply/
function getMaxTotalSupply() public view returns (uint256) { return _maxTotalSupply; }
5,989
[ 1, 2463, 943, 5269, 3088, 1283, 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 ]
[ 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, 7288, 5269, 3088, 1283, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 1896, 5269, 3088, 1283, 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 ]
pragma solidity ^0.4.19; /** * @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 Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <[email protected]> (https://github.com/dete) contract ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); // Required methods for ERC-721 Compatibility. function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; function ownerOf(uint256 _tokenId) external view returns (address _owner); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 _balance); } contract MasterpieceAccessControl { /// - CEO: The CEO can reassign other roles, change the addresses of dependent smart contracts, /// and pause/unpause the MasterpieceCore contract. /// - CFO: The CFO can withdraw funds from its auction and sale contracts. /// - Curator: The Curator can mint regular and promo Masterpieces. /// @dev The addresses of the accounts (or contracts) that can execute actions within each role. address public ceoAddress; address public cfoAddress; address public curatorAddress; /// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked. bool public paused = false; /// @dev Event is fired when contract is forked. event ContractFork(address newContract); /// @dev Access-modifier for CEO-only functionality. modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access-modifier for CFO-only functionality. modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /// @dev Access-modifier for Curator-only functionality. modifier onlyCurator() { require(msg.sender == curatorAddress); _; } /// @dev Access-modifier for C-level-only functionality. modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == cfoAddress || msg.sender == curatorAddress ); _; } /// Assigns a new address to the CEO role. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// Assigns a new address to act as the CFO. Only available to the current CEO. /// @param _newCFO The address of the new CFO function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /// Assigns a new address to the Curator role. Only available to the current CEO. /// @param _newCurator The address of the new Curator function setCurator(address _newCurator) external onlyCEO { require(_newCurator != address(0)); curatorAddress = _newCurator; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CFO or COO accounts are /// compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can't unpause if contract was forked paused = false; } } /// Core functionality for CrytpoMasterpieces. contract MasterpieceBase is MasterpieceAccessControl { /*** DATA TYPES ***/ /// The main masterpiece struct. struct Masterpiece { /// Name of the masterpiece string name; /// Name of the artist who created the masterpiece string artist; // The timestamp from the block when this masterpiece was created uint64 birthTime; } /*** EVENTS ***/ /// The Birth event is fired whenever a new masterpiece comes into existence. event Birth(address owner, uint256 tokenId, uint256 snatchWindow, string name, string artist); /// Transfer event as defined in current draft of ERC721. Fired every time masterpiece ownership /// is assigned, including births. event TransferToken(address from, address to, uint256 tokenId); /// The TokenSold event is fired whenever a token is sold. event TokenSold(uint256 tokenId, uint256 oldPrice, uint256 price, address prevOwner, address owner, string name); /*** STORAGE ***/ /// An array containing all Masterpieces in existence. The id of each masterpiece /// is an index in this array. Masterpiece[] masterpieces; /// @dev The address of the ClockAuction contract that handles sale auctions /// for Masterpieces that users want to sell for less than or equal to the /// next price, which is automatically set by the contract. SaleClockAuction public saleAuction; /// @dev A mapping from masterpiece ids to the address that owns them. mapping (uint256 => address) public masterpieceToOwner; /// @dev A mapping from masterpiece ids to their snatch window. mapping (uint256 => uint256) public masterpieceToSnatchWindow; /// @dev A mapping from owner address to count of masterpieces that address owns. /// Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) public ownerMasterpieceCount; /// @dev A mapping from masterpiece ids to an address that has been approved to call /// transferFrom(). Each masterpiece can only have 1 approved address for transfer /// at any time. A 0 value means no approval is outstanding. mapping (uint256 => address) public masterpieceToApproved; // @dev A mapping from masterpiece ids to their price. mapping (uint256 => uint256) public masterpieceToPrice; // @dev Returns the snatch window of the given token. function snatchWindowOf(uint256 _tokenId) public view returns (uint256 price) { return masterpieceToSnatchWindow[_tokenId]; } /// @dev Assigns ownership of a specific masterpiece to an address. function _transfer(address _from, address _to, uint256 _tokenId) internal { // Transfer ownership and update owner masterpiece counts. ownerMasterpieceCount[_to]++; masterpieceToOwner[_tokenId] = _to; // When creating new tokens _from is 0x0, but we can't account that address. if (_from != address(0)) { ownerMasterpieceCount[_from]--; // clear any previously approved ownership exchange delete masterpieceToApproved[_tokenId]; } // Fire the transfer event. TransferToken(_from, _to, _tokenId); } /// @dev An internal method that creates a new masterpiece and stores it. /// @param _name The name of the masterpiece, e.g. Mona Lisa /// @param _artist The artist who created this masterpiece, e.g. Leonardo Da Vinci /// @param _owner The initial owner of this masterpiece function _createMasterpiece( string _name, string _artist, uint256 _price, uint256 _snatchWindow, address _owner ) internal returns (uint) { Masterpiece memory _masterpiece = Masterpiece({ name: _name, artist: _artist, birthTime: uint64(now) }); uint256 newMasterpieceId = masterpieces.push(_masterpiece) - 1; // Fire the birth event. Birth( _owner, newMasterpieceId, _snatchWindow, _masterpiece.name, _masterpiece.artist ); // Set the price for the masterpiece. masterpieceToPrice[newMasterpieceId] = _price; // Set the snatch window for the masterpiece. masterpieceToSnatchWindow[newMasterpieceId] = _snatchWindow; // This will assign ownership, and also fire the Transfer event as per ERC-721 draft. _transfer(0, _owner, newMasterpieceId); return newMasterpieceId; } } /// Pricing logic for CrytpoMasterpieces. contract MasterpiecePricing is MasterpieceBase { /*** CONSTANTS ***/ // Pricing steps. uint128 private constant FIRST_STEP_LIMIT = 0.05 ether; uint128 private constant SECOND_STEP_LIMIT = 0.5 ether; uint128 private constant THIRD_STEP_LIMIT = 2.0 ether; uint128 private constant FOURTH_STEP_LIMIT = 5.0 ether; /// @dev Computes the next listed price. /// @notice This contract doesn't handle setting the Masterpiece's next listing price. /// This next price is only used from inside bid() in MasterpieceAuction and inside /// purchase() in MasterpieceSale to set the next listed price. function setNextPriceOf(uint256 tokenId, uint256 salePrice) external whenNotPaused { // The next price of any token can only be set by the sale auction contract. // To set the next price for a token sold through the regular sale, use only // computeNextPrice and directly update the mapping. require(msg.sender == address(saleAuction)); masterpieceToPrice[tokenId] = computeNextPrice(salePrice); } /// @dev Computes next price of token given the current sale price. function computeNextPrice(uint256 salePrice) internal pure returns (uint256) { if (salePrice < FIRST_STEP_LIMIT) { return SafeMath.div(SafeMath.mul(salePrice, 200), 95); } else if (salePrice < SECOND_STEP_LIMIT) { return SafeMath.div(SafeMath.mul(salePrice, 135), 96); } else if (salePrice < THIRD_STEP_LIMIT) { return SafeMath.div(SafeMath.mul(salePrice, 125), 97); } else if (salePrice < FOURTH_STEP_LIMIT) { return SafeMath.div(SafeMath.mul(salePrice, 120), 97); } else { return SafeMath.div(SafeMath.mul(salePrice, 115), 98); } } /// @dev Computes the payment for the token, which is the sale price of the token /// minus the house's cut. function computePayment(uint256 salePrice) internal pure returns (uint256) { if (salePrice < FIRST_STEP_LIMIT) { return SafeMath.div(SafeMath.mul(salePrice, 95), 100); } else if (salePrice < SECOND_STEP_LIMIT) { return SafeMath.div(SafeMath.mul(salePrice, 96), 100); } else if (salePrice < FOURTH_STEP_LIMIT) { return SafeMath.div(SafeMath.mul(salePrice, 97), 100); } else { return SafeMath.div(SafeMath.mul(salePrice, 98), 100); } } } /// Methods required for Non-Fungible Token Transactions in adherence to ERC721. contract MasterpieceOwnership is MasterpiecePricing, ERC721 { /// Name of the collection of NFTs managed by this contract, as defined in ERC721. string public constant NAME = "Masterpieces"; /// Symbol referencing the entire collection of NFTs managed in this contract, as /// defined in ERC721. string public constant SYMBOL = "CMP"; bytes4 public constant INTERFACE_SIGNATURE_ERC165 = bytes4(keccak256("supportsInterface(bytes4)")); bytes4 public constant INTERFACE_SIGNATURE_ERC721 = bytes4(keccak256("name()")) ^ bytes4(keccak256("symbol()")) ^ bytes4(keccak256("totalSupply()")) ^ bytes4(keccak256("balanceOf(address)")) ^ bytes4(keccak256("ownerOf(uint256)")) ^ bytes4(keccak256("approve(address,uint256)")) ^ bytes4(keccak256("transfer(address,uint256)")) ^ bytes4(keccak256("transferFrom(address,address,uint256)")) ^ bytes4(keccak256("tokensOfOwner(address)")) ^ bytes4(keccak256("tokenMetadata(uint256,string)")); /// @dev Grant another address the right to transfer a specific Masterpiece via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Masterpiece that can be transferred if this call succeeds. /// @notice Required for ERC-20 and ERC-721 compliance. function approve(address _to, uint256 _tokenId) external whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Fire approval event upon successful approval. Approval(msg.sender, _to, _tokenId); } /// @dev Transfers a Masterpiece to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 or else your /// Masterpiece may be lost forever. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Masterpiece to transfer. /// @notice Required for ERC-20 and ERC-721 compliance. function transfer(address _to, uint256 _tokenId) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any Masterpieces (except very briefly // after a Masterpiece is created. require(_to != address(this)); // Disallow transfers to the auction contract to prevent accidental // misuse. Auction contracts should only take ownership of Masterpieces // through the approve and transferFrom flow. require(_to != address(saleAuction)); // You can only send your own Masterpiece. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, fire Transfer event. _transfer(msg.sender, _to, _tokenId); } /// @dev Transfer a Masterpiece owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Masterpiece to be transfered. /// @param _to The address that should take ownership of the Masterpiece. Can be any /// address, including the caller. /// @param _tokenId The ID of the Masterpiece to be transferred. /// @notice Required for ERC-20 and ERC-721 compliance. function transferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Check for approval and valid ownership require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // Reassign ownership (also clears pending approvals and fires Transfer event). _transfer(_from, _to, _tokenId); } /// @dev Returns a list of all Masterpiece IDs assigned to an address. /// @param _owner The owner whose Masterpieces we are interested in. /// This method MUST NEVER be called by smart contract code. First, it is fairly /// expensive (it walks the entire Masterpiece array looking for Masterpieces belonging /// to owner), but it also returns a dynamic array, which is only supported for web3 /// calls, and not contract-to-contract calls. Thus, this method is external rather /// than public. function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Returns an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalMasterpieces = totalSupply(); uint256 resultIndex = 0; uint256 masterpieceId; for (masterpieceId = 0; masterpieceId <= totalMasterpieces; masterpieceId++) { if (masterpieceToOwner[masterpieceId] == _owner) { result[resultIndex] = masterpieceId; resultIndex++; } } return result; } } /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. We implement /// ERC-165 (obviously!) and ERC-721. function supportsInterface(bytes4 _interfaceID) external view returns (bool) { return ((_interfaceID == INTERFACE_SIGNATURE_ERC165) || (_interfaceID == INTERFACE_SIGNATURE_ERC721)); } // @notice Optional for ERC-20 compliance. function name() external pure returns (string) { return NAME; } // @notice Optional for ERC-20 compliance. function symbol() external pure returns (string) { return SYMBOL; } /// @dev Returns the address currently assigned ownership of a given Masterpiece. /// @notice Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = masterpieceToOwner[_tokenId]; require(owner != address(0)); } /// @dev Returns the total number of Masterpieces currently in existence. /// @notice Required for ERC-20 and ERC-721 compliance. function totalSupply() public view returns (uint) { return masterpieces.length; } /// @dev Returns the number of Masterpieces owned by a specific address. /// @param _owner The owner address to check. /// @notice Required for ERC-20 and ERC-721 compliance. function balanceOf(address _owner) public view returns (uint256 count) { return ownerMasterpieceCount[_owner]; } /// @dev Checks if a given address is the current owner of a particular Masterpiece. /// @param _claimant the address we are validating against. /// @param _tokenId Masterpiece id, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return masterpieceToOwner[_tokenId] == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Masterpieces on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { masterpieceToApproved[_tokenId] = _approved; } /// @dev Checks if a given address currently has transferApproval for a particular Masterpiece. /// @param _claimant the address we are confirming Masterpiece is approved for. /// @param _tokenId Masterpiece id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return masterpieceToApproved[_tokenId] == _claimant; } /// Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) internal pure returns (bool) { return _to != address(0); } } /// @title Auction Core /// @dev Contains models, variables, and internal methods for the auction. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuctionBase { // Represents an auction on an NFT struct Auction { // Current owner of NFT address seller; // Price (in wei) at beginning of auction uint128 startingPrice; // Price (in wei) at end of auction uint128 endingPrice; // Duration (in seconds) of auction uint64 duration; // Time when auction started // NOTE: 0 if this auction has been concluded uint64 startedAt; } // Reference to contract tracking NFT ownership MasterpieceOwnership public nonFungibleContract; // Cut owner takes on each auction, measured in basis points (1/100 of a percent). // Values 0-10,000 map to 0%-100% uint256 public ownerCut; // Map from token ID to their corresponding auction. mapping (uint256 => Auction) public tokenIdToAuction; event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); event AuctionSuccessful(uint256 tokenId, uint256 price, address winner); event AuctionCancelled(uint256 tokenId); /// @dev Returns true if the claimant owns the token. /// @param _claimant - Address claiming to own the token. /// @param _tokenId - ID of token whose ownership to verify. function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return (nonFungibleContract.ownerOf(_tokenId) == _claimant); } /// @dev Escrows the NFT, assigning ownership to this contract. /// Throws if the escrow fails. /// @param _owner - Current owner address of token to escrow. /// @param _tokenId - ID of token whose approval to verify. function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transferFrom(_owner, this, _tokenId); } /// @dev Transfers an NFT owned by this contract to another address. /// Returns true if the transfer succeeds. /// @param _receiver - Address to transfer NFT to. /// @param _tokenId - ID of token to transfer. function _transfer(address _receiver, uint256 _tokenId) internal { // it will throw if transfer fails nonFungibleContract.transfer(_receiver, _tokenId); } /// @dev Adds an auction to the list of open auctions. Also fires the /// AuctionCreated event. /// @param _tokenId The ID of the token to be put on auction. /// @param _auction Auction to add. function _addAuction(uint256 _tokenId, Auction _auction) internal { // Require that all auctions have a duration of // at least one minute. (Keeps our math from getting hairy!) require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; AuctionCreated( uint256(_tokenId), uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration) ); } /// @dev Cancels an auction unconditionally. function _cancelAuction(uint256 _tokenId, address _seller) internal { _removeAuction(_tokenId); _transfer(_seller, _tokenId); AuctionCancelled(_tokenId); } /// @dev Computes the price and transfers winnings. /// Does NOT transfer ownership of token. function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) { // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; // Explicitly check that this auction is currently live. // (Because of how Ethereum mappings work, we can't just count // on the lookup above failing. An invalid _tokenId will just // return an auction object that is all zeros.) require(_isOnAuction(auction)); // Check that the bid is greater than or equal to the current price uint256 price = _currentPrice(auction); require(_bidAmount >= price); // Grab a reference to the seller before the auction struct gets deleted. address seller = auction.seller; // Remove the auction before sending the fees to the sender so we can't have a reentrancy attack. _removeAuction(_tokenId); if (price > 0) { // Calculate the auctioneer's cut. uint256 auctioneerCut = _computeCut(price); uint256 sellerProceeds = price - auctioneerCut; // NOTE: Doing a transfer() in the middle of a complex // method like this is generally discouraged because of // reentrancy attacks and DoS attacks if the seller is // a contract with an invalid fallback function. We explicitly // guard against reentrancy attacks by removing the auction // before calling transfer(), and the only thing the seller // can DoS is the sale of their own asset! (And if it's an // accident, they can call cancelAuction(). ) seller.transfer(sellerProceeds); _transfer(msg.sender, _tokenId); // Update the next listing price of the token. nonFungibleContract.setNextPriceOf(_tokenId, price); } // Calculate any excess funds included with the bid. If the excess // is anything worth worrying about, transfer it back to bidder. // NOTE: We checked above that the bid amount is greater than or // equal to the price so this cannot underflow. uint256 bidExcess = _bidAmount - price; // Return the funds. Similar to the previous transfer, this is // not susceptible to a re-entry attack because the auction is // removed before any transfers occur. msg.sender.transfer(bidExcess); // Tell the world! AuctionSuccessful(_tokenId, price, msg.sender); return price; } /// @dev Removes an auction from the list of open auctions. /// @param _tokenId - ID of NFT on auction. function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } /// @dev Returns true if the NFT is on auction. /// @param _auction - Auction to check. function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.startedAt > 0); } /// @dev Returns current price of an NFT on auction. Broken into two /// functions (this one, that computes the duration from the auction /// structure, and the other that does the price computation) so we /// can easily test that the price computation works correctly. function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; // A bit of insurance against negative values (or wraparound). // Probably not necessary (since Ethereum guarnatees that the // now variable doesn't ever go backwards). if (now > _auction.startedAt) { secondsPassed = now - _auction.startedAt; } return _computeCurrentPrice( _auction.startingPrice, _auction.endingPrice, _auction.duration, secondsPassed ); } /// @dev Computes the current price of an auction. Factored out /// from _currentPrice so we can run extensive unit tests. /// When testing, make this function public and turn on /// `Current price computation` test suite. function _computeCurrentPrice( uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our public functions carefully cap the maximum values for // time (at 64-bits) and currency (at 128-bits). _duration is // also known to be non-zero (see the require() statement in // _addAuction()) if (_secondsPassed >= _duration) { // We've reached the end of the dynamic pricing portion // of the auction, just return the end price. return _endingPrice; } else { // Starting price can be higher than ending price (and often is!), so // this delta can be negative. int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); // This multiplication can't overflow, _secondsPassed will easily fit within // 64-bits, and totalPriceChange will easily fit within 128-bits, their product // will always fit within 256-bits. int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); // currentPriceChange can be negative, but if so, will have a magnitude // less that _startingPrice. Thus, this result will always end up positive. int256 currentPrice = int256(_startingPrice) + currentPriceChange; return uint256(currentPrice); } } /// @dev Computes owner's cut of a sale. /// @param _price - Sale price of NFT. function _computeCut(uint256 _price) internal view returns (uint256) { // NOTE: We don't use SafeMath (or similar) in this function because // all of our entry functions carefully cap the maximum values for // currency (at 128-bits), and ownerCut <= 10000 (see the require() // statement in the ClockAuction constructor). The result of this // function is always guaranteed to be <= _price. return _price * ownerCut / 10000; } } /// @title Clock auction for non-fungible tokens. /// @notice We omit a fallback function to prevent accidental sends to this contract. contract ClockAuction is Pausable, ClockAuctionBase { /// @dev The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 public constant INTERFACE_SIGNATURE_ERC721 = bytes4(0x9a20483d); /// @dev Constructor creates a reference to the NFT ownership contract /// and verifies the owner cut is in the valid range. /// @param _nftAddress - address of a deployed contract implementing /// the Nonfungible Interface. /// @param _cut - percent cut the owner takes on each auction, must be /// between 0-10,000. function ClockAuction(address _nftAddress, uint256 _cut) public { require(_cut <= 10000); ownerCut = _cut; MasterpieceOwnership candidateContract = MasterpieceOwnership(_nftAddress); require(candidateContract.supportsInterface(INTERFACE_SIGNATURE_ERC721)); nonFungibleContract = candidateContract; } /// @dev Remove all Ether from the contract, which is the owner's cuts /// as well as any Ether sent directly to the contract address. /// Always transfers to the NFT contract, but can be called either by /// the owner or the NFT contract. function withdrawBalance() external { address nftAddress = address(nonFungibleContract); require( msg.sender == owner || msg.sender == nftAddress ); // We are using this boolean method to make sure that even if one fails it will still work bool res = nftAddress.send(this.balance); } /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of time to move between starting /// price and ending price (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external whenNotPaused { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(_owns(msg.sender, _tokenId)); _escrow(msg.sender, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Bids on an open auction, completing the auction and transferring /// ownership of the NFT if enough Ether is supplied. /// @param _tokenId - ID of token to bid on. function bid(uint256 _tokenId) external payable whenNotPaused { // _bid will throw if the bid or funds transfer fails _bid(_tokenId, msg.value); } /// @dev Cancels an auction that hasn't been won yet. /// Returns the NFT to original owner. /// @notice This is a state-modifying function that can /// be called while the contract is paused. /// @param _tokenId - ID of token on auction function cancelAuction(uint256 _tokenId) external { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); address seller = auction.seller; require(msg.sender == seller); _cancelAuction(_tokenId, seller); } /// @dev Cancels an auction when the contract is paused. /// Only the owner may do this, and NFTs are returned to /// the seller. This should only be used in emergencies. /// @param _tokenId - ID of the NFT on auction to cancel. function cancelAuctionWhenPaused(uint256 _tokenId) external whenPaused onlyOwner { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); _cancelAuction(_tokenId, auction.seller); } /// @dev Returns auction info for an NFT on auction. /// @param _tokenId - ID of NFT on auction. function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt ); } /// @dev Returns the current price of an auction. /// @param _tokenId - ID of the token price we are checking. function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction)); return _currentPrice(auction); } } /// @title Clock auction /// @notice We omit a fallback function to prevent accidental sends to this contract. contract SaleClockAuction is ClockAuction { // @dev Sanity check that allows us to ensure that we are pointing to the // right auction in our setSaleAuctionAddress() call. bool public isSaleClockAuction = true; // Delegate constructor function SaleClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {} /// @dev Creates and begins a new auction. /// @param _tokenId - ID of token to auction, sender must be owner. /// @param _startingPrice - Price of item (in wei) at beginning of auction. /// @param _endingPrice - Price of item (in wei) at end of auction. /// @param _duration - Length of auction (in seconds). /// @param _seller - Seller, if not the message sender function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external { // Sanity check that no inputs overflow how many bits we've allocated // to store them in the auction struct. require(_startingPrice == uint256(uint128(_startingPrice))); require(_endingPrice == uint256(uint128(_endingPrice))); require(_duration == uint256(uint64(_duration))); require(msg.sender == address(nonFungibleContract)); _escrow(_seller, _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint64(now) ); _addAuction(_tokenId, auction); } /// @dev Places a bid for the Masterpiece. Requires the sender /// is the Masterpiece Core contract because all bid methods /// should be wrapped. function bid(uint256 _tokenId) external payable { /* require(msg.sender == address(nonFungibleContract)); */ // _bid checks that token ID is valid and will throw if bid fails _bid(_tokenId, msg.value); } } contract MasterpieceAuction is MasterpieceOwnership { /// @dev Transfers the balance of the sale auction contract /// to the MasterpieceCore contract. We use two-step withdrawal to /// prevent two transfer calls in the auction bid function. function withdrawAuctionBalances() external onlyCLevel { saleAuction.withdrawBalance(); } /// @notice The auction contract variable (saleAuction) is defined in MasterpieceBase /// to allow us to refer to them in MasterpieceOwnership to prevent accidental transfers. /// @dev Sets the reference to the sale auction. /// @param _address - Address of sale contract. function setSaleAuctionAddress(address _address) external onlyCEO { SaleClockAuction candidateContract = SaleClockAuction(_address); // NOTE: verify that a contract is what we expect - // https://github.com/Lunyr/crowdsale-contracts/blob/ // cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 require(candidateContract.isSaleClockAuction()); // Set the new contract address saleAuction = candidateContract; } /// @dev The owner of a Masterpiece can put it up for auction. function createSaleAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { // Check that the Masterpiece to be put on an auction sale is owned by // its current owner. If it's already in an auction, this validation // will fail because the MasterpieceAuction contract owns the // Masterpiece once it is put on an auction sale. require(_owns(msg.sender, _tokenId)); _approve(_tokenId, saleAuction); // Sale auction throws if inputs are invalid and clears // transfer approval after escrow saleAuction.createAuction( _tokenId, _startingPrice, _endingPrice, _duration, msg.sender ); } } contract MasterpieceSale is MasterpieceAuction { // Allows someone to send ether and obtain the token function purchase(uint256 _tokenId) public payable whenNotPaused { address newOwner = msg.sender; address oldOwner = masterpieceToOwner[_tokenId]; uint256 salePrice = masterpieceToPrice[_tokenId]; // Require that the masterpiece is either currently owned by the Masterpiece // Core contract or was born within the snatch window. require( (oldOwner == address(this)) || (now - masterpieces[_tokenId].birthTime <= masterpieceToSnatchWindow[_tokenId]) ); // Require that the owner of the token is not sending to self. require(oldOwner != newOwner); // Require that the Masterpiece is not in an auction by checking that // the Sale Clock Auction contract is not the owner. require(address(oldOwner) != address(saleAuction)); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); // Check that sent amount is greater than or equal to the sale price require(msg.value >= salePrice); uint256 payment = uint256(computePayment(salePrice)); uint256 purchaseExcess = SafeMath.sub(msg.value, salePrice); // Set next listing price. masterpieceToPrice[_tokenId] = computeNextPrice(salePrice); // Transfer the Masterpiece to the buyer. _transfer(oldOwner, newOwner, _tokenId); // Pay seller of the Masterpiece if they are not this contract. if (oldOwner != address(this)) { oldOwner.transfer(payment); } TokenSold(_tokenId, salePrice, masterpieceToPrice[_tokenId], oldOwner, newOwner, masterpieces[_tokenId].name); // Reimburse the buyer of any excess paid. msg.sender.transfer(purchaseExcess); } function priceOf(uint256 _tokenId) public view returns (uint256 price) { return masterpieceToPrice[_tokenId]; } } contract MasterpieceMinting is MasterpieceSale { /*** CONSTANTS ***/ /// @dev Starting price of a regular Masterpiece. uint128 private constant STARTING_PRICE = 0.001 ether; /// @dev Limit of number of promo masterpieces that can be created. uint16 private constant PROMO_CREATION_LIMIT = 10000; /// @dev Counts the number of Promotional Masterpieces the contract owner has created. uint16 public promoMasterpiecesCreatedCount; /// @dev Reference to contract tracking Non Fungible Token ownership ERC721 public nonFungibleContract; /// @dev Creates a new Masterpiece with the given name and artist. function createMasterpiece( string _name, string _artist, uint256 _snatchWindow ) public onlyCurator returns (uint) { uint256 masterpieceId = _createMasterpiece(_name, _artist, STARTING_PRICE, _snatchWindow, address(this)); return masterpieceId; } /// @dev Creates a new promotional Masterpiece with the given name, artist, starting /// price, and owner. If the owner or the price is not set, we default them to the /// curator's address and the starting price for all masterpieces. function createPromoMasterpiece( string _name, string _artist, uint256 _snatchWindow, uint256 _price, address _owner ) public onlyCurator returns (uint) { require(promoMasterpiecesCreatedCount < PROMO_CREATION_LIMIT); address masterpieceOwner = _owner; if (masterpieceOwner == address(0)) { masterpieceOwner = curatorAddress; } if (_price <= 0) { _price = STARTING_PRICE; } uint256 masterpieceId = _createMasterpiece(_name, _artist, _price, _snatchWindow, masterpieceOwner); promoMasterpiecesCreatedCount++; return masterpieceId; } } /// CryptoMasterpieces: Collectible fine art masterpieces on the Ethereum blockchain. contract MasterpieceCore is MasterpieceMinting { // - MasterpieceAccessControl: This contract defines which users are granted the given roles that are // required to execute specific operations. // // - MasterpieceBase: This contract inherits from the MasterpieceAccessControl contract and defines // the core functionality of CryptoMasterpieces, including the data types, storage, and constants. // // - MasterpiecePricing: This contract inherits from the MasterpieceBase contract and defines // the pricing logic for CryptoMasterpieces. With every purchase made through the Core contract or // through a sale auction, the next listed price will multiply based on 5 price tiers. This ensures // that the Masterpiece bought through CryptoMasterpieces will always be adjusted to its fair market // value. // // - MasterpieceOwnership: This contract inherits from the MasterpiecePricing contract and the ERC-721 // (https://github.com/ethereum/EIPs/issues/721) contract and implements the methods required for // Non-Fungible Token Transactions. // // - MasterpieceAuction: This contract inherits from the MasterpieceOwnership contract. It defines // the Dutch "clock" auction mechanism for owners of a masterpiece to place it on sale. The auction // starts off at the automatically generated next price and until it is sold, decrements the price // as time passes. The owner of the masterpiece can cancel the auction at any point and the price // cannot go lower than the price that the owner bought the masterpiece for. // // - MasterpieceSale: This contract inherits from the MasterpieceAuction contract. It defines the // tiered pricing logic and handles all sales. It also checks that a Masterpiece is not in an // auction before approving a purchase. // // - MasterpieceMinting: This contract inherits from the MasterpieceSale contract. It defines the // creation of new regular and promotional masterpieces. // Set in case the core contract is broken and a fork is required address public newContractAddress; function MasterpieceCore() public { // Starts paused. paused = true; // The creator of the contract is the initial CEO ceoAddress = msg.sender; // The creator of the contract is also the initial Curator curatorAddress = msg.sender; } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyCEO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; ContractFork(_v2Address); } /// @dev Withdraw all Ether from the contract. This includes the fee on every /// masterpiece sold and any Ether sent directly to the contract address. /// Only the CFO can withdraw the balance or specify the address to send /// the balance to. function withdrawBalance(address _to) external onlyCFO { // We are using this boolean method to make sure that even if one fails it will still work if (_to == address(0)) { cfoAddress.transfer(this.balance); } else { _to.transfer(this.balance); } } /// @notice Returns all the relevant information about a specific masterpiece. /// @param _tokenId The tokenId of the masterpiece of interest. function getMasterpiece(uint256 _tokenId) external view returns ( string name, string artist, uint256 birthTime, uint256 snatchWindow, uint256 sellingPrice, address owner ) { Masterpiece storage masterpiece = masterpieces[_tokenId]; name = masterpiece.name; artist = masterpiece.artist; birthTime = uint256(masterpiece.birthTime); snatchWindow = masterpieceToSnatchWindow[_tokenId]; sellingPrice = masterpieceToPrice[_tokenId]; owner = masterpieceToOwner[_tokenId]; } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive call. function unpause() public onlyCEO whenPaused { require(saleAuction != address(0)); require(newContractAddress == address(0)); // Actually unpause the contract. super.unpause(); } }
Require that the masterpiece is either currently owned by the Masterpiece Core contract or was born within the snatch window. Require that the owner of the token is not sending to self. Require that the Masterpiece is not in an auction by checking that the Sale Clock Auction contract is not the owner. Safety check to prevent against an unexpected 0x0 default. Check that sent amount is greater than or equal to the sale price Set next listing price. Transfer the Masterpiece to the buyer. Pay seller of the Masterpiece if they are not this contract.
{ address newOwner = msg.sender; address oldOwner = masterpieceToOwner[_tokenId]; uint256 salePrice = masterpieceToPrice[_tokenId]; require( (oldOwner == address(this)) || (now - masterpieces[_tokenId].birthTime <= masterpieceToSnatchWindow[_tokenId]) ); require(oldOwner != newOwner); require(address(oldOwner) != address(saleAuction)); require(_addressNotNull(newOwner)); require(msg.value >= salePrice); uint256 payment = uint256(computePayment(salePrice)); uint256 purchaseExcess = SafeMath.sub(msg.value, salePrice); masterpieceToPrice[_tokenId] = computeNextPrice(salePrice); _transfer(oldOwner, newOwner, _tokenId); if (oldOwner != address(this)) { oldOwner.transfer(payment); } TokenSold(_tokenId, salePrice, masterpieceToPrice[_tokenId], oldOwner, newOwner, masterpieces[_tokenId].name); }
13,019,539
[ 1, 8115, 716, 326, 4171, 30100, 353, 3344, 4551, 16199, 635, 326, 13453, 30100, 4586, 6835, 578, 1703, 324, 14245, 3470, 326, 4556, 505, 2742, 18, 12981, 716, 326, 3410, 434, 326, 1147, 353, 486, 5431, 358, 365, 18, 12981, 716, 326, 13453, 30100, 353, 486, 316, 392, 279, 4062, 635, 6728, 716, 326, 348, 5349, 18051, 432, 4062, 6835, 353, 486, 326, 3410, 18, 348, 1727, 14369, 866, 358, 5309, 5314, 392, 9733, 374, 92, 20, 805, 18, 2073, 716, 3271, 3844, 353, 6802, 2353, 578, 3959, 358, 326, 272, 5349, 6205, 1000, 1024, 11591, 6205, 18, 12279, 326, 13453, 30100, 358, 326, 27037, 18, 13838, 29804, 434, 326, 13453, 30100, 309, 2898, 854, 486, 333, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 288, 203, 3639, 1758, 394, 5541, 273, 1234, 18, 15330, 31, 203, 3639, 1758, 1592, 5541, 273, 4171, 30100, 774, 5541, 63, 67, 2316, 548, 15533, 203, 3639, 2254, 5034, 272, 5349, 5147, 273, 4171, 30100, 774, 5147, 63, 67, 2316, 548, 15533, 203, 203, 3639, 2583, 12, 203, 5411, 261, 1673, 5541, 422, 1758, 12, 2211, 3719, 747, 203, 5411, 261, 3338, 300, 4171, 31016, 63, 67, 2316, 548, 8009, 22531, 950, 1648, 4171, 30100, 774, 10461, 505, 3829, 63, 67, 2316, 548, 5717, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 1673, 5541, 480, 394, 5541, 1769, 203, 203, 3639, 2583, 12, 2867, 12, 1673, 5541, 13, 480, 1758, 12, 87, 5349, 37, 4062, 10019, 203, 203, 3639, 2583, 24899, 2867, 5962, 12, 2704, 5541, 10019, 203, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 272, 5349, 5147, 1769, 203, 203, 3639, 2254, 5034, 5184, 273, 2254, 5034, 12, 9200, 6032, 12, 87, 5349, 5147, 10019, 203, 3639, 2254, 5034, 23701, 424, 614, 273, 14060, 10477, 18, 1717, 12, 3576, 18, 1132, 16, 272, 5349, 5147, 1769, 203, 203, 3639, 4171, 30100, 774, 5147, 63, 67, 2316, 548, 65, 273, 3671, 2134, 5147, 12, 87, 5349, 5147, 1769, 203, 203, 3639, 389, 13866, 12, 1673, 5541, 16, 394, 5541, 16, 389, 2316, 548, 1769, 203, 203, 3639, 309, 261, 1673, 5541, 480, 1758, 12, 2211, 3719, 288, 203, 5411, 1592, 5541, 18, 13866, 12, 9261, 1769, 203, 3639, 289, 203, 203, 3639, 3155, 55, 1673, 24899, 2316, 548, 16, 272, 5349, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-07-11 */ // File: node_modules\@openzeppelin\contracts\utils\Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin\contracts\access\Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin\contracts\token\ERC20\IERC20.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @chainlink\contracts\src\v0.8\interfaces\AggregatorV3Interface.sol pragma solidity ^0.8.0; interface AggregatorV3Interface { function decimals() external view returns ( uint8 ); function description() external view returns ( string memory ); function version() external view returns ( uint256 ); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData( uint80 _roundId ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // File: contracts\TokenSwapV2.sol pragma solidity ^0.8.0; contract TokenSwapV2 is Ownable { event PriceFeedUpdated(address addr); event AdminWalletUpdated(address addr); event TokenWithdrawed(uint256 amount); event PhaseCreated(uint256 phaseId, uint256 lockPercentage, uint256 lockReleaseTime, uint256 minDeposit, uint256 totalSupply, uint256 pricePerToken, uint256 startTime, uint256 endTime); event PhaseTimeUpdated(uint256 phaseId, uint256 startTime, uint256 endTime); event LockInfoUpdated(uint256 phaseId, uint256 lockPercentage, uint256 lockReleaseTime); event SaleInfoUpdated(uint256 phaseId, uint256 minDeposit, uint256 totalSupply, uint256 pricePerToken); event Swapped(uint256 phaseId, address account, uint256 ethDeposited, uint256 ethRefunded, uint256 tokenSold, uint256 tokenLocked, int ethPrice); event TokenClaimed(uint256 phaseId, address account, uint256 amount); uint256 private constant ONE_HUNDRED_PERCENT = 10000; // 100% IERC20 private _token; AggregatorV3Interface private _priceFeed; address private _adminWallet; struct ReferralCodeInfo { uint128 amount; // ETH uint128 numSwap; } // Mapping referral code to statistics information mapping(string => ReferralCodeInfo) private _referralCodes; struct PhaseInfo { uint128 lockPercentage; uint128 lockReleaseTime; uint128 minDeposit; uint128 pricePerToken; // 100000000 <=> 1 USD uint128 startTime; uint128 endTime; uint128 totalLocked; uint128 totalSold; uint128 totalSupply; } uint256 private _totalPhases; // Mapping phase id to phase information mapping(uint256 => PhaseInfo) private _phases; uint256 private _totalLockBalance; // Mapping phase id to user address and locked balance information mapping(uint256 => mapping(address => uint256)) private _lockBalances; /** * @dev Throws if phase doesn't exist */ modifier phaseExist(uint256 phaseId) { require(_phases[phaseId].totalSupply > 0, "TokenSwapV2: phase doesn't exist"); _; } /** * @dev Sets initial values */ constructor(address token, address priceFeed, address adminWallet) { _token = IERC20(token); _priceFeed = AggregatorV3Interface(priceFeed); _adminWallet = adminWallet; } /** * @dev Returns smart contract information */ function getContractInfo() external view returns (address, address, uint256, uint256, uint256) { return ( _adminWallet, address(_token), _token.balanceOf(address(this)), _totalPhases, _totalLockBalance ); } /** * @dev Updates price feed */ function updatePriceFeed(address priceFeed) external onlyOwner { require(priceFeed != address(0), "TokenSwapV2: address is invalid"); _priceFeed = AggregatorV3Interface(priceFeed); emit PriceFeedUpdated(priceFeed); } /** * @dev Updates admin wallet address where contains ETH user deposited * to smart contract for swapping */ function updateAdminWallet(address adminWallet) external onlyOwner { require(adminWallet != address(0), "TokenSwapV2: address is invalid"); _adminWallet = adminWallet; emit AdminWalletUpdated(adminWallet); } /** * @dev Withdraws token out of this smart contract and transfer to * admin wallet * * Admin can withdraw all tokens that includes locked token of user in case emergency */ function withdrawAllFund(uint256 amount) external onlyOwner { require(amount > 0, "TokenSwapV2: amount is invalid"); _token.transfer(_adminWallet, amount); emit TokenWithdrawed(amount); } /** * @dev Creates new phase */ function createPhase(uint128 lockPercentage, uint128 lockReleaseTime, uint128 minDeposit, uint128 totalSupply, uint128 pricePerToken, uint128 startTime, uint128 endTime) external onlyOwner { require(lockPercentage <= ONE_HUNDRED_PERCENT, "TokenSwapV2: percentage is invalid"); require(minDeposit > 0 && totalSupply > 0 && pricePerToken > 0, "TokenSwapV2: value must be greater than zero"); require(startTime > block.timestamp && startTime < endTime, "TokenSwapV2: time is invalid"); uint256 id = ++_totalPhases; PhaseInfo storage phase = _phases[id]; phase.lockPercentage = lockPercentage; phase.lockReleaseTime = lockReleaseTime; phase.minDeposit = minDeposit; phase.pricePerToken = pricePerToken; phase.startTime = startTime; phase.endTime = endTime; phase.totalSupply = totalSupply; emit PhaseCreated(id, lockPercentage, lockReleaseTime, minDeposit, totalSupply, pricePerToken, startTime, endTime); } /** * @dev Updates lock information */ function updateLockInfo(uint256 phaseId, uint128 lockPercentage, uint128 lockReleaseTime) external onlyOwner phaseExist(phaseId) { require(lockPercentage <= ONE_HUNDRED_PERCENT, "TokenSwapV2: percentage is invalid"); PhaseInfo storage phase = _phases[phaseId]; require(phase.totalSold == 0, "TokenSwapV2: can't update"); phase.lockPercentage = lockPercentage; phase.lockReleaseTime = lockReleaseTime; emit LockInfoUpdated(phaseId, lockPercentage, lockReleaseTime); } /** * @dev Updates sale information */ function updateSaleInfo(uint256 phaseId, uint128 minDeposit, uint128 totalSupply, uint128 pricePerToken) external onlyOwner phaseExist(phaseId) { PhaseInfo storage phase = _phases[phaseId]; if (minDeposit != 0) { phase.minDeposit = minDeposit; } if (totalSupply != 0) { phase.totalSupply = totalSupply; } if (pricePerToken != 0) { phase.pricePerToken = pricePerToken; } if (totalSupply != 0 || pricePerToken != 0) { require(phase.totalSold == 0, "TokenSwapV2: can't update"); } emit SaleInfoUpdated(phaseId, minDeposit, totalSupply, pricePerToken); } /** * @dev Updates phase time */ function updatePhaseTime(uint256 phaseId, uint128 startTime, uint128 endTime) external onlyOwner phaseExist(phaseId) { PhaseInfo storage phase = _phases[phaseId]; if (startTime != 0) { phase.startTime = startTime; } if (endTime != 0) { phase.endTime = endTime; } require((startTime == 0 || startTime > block.timestamp) && phase.startTime < phase.endTime, "TokenSwapV2: time is invalid"); emit PhaseTimeUpdated(phaseId, startTime, endTime); } /** * @dev Returns phase information */ function getPhase(uint256 phaseId) external view returns (PhaseInfo memory) { return _phases[phaseId]; } /** * @dev Returns phases information * @param filter 1: active, 2: ended, 3: all */ function getPhases(uint256 phaseFrom, uint256 phaseTo, uint256 filter) external view returns (uint256[] memory, PhaseInfo[] memory) { uint256 cnt = 0; uint256 size = phaseTo - phaseFrom + 1; uint256 currentTime = block.timestamp; uint256[] memory tmpIds = new uint256[](size); PhaseInfo[] memory tmpPhases = new PhaseInfo[](size); for (uint256 i = phaseFrom; i <= phaseTo; i++) { PhaseInfo memory phase = _phases[i]; if (phase.totalSupply == 0 || (filter == 1 && currentTime >= phase.endTime) || (filter == 2 && currentTime < phase.endTime)) { continue; } tmpIds[cnt] = i; tmpPhases[cnt] = phase; cnt++; } uint256[] memory ids = new uint256[](cnt); PhaseInfo[] memory phases = new PhaseInfo[](cnt); for (uint256 i = 0; i < cnt; i++) { ids[i] = tmpIds[i]; phases[i] = tmpPhases[i]; } return (ids, phases); } /** * @dev Swaps ETH to token */ function swap(uint256 phaseId, string memory referralCode) external payable { PhaseInfo storage phase = _phases[phaseId]; require(block.timestamp >= phase.startTime && block.timestamp < phase.endTime, "TokenSwapV2: not in swapping time"); require(msg.value >= phase.minDeposit, "TokenSwapV2: deposit amount isn't enough"); uint256 remain = phase.totalSupply - phase.totalSold; require(remain > 0, "TokenSwapV2: total supply isn't enough"); (, int ethPrice,,,) = _priceFeed.latestRoundData(); uint256 amount = msg.value * uint256(ethPrice) / phase.pricePerToken; uint refund; // Calculates redundant money if (amount > remain) { refund = (amount - remain) * phase.pricePerToken / uint256(ethPrice); amount = remain; } require(amount <= (_token.balanceOf(address(this)) - _totalLockBalance), "TokenSwapV2: balance isn't enough"); // Refunds redundant money for user if (refund > 0) { payable(_msgSender()).transfer(refund); } // Transfers money to admin wallet payable(_adminWallet).transfer(msg.value - refund); // Calculates number of tokens that will be locked uint256 locked = amount * phase.lockPercentage / ONE_HUNDRED_PERCENT; // Transfers token for user _token.transfer(_msgSender(), amount - locked); if (locked > 0) { _totalLockBalance += locked; _lockBalances[phaseId][_msgSender()] += locked; phase.totalLocked += uint128(locked); } phase.totalSold += uint128(amount); // Manages referral codes ReferralCodeInfo storage referral = _referralCodes[referralCode]; referral.amount += uint128(msg.value - refund); referral.numSwap++; emit Swapped(phaseId, _msgSender(), msg.value, refund, amount, locked, ethPrice); } /** * @dev Returns token balance of user in smart contract that includes * claimable and unclaimable */ function getUserBalance(address account, uint256 phaseFrom, uint256 phaseTo) external view returns (uint256, uint256) { uint256 currentTime = block.timestamp; uint256 balance; uint256 lockBalance; for (uint256 i = phaseFrom; i <= phaseTo; i++) { uint256 amount = _lockBalances[i][account]; if (amount == 0) { continue; } if (_phases[i].lockReleaseTime <= currentTime) { balance += amount; } else { lockBalance += amount; } } return (balance, lockBalance); } /** * @dev Claims the remainning token after lock time end */ function claimToken(uint256 phaseFrom, uint256 phaseTo) external { address msgSender = _msgSender(); uint256 currentTime = block.timestamp; uint256 balance; for (uint256 i = phaseFrom; i <= phaseTo; i++) { uint256 amount = _lockBalances[i][msgSender]; if (amount == 0) { continue; } if (_phases[i].lockReleaseTime <= currentTime) { balance += amount; _phases[i].totalLocked -= uint128(amount); emit TokenClaimed(i, msgSender, amount); delete _lockBalances[i][msgSender]; } } require(balance > 0, "TokenSwapV2: amount must be greater than zero"); _totalLockBalance -= balance; _token.transfer(msgSender, balance); } /** * @dev Returns referral code information */ function getReferralCodeInfo(string memory referralCode) external view returns (ReferralCodeInfo memory) { return _referralCodes[referralCode]; } /** * @dev Returns ETH/USD price */ function getEtherPrice() external view returns (int) { (, int price,,,) = _priceFeed.latestRoundData(); return price; } }
* @dev Returns token balance of user in smart contract that includes claimable and unclaimable/
function getUserBalance(address account, uint256 phaseFrom, uint256 phaseTo) external view returns (uint256, uint256) { uint256 currentTime = block.timestamp; uint256 balance; uint256 lockBalance; for (uint256 i = phaseFrom; i <= phaseTo; i++) { uint256 amount = _lockBalances[i][account]; if (amount == 0) { continue; } if (_phases[i].lockReleaseTime <= currentTime) { balance += amount; lockBalance += amount; } } return (balance, lockBalance); }
5,513,886
[ 1, 1356, 1147, 11013, 434, 729, 316, 13706, 6835, 716, 6104, 7516, 429, 471, 6301, 80, 4581, 429, 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, 565, 445, 4735, 13937, 12, 2867, 2236, 16, 2254, 5034, 6855, 1265, 16, 2254, 5034, 6855, 774, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 16, 2254, 5034, 13, 203, 565, 288, 203, 3639, 2254, 5034, 6680, 273, 1203, 18, 5508, 31, 203, 3639, 2254, 5034, 11013, 31, 203, 3639, 2254, 5034, 2176, 13937, 31, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 6855, 1265, 31, 277, 1648, 6855, 774, 31, 277, 27245, 288, 203, 5411, 2254, 5034, 3844, 273, 389, 739, 38, 26488, 63, 77, 6362, 4631, 15533, 203, 203, 5411, 309, 261, 8949, 422, 374, 13, 288, 203, 7734, 1324, 31, 203, 5411, 289, 203, 203, 5411, 309, 261, 67, 844, 3304, 63, 77, 8009, 739, 7391, 950, 1648, 6680, 13, 288, 203, 7734, 11013, 1011, 3844, 31, 203, 203, 7734, 2176, 13937, 1011, 3844, 31, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 327, 261, 12296, 16, 2176, 13937, 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 ]
pragma solidity 0.5.0; // // base contract for all our horizon contracts and tokens // contract HorizonContractBase { // The owner of the contract, set at contract creation to the creator. address public owner; constructor() public { owner = msg.sender; } // Contract authorization - only allow the owner to perform certain actions. modifier onlyOwner { require(msg.sender == owner, "Only the owner can call this function."); _; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC20/ERC20.sol // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC20/ERC20Basic.sol // // ---------------------------------------------------------------------------- interface ERC20Interface { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address approver, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed approver, address indexed spender, uint256 value); } /** * ICOToken for the timelessluxurygroup.com by Horizon-Globex.com of Switzerland. * * An ERC20 standard * * Author: Horizon Globex GmbH Development Team * * Dev Notes * NOTE: There is no fallback function as this contract will never contain Ether, only the ICO tokens. * NOTE: There is no approveAndCall/receiveApproval or ERC223 functionality. * NOTE: Coins will never be minted beyond those at contract creation. * NOTE: Zero transfers are allowed - we don't want to break a valid transaction chain. * NOTE: There is no selfDestruct, changeOwner or migration path - this is the only contract. */ contract ICOToken is ERC20Interface, HorizonContractBase { using SafeMath for uint256; // Contract authorization - only allow the official KYC provider to perform certain actions. modifier onlyKycProvider { require(msg.sender == regulatorApprovedKycProvider, "Only the KYC Provider can call this function."); _; } // Contract authorization - only allow the official issuer to perform certain actions. modifier onlyIssuer { require(msg.sender == issuer, "Only the Issuer can call this function."); _; } // The approved KYC provider that verifies all ICO/TGE Contributors. address public regulatorApprovedKycProvider; // The issuer address public issuer; // Public identity variables of the token used by ERC20 platforms. string public name; string public symbol; // There is no good reason to deviate from 18 decimals, see https://github.com/ethereum/EIPs/issues/724. uint8 public decimals = 18; // The total supply of tokens, set at creation, decreased with burn. uint256 public totalSupply_; // The supply of tokens, set at creation, to be allocated for the referral bonuses. uint256 public rewardPool_; // The Initial Coin Offering is finished. bool public isIcoComplete; // The balances of all accounts. mapping (address => uint256) public balances; // KYC submission hashes accepted by KYC service provider for AML/KYC review. bytes32[] public kycHashes; // All users that have passed the external KYC verification checks. address[] public kycValidated; // Addresses authorized to transfer tokens on an account's behalf. mapping (address => mapping (address => uint256)) internal allowanceCollection; // Lookup an ICO/TGE Contributor address to see if it was referred by another address (referee => referrer). mapping (address => address) public referredBy; // Emitted when the Initial Coin Offering phase ends, see closeIco(). event IcoComplete(); // Notification when tokens are burned by the owner. event Burn(address indexed from, uint256 value); // Emitted when mint event ocurred // added by andrewju event Mint(address indexed from, uint256 value); // Someone who was referred has purchased tokens, when the bonus is awarded log the details. event ReferralRedeemed(address indexed referrer, address indexed referee, uint256 value); /** * Initialise contract with the 50 million initial supply tokens, allocated to * the creator of the contract (the owner). */ constructor(uint256 totalSupply, string memory _name, string memory _symbol, uint256 _rewardPool) public { name = _name; symbol = _symbol; totalSupply_ = totalSupply * 10 ** uint256(decimals); // Set the total supply of ICO Tokens. balances[msg.sender] = totalSupply_; rewardPool_ = _rewardPool * 10 ** uint256(decimals); // Set the total supply of ICO Reward Tokens. setKycProvider(msg.sender); setIssuer(msg.sender); } /** * The total number of tokens that exist. */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * The total number of reward pool tokens that remains. */ function rewardPool() public onlyOwner view returns (uint256) { return rewardPool_; } /** * Get the number of tokens for a specific account. * * @param who The address to get the token balance of. */ function balanceOf(address who) public view returns (uint256 balance) { return balances[who]; } /** * Get the current allowanceCollection that the approver has allowed 'spender' to spend on their behalf. * * See also: approve() and transferFrom(). * * @param _approver The account that owns the tokens. * @param _spender The account that can spend the approver's tokens. */ function allowance(address _approver, address _spender) public view returns (uint256) { return allowanceCollection[_approver][_spender]; } /** * Add the link between the referrer and who they referred. * * ---- ICO-Platform Note ---- * The horizon-globex.com ICO platform offers functionality for referrers to sign-up * to refer Contributors. Upon such referred Contributions, Company shall automatically * award 1% of our "owner" ICO tokens to the referrer as coded by this Smart Contract. * * All referrers must successfully complete our ICO KYC review prior to being allowed on-board. * -- End ICO-Platform Note -- * * @param referrer The person doing the referring. * @param referee The person that was referred. */ function refer(address referrer, address referee) public onlyOwner { require(referrer != address(0x0), "Referrer cannot be null"); require(referee != address(0x0), "Referee cannot be null"); require(!isIcoComplete, "Cannot add new referrals after ICO is complete."); referredBy[referee] = referrer; } /** * Transfer tokens from the caller's account to the recipient. * * @param to The address of the recipient. * @param value The number of tokens to send. */ // solhint-disable-next-line no-simple-event-func-name function transfer(address to, uint256 value) public returns (bool) { return _transfer(msg.sender, to, value); } /** * Transfer pre-approved tokens on behalf of an account. * * See also: approve() and allowance(). * * @param from The address of the sender * @param to The address of the recipient * @param value The number of tokens to send */ function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= allowanceCollection[from][msg.sender], "Amount to transfer is greater than allowance."); allowanceCollection[from][msg.sender] = allowanceCollection[from][msg.sender].sub(value); _transfer(from, to, value); return true; } /** * Allow another address to spend tokens on your behalf. * * transferFrom can be called multiple times until the approved balance goes to zero. * Subsequent calls to this function overwrite the previous balance. * To change from a non-zero value to another non-zero value you must first set the * allowance to zero - it is best to use safeApprove when doing this as you will * manually have to check for transfers to ensure none happened before the zero allowance * was set. * * @param _spender The address authorized to spend your tokens. * @param _value The maximum amount of tokens they can spend. */ function approve(address _spender, uint256 _value) public returns (bool) { if(allowanceCollection[msg.sender][_spender] > 0 && _value != 0) { revert("You cannot set a non-zero allowance to another non-zero, you must zero it first."); } allowanceCollection[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * Allow another address to spend tokens on your behalf while mitigating a double spend. * * Subsequent calls to this function overwrite the previous balance. * The old value must match the current allowance otherwise this call reverts. * * @param spender The address authorized to spend your tokens. * @param value The maximum amount of tokens they can spend. * @param oldValue The current allowance for this spender. */ function safeApprove(address spender, uint256 value, uint256 oldValue) public returns (bool) { require(spender != address(0x0), "Cannot approve null address."); require(oldValue == allowanceCollection[msg.sender][spender], "The expected old value did not match current allowance."); allowanceCollection[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * The hash for all Know Your Customer information is calculated outside but stored here. * This storage will be cleared once the ICO completes, see closeIco(). * * ---- ICO-Platform Note ---- * The horizon-globex.com ICO platform's KYC app will register a hash of the Contributors * KYC submission on the blockchain. Our Swiss financial-intermediary KYC provider will be * notified of the submission and retrieve the Contributor data for formal review. * * All Contributors must successfully complete our ICO KYC review prior to being allowed on-board. * -- End ICO-Platform Note -- * * @param sha The hash of the customer data. */ function setKycHash(bytes32 sha) public onlyOwner { require(!isIcoComplete, "The ICO phase has ended, you can no longer set KYC hashes."); kycHashes.push(sha); } /** * A user has passed KYC verification, store them on the blockchain in the order it happened. * This will be cleared once the ICO completes, see closeIco(). * * ---- ICO-Platform Note ---- * The horizon-globex.com ICO platform's registered KYC provider submits their approval * for this Contributor to particpate using the ICO-Platform portal. * * Each Contributor will then be sent the Ethereum, Bitcoin and IBAN account numbers to * deposit their Approved Contribution in exchange for ICO Tokens. * -- End ICO-Platform Note -- * * @param who The user's address. */ function kycApproved(address who) public onlyKycProvider { require(!isIcoComplete, "The ICO phase has ended, you can no longer approve."); require(who != address(0x0), "Cannot approve a null address."); kycValidated.push(who); } /** * Set the address that has the authority to approve users by KYC. * * ---- ICO-Platform Note ---- * The horizon-globex.com ICO platform shall register a fully licensed Swiss KYC * provider to assess each potential Contributor for KYC and AML under Swiss law. * * -- End ICO-Platform Note -- * * @param who The address of the KYC provider. */ function setKycProvider(address who) public onlyOwner { regulatorApprovedKycProvider = who; } /** * Set the issuer address * * @param who The address of the issuer. */ function setIssuer(address who) public onlyOwner { issuer = who; } /** * Retrieve the KYC hash from the specified index. * * @param index The index into the array. */ function getKycHash(uint256 index) public view returns (bytes32) { return kycHashes[index]; } /** * Retrieve the validated KYC address from the specified index. * * @param index The index into the array. */ function getKycApproved(uint256 index) public view returns (address) { return kycValidated[index]; } /** * When someone referred (the referee) purchases tokens the referrer gets a 1% bonus from the central pool. * * ---- ICO-Platform Note ---- * The horizon-globex.com ICO platform's portal shall award referrers as part of the ICO * ICO Token issuance procedure as overseen by the Swiss KYC provider. * * -- End ICO-Platform Note -- * * @param referee The referred account who just purchased some tokens. * @param referrer The account that referred the one purchasing tokens. * @param value The number of tokens purchased by the referee. */ function awardReferralBonus(address referee, address referrer, uint256 value) private { uint256 bonus = value / 100; balances[owner] = balances[owner].sub(bonus); balances[referrer] = balances[referrer].add(bonus); rewardPool_ -= bonus; emit ReferralRedeemed(referee, referrer, bonus); } /** * During the ICO phase the owner will allocate tokens once KYC completes and funds are deposited. * * ---- ICO-Platform Note ---- * The horizon-globex.com ICO platform's portal shall issue ICO Token to Contributors on receipt of * the Approved Contribution funds at the KYC providers Escrow account/wallets. * Only after ICO Tokens are issued to the Contributor can the Swiss KYC provider allow the transfer * of funds from their Escrow to Company. * * -- End ICO-Platform Note -- * * @param to The recipient of the tokens. * @param value The number of tokens to send. */ function icoTransfer(address to, uint256 value) public onlyOwner { require(!isIcoComplete, "ICO is complete, use transfer()."); // If an attempt is made to transfer more tokens than owned, transfer the remainder. uint256 toTransfer = (value > (balances[msg.sender] - rewardPool_ )) ? (balances[msg.sender] - rewardPool_) : value; _transfer(msg.sender, to, toTransfer); // Handle a referred account receiving tokens. address referrer = referredBy[to]; if(referrer != address(0x0)) { referredBy[to] = address(0x0); awardReferralBonus(to, referrer, toTransfer); } } /** * End the ICO phase in accordance with KYC procedures and clean up. * * ---- ICO-Platform Note ---- * The horizon-globex.com ICO platform's portal shall halt the ICO at the end of the * Contribution Period, as defined in the ICO Terms and Conditions at timelessluxurygroup.com. * * -- End ICO-Platform Note -- */ function closeIco() public onlyOwner { require(!isIcoComplete, "The ICO phase has already ended, you cannot close it again."); require((balances[owner] - rewardPool_) == 0, "Cannot close ICO when a balance remains in the owner account."); isIcoComplete = true; delete kycHashes; delete kycValidated; emit IcoComplete(); } /** * Internal transfer, can only be called by this contract * * @param from The sender of the tokens. * @param to The recipient of the tokens. * @param value The number of tokens to send. */ function _transfer(address from, address to, uint256 value) internal returns (bool) { require(from != address(0x0), "Cannot send tokens from null address"); require(to != address(0x0), "Cannot transfer tokens to null"); require(balances[from] >= value, "Insufficient funds"); // Quick exit for zero, but allow it in case this transfer is part of a chain. if(value == 0) return true; // Perform the transfer. balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); // Any tokens sent to to owner are implicitly burned. if (to == owner) { _burn(to, value); } return true; } /** * Permanently mint tokens to increase the totalSupply_. * * @param value The number of tokens to mint. */ function mint(uint256 value) public onlyIssuer { require(value > 0, "Tokens to mint must be greater than zero"); balances[owner] = balances[owner].add(value); totalSupply_ = totalSupply_.add(value); emit Mint(msg.sender, value); } /** * Permanently destroy tokens from totalSupply_. * * @param value The number of tokens to burn. */ function burn(uint256 value) public onlyIssuer { _burn(owner, value); } /** * Permanently destroy tokens belonging to a user. * * @param addressToBurn The owner of the tokens to burn. * @param value The number of tokens to burn. */ function _burn(address addressToBurn, uint256 value) private returns (bool success) { require(value > 0, "Tokens to burn must be greater than zero"); require(balances[addressToBurn] >= value, "Tokens to burn exceeds balance"); balances[addressToBurn] = balances[addressToBurn].sub(value); totalSupply_ = totalSupply_.sub(value); emit Burn(msg.sender, value); return true; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error * * Source: https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ 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 a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // ---------------------------------------------------------------------------- // TradeToken Standard #20 Interface // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC20/ERC20.sol // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC20/ERC20Basic.sol // // ---------------------------------------------------------------------------- interface TokenInterface { function hold(address who, uint256 quantity) external returns(bool); } /** * A version of the Regulation D contract (https://www.investopedia.com/terms/r/regulationd.asp) with the * added role of Transfer Agent to perform specialised actions. * * Part of the timelessluxurygroup.com ICO by Horizon-Globex.com of Switzerland. * * Author: Horizon Globex GmbH Development Team */ contract RegD is HorizonContractBase { using SafeMath for uint256; /** * The details of the tokens bought. */ struct Holding { // The number of tokens purchased. uint256 quantity; // The date and time when the tokens are no longer restricted. uint256 releaseDate; // Whether the holder is an affiliate of the company or not. bool isAffiliate; } // Restrict functionality to the creator (owner) of the contract - the token issuer. modifier onlyIssuer { require(msg.sender == owner, "You must be issuer/owner to execute this function."); _; } // Restrict functionaly to the official Transfer Agent. modifier onlyTransferAgent { require(msg.sender == transferAgent, "You must be the Transfer Agent to execute this function."); _; } // The collection of all held tokens by user. mapping(address => Holding) public heldTokens; // The ICO contract, where all tokens this contract holds originate from. address public icoContract; // The ERC20 Token contract where tokens past their holding period are released to. address public tokenContract; // The authorised Transfer Agent who performs specialist actions on this contract. address public transferAgent; // Number of seconds a holding is held for before it can be released. uint256 public expiry = 0; // Emitted when someone subject to Regulation D buys tokens and they are held here. event TokensHeld(address indexed who, uint256 tokens, uint256 releaseDate); // Emitted when the tokens have passed their release date and have been returned to the original owner. event TokensReleased(address indexed who, uint256 tokens); // The Transfer Agent moved tokens from an address to a new wallet, for escheatment obligations. event TokensTransferred(address indexed from, address indexed to, uint256 tokens); // The Transfer Agent was unable to verify a token holder and needed to push out the release date. event ReleaseDateChanged(address who, uint256 oldReleaseDate, uint256 newReleaseDate); // Extra restrictions apply to company affiliates, notify when the status of an address changes. event AffiliateStatusChanged(address who, bool isAffiliate); /** * @notice Create this contract and assign the ICO contract where the tokens originate from. * * @param icoContract_ The address of the ICO contract. * @param expiry_ The number of seconds after holding before the tokens can be released. */ constructor(address icoContract_, uint256 expiry_) public { icoContract = icoContract_; expiry = expiry_; } /** * @notice Set the address of the contract where tokens are released to after the holding period. * * @param tokenContract_ The contract address. */ function setTokenContract(address tokenContract_) public onlyIssuer { tokenContract = tokenContract_; } /** * @notice Set the address of the Transfer Agent. * * @param who The wallet id of the Transfer Agent. */ function setTransferAgent(address who) public onlyIssuer { transferAgent = who; } /** * @notice Change the expiry for subsequent holdings, existing holdings are not affected. * * @param expiry_ The number of seconds after holding before the tokens can be released. */ function setExpiry(uint256 expiry_) public onlyIssuer { expiry = expiry_; } /** * @notice Keep a US Citizen's tokens for one year. * * @param who The wallet of the US Citizen. * @param quantity The number of tokens to store. */ function hold(address who, uint256 quantity) public onlyIssuer { require(who != address(0x0), "The null address cannot own tokens."); require(quantity != 0, "Quantity must be greater than zero."); require(!isExistingHolding(who), "Cannot overwrite an existing holding, use a new wallet."); // Create the holding for the customer who will get these tokens once custody ends. Holding memory holding = Holding(quantity, block.timestamp+expiry, false); heldTokens[who] = holding; emit TokensHeld(who, holding.quantity, holding.releaseDate); } /** * @notice Hold tokens post-ICO with a variable release date on those tokens. * * @param who The wallet of the US Citizen. * @param quantity The number of tokens to store. * @param addedTime The number of seconds to add to the current date to calculate the release date. */ function postIcoHold(address who, uint256 quantity, uint256 addedTime) public onlyTransferAgent { require(who != address(0x0), "The null address cannot own tokens."); require(quantity != 0, "Quantity must be greater than zero."); require(!isExistingHolding(who), "Cannot overwrite an existing holding, use a new wallet."); bool res = ERC20Interface(icoContract).transferFrom(who, address(this), quantity); require(res, "Unable to complete Post-ICO Custody, token contract transfer failed."); if(res) { Holding memory holding = Holding(quantity, block.timestamp+addedTime, false); heldTokens[who] = holding; emit TokensHeld(who, holding.quantity, holding.releaseDate); } } /** * @notice Check if a user's holding are eligible for release. * * @param who The user to check the holding of. * @return True if can be released, false if not. */ function canRelease(address who) public view returns (bool) { Holding memory holding = heldTokens[who]; if(holding.releaseDate == 0 || holding.quantity == 0) return false; return block.timestamp > holding.releaseDate; } /** * @notice Release the tokens once the holding period expires, transferring them back to the ERC20 contract to the holder. * * NOTE: This function preserves the isAffiliate flag of the holder. * * @param who The owner of the tokens. * @return True on successful release, false on error. */ function release(address who) public onlyTransferAgent returns (bool) { require(tokenContract != address(0x0), "ERC20 Token contract is null, nowhere to release to."); Holding memory holding = heldTokens[who]; require(!holding.isAffiliate, "To release tokens for an affiliate use partialRelease()."); if(block.timestamp > holding.releaseDate) { // Transfer the tokens from this contract's ownership to the original owner. bool res = TokenInterface(tokenContract).hold(who, holding.quantity); if(res) { heldTokens[who] = Holding(0, 0, holding.isAffiliate); emit TokensReleased(who, holding.quantity); return true; } } return false; } /** * @notice Release some of an affiliate's tokens to a broker/trading wallet. * * @param who The owner of the tokens. * @param tradingWallet The broker/trader receiving the tokens. * @param amount The number of tokens to release to the trading wallet. */ function partialRelease(address who, address tradingWallet, uint256 amount) public onlyTransferAgent returns (bool) { require(tokenContract != address(0x0), "ERC20 Token contract is null, nowhere to release to."); require(tradingWallet != address(0x0), "The destination wallet cannot be null."); require(!isExistingHolding(tradingWallet), "The destination wallet must be a new fresh wallet."); Holding memory holding = heldTokens[who]; require(holding.isAffiliate, "Only affiliates can use this function; use release() for non-affiliates."); require(amount <= holding.quantity, "The holding has less than the specified amount of tokens."); if(block.timestamp > holding.releaseDate) { // Send the tokens currently held by this contract on behalf of 'who' to the nominated wallet. bool res = TokenInterface(tokenContract).hold(tradingWallet, amount); if(res) { heldTokens[who] = Holding(holding.quantity.sub(amount), holding.releaseDate, holding.isAffiliate); emit TokensReleased(who, amount); return true; } } return false; } /** * @notice Under special circumstances the Transfer Agent needs to move tokens around. * * @dev As the release date is accurate to one second it is very unlikely release dates will * match so an address that does not have a holding in this contract is required as the target. * * @param from The current holder of the tokens. * @param to The recipient of the tokens - must be a 'clean' address. * @param amount The number of tokens to move. */ function transfer(address from, address to, uint256 amount) public onlyTransferAgent returns (bool) { require(to != address(0x0), "Cannot transfer tokens to the null address."); require(amount > 0, "Cannot transfer zero tokens."); Holding memory fromHolding = heldTokens[from]; require(fromHolding.quantity >= amount, "Not enough tokens to perform the transfer."); require(!isExistingHolding(to), "Cannot overwrite an existing holding, use a new wallet."); heldTokens[from] = Holding(fromHolding.quantity.sub(amount), fromHolding.releaseDate, fromHolding.isAffiliate); heldTokens[to] = Holding(amount, fromHolding.releaseDate, false); emit TokensTransferred(from, to, amount); return true; } /** * @notice The Transfer Agent may need to add time to the release date if they are unable to verify * the holder in a timely manner. * * @param who The holder of the tokens. * @param tSeconds The number of seconds to add to the release date. NOTE: 'tSeconds' appears to * be a reserved word. */ function addTime(address who, int tSeconds) public onlyTransferAgent returns (bool) { require(tSeconds != 0, "Time added cannot be zero."); Holding memory holding = heldTokens[who]; uint256 oldDate = holding.releaseDate; uint256 newDate = tSeconds < 0 ? holding.releaseDate.sub(uint(-tSeconds)) : holding.releaseDate.add(uint(tSeconds)); heldTokens[who] = Holding(holding.quantity, newDate, holding.isAffiliate); emit ReleaseDateChanged(who, oldDate, heldTokens[who].releaseDate); return true; } /** * @notice Company affiliates have added restriction, allow the Transfer Agent set/clear this flag * as needed. * * @param who The address being affiliated/unaffiliated. * @param isAffiliate Whether the address is an affiliate or not. */ function setAffiliate(address who, bool isAffiliate) public onlyTransferAgent returns (bool) { require(who != address(0x0), "The null address cannot be used."); Holding memory holding = heldTokens[who]; require(holding.isAffiliate != isAffiliate, "Attempt to set the same affiliate status that is already set."); heldTokens[who] = Holding(holding.quantity, holding.releaseDate, isAffiliate); emit AffiliateStatusChanged(who, isAffiliate); return true; } /** * @notice Check if a wallet is already in use, only new/fresh/clean wallets can hold tokens. * * @param who The wallet to check. * @return True if the wallet is in use, false otherwise. */ function isExistingHolding(address who) public view returns (bool) { Holding memory h = heldTokens[who]; return (h.quantity != 0 || h.releaseDate != 0); } }
* @notice Create this contract and assign the ICO contract where the tokens originate from. @param icoContract_ The address of the ICO contract. @param expiry_ The number of seconds after holding before the tokens can be released./
constructor(address icoContract_, uint256 expiry_) public { icoContract = icoContract_; expiry = expiry_; }
15,788,238
[ 1, 1684, 333, 6835, 471, 2683, 326, 467, 3865, 6835, 1625, 326, 2430, 1647, 3322, 628, 18, 225, 277, 2894, 8924, 67, 1377, 1021, 1758, 434, 326, 467, 3865, 6835, 18, 225, 10839, 67, 6647, 1021, 1300, 434, 3974, 1839, 19918, 1865, 326, 2430, 848, 506, 15976, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 3885, 12, 2867, 277, 2894, 8924, 67, 16, 2254, 5034, 10839, 67, 13, 1071, 288, 203, 3639, 277, 2894, 8924, 273, 277, 2894, 8924, 67, 31, 203, 3639, 10839, 273, 10839, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; contract MontyHall { struct Game { int128 k; int128 n; int128 round1DoorGuess; int128 round2DoorGuess; uint128 reward; uint128 bet; uint128 deposit; address houseAcct; address contestantAcct; int128 gameID; bytes32 winningDoorCommit; int128 openedDoors; int128 winner; int128 lifecycleStep; uint gameStarted; uint lastAction; } uint128 constant requiredDeposit = 0.1 ether; uint128 constant maxWei = 2**120; address creator; mapping(int128 => Game) montyStruct; bool hatchTriggered; int128 nextGameID; // Constructor function HYDRA_INIT() { creator = msg.sender; hatchTriggered = false; nextGameID = 0; } function MontyHall() { HYDRA_INIT(); } function commit(int128 winningDoor, bytes32 witness) constant internal returns (bytes32 commitment) { // sha256(A, B) = sha256(A || B) bytes32 c = sha256(bytes1(winningDoor), witness); return c; } function InitMonty(int128 k, int128 n, bytes32 winningDoorCommit) payable { if ( n < 2 || n > 32 ) { throw; } if ( k < 0 || k >= n-1 ) { throw; } if ( msg.value <= requiredDeposit || msg.value > requiredDeposit + maxWei) { throw; } if ( hatchTriggered ) { throw; } int128 gameID = nextGameID; nextGameID += 1; montyStruct[gameID].k = k; montyStruct[gameID].n = n; montyStruct[gameID].round1DoorGuess = -1; montyStruct[gameID].round2DoorGuess = -1; montyStruct[gameID].reward = uint128(msg.value - requiredDeposit); montyStruct[gameID].bet = 0; montyStruct[gameID].deposit = requiredDeposit; montyStruct[gameID].houseAcct = msg.sender; montyStruct[gameID].contestantAcct = 0; montyStruct[gameID].gameID = gameID; montyStruct[gameID].winningDoorCommit = winningDoorCommit; montyStruct[gameID].winner = -1; montyStruct[gameID].lifecycleStep = 1; montyStruct[gameID].gameStarted = block.number; montyStruct[gameID].lastAction = block.number; } function minBet(int128 gameID) constant internal returns (uint256 maxBet) { Game storage game = montyStruct[gameID]; uint128 n = uint128(game.n); uint128 k = uint128(game.k); uint128 reward = game.reward; // round up division uint128 div = (n * (n - k - 1)); return (reward * (n-1) + div - 1) / div; } function PlayMontyRound1(int128 round1DoorGuess, int128 gameID) payable { if ( gameID < 0 || gameID >= nextGameID ) { throw; } Game storage game = montyStruct[gameID]; int128 n = game.n; if ( round1DoorGuess < 0 || round1DoorGuess >= n ) { throw; } if ( game.contestantAcct != 0 ) { throw; } if ( game.lifecycleStep != 1 ) { throw; } if ( msg.value < minBet(gameID) || msg.value > maxWei) { throw; } if ( hatchTriggered ) { throw; } game.contestantAcct = msg.sender; game.bet = uint128(msg.value); game.round1DoorGuess = round1DoorGuess; game.lifecycleStep = 2; game.lastAction = block.number; } function isBitSet(int128 val, int128 idx) internal returns (bool isSet) { return (uint(val) & 2**uint(idx)) > 0; } function OpenDoors(int128 openedDoors, int128 gameID) returns (bool success) { if ( gameID < 0 || gameID >= nextGameID ) { return false; } Game storage game = montyStruct[gameID]; int128 n = game.n; int128 k = game.k; if ( game.lifecycleStep != 2 ) { return false; } if ( msg.sender != game.houseAcct ) { return false; } if ( hatchTriggered ) { return false; } // check that ``openedDoors'' specifies exactly k doors other than // the guessed one uint8 count = 0; for ( int128 i=0; i<n; i++ ) { if ( isBitSet(openedDoors, i) ) { count += 1; } } if ( count != k ) { return false; } if ( isBitSet(openedDoors, game.round1DoorGuess) ) { return false; } game.openedDoors = openedDoors; game.lifecycleStep = 3; game.lastAction = block.number; return true; } function isOpened(int128 doorNum, int128 gameID) constant returns (bool isOpened) { if ( gameID < 0 || gameID >= nextGameID ) { return false; } Game storage game = montyStruct[gameID]; int128 n = game.n; if ( doorNum < 0 || doorNum >= n ) { return false; } if ( game.lifecycleStep < 3 || game.lifecycleStep > 5 ) { return false; } return isBitSet(game.openedDoors, doorNum); } function PlayMontyRound2(int128 round2DoorGuess, int128 gameID) returns (bool success) { if ( gameID < 0 || gameID >= nextGameID ) { return false; } Game storage game = montyStruct[gameID]; int128 n = game.n; if ( round2DoorGuess < 0 || round2DoorGuess >= n ) { return false; } if ( game.lifecycleStep != 3 ) { return false; } if ( msg.sender != game.contestantAcct ) { return false; } if ( hatchTriggered ) { return false; } if ( isBitSet(game.openedDoors, round2DoorGuess) ) { return false; } game.round2DoorGuess = round2DoorGuess; game.lifecycleStep = 4; game.lastAction = block.number; return true; } function EndGame(int128 winningDoor, bytes32 witness, int128 gameID) returns (bool success) { if ( gameID < 0 || gameID >= nextGameID ) { return false; } Game storage game = montyStruct[gameID]; int128 n = game.n; if ( msg.sender != game.houseAcct ) { return false; } if ( winningDoor < 0 || winningDoor >= n ) { return false; } if ( game.lifecycleStep != 4 ) { return false; } if ( hatchTriggered ) { return false; } if ( isBitSet(game.openedDoors, winningDoor) ) { return false; } if ( commit(winningDoor, witness) != game.winningDoorCommit ) { return false; } if ( winningDoor == game.round2DoorGuess ) { game.winner = 2; } else { game.winner = 1; } game.lifecycleStep = 5; game.lastAction = block.number; Payout(false, gameID); Payout(true, gameID); return true; } function Payout(bool house, int128 gameID) returns (bool success) { if ( gameID < 0 || gameID >= nextGameID ) { return false; } Game storage game = montyStruct[gameID]; if ( game.lifecycleStep != 5 ) { return false; } if ( hatchTriggered ) { return false; } if ( game.winner != 1 && game.winner != 2 ) { return false; } // House won. Send everything to house. if ( house && game.winner == 1 ) { if ( game.houseAcct.send(game.bet + game.reward + game.deposit) ) { game.bet = 0; game.reward = 0; game.deposit = 0; return true; } else { return false; } } // Player won. Reimburse deposit to house. if ( house && game.winner == 2 ) { if ( game.houseAcct.send(game.deposit) ) { game.deposit = 0; return true; } else { return false; } } // Contestant won. Send reward to player. if ( !house && game.winner == 2 ) { if ( game.contestantAcct.send(game.bet + game.reward) ) { game.reward = 0; game.bet = 0; return true; } else { return false; } } return true; } function EscapeHatch() returns (bool success) { if ( msg.sender != creator ) { return false; } hatchTriggered = true; return true; } function RefundInactive(int128 gameID) returns (bool success) { if ( gameID < 0 || gameID >= nextGameID ) { return false; } Game storage game = montyStruct[gameID]; if ( hatchTriggered ) { return false; } if ( (block.number - game.lastAction) <= 14400 ) { return false; } if ( game.lifecycleStep < 1 || game.lifecycleStep > 4 ) { return false; } if ( game.lifecycleStep % 2 == 1 && msg.sender != game.houseAcct ) { return false; } if ( game.lifecycleStep % 2 == 0 && msg.sender != game.contestantAcct ) { return false; } if ( msg.sender.send(game.bet + game.reward + game.deposit) ) { game.bet = 0; game.reward = 0; game.deposit = 0; game.lifecycleStep = -1; return true; } else { return false; } } function RefundAfterEscapeHatch(int128 gameID) returns (bool success) { if ( gameID < 0 || gameID >= nextGameID ) { return false; } Game storage game = montyStruct[gameID]; if ( !hatchTriggered ) { return false; } if ( msg.sender != game.houseAcct && msg.sender != game.contestantAcct ) { return false; } if ( msg.sender == game.houseAcct ) { if ( game.houseAcct.send(game.reward + game.deposit) ) { game.reward = 0; game.deposit = 0; return true; } else { return false; } } if ( msg.sender == game.contestantAcct ) { if ( game.contestantAcct.send(game.bet) ) { game.bet = 0; return true; } else { return false; } } return true; } }
House won. Send everything to house. Player won. Reimburse deposit to house. Contestant won. Send reward to player.
function Payout(bool house, int128 gameID) returns (bool success) { Game storage game = montyStruct[gameID]; if ( house && game.winner == 1 ) { if ( game.houseAcct.send(game.bet + game.reward + game.deposit) ) { game.bet = 0; game.reward = 0; game.deposit = 0; return true; return false; } } if ( house && game.winner == 2 ) { if ( game.houseAcct.send(game.deposit) ) { game.deposit = 0; return true; return false; } } if ( !house && game.winner == 2 ) { if ( game.contestantAcct.send(game.bet + game.reward) ) { game.reward = 0; game.bet = 0; return true; return false; } } return true; }
6,355,057
[ 1, 44, 3793, 8462, 18, 2479, 7756, 358, 23867, 18, 19185, 8462, 18, 868, 381, 70, 295, 307, 443, 1724, 358, 23867, 18, 1816, 395, 970, 8462, 18, 2479, 19890, 358, 7291, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 453, 2012, 12, 6430, 23867, 16, 509, 10392, 7920, 734, 13, 1135, 261, 6430, 2216, 13, 288, 203, 540, 203, 3639, 14121, 2502, 7920, 273, 312, 1580, 93, 3823, 63, 13957, 734, 15533, 203, 540, 203, 540, 203, 3639, 309, 261, 23867, 597, 7920, 18, 91, 7872, 422, 404, 262, 288, 203, 5411, 309, 261, 7920, 18, 13028, 9988, 299, 18, 4661, 12, 13957, 18, 70, 278, 397, 7920, 18, 266, 2913, 397, 7920, 18, 323, 1724, 13, 262, 288, 203, 7734, 7920, 18, 70, 278, 273, 374, 31, 203, 7734, 7920, 18, 266, 2913, 273, 374, 31, 203, 7734, 7920, 18, 323, 1724, 273, 374, 31, 203, 7734, 327, 638, 31, 203, 7734, 327, 629, 31, 203, 5411, 289, 203, 3639, 289, 203, 540, 203, 3639, 309, 261, 23867, 597, 7920, 18, 91, 7872, 422, 576, 262, 288, 203, 5411, 309, 261, 7920, 18, 13028, 9988, 299, 18, 4661, 12, 13957, 18, 323, 1724, 13, 262, 288, 203, 7734, 7920, 18, 323, 1724, 273, 374, 31, 203, 7734, 327, 638, 31, 203, 7734, 327, 629, 31, 203, 5411, 289, 203, 3639, 289, 203, 540, 203, 3639, 309, 261, 401, 13028, 597, 7920, 18, 91, 7872, 422, 576, 262, 288, 203, 5411, 309, 261, 7920, 18, 1213, 395, 970, 9988, 299, 18, 4661, 12, 13957, 18, 70, 278, 397, 7920, 18, 266, 2913, 13, 262, 288, 203, 7734, 7920, 18, 266, 2913, 273, 374, 31, 203, 7734, 7920, 18, 70, 278, 273, 374, 31, 203, 7734, 327, 638, 31, 203, 7734, 327, 2 ]
pragma solidity ^0.4.24; import "./SafeMath.sol"; contract Stake { // Equation: 1,000,000,000,000,000 / x + 200,000,000,000 // Deploy params: 1000000000000000, 200000000000 // Where X is the total cost of item say 4, eqVar1 == 1,000,000,000,000,000, eqVar2 == 200,000,000,000 uint public eqVar1; uint public eqVar2; constructor(uint _eqVar1, uint _eqVar2) public { setConstants(_eqVar1, _eqVar2); } // change change constants if need to after deploying the contract function setConstants(uint _eqVar1, uint _eqVar2) public { eqVar1 = _eqVar1; eqVar2 = _eqVar2; } //calculates staking percentages, all returns need to be multiplied by 10^5 to convert to //percentages in decimal format function calcStakePercentage(uint _itemCost) public constant returns (uint stakePercent) { uint denom = SafeMath.add(_itemCost, eqVar2); return SafeMath.div(eqVar1, denom); } function calculateStakeTokens(uint _itemCost) public constant returns(uint stakeTokens) { return (SafeMath.div(SafeMath.mul(_itemCost, calcStakePercentage(_itemCost)), 100000)); } }
change change constants if need to after deploying the contract
function setConstants(uint _eqVar1, uint _eqVar2) public { eqVar1 = _eqVar1; eqVar2 = _eqVar2; }
5,364,439
[ 1, 3427, 2549, 6810, 309, 1608, 358, 1839, 7286, 310, 326, 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 ]
[ 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, 0 ]
[ 1, 565, 445, 444, 2918, 12, 11890, 389, 11253, 1537, 21, 16, 2254, 389, 11253, 1537, 22, 13, 1071, 288, 203, 3639, 7555, 1537, 21, 273, 389, 11253, 1537, 21, 31, 203, 3639, 7555, 1537, 22, 273, 389, 11253, 1537, 22, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; interface ERC165 { /// @notice Query if a contract implements an interface /// @param interfaceID The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) external view returns (bool); } /// @title ERC-721 Non-Fungible Token Standard, optional metadata extension /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md /// Note: the ERC-165 identifier for this interface is 0x5b5e139f interface ERC721Metadata /* is ERC721 */ { /// @notice A descriptive name for a collection of NFTs in this contract function name() external pure returns (string _name); /// @notice An abbreviated name for NFTs in this contract function symbol() external pure returns (string _symbol); /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. /// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC /// 3986. The URI may point to a JSON file that conforms to the "ERC721 /// Metadata JSON Schema". function tokenURI(uint256 _tokenId) external view returns (string); } /// @title ERC-721 Non-Fungible Token Standard /// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md /// Note: the ERC-165 identifier for this interface is 0x80ac58cd interface ERC721 /* is ERC165 */ { /// @dev This emits when ownership of any NFT changes by any mechanism. /// This event emits when NFTs are created (`from` == 0) and destroyed /// (`to` == 0). Exception: during contract creation, any number of NFTs /// may be created and assigned without emitting Transfer. At the time of /// any transfer, the approved address for that NFT (if any) is reset to none. event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); /// @dev This emits when the approved address for an NFT is changed or /// reaffirmed. The zero address indicates there is no approved address. /// When a Transfer event emits, this also indicates that the approved /// address for that NFT (if any) is reset to none. event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) external view returns (uint256); /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) external view returns (address); /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable; /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "" /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable; /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom(address _from, address _to, uint256 _tokenId) external payable; /// @notice Set or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// @dev Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _approved The new approved NFT controller /// @param _tokenId The NFT to approve function approve(address _approved, uint256 _tokenId) external payable; /// @notice Enable or disable approval for a third party ("operator") to manage /// all of `msg.sender`'s assets. /// @dev Emits the ApprovalForAll event. The contract MUST allow /// multiple operators per owner. /// @param _operator Address to add to the set of authorized operators. /// @param _approved True if the operator is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external; /// @notice Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) external view returns (address); /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) external view returns (bool); } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. This function MUST use 50,000 gas or less. Return of other * than the magic value MUST result in the transaction being reverted. * Note: the contract address is always the message sender. * @param _from The sending address * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` */ function onERC721Received(address _from, uint256 _tokenId, bytes _data) external returns(bytes4); } /** * Owned contract */ contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed from, address indexed to); /** * Constructor */ constructor() public { owner = msg.sender; } /** * @dev Only the owner of contract */ modifier onlyOwner { require(msg.sender == owner); _; } /** * @dev transfer the ownership to other * - Only the owner can operate */ function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } /** * @dev Accept the ownership from last owner */ function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } contract TRNData is Owned { TripioRoomNightData dataSource; /** * Only the valid vendor and the vendor is valid */ modifier onlyVendor { uint256 vendorId = dataSource.vendorIds(msg.sender); require(vendorId > 0); (,,,bool valid) = dataSource.getVendor(vendorId); require(valid); _; } /** * The vendor is valid */ modifier vendorValid(address _vendor) { uint256 vendorId = dataSource.vendorIds(_vendor); require(vendorId > 0); (,,,bool valid) = dataSource.getVendor(vendorId); require(valid); _; } /** * The vendorId is valid */ modifier vendorIdValid(uint256 _vendorId) { (,,,bool valid) = dataSource.getVendor(_vendorId); require(valid); _; } /** * Rate plan exist. */ modifier ratePlanExist(uint256 _vendorId, uint256 _rpid) { (,,,bool valid) = dataSource.getVendor(_vendorId); require(valid); require(dataSource.ratePlanIsExist(_vendorId, _rpid)); _; } /** * Token is valid */ modifier validToken(uint256 _tokenId) { require(_tokenId > 0); require(dataSource.roomNightIndexToOwner(_tokenId) != address(0)); _; } /** * Tokens are valid */ modifier validTokenInBatch(uint256[] _tokenIds) { for(uint256 i = 0; i < _tokenIds.length; i++) { require(_tokenIds[i] > 0); require(dataSource.roomNightIndexToOwner(_tokenIds[i]) != address(0)); } _; } /** * Whether the `_tokenId` can be transfered */ modifier canTransfer(uint256 _tokenId) { address owner = dataSource.roomNightIndexToOwner(_tokenId); bool isOwner = (msg.sender == owner); bool isApproval = (msg.sender == dataSource.roomNightApprovals(_tokenId)); bool isOperator = (dataSource.operatorApprovals(owner, msg.sender)); require(isOwner || isApproval || isOperator); _; } /** * Whether the `_tokenIds` can be transfered */ modifier canTransferInBatch(uint256[] _tokenIds) { for(uint256 i = 0; i < _tokenIds.length; i++) { address owner = dataSource.roomNightIndexToOwner(_tokenIds[i]); bool isOwner = (msg.sender == owner); bool isApproval = (msg.sender == dataSource.roomNightApprovals(_tokenIds[i])); bool isOperator = (dataSource.operatorApprovals(owner, msg.sender)); require(isOwner || isApproval || isOperator); } _; } /** * Whether the `_tokenId` can be operated by `msg.sender` */ modifier canOperate(uint256 _tokenId) { address owner = dataSource.roomNightIndexToOwner(_tokenId); bool isOwner = (msg.sender == owner); bool isOperator = (dataSource.operatorApprovals(owner, msg.sender)); require(isOwner || isOperator); _; } /** * Whether the `_date` is valid(no hours, no seconds) */ modifier validDate(uint256 _date) { require(_date > 0); require(dateIsLegal(_date)); _; } /** * Whether the `_dates` are valid(no hours, no seconds) */ modifier validDates(uint256[] _dates) { for(uint256 i = 0;i < _dates.length; i++) { require(_dates[i] > 0); require(dateIsLegal(_dates[i])); } _; } function dateIsLegal(uint256 _date) pure private returns(bool) { uint256 year = _date / 10000; uint256 mon = _date / 100 - year * 100; uint256 day = _date - mon * 100 - year * 10000; if(year < 1970 || mon <= 0 || mon > 12 || day <= 0 || day > 31) return false; if(4 == mon || 6 == mon || 9 == mon || 11 == mon){ if (day == 31) { return false; } } if(((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) { if(2 == mon && day > 29) { return false; } }else { if(2 == mon && day > 28){ return false; } } return true; } /** * Constructor */ constructor() public { } } contract TRNOwners is TRNData { /** * Constructor */ constructor() public { } /** * Add room night token to `_owner`'s account(from the header) */ function _pushRoomNight(address _owner, uint256 _rnid, bool _isVendor) internal { require(_owner != address(0)); require(_rnid != 0); if (_isVendor) { dataSource.pushOrderOfVendor(_owner, _rnid, false); } else { dataSource.pushOrderOfOwner(_owner, _rnid, false); } } /** * Remove room night token from `_owner`'s account */ function _removeRoomNight(address _owner, uint256 _rnid) internal { dataSource.removeOrderOfOwner(_owner, _rnid); } /** * @dev Returns all the room nights of the `msg.sender`(Customer) * @param _from The begin of room nights Id * @param _limit The total room nights * @param _isVendor Is Vendor * @return Room nights of the `msg.sender` and the next vernier */ function roomNightsOfOwner(uint256 _from, uint256 _limit, bool _isVendor) external view returns(uint256[], uint256) { if(_isVendor) { return dataSource.getOrdersOfVendor(msg.sender, _from, _limit, true); }else { return dataSource.getOrdersOfOwner(msg.sender, _from, _limit, true); } } /** * @dev Returns the room night infomation in detail * @param _rnid Room night id * @return Room night infomation in detail */ function roomNight(uint256 _rnid) external view returns(uint256 _vendorId,uint256 _rpid,uint256 _token,uint256 _price,uint256 _timestamp,uint256 _date,bytes32 _ipfs, string _name) { (_vendorId, _rpid, _token, _price, _timestamp, _date, _ipfs) = dataSource.roomnights(_rnid); (_name,,) = dataSource.getRatePlan(_vendorId, _rpid); } } library IPFSLib { bytes constant ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; bytes constant HEX = "0123456789abcdef"; /** * @dev Base58 encoding * @param _source Bytes data * @return Encoded bytes data */ function base58Address(bytes _source) internal pure returns (bytes) { uint8[] memory digits = new uint8[](_source.length * 136/100 + 1); digits[0] = 0; uint8 digitlength = 1; for (uint i = 0; i < _source.length; ++i) { uint carry = uint8(_source[i]); for (uint j = 0; j<digitlength; ++j) { carry += uint(digits[j]) * 256; digits[j] = uint8(carry % 58); carry = carry / 58; } while (carry > 0) { digits[digitlength] = uint8(carry % 58); digitlength++; carry = carry / 58; } } return toAlphabet(reverse(truncate(digits, digitlength))); } /** * @dev Hex encoding, convert bytes32 data to hex string * @param _source Bytes32 data * @return hex string bytes */ function hexAddress(bytes32 _source) internal pure returns(bytes) { uint256 value = uint256(_source); bytes memory result = "0000000000000000000000000000000000000000000000000000000000000000"; uint8 index = 0; while(value > 0) { result[index] = HEX[value & 0xf]; index++; value = value>>4; } bytes memory ipfsBytes = reverseBytes(result); return ipfsBytes; } /** * @dev Truncate `_array` by `_length` * @param _array The source array * @param _length The target length of the `_array` * @return The truncated array */ function truncate(uint8[] _array, uint8 _length) internal pure returns (uint8[]) { uint8[] memory output = new uint8[](_length); for (uint i = 0; i < _length; i++) { output[i] = _array[i]; } return output; } /** * @dev Reverse `_input` array * @param _input The source array * @return The reversed array */ function reverse(uint8[] _input) internal pure returns (uint8[]) { uint8[] memory output = new uint8[](_input.length); for (uint i = 0; i < _input.length; i++) { output[i] = _input[_input.length - 1 - i]; } return output; } /** * @dev Reverse `_input` bytes * @param _input The source bytes * @return The reversed bytes */ function reverseBytes(bytes _input) private pure returns (bytes) { bytes memory output = new bytes(_input.length); for (uint8 i = 0; i < _input.length; i++) { output[i] = _input[_input.length-1-i]; } return output; } /** * @dev Convert the indices to alphabet * @param _indices The indices of alphabet * @return The alphabets */ function toAlphabet(uint8[] _indices) internal pure returns (bytes) { bytes memory output = new bytes(_indices.length); for (uint i = 0; i < _indices.length; i++) { output[i] = ALPHABET[_indices[i]]; } return output; } /** * @dev Convert bytes32 to bytes * @param _input The source bytes32 * @return The bytes */ function toBytes(bytes32 _input) internal pure returns (bytes) { bytes memory output = new bytes(32); for (uint8 i = 0; i < 32; i++) { output[i] = _input[i]; } return output; } /** * @dev Concat two bytes to one * @param _byteArray The first bytes * @param _byteArray2 The second bytes * @return The concated bytes */ function concat(bytes _byteArray, bytes _byteArray2) internal pure returns (bytes) { bytes memory returnArray = new bytes(_byteArray.length + _byteArray2.length); for (uint16 i = 0; i < _byteArray.length; i++) { returnArray[i] = _byteArray[i]; } for (i; i < (_byteArray.length + _byteArray2.length); i++) { returnArray[i] = _byteArray2[i - _byteArray.length]; } return returnArray; } } contract TRNAsset is TRNData, ERC721Metadata { using IPFSLib for bytes; using IPFSLib for bytes32; /** * Constructor */ constructor() public { } /** * @dev Descriptive name for Tripio's Room Night Token in this contract * @return The name of the contract */ function name() external pure returns (string _name) { return "Tripio Room Night"; } /** * @dev Abbreviated name for Tripio's Room Night Token in this contract * @return The simple name of the contract */ function symbol() external pure returns (string _symbol) { return "TRN"; } /** * @dev If `_tokenId` is not valid trows an exception otherwise return a URI which point to a JSON file like: * { * "name": "Identifies the asset to which this NFT represents", * "description": "Describes the asset to which this NFT represents", * "image": "A URI pointing to a resource with mime type image/* representing the asset to which this NFT represents. Consider making any images at a width between 320 and 1080 pixels and aspect ratio between 1.91:1 and 4:5 inclusive." * } * @param _tokenId The RoomNight digital token * @return The digital token asset uri */ function tokenURI(uint256 _tokenId) external view validToken(_tokenId) returns (string) { bytes memory prefix = new bytes(2); prefix[0] = 0x12; prefix[1] = 0x20; (,,,,,,bytes32 ipfs) = dataSource.roomnights(_tokenId); bytes memory value = prefix.concat(ipfs.toBytes()); bytes memory ipfsBytes = value.base58Address(); bytes memory tokenBaseURIBytes = bytes(dataSource.tokenBaseURI()); return string(tokenBaseURIBytes.concat(ipfsBytes)); } } contract TRNOwnership is TRNOwners, ERC721 { /** * Constructor */ constructor() public { } /** * This emits when ownership of any TRN changes by any mechanism. */ event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); /** * This emits when the approved address for an RTN is changed or reaffirmed. */ event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); /** * This emits when an operator is enabled or disabled for an owner. * The operator can manage all RTNs of the owner. */ event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /** * @dev Transfer the `_tokenId` to `_to` directly * @param _tokenId The room night token * @param _to The target owner */ function _transfer(uint256 _tokenId, address _to) private { // Find the FROM address address from = dataSource.roomNightIndexToOwner(_tokenId); // Remove room night from the `from` _removeRoomNight(from, _tokenId); // Add room night to the `_to` _pushRoomNight(_to, _tokenId, false); // Change the owner of `_tokenId` // Remove approval of `_tokenId` dataSource.transferTokenTo(_tokenId, _to); // Emit Transfer event emit Transfer(from, _to, _tokenId); } function _safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) private validToken(_tokenId) canTransfer(_tokenId) { // The token's owner is equal to `_from` address owner = dataSource.roomNightIndexToOwner(_tokenId); require(owner == _from); // Avoid `_to` is equal to address(0) require(_to != address(0)); _transfer(_tokenId, _to); uint256 codeSize; assembly { codeSize := extcodesize(_to) } if (codeSize == 0) { return; } bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data); require (retval == dataSource.ERC721_RECEIVED()); } /** * @dev Count all TRNs assigned to an owner. * Throw when `_owner` is equal to address(0) * @param _owner An address for whom to query the balance. * @return The number of TRNs owned by `_owner`. */ function balanceOf(address _owner) external view returns (uint256) { require(_owner != address(0)); return dataSource.balanceOf(_owner); } /** * @dev Find the owner of an TRN * Throw unless `_tokenId` more than zero * @param _tokenId The identifier for an TRN * @return The address of the owner of the TRN */ function ownerOf(uint256 _tokenId) external view returns (address) { require(_tokenId > 0); return dataSource.roomNightIndexToOwner(_tokenId); } /** * @dev Transfers the ownership of an TRN from one address to another address. * Throws unless `msg.sender` is the current owner or an approved address for this TRN. * Throws if `_tokenId` is not a valid TRN. When transfer is complete, this function checks if * `_to` is a smart contract (code size > 0). If so, it calls `onERC721Received` on `_to` and * throws if the return value is not `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. * @param _from The current owner of the TRN * @param _to The new owner * @param _tokenId The TRN to transfer * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) external payable { _safeTransferFrom(_from, _to, _tokenId, _data); } /** * @dev Same like safeTransferFrom with an extra data parameter, except this function just sets data to ""(empty) * @param _from The current owner of the TRN * @param _to The new owner * @param _tokenId The TRN to transfer */ function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable { _safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Transfers the ownership of an TRN from one address to another address. * Throws unless `msg.sender` is the current owner or an approved address for this TRN. * Throws if `_tokenId` is not a valid TRN. * @param _from The current owner of the TRN * @param _to The new owner * @param _tokenId The TRN to transfer */ function transferFrom(address _from, address _to, uint256 _tokenId) external payable validToken(_tokenId) canTransfer(_tokenId) { // The token's owner is equal to `_from` address owner = dataSource.roomNightIndexToOwner(_tokenId); require(owner == _from); // Avoid `_to` is equal to address(0) require(_to != address(0)); _transfer(_tokenId, _to); } /** * @dev Transfers the ownership of TRNs from one address to another address. * Throws unless `msg.sender` is the current owner or an approved address for this TRN. * Throws if `_tokenIds` are not valid TRNs. * @param _from The current owner of the TRN * @param _to The new owner * @param _tokenIds The TRNs to transfer */ function transferFromInBatch(address _from, address _to, uint256[] _tokenIds) external payable validTokenInBatch(_tokenIds) canTransferInBatch(_tokenIds) { for(uint256 i = 0; i < _tokenIds.length; i++) { // The token's owner is equal to `_from` address owner = dataSource.roomNightIndexToOwner(_tokenIds[i]); require(owner == _from); // Avoid `_to` is equal to address(0) require(_to != address(0)); _transfer(_tokenIds[i], _to); } } /** * @dev Set or reaffirm the approved address for an TRN. * Throws unless `msg.sender` is the current TRN owner, or an authorized * @param _approved The new approved TRN controller * @param _tokenId The TRN to approve */ function approve(address _approved, uint256 _tokenId) external payable validToken(_tokenId) canOperate(_tokenId) { address owner = dataSource.roomNightIndexToOwner(_tokenId); dataSource.approveTokenTo(_tokenId, _approved); emit Approval(owner, _approved, _tokenId); } /** * @dev Enable or disable approval for a third party ("operator") to manage * all of `msg.sender`'s assets. * Emits the ApprovalForAll event. * @param _operator Address to add to the set of authorized operators. * @param _approved True if the operator is approved, false to revoke approval. */ function setApprovalForAll(address _operator, bool _approved) external { require(_operator != address(0)); dataSource.approveOperatorTo(_operator, msg.sender, _approved); emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @dev Get the approved address for a single TRN. * Throws if `_tokenId` is not a valid TRN. * @param _tokenId The TRN to find the approved address for * @return The approved address for this TRN, or the zero address if there is none */ function getApproved(uint256 _tokenId) external view validToken(_tokenId) returns (address) { return dataSource.roomNightApprovals(_tokenId); } /** * @dev Query if an address is an authorized operator for another address. * @param _owner The address that owns The TRNs * @param _operator The address that acts on behalf of the owner * @return True if `_operator` is an approved operator for `_owner`, false otherwise */ function isApprovedForAll(address _owner, address _operator) external view returns (bool) { return dataSource.operatorApprovals(_owner, _operator); } } contract TRNSupportsInterface is TRNData, ERC165 { /** * Constructor */ constructor() public { } /** * @dev Query if a contract implements an interface * @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) { return ((interfaceID == dataSource.interfaceSignature_ERC165()) || (interfaceID == dataSource.interfaceSignature_ERC721Metadata()) || (interfaceID == dataSource.interfaceSignature_ERC721())) && (interfaceID != 0xffffffff); } } /** * This utility library was forked from https://github.com/o0ragman0o/LibCLL */ library LinkedListLib { uint256 constant NULL = 0; uint256 constant HEAD = 0; bool constant PREV = false; bool constant NEXT = true; struct LinkedList { mapping (uint256 => mapping (bool => uint256)) list; uint256 length; uint256 index; } /** * @dev returns true if the list exists * @param self stored linked list from contract */ function listExists(LinkedList storage self) internal view returns (bool) { return self.length > 0; } /** * @dev returns true if the node exists * @param self stored linked list from contract * @param _node a node to search for */ function nodeExists(LinkedList storage self, uint256 _node) internal view returns (bool) { if (self.list[_node][PREV] == HEAD && self.list[_node][NEXT] == HEAD) { if (self.list[HEAD][NEXT] == _node) { return true; } else { return false; } } else { return true; } } /** * @dev Returns the number of elements in the list * @param self stored linked list from contract */ function sizeOf(LinkedList storage self) internal view returns (uint256 numElements) { return self.length; } /** * @dev Returns the links of a node as a tuple * @param self stored linked list from contract * @param _node id of the node to get */ function getNode(LinkedList storage self, uint256 _node) public view returns (bool, uint256, uint256) { if (!nodeExists(self,_node)) { return (false, 0, 0); } else { return (true, self.list[_node][PREV], self.list[_node][NEXT]); } } /** * @dev Returns the link of a node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node id of the node to step from * @param _direction direction to step in */ function getAdjacent(LinkedList storage self, uint256 _node, bool _direction) public view returns (bool, uint256) { if (!nodeExists(self,_node)) { return (false,0); } else { return (true,self.list[_node][_direction]); } } /** * @dev Can be used before `insert` to build an ordered list * @param self stored linked list from contract * @param _node an existing node to search from, e.g. HEAD. * @param _value value to seek * @param _direction direction to seek in * @return next first node beyond '_node' in direction `_direction` */ function getSortedSpot(LinkedList storage self, uint256 _node, uint256 _value, bool _direction) public view returns (uint256) { if (sizeOf(self) == 0) { return 0; } require((_node == 0) || nodeExists(self,_node)); bool exists; uint256 next; (exists,next) = getAdjacent(self, _node, _direction); while ((next != 0) && (_value != next) && ((_value < next) != _direction)) next = self.list[next][_direction]; return next; } /** * @dev Creates a bidirectional link between two nodes on direction `_direction` * @param self stored linked list from contract * @param _node first node for linking * @param _link node to link to in the _direction */ function createLink(LinkedList storage self, uint256 _node, uint256 _link, bool _direction) private { self.list[_link][!_direction] = _node; self.list[_node][_direction] = _link; } /** * @dev Insert node `_new` beside existing node `_node` in direction `_direction`. * @param self stored linked list from contract * @param _node existing node * @param _new new node to insert * @param _direction direction to insert node in */ function insert(LinkedList storage self, uint256 _node, uint256 _new, bool _direction) internal returns (bool) { if(!nodeExists(self,_new) && nodeExists(self,_node)) { uint256 c = self.list[_node][_direction]; createLink(self, _node, _new, _direction); createLink(self, _new, c, _direction); self.length++; return true; } else { return false; } } /** * @dev removes an entry from the linked list * @param self stored linked list from contract * @param _node node to remove from the list */ function remove(LinkedList storage self, uint256 _node) internal returns (uint256) { if ((_node == NULL) || (!nodeExists(self,_node))) { return 0; } createLink(self, self.list[_node][PREV], self.list[_node][NEXT], NEXT); delete self.list[_node][PREV]; delete self.list[_node][NEXT]; self.length--; return _node; } /** * @dev pushes an enrty to the head of the linked list * @param self stored linked list from contract * @param _index The node Id * @param _direction push to the head (NEXT) or tail (PREV) */ function add(LinkedList storage self, uint256 _index, bool _direction) internal returns (uint256) { insert(self, HEAD, _index, _direction); return self.index; } /** * @dev pushes an enrty to the head of the linked list * @param self stored linked list from contract * @param _direction push to the head (NEXT) or tail (PREV) */ function push(LinkedList storage self, bool _direction) internal returns (uint256) { self.index++; insert(self, HEAD, self.index, _direction); return self.index; } /** * @dev pops the first entry from the linked list * @param self stored linked list from contract * @param _direction pop from the head (NEXT) or the tail (PREV) */ function pop(LinkedList storage self, bool _direction) internal returns (uint256) { bool exists; uint256 adj; (exists,adj) = getAdjacent(self, HEAD, _direction); return remove(self, adj); } } contract TripioToken { string public name; string public symbol; uint8 public decimals; function transfer(address _to, uint256 _value) public returns (bool); function balanceOf(address who) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); } contract TripioRoomNightData is Owned { using LinkedListLib for LinkedListLib.LinkedList; // Interface signature of erc165. // bytes4(keccak256("supportsInterface(bytes4)")) bytes4 constant public interfaceSignature_ERC165 = 0x01ffc9a7; // Interface signature of erc721 metadata. // bytes4(keccak256("name()")) ^ bytes4(keccak256("symbol()")) ^ bytes4(keccak256("tokenURI(uint256)")); bytes4 constant public interfaceSignature_ERC721Metadata = 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd; // Interface signature of erc721. // bytes4(keccak256("balanceOf(address)")) ^ // bytes4(keccak256("ownerOf(uint256)")) ^ // bytes4(keccak256("safeTransferFrom(address,address,uint256,bytes)")) ^ // bytes4(keccak256("safeTransferFrom(address,address,uint256)")) ^ // bytes4(keccak256("transferFrom(address,address,uint256)")) ^ // bytes4(keccak256("approve(address,uint256)")) ^ // bytes4(keccak256("setApprovalForAll(address,bool)")) ^ // bytes4(keccak256("getApproved(uint256)")) ^ // bytes4(keccak256("isApprovedForAll(address,address)")); bytes4 constant public interfaceSignature_ERC721 = 0x70a08231 ^ 0x6352211e ^ 0xb88d4fde ^ 0x42842e0e ^ 0x23b872dd ^ 0x095ea7b3 ^ 0xa22cb465 ^ 0x081812fc ^ 0xe985e9c5; // Base URI of token asset string public tokenBaseURI; // Authorized contracts struct AuthorizedContract { string name; address acontract; } mapping (address=>uint256) public authorizedContractIds; mapping (uint256 => AuthorizedContract) public authorizedContracts; LinkedListLib.LinkedList public authorizedContractList = LinkedListLib.LinkedList(0, 0); // Rate plan prices struct Price { uint16 inventory; // Rate plan inventory bool init; // Whether the price is initied mapping (uint256 => uint256) tokens; } // Vendor hotel RPs struct RatePlan { string name; // Name of rate plan. uint256 timestamp; // Create timestamp. bytes32 ipfs; // The address of rate plan detail on IPFS. Price basePrice; // The base price of rate plan mapping (uint256 => Price) prices; // date -> Price } // Vendors struct Vendor { string name; // Name of vendor. address vendor; // Address of vendor. uint256 timestamp; // Create timestamp. bool valid; // Whether the vendor is valid(default is true) LinkedListLib.LinkedList ratePlanList; mapping (uint256=>RatePlan) ratePlans; } mapping (address => uint256) public vendorIds; mapping (uint256 => Vendor) vendors; LinkedListLib.LinkedList public vendorList = LinkedListLib.LinkedList(0, 0); // Supported digital currencies mapping (uint256 => address) public tokenIndexToAddress; LinkedListLib.LinkedList public tokenList = LinkedListLib.LinkedList(0, 0); // RoomNight tokens struct RoomNight { uint256 vendorId; uint256 rpid; uint256 token; // The digital currency token uint256 price; // The digital currency price uint256 timestamp; // Create timestamp. uint256 date; // The checkin date bytes32 ipfs; // The address of rate plan detail on IPFS. } RoomNight[] public roomnights; // rnid -> owner mapping (uint256 => address) public roomNightIndexToOwner; // Owner Account mapping (address => LinkedListLib.LinkedList) public roomNightOwners; // Vendor Account mapping (address => LinkedListLib.LinkedList) public roomNightVendors; // The authorized address for each TRN mapping (uint256 => address) public roomNightApprovals; // The authorized operators for each address mapping (address => mapping (address => bool)) public operatorApprovals; // The applications of room night redund mapping (address => mapping (uint256 => bool)) public refundApplications; // The signature of `onERC721Received(address,uint256,bytes)` // bytes4(keccak256("onERC721Received(address,uint256,bytes)")); bytes4 constant public ERC721_RECEIVED = 0xf0b9e5ba; /** * This emits when contract authorized */ event ContractAuthorized(address _contract); /** * This emits when contract deauthorized */ event ContractDeauthorized(address _contract); /** * The contract is valid */ modifier authorizedContractValid(address _contract) { require(authorizedContractIds[_contract] > 0); _; } /** * The contract is valid */ modifier authorizedContractIdValid(uint256 _cid) { require(authorizedContractList.nodeExists(_cid)); _; } /** * Only the owner or authorized contract is valid */ modifier onlyOwnerOrAuthorizedContract { require(msg.sender == owner || authorizedContractIds[msg.sender] > 0); _; } /** * Constructor */ constructor() public { // Add one invalid RoomNight, avoid subscript 0 roomnights.push(RoomNight(0, 0, 0, 0, 0, 0, 0)); } /** * @dev Returns the node list and next node as a tuple * @param self stored linked list from contract * @param _node the begin id of the node to get * @param _limit the total nodes of one page * @param _direction direction to step in */ function getNodes(LinkedListLib.LinkedList storage self, uint256 _node, uint256 _limit, bool _direction) private view returns (uint256[], uint256) { bool exists; uint256 i = 0; uint256 ei = 0; uint256 index = 0; uint256 count = _limit; if(count > self.length) { count = self.length; } (exists, i) = self.getAdjacent(_node, _direction); if(!exists || count == 0) { return (new uint256[](0), 0); }else { uint256[] memory temp = new uint256[](count); if(_node != 0) { index++; temp[0] = _node; } while (i != 0 && index < count) { temp[index] = i; (exists,i) = self.getAdjacent(i, _direction); index++; } ei = i; if(index < count) { uint256[] memory result = new uint256[](index); for(i = 0; i < index; i++) { result[i] = temp[i]; } return (result, ei); }else { return (temp, ei); } } } /** * @dev Authorize `_contract` to execute this contract's funs * @param _contract The contract address * @param _name The contract name */ function authorizeContract(address _contract, string _name) public onlyOwner returns(bool) { uint256 codeSize; assembly { codeSize := extcodesize(_contract) } require(codeSize != 0); // Not exists require(authorizedContractIds[_contract] == 0); // Add uint256 id = authorizedContractList.push(false); authorizedContractIds[_contract] = id; authorizedContracts[id] = AuthorizedContract(_name, _contract); // Event emit ContractAuthorized(_contract); return true; } /** * @dev Deauthorized `_contract` by address * @param _contract The contract address */ function deauthorizeContract(address _contract) public onlyOwner authorizedContractValid(_contract) returns(bool) { uint256 id = authorizedContractIds[_contract]; authorizedContractList.remove(id); authorizedContractIds[_contract] = 0; delete authorizedContracts[id]; // Event emit ContractDeauthorized(_contract); return true; } /** * @dev Deauthorized `_contract` by contract id * @param _cid The contract id */ function deauthorizeContractById(uint256 _cid) public onlyOwner authorizedContractIdValid(_cid) returns(bool) { address acontract = authorizedContracts[_cid].acontract; authorizedContractList.remove(_cid); authorizedContractIds[acontract] = 0; delete authorizedContracts[_cid]; // Event emit ContractDeauthorized(acontract); return true; } /** * @dev Get authorize contract ids by page * @param _from The begin authorize contract id * @param _limit How many authorize contract ids one page * @return The authorize contract ids and the next authorize contract id as tuple, the next page not exists when next eq 0 */ function getAuthorizeContractIds(uint256 _from, uint256 _limit) external view returns(uint256[], uint256){ return getNodes(authorizedContractList, _from, _limit, true); } /** * @dev Get authorize contract by id * @param _cid Then authorize contract id * @return The authorize contract info(_name, _acontract) */ function getAuthorizeContract(uint256 _cid) external view returns(string _name, address _acontract) { AuthorizedContract memory acontract = authorizedContracts[_cid]; _name = acontract.name; _acontract = acontract.acontract; } /*************************************** GET ***************************************/ /** * @dev Get the rate plan by `_vendorId` and `_rpid` * @param _vendorId The vendor id * @param _rpid The rate plan id */ function getRatePlan(uint256 _vendorId, uint256 _rpid) public view returns (string _name, uint256 _timestamp, bytes32 _ipfs) { _name = vendors[_vendorId].ratePlans[_rpid].name; _timestamp = vendors[_vendorId].ratePlans[_rpid].timestamp; _ipfs = vendors[_vendorId].ratePlans[_rpid].ipfs; } /** * @dev Get the rate plan price by `_vendorId`, `_rpid`, `_date` and `_tokenId` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _tokenId The digital token id * @return The price info(inventory, init, price) */ function getPrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId) public view returns(uint16 _inventory, bool _init, uint256 _price) { _inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory; _init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init; _price = vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId]; if(!_init) { // Get the base price _inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory; _price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId]; _init = vendors[_vendorId].ratePlans[_rpid].basePrice.init; } } /** * @dev Get the rate plan prices by `_vendorId`, `_rpid`, `_dates` and `_tokenId` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _dates The dates desc ([20180723,20180724,20180725]) * @param _tokenId The digital token id * @return The price info(inventory, init, price) */ function getPrices(uint256 _vendorId, uint256 _rpid, uint256[] _dates, uint256 _tokenId) public view returns(uint16[] _inventories, uint256[] _prices) { uint16[] memory inventories = new uint16[](_dates.length); uint256[] memory prices = new uint256[](_dates.length); uint256 date; for(uint256 i = 0; i < _dates.length; i++) { date = _dates[i]; uint16 inventory = vendors[_vendorId].ratePlans[_rpid].prices[date].inventory; bool init = vendors[_vendorId].ratePlans[_rpid].prices[date].init; uint256 price = vendors[_vendorId].ratePlans[_rpid].prices[date].tokens[_tokenId]; if(!init) { // Get the base price inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory; price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId]; init = vendors[_vendorId].ratePlans[_rpid].basePrice.init; } inventories[i] = inventory; prices[i] = price; } return (inventories, prices); } /** * @dev Get the inventory by by `_vendorId`, `_rpid` and `_date` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @return The inventory info(inventory, init) */ function getInventory(uint256 _vendorId, uint256 _rpid, uint256 _date) public view returns(uint16 _inventory, bool _init) { _inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory; _init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init; if(!_init) { // Get the base price _inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory; } } /** * @dev Whether the rate plan is exist * @param _vendorId The vendor id * @param _rpid The rate plan id * @return If the rate plan of the vendor is exist returns true otherwise return false */ function ratePlanIsExist(uint256 _vendorId, uint256 _rpid) public view returns (bool) { return vendors[_vendorId].ratePlanList.nodeExists(_rpid); } /** * @dev Get orders of owner by page * @param _owner The owner address * @param _from The begin id of the node to get * @param _limit The total nodes of one page * @param _direction Direction to step in * @return The order ids and the next id */ function getOrdersOfOwner(address _owner, uint256 _from, uint256 _limit, bool _direction) public view returns (uint256[], uint256) { return getNodes(roomNightOwners[_owner], _from, _limit, _direction); } /** * @dev Get orders of vendor by page * @param _owner The vendor address * @param _from The begin id of the node to get * @param _limit The total nodes of on page * @param _direction Direction to step in * @return The order ids and the next id */ function getOrdersOfVendor(address _owner, uint256 _from, uint256 _limit, bool _direction) public view returns (uint256[], uint256) { return getNodes(roomNightVendors[_owner], _from, _limit, _direction); } /** * @dev Get the token count of somebody * @param _owner The owner of token * @return The token count of `_owner` */ function balanceOf(address _owner) public view returns(uint256) { return roomNightOwners[_owner].length; } /** * @dev Get rate plan ids of `_vendorId` * @param _from The begin id of the node to get * @param _limit The total nodes of on page * @param _direction Direction to step in * @return The rate plan ids and the next id */ function getRatePlansOfVendor(uint256 _vendorId, uint256 _from, uint256 _limit, bool _direction) public view returns(uint256[], uint256) { return getNodes(vendors[_vendorId].ratePlanList, _from, _limit, _direction); } /** * @dev Get token ids * @param _from The begin id of the node to get * @param _limit The total nodes of on page * @param _direction Direction to step in * @return The token ids and the next id */ function getTokens(uint256 _from, uint256 _limit, bool _direction) public view returns(uint256[], uint256) { return getNodes(tokenList, _from, _limit, _direction); } /** * @dev Get token Info * @param _tokenId The token id * @return The token info(symbol, name, decimals) */ function getToken(uint256 _tokenId) public view returns(string _symbol, string _name, uint8 _decimals, address _token) { _token = tokenIndexToAddress[_tokenId]; TripioToken tripio = TripioToken(_token); _symbol = tripio.symbol(); _name = tripio.name(); _decimals = tripio.decimals(); } /** * @dev Get vendor ids * @param _from The begin id of the node to get * @param _limit The total nodes of on page * @param _direction Direction to step in * @return The vendor ids and the next id */ function getVendors(uint256 _from, uint256 _limit, bool _direction) public view returns(uint256[], uint256) { return getNodes(vendorList, _from, _limit, _direction); } /** * @dev Get the vendor infomation by vendorId * @param _vendorId The vendor id * @return The vendor infomation(name, vendor, timestamp, valid) */ function getVendor(uint256 _vendorId) public view returns(string _name, address _vendor,uint256 _timestamp, bool _valid) { _name = vendors[_vendorId].name; _vendor = vendors[_vendorId].vendor; _timestamp = vendors[_vendorId].timestamp; _valid = vendors[_vendorId].valid; } /*************************************** SET ***************************************/ /** * @dev Update base uri of token metadata * @param _tokenBaseURI The base uri */ function updateTokenBaseURI(string _tokenBaseURI) public onlyOwnerOrAuthorizedContract { tokenBaseURI = _tokenBaseURI; } /** * @dev Push order to user's order list * @param _owner The buyer address * @param _rnid The room night order id * @param _direction direction to step in */ function pushOrderOfOwner(address _owner, uint256 _rnid, bool _direction) public onlyOwnerOrAuthorizedContract { if(!roomNightOwners[_owner].listExists()) { roomNightOwners[_owner] = LinkedListLib.LinkedList(0, 0); } roomNightOwners[_owner].add(_rnid, _direction); } /** * @dev Remove order from owner's order list * @param _owner The owner address * @param _rnid The room night order id */ function removeOrderOfOwner(address _owner, uint _rnid) public onlyOwnerOrAuthorizedContract { require(roomNightOwners[_owner].nodeExists(_rnid)); roomNightOwners[_owner].remove(_rnid); } /** * @dev Push order to the vendor's order list * @param _vendor The vendor address * @param _rnid The room night order id * @param _direction direction to step in */ function pushOrderOfVendor(address _vendor, uint256 _rnid, bool _direction) public onlyOwnerOrAuthorizedContract { if(!roomNightVendors[_vendor].listExists()) { roomNightVendors[_vendor] = LinkedListLib.LinkedList(0, 0); } roomNightVendors[_vendor].add(_rnid, _direction); } /** * @dev Remove order from vendor's order list * @param _vendor The vendor address * @param _rnid The room night order id */ function removeOrderOfVendor(address _vendor, uint256 _rnid) public onlyOwnerOrAuthorizedContract { require(roomNightVendors[_vendor].nodeExists(_rnid)); roomNightVendors[_vendor].remove(_rnid); } /** * @dev Transfer token to somebody * @param _tokenId The token id * @param _to The target owner of the token */ function transferTokenTo(uint256 _tokenId, address _to) public onlyOwnerOrAuthorizedContract { roomNightIndexToOwner[_tokenId] = _to; roomNightApprovals[_tokenId] = address(0); } /** * @dev Approve `_to` to operate the `_tokenId` * @param _tokenId The token id * @param _to Somebody to be approved */ function approveTokenTo(uint256 _tokenId, address _to) public onlyOwnerOrAuthorizedContract { roomNightApprovals[_tokenId] = _to; } /** * @dev Approve `_operator` to operate all the Token of `_to` * @param _operator The operator to be approved * @param _to The owner of tokens to be operate * @param _approved Approved or not */ function approveOperatorTo(address _operator, address _to, bool _approved) public onlyOwnerOrAuthorizedContract { operatorApprovals[_to][_operator] = _approved; } /** * @dev Update base price of rate plan * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _tokenId The digital token id * @param _price The price to be updated */ function updateBasePrice(uint256 _vendorId, uint256 _rpid, uint256 _tokenId, uint256 _price) public onlyOwnerOrAuthorizedContract { vendors[_vendorId].ratePlans[_rpid].basePrice.init = true; vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId] = _price; } /** * @dev Update base inventory of rate plan * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _inventory The inventory to be updated */ function updateBaseInventory(uint256 _vendorId, uint256 _rpid, uint16 _inventory) public onlyOwnerOrAuthorizedContract { vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = _inventory; } /** * @dev Update price by `_vendorId`, `_rpid`, `_date`, `_tokenId` and `_price` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _tokenId The digital token id * @param _price The price to be updated */ function updatePrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price) public onlyOwnerOrAuthorizedContract { if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) { vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price; } else { vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(0, true); vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price; } } /** * @dev Update inventory by `_vendorId`, `_rpid`, `_date`, `_inventory` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _inventory The inventory to be updated */ function updateInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory) public onlyOwnerOrAuthorizedContract { if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) { vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory; } else { vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true); } } /** * @dev Reduce inventories * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _inventory The amount to be reduced */ function reduceInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory) public onlyOwnerOrAuthorizedContract { uint16 a = 0; if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) { a = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory; require(_inventory <= a); vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = a - _inventory; }else if(vendors[_vendorId].ratePlans[_rpid].basePrice.init){ a = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory; require(_inventory <= a); vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = a - _inventory; } } /** * @dev Add inventories * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _inventory The amount to be add */ function addInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory) public onlyOwnerOrAuthorizedContract { uint16 c = 0; if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) { c = _inventory + vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory; require(c >= _inventory); vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = c; }else if(vendors[_vendorId].ratePlans[_rpid].basePrice.init) { c = _inventory + vendors[_vendorId].ratePlans[_rpid].basePrice.inventory; require(c >= _inventory); vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = c; } } /** * @dev Update inventory and price by `_vendorId`, `_rpid`, `_date`, `_tokenId`, `_price` and `_inventory` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _tokenId The digital token id * @param _price The price to be updated * @param _inventory The inventory to be updated */ function updatePriceAndInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price, uint16 _inventory) public onlyOwnerOrAuthorizedContract { if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) { vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory; vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price; } else { vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true); vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price; } } /** * @dev Push rate plan to `_vendorId`'s rate plan list * @param _vendorId The vendor id * @param _name The name of rate plan * @param _ipfs The rate plan IPFS address * @param _direction direction to step in */ function pushRatePlan(uint256 _vendorId, string _name, bytes32 _ipfs, bool _direction) public onlyOwnerOrAuthorizedContract returns(uint256) { RatePlan memory rp = RatePlan(_name, uint256(now), _ipfs, Price(0, false)); uint256 id = vendors[_vendorId].ratePlanList.push(_direction); vendors[_vendorId].ratePlans[id] = rp; return id; } /** * @dev Remove rate plan of `_vendorId` by `_rpid` * @param _vendorId The vendor id * @param _rpid The rate plan id */ function removeRatePlan(uint256 _vendorId, uint256 _rpid) public onlyOwnerOrAuthorizedContract { delete vendors[_vendorId].ratePlans[_rpid]; vendors[_vendorId].ratePlanList.remove(_rpid); } /** * @dev Update `_rpid` of `_vendorId` by `_name` and `_ipfs` * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _name The rate plan name * @param _ipfs The rate plan IPFS address */ function updateRatePlan(uint256 _vendorId, uint256 _rpid, string _name, bytes32 _ipfs) public onlyOwnerOrAuthorizedContract { vendors[_vendorId].ratePlans[_rpid].ipfs = _ipfs; vendors[_vendorId].ratePlans[_rpid].name = _name; } /** * @dev Push token contract to the token list * @param _direction direction to step in */ function pushToken(address _contract, bool _direction) public onlyOwnerOrAuthorizedContract returns(uint256) { uint256 id = tokenList.push(_direction); tokenIndexToAddress[id] = _contract; return id; } /** * @dev Remove token by `_tokenId` * @param _tokenId The digital token id */ function removeToken(uint256 _tokenId) public onlyOwnerOrAuthorizedContract { delete tokenIndexToAddress[_tokenId]; tokenList.remove(_tokenId); } /** * @dev Generate room night token * @param _vendorId The vendor id * @param _rpid The rate plan id * @param _date The date desc (20180723) * @param _token The token id * @param _price The token price * @param _ipfs The rate plan IPFS address */ function generateRoomNightToken(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _token, uint256 _price, bytes32 _ipfs) public onlyOwnerOrAuthorizedContract returns(uint256) { roomnights.push(RoomNight(_vendorId, _rpid, _token, _price, now, _date, _ipfs)); // Give the token to `_customer` uint256 rnid = uint256(roomnights.length - 1); return rnid; } /** * @dev Update refund applications * @param _buyer The room night token holder * @param _rnid The room night token id * @param _isRefund Is redund or not */ function updateRefundApplications(address _buyer, uint256 _rnid, bool _isRefund) public onlyOwnerOrAuthorizedContract { refundApplications[_buyer][_rnid] = _isRefund; } /** * @dev Push vendor info to the vendor list * @param _name The name of vendor * @param _vendor The vendor address * @param _direction direction to step in */ function pushVendor(string _name, address _vendor, bool _direction) public onlyOwnerOrAuthorizedContract returns(uint256) { uint256 id = vendorList.push(_direction); vendorIds[_vendor] = id; vendors[id] = Vendor(_name, _vendor, uint256(now), true, LinkedListLib.LinkedList(0, 0)); return id; } /** * @dev Remove vendor from vendor list * @param _vendorId The vendor id */ function removeVendor(uint256 _vendorId) public onlyOwnerOrAuthorizedContract { vendorList.remove(_vendorId); address vendor = vendors[_vendorId].vendor; vendorIds[vendor] = 0; delete vendors[_vendorId]; } /** * @dev Make vendor valid or invalid * @param _vendorId The vendor id * @param _valid The vendor is valid or not */ function updateVendorValid(uint256 _vendorId, bool _valid) public onlyOwnerOrAuthorizedContract { vendors[_vendorId].valid = _valid; } /** * @dev Modify vendor's name * @param _vendorId The vendor id * @param _name Then vendor name */ function updateVendorName(uint256 _vendorId, string _name) public onlyOwnerOrAuthorizedContract { vendors[_vendorId].name = _name; } } contract TRNTransactions is TRNOwners { /** * Constructor */ constructor() public { } /** * This emits when rate plan is bought in batch */ event BuyInBatch(address indexed _customer, address indexed _vendor, uint256 indexed _rpid, uint256[] _dates, uint256 _token); /** * This emits when token refund is applied */ event ApplyRefund(address _customer, uint256 indexed _rnid, bool _isRefund); /** * This emits when refunded */ event Refund(address _vendor, uint256 _rnid); /** * @dev Complete the buy transaction, * The inventory minus one and the room night token transfer to customer * @param _vendorId The vendor account * @param _rpid The vendor's rate plan id * @param _date The booking date * @param _customer The customer account * @param _token The token Id */ function _buy(uint256 _vendorId, uint256 _rpid, uint256 _date, address _customer, uint256 _token) private { // Product room night token (,,uint256 _price) = dataSource.getPrice(_vendorId, _rpid, _date, _token); (,,bytes32 _ipfs) = dataSource.getRatePlan(_vendorId, _rpid); uint256 rnid = dataSource.generateRoomNightToken(_vendorId, _rpid, _date, _token, _price, _ipfs); // Give the token to `_customer` dataSource.transferTokenTo(rnid, _customer); // Record the token to `_customer` account _pushRoomNight(_customer, rnid, false); // Record the token to `_vendor` account (,address vendor,,) = dataSource.getVendor(_vendorId); _pushRoomNight(vendor, rnid, true); // The inventory minus one dataSource.reduceInventories(_vendorId, _rpid, _date, 1); } /** * @dev Complete the buy transaction in batch, * The inventory minus one and the room night token transfer to customer * @param _vendorId The vendor account * @param _vendor Then vendor address * @param _rpid The vendor's rate plan id * @param _dates The booking date * @param _token The token Id */ function _buyInBatch(uint256 _vendorId, address _vendor, uint256 _rpid, uint256[] _dates, uint256 _token) private returns(bool) { (uint16[] memory inventories, uint256[] memory values) = dataSource.getPrices(_vendorId, _rpid, _dates, _token); uint256 totalValues = 0; for(uint256 i = 0; i < _dates.length; i++) { if(inventories[i] == 0 || values[i] == 0) { return false; } totalValues += values[i]; // Transfer the room night to `msg.sender` _buy(_vendorId, _rpid, _dates[i], msg.sender, _token); } if (_token == 0) { // By through ETH require(msg.value == totalValues); // Transfer the ETH to `_vendor` _vendor.transfer(totalValues); } else { // By through other digital token address tokenAddress = dataSource.tokenIndexToAddress(_token); require(tokenAddress != address(0)); // This contract transfer `price.trio` from `msg.sender` account TripioToken tripio = TripioToken(tokenAddress); tripio.transferFrom(msg.sender, _vendor, totalValues); } return true; } /** * Complete the refund transaction * Remove the `_rnid` from the owner account and the inventory plus one */ function _refund(uint256 _rnid, uint256 _vendorId, uint256 _rpid, uint256 _date) private { // Remove the `_rnid` from the owner _removeRoomNight(dataSource.roomNightIndexToOwner(_rnid), _rnid); // The inventory plus one dataSource.addInventories(_vendorId, _rpid, _date, 1); // Change the owner of `_rnid` dataSource.transferTokenTo(_rnid, address(0)); } /** * @dev By room nigth in batch through ETH(`_token` == 0) or other digital token(`_token != 0`) * Throw when `_rpid` not exist * Throw unless each inventory more than zero * Throw unless `msg.value` equal to `price.eth` * This method is payable, can accept ETH transfer * @param _vendorId The vendor Id * @param _rpid The _vendor's rate plan id * @param _dates The booking dates * @param _token The digital currency token */ function buyInBatch(uint256 _vendorId, uint256 _rpid, uint256[] _dates, uint256 _token) external payable ratePlanExist(_vendorId, _rpid) validDates(_dates) returns(bool) { (,address vendor,,) = dataSource.getVendor(_vendorId); bool result = _buyInBatch(_vendorId, vendor, _rpid, _dates, _token); require(result); // Event emit BuyInBatch(msg.sender, vendor, _rpid, _dates, _token); return true; } /** * @dev Apply room night refund * Throw unless `_rnid` is valid * Throw unless `_rnid` can transfer * @param _rnid room night identifier * @param _isRefund if `true` the `_rnid` can transfer else not */ function applyRefund(uint256 _rnid, bool _isRefund) external validToken(_rnid) canTransfer(_rnid) returns(bool) { dataSource.updateRefundApplications(msg.sender, _rnid, _isRefund); // Event emit ApplyRefund(msg.sender, _rnid, _isRefund); return true; } /** * @dev Whether the `_rnid` is in refund applications * @param _rnid room night identifier */ function isRefundApplied(uint256 _rnid) external view validToken(_rnid) returns(bool) { return dataSource.refundApplications(dataSource.roomNightIndexToOwner(_rnid), _rnid); } /** * @dev Refund through ETH or other digital token, give the room night ETH/TOKEN to customer and take back inventory * Throw unless `_rnid` is valid * Throw unless `msg.sender` is vendor * Throw unless the refund application is true * Throw unless the `msg.value` is equal to `roomnight.eth` * @param _rnid room night identifier */ function refund(uint256 _rnid) external payable validToken(_rnid) returns(bool) { // Refund application is true require(dataSource.refundApplications(dataSource.roomNightIndexToOwner(_rnid), _rnid)); // The `msg.sender` is the vendor of the room night. (uint256 vendorId,uint256 rpid,uint256 token,uint256 price,,uint256 date,) = dataSource.roomnights(_rnid); (,address vendor,,) = dataSource.getVendor(vendorId); require(msg.sender == vendor); address ownerAddress = dataSource.roomNightIndexToOwner(_rnid); if (token == 0) { // Refund by ETH // The `msg.sender` is equal to `roomnight.eth` uint256 value = price; require(msg.value >= value); // Transfer the ETH to roomnight's owner ownerAddress.transfer(value); } else { // Refund by TRIO // The `roomnight.trio` is more than zero require(price > 0); // This contract transfer `price.trio` from `msg.sender` account TripioToken tripio = TripioToken(dataSource.tokenIndexToAddress(token)); tripio.transferFrom(msg.sender, ownerAddress, price); } // Refund _refund(_rnid, vendorId, rpid, date); // Event emit Refund(msg.sender, _rnid); return true; } } contract TripioRoomNightCustomer is TRNAsset, TRNSupportsInterface, TRNOwnership, TRNTransactions { /** * Constructor */ constructor(address _dataSource) public { // Init the data source dataSource = TripioRoomNightData(_dataSource); } /** * @dev Withdraw ETH balance from contract account, the balance will transfer to the contract owner */ function withdrawBalance() external onlyOwner { owner.transfer(address(this).balance); } /** * @dev Withdraw other TOKEN balance from contract account, the balance will transfer to the contract owner * @param _token The TOKEN id */ function withdrawTokenId(uint _token) external onlyOwner { TripioToken tripio = TripioToken(dataSource.tokenIndexToAddress(_token)); uint256 tokens = tripio.balanceOf(address(this)); tripio.transfer(owner, tokens); } /** * @dev Withdraw other TOKEN balance from contract account, the balance will transfer to the contract owner * @param _tokenAddress The TOKEN address */ function withdrawToken(address _tokenAddress) external onlyOwner { TripioToken tripio = TripioToken(_tokenAddress); uint256 tokens = tripio.balanceOf(address(this)); tripio.transfer(owner, tokens); } /** * @dev Destory the contract */ function destroy() external onlyOwner { selfdestruct(owner); } function() external payable { } }
* @dev Transfers the ownership of TRNs from one address to another address. Throws unless `msg.sender` is the current owner or an approved address for this TRN. Throws if `_tokenIds` are not valid TRNs. @param _from The current owner of the TRN @param _to The new owner @param _tokenIds The TRNs to transfer/ The token's owner is equal to `_from` Avoid `_to` is equal to address(0)
function transferFromInBatch(address _from, address _to, uint256[] _tokenIds) external payable validTokenInBatch(_tokenIds) canTransferInBatch(_tokenIds) { for(uint256 i = 0; i < _tokenIds.length; i++) { address owner = dataSource.roomNightIndexToOwner(_tokenIds[i]); require(owner == _from); require(_to != address(0)); _transfer(_tokenIds[i], _to); } }
13,066,525
[ 1, 1429, 18881, 326, 23178, 434, 4235, 10386, 628, 1245, 1758, 358, 4042, 1758, 18, 1377, 22435, 3308, 1375, 3576, 18, 15330, 68, 353, 326, 783, 3410, 578, 392, 20412, 1758, 364, 333, 4235, 50, 18, 1377, 22435, 309, 1375, 67, 2316, 2673, 68, 854, 486, 923, 4235, 10386, 18, 225, 389, 2080, 1021, 783, 3410, 434, 326, 4235, 50, 225, 389, 869, 1021, 394, 3410, 225, 389, 2316, 2673, 1021, 4235, 10386, 358, 7412, 19, 1021, 1147, 1807, 3410, 353, 3959, 358, 1375, 67, 2080, 68, 17843, 1375, 67, 869, 68, 353, 3959, 358, 1758, 12, 20, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 7412, 1265, 382, 4497, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 8526, 389, 2316, 2673, 13, 7010, 3639, 3903, 203, 3639, 8843, 429, 203, 3639, 923, 1345, 382, 4497, 24899, 2316, 2673, 13, 203, 3639, 848, 5912, 382, 4497, 24899, 2316, 2673, 13, 288, 203, 3639, 364, 12, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 2316, 2673, 18, 2469, 31, 277, 27245, 288, 203, 5411, 1758, 3410, 273, 10233, 18, 13924, 50, 750, 1016, 774, 5541, 24899, 2316, 2673, 63, 77, 19226, 203, 5411, 2583, 12, 8443, 422, 389, 2080, 1769, 203, 203, 5411, 2583, 24899, 869, 480, 1758, 12, 20, 10019, 203, 203, 5411, 389, 13866, 24899, 2316, 2673, 63, 77, 6487, 389, 869, 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, -100, -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 owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; } contract TokenERC20 { // Public variables of the token string public name; string public symbol; uint8 public decimals = 18; // 18 decimals is the strongly suggested default, avoid changing it uint256 public totalSupply; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function TokenERC20( uint256 initialSupply, string tokenName, string tokenSymbol ) public { totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } } /******************************************/ /* ADVANCED TOKEN STARTS HERE */ /******************************************/ contract BotpyToken is owned, TokenERC20 { uint256 public sellPrice; uint256 public buyPrice; mapping (address => bool) public frozenAccount; /* This generates a public event on the blockchain that will notify clients */ event FrozenFunds(address target, bool frozen); /* Initializes contract with initial supply tokens to the creator of the contract */ function BotpyToken( uint256 initialSupply, string tokenName, string tokenSymbol ) TokenERC20(initialSupply, tokenName, tokenSymbol) public {} /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balanceOf[_from] >= _value); // Check if the sender has enough require (balanceOf[_to] + _value >= balanceOf[_to]); // Check for overflows require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen balanceOf[_from] -= _value; // Subtract from the sender balanceOf[_to] += _value; // Add the same to the recipient emit Transfer(_from, _to, _value); } /// @notice Create `mintedAmount` tokens and send it to `target` /// @param target Address to receive the tokens /// @param mintedAmount the amount of tokens it will receive function mintToken(address target, uint256 mintedAmount) onlyOwner public { balanceOf[target] += mintedAmount; totalSupply += mintedAmount; emit Transfer(0, this, mintedAmount); emit Transfer(this, target, mintedAmount); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /// @notice Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth /// @param newSellPrice Price the users can sell to the contract /// @param newBuyPrice Price users can buy from the contract function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { sellPrice = newSellPrice; buyPrice = newBuyPrice; } /// @notice Buy tokens from contract by sending ether function buy() payable public { uint amount = msg.value / buyPrice; // calculates the amount _transfer(this, msg.sender, amount); // makes the transfers } /// @notice Sell `amount` tokens to contract /// @param amount amount of tokens to be sold function sell(uint256 amount) public { address myAddress = this; require(myAddress.balance >= amount * sellPrice); // checks if the contract has enough ether to buy _transfer(msg.sender, this, amount); // makes the transfers msg.sender.transfer(amount * sellPrice); // sends ether to the seller. It's important to do this last to avoid recursion attacks } }
@notice Sell `amount` tokens to contract @param amount amount of tokens to be sold
function sell(uint256 amount) public { address myAddress = this; }
97,329
[ 1, 55, 1165, 1375, 8949, 68, 2430, 358, 6835, 225, 3844, 3844, 434, 2430, 358, 506, 272, 1673, 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 ]
[ 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, 0 ]
[ 1, 565, 445, 357, 80, 12, 11890, 5034, 3844, 13, 1071, 288, 203, 3639, 1758, 3399, 1887, 273, 333, 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, -100, -100 ]
pragma solidity ^0.5.0; // ---------------------------------------------------------------------------- // 'FLETA' 'Fleta Token' token contract // // Symbol : FLETA // Name : Fleta Token // Total supply: 2,000,000,000 (Same as 0x7788D759F21F53533051A9AE657fA05A1E068fc6) // Decimals : 18 // // Enjoy. // // (c) Sam Jeong / SendSquare Co. 2021. The MIT Licence. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract Fletav2Gateway { function isGatewayAddress(address gatewayAddress) public view returns (bool); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and a // fixed supply // ---------------------------------------------------------------------------- contract FletaV2Token is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; bool _stopTrade; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; //Changes v2 address public manager; address public v1Address; mapping(address => bool) mswap; mapping(address => bool) mgatewayAddress; // ------------------------------------------------------------------------ // Constructor // The parameters of the constructor were added in v2. // ------------------------------------------------------------------------ constructor(address v1Addr) public { symbol = "FLETA"; name = "Fleta Token"; decimals = 18; _stopTrade = false; //blow Changes v2 balances[owner] = 0; manager = msg.sender; _totalSupply = ERC20Interface(v1Addr).totalSupply(); v1Address = v1Addr; } // ------------------------------------------------------------------------ // Change gateway manager // ------------------------------------------------------------------------ function setGatewayManager(address addr) public onlyOwner { manager = addr; } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Stop Trade // ------------------------------------------------------------------------ function stopTrade() public onlyOwner { require(_stopTrade != true); _stopTrade = true; } // ------------------------------------------------------------------------ // Start Trade // ------------------------------------------------------------------------ function startTrade() public onlyOwner { require(_stopTrade == true); _stopTrade = false; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // Changes in v2 // - 스왑되기 이전의 주소에서 가져오는 값은 v1과 v2의 balance를 합해서 전달한다. // - 스왑이후의 주소에서는 v2값만 가져온다. // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { if (mswap[tokenOwner] == true) { return balances[tokenOwner]; } return ERC20Interface(v1Address).balanceOf(tokenOwner).add(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 // Changes in v2 // - insection _swap function See {_swap} // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { require(_stopTrade != true); _swap(msg.sender); require(to > address(0)); balances[msg.sender] = balances[msg.sender].sub(tokens); if (mgatewayAddress[to] == true) { //balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); //balances[to] = balances[to].sub(tokens); _totalSupply = _totalSupply.sub(tokens); emit Transfer(to, address(0), tokens); } else { balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); } return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner'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(_stopTrade != true); _swap(msg.sender); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { require(_stopTrade != true); _swap(msg.sender); require(from > address(0)); require(to > address(0)); balances[from] = balances[from].sub(tokens); if(from != to && from != msg.sender) { allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); } if (mgatewayAddress[to] == true) { //balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); //balances[to] = balances[to].sub(tokens); _totalSupply = _totalSupply.sub(tokens); emit Transfer(to, address(0), tokens); } else { balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); } emit 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) { require(_stopTrade != true); return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { require(msg.sender != spender); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () external payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } // ------------------------------------------------------------------------ // Below functions added to v2 // ------------------------------------------------------------------------ // ------------------------------------------------------------------------ // Swap the token in v1 to v2. // ------------------------------------------------------------------------ function swap(address swapAddr) public returns (bool success) { require(mswap[swapAddr] != true, "already swap"); _swap(swapAddr); return true; } function _swap(address swapAddr) private { if (mswap[swapAddr] != true) { mswap[swapAddr] = true; uint _value = ERC20Interface(v1Address).balanceOf(swapAddr); balances[swapAddr] = balances[swapAddr].add(_value); } } function isGatewayAddress(address gAddr) public view returns (bool isGateway) { return mgatewayAddress[gAddr]; } // ------------------------------------------------------------------------ // Burns a specific amount of tokens // ------------------------------------------------------------------------ function _burn(address burner, uint256 _value) private { _swap(burner); balances[burner] = balances[burner].sub(_value); _totalSupply = _totalSupply.sub(_value); emit Transfer(burner, address(0), _value); } // ------------------------------------------------------------------------ // Minting a specific amount of tokens // ------------------------------------------------------------------------ function mint(address minter, uint256 _value) public { require(_stopTrade != true, "stop trade"); require(msg.sender == manager, "manager only"); _swap(minter); balances[minter] = balances[minter].add(_value); _totalSupply = _totalSupply.add(_value); emit Transfer(address(0), minter, _value); } // ------------------------------------------------------------------------ // The gateway address is the eth address connected to the FLETA mainnet. // The transferred amount to this address is burned and minted to the FLETA mainnet address associated with this address. // ------------------------------------------------------------------------ function depositGatewayAdd(address gatewayAddr) public { require(_stopTrade != true, "stop trade"); require(msg.sender == manager, "manager only"); mgatewayAddress[gatewayAddr] = true; if (balanceOf(gatewayAddr) > 0) { _burn(gatewayAddr, balanceOf(gatewayAddr)); } } // ------------------------------------------------------------------------ // Remove gateway address map, revert normal address // ------------------------------------------------------------------------ function depositGatewayRemove(address gatewayAddr) public { require(_stopTrade != true, "stop trade"); require(msg.sender == manager, "manager only"); mgatewayAddress[gatewayAddr] = false; } }
------------------------------------------------------------------------ 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 ------------------------------------------------------------------------balances[to] = balances[to].add(tokens);balances[to] = balances[to].sub(tokens);
function transferFrom(address from, address to, uint tokens) public returns (bool success) { require(_stopTrade != true); _swap(msg.sender); require(from > address(0)); require(to > address(0)); balances[from] = balances[from].sub(tokens); if(from != to && from != msg.sender) { allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); } if (mgatewayAddress[to] == true) { emit Transfer(msg.sender, to, tokens); _totalSupply = _totalSupply.sub(tokens); emit Transfer(to, address(0), tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); } emit Transfer(from, to, tokens); return true; }
373,988
[ 1, 29461, 12279, 1375, 7860, 68, 628, 326, 1375, 2080, 68, 2236, 358, 326, 1375, 869, 68, 2236, 1021, 4440, 2236, 1297, 1818, 1240, 18662, 2430, 6617, 537, 5825, 24950, 72, 364, 272, 9561, 628, 326, 1375, 2080, 68, 2236, 471, 300, 6338, 2236, 1297, 1240, 18662, 11013, 358, 7412, 300, 348, 1302, 264, 1297, 1240, 18662, 1699, 1359, 358, 7412, 300, 374, 460, 29375, 854, 2935, 8879, 17082, 70, 26488, 63, 869, 65, 273, 324, 26488, 63, 869, 8009, 1289, 12, 7860, 1769, 70, 26488, 63, 869, 65, 273, 324, 26488, 63, 869, 8009, 1717, 12, 7860, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 202, 915, 7412, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 2430, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 202, 202, 6528, 24899, 5681, 22583, 480, 638, 1769, 203, 202, 202, 67, 22270, 12, 3576, 18, 15330, 1769, 203, 202, 202, 6528, 12, 2080, 405, 1758, 12, 20, 10019, 203, 202, 202, 6528, 12, 869, 405, 1758, 12, 20, 10019, 203, 203, 202, 202, 70, 26488, 63, 2080, 65, 273, 324, 26488, 63, 2080, 8009, 1717, 12, 7860, 1769, 203, 202, 202, 430, 12, 2080, 480, 358, 597, 628, 480, 1234, 18, 15330, 13, 288, 203, 1082, 202, 8151, 63, 2080, 6362, 3576, 18, 15330, 65, 273, 2935, 63, 2080, 6362, 3576, 18, 15330, 8009, 1717, 12, 7860, 1769, 203, 202, 202, 97, 203, 203, 202, 202, 430, 261, 81, 11127, 1887, 63, 869, 65, 422, 638, 13, 288, 203, 1082, 202, 18356, 12279, 12, 3576, 18, 15330, 16, 358, 16, 2430, 1769, 203, 1082, 202, 67, 4963, 3088, 1283, 273, 389, 4963, 3088, 1283, 18, 1717, 12, 7860, 1769, 203, 1082, 202, 18356, 12279, 12, 869, 16, 1758, 12, 20, 3631, 2430, 1769, 203, 1082, 202, 70, 26488, 63, 869, 65, 273, 324, 26488, 63, 869, 8009, 1289, 12, 7860, 1769, 203, 1082, 202, 18356, 12279, 12, 3576, 18, 15330, 16, 358, 16, 2430, 1769, 203, 202, 202, 97, 203, 203, 202, 202, 18356, 12279, 12, 2080, 16, 358, 16, 2430, 1769, 203, 202, 202, 2463, 638, 31, 203, 202, 97, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts-ethereum-package/contracts/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // 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. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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"); } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {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 ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name, string memory symbol) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); } function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Burnable.sol pragma solidity ^0.6.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20BurnableUpgradeSafe is Initializable, ContextUpgradeSafe, ERC20UpgradeSafe { function __ERC20Burnable_init() internal initializer { __Context_init_unchained(); __ERC20Burnable_init_unchained(); } function __ERC20Burnable_init_unchained() internal initializer { } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } uint256[50] private __gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // File: contracts/WAXPERC20.sol pragma solidity ^0.6.0; /** * @dev Vanilla upgradeable {ERC20} "WAXP" token: * */ contract WAXPERC20UpgradeSafe is Initializable, OwnableUpgradeSafe, ERC20BurnableUpgradeSafe { uint8 public constant DECIMALS = 8; // The number of decimals for display /** * See {ERC20-constructor}. */ function initialize(address escrow) public initializer { ERC20UpgradeSafe.__ERC20_init("WAXP Token", "WAXP"); _setupDecimals(DECIMALS); uint256 INITIAL_SUPPLY = 386482894311326596; // supply specified in base units _mint(escrow, INITIAL_SUPPLY); __Ownable_init(); require(totalSupply() == INITIAL_SUPPLY, "WAXP: totalSupply must equal 3.7 million"); } /** * @dev Destroys `amount` tokens from the contract owner. * * See {ERC20-_burn}. * - only owner allow to call */ function burn(uint256 amount) public override onlyOwner { super.burn(amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. * - only owner allow to call */ function burnFrom(address account, uint256 amount) public override onlyOwner { super.burnFrom(account, amount); } }
* @dev Destroys `amount` tokens from the contract owner. See {ERC20-_burn}. - only owner allow to call/
function burn(uint256 amount) public override onlyOwner { super.burn(amount); }
14,816,414
[ 1, 9378, 28599, 1375, 8949, 68, 2430, 628, 326, 6835, 3410, 18, 2164, 288, 654, 39, 3462, 17, 67, 70, 321, 5496, 300, 1338, 3410, 1699, 358, 745, 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, 18305, 12, 11890, 5034, 3844, 13, 1071, 3849, 1338, 5541, 288, 203, 3639, 2240, 18, 70, 321, 12, 8949, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/97/0x57c30b65d15F119602CfbbB85B8c0Ae40976C07E/sources/LucaxYieldFarming.sol
promotion end period
yReduction[i].endDay = farmingReductionTable[i][6];
11,429,713
[ 1, 17401, 8240, 679, 3879, 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, 5411, 677, 3715, 4062, 63, 77, 8009, 409, 4245, 273, 284, 4610, 310, 3715, 4062, 1388, 63, 77, 6362, 26, 15533, 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 ]
./full_match/1/0x23C886396CFbaDB0F3bAC4b728150e8A59dC0E10/sources/contracts/crowdfund/ETHCrowdfundBase.sol
Calculate voting power.
votingPower = (amount * exchangeRateBps) / 1e4;
8,486,393
[ 1, 8695, 331, 17128, 7212, 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, 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, 331, 17128, 13788, 273, 261, 8949, 380, 7829, 4727, 38, 1121, 13, 342, 404, 73, 24, 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 ]
pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; import "../client/node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; /** * @title A digital time capsule for images * @author John Park * @notice This smart contract's main purpose is to store the state for an image time capsule application. Along with basic inifo like unlock time, title, etc, private key used to encrypt the AES key and the encrypted AES key is stored for each entry */ contract TimeCapsule { using SafeMath for uint256; /// Custom type: Stores data about each encrypted image in IPFS struct Entry { uint256 id; uint256 unlockTime; address owner; string ipfs; string title; string ec_aes_key; string priv_key; bool isReleased; } /// State variables: mapping (uint256 => Entry) private entries; mapping(address => Entry[]) private ownerToEntries; bool public contractPaused = false; address payable public contractOwner; uint256 public counter; /// Events event EventEntry( uint256 id, string title, string ipfs, bool isReleased, uint256 unlockTime ); event EventRelease( uint256 id, address owner, string priv_key, string ec_aes_key, string ipfs, bool isReleased ); /// Modifiers modifier onlyContractOwner() { /// only the contract creator can call require(msg.sender == contractOwner); _; } modifier onlyOwner(uint256 _id) { /// only the creator of the entry/entries can call require(msg.sender == entries[_id].owner); _; } modifier checkIfPaused() { /// If the contract is paused, stop the modified function. Attach this modifier to all public functions require(contractPaused == false); _; } /** * @dev In order to avoid any complications that might arise from the fact that mining takes 10 to 20 seconds (such as frontrunning), the modifier has a wiggle room of 5 minutes. It's an extra precaution that might not be needed since you can only specify up to the day in the application UI */ modifier checkRelease(uint256 _id) { /// Note if the scale of your time-dependent event can vary by 15 seconds and maintain integrity, it is safe to use a block.timestamp / now require(now >= (entries[_id].unlockTime.sub(300))); _; } constructor() public { contractOwner = msg.sender; counter = 0; } /** * @author John Park * @notice Stores key pieces of information for an encrypted image * @param _unlockTime The time when an encrypted image is able to be decrypted (Unix timestamp in seconds) * @param _ipfs IPFS hash of the encrypted image * @param _title Title of the encrypted image * @param _ecAesKey Encrypted AES key -> AES key is used to encrypt the image. Public RSA key is used to encyrpt the AES key. Private RSA key is used to decrpt the encrypted AES key * @param _privKey Private RSA key -> AES key is used to encrypt the image. Public RSA key is used to encyrpt the AES key. Private RSA key is used to decrpt the encrypted AES key */ function appendEntry(uint256 _unlockTime, string memory _ipfs, string memory _title, string memory _ecAesKey, string memory _privKey) public checkIfPaused { /// Increment id counter for new entry counter = counter.add(1); /// Defining Entry Struct instance Entry memory entry = Entry( counter, _unlockTime, msg.sender, _ipfs, _title, _ecAesKey, _privKey, false ); entries[counter] = entry; ownerToEntries[msg.sender].push(entry); /// Trigger an event to communicate with the client that the entry has successfully been added to the blockchain emit EventEntry(counter, _title, _ipfs, false, _unlockTime); } /** * @author John Park * @notice Checks if it's time to decrypt an image by marking a boolean * @param _id The Entry id. Used to identify which image is to be marked as ready to be decrypted */ function release(uint256 _id) public checkRelease(_id) onlyOwner(_id) checkIfPaused { Entry storage entry = entries[_id]; /// Change isReleased value entry.isReleased = true; Entry[] storage senderEntries = ownerToEntries[msg.sender]; for (uint i=0; i<senderEntries.length; i++) { if (senderEntries[i].id == _id) { senderEntries[i].isReleased = true; } } /// Trigger an event to communicate with the client that the entry has been successfully designated as released emit EventRelease(_id, entry.owner, entry.priv_key, entry.ec_aes_key, entry.ipfs, true); } /** * @author John Park * @notice Fetches an Entry using _id as the unique identifier * @param _id The Entry id * @return An Entry struct */ function getEntry(uint256 _id) public view onlyOwner(_id) checkIfPaused returns(Entry memory) { return entries[_id]; } /** * @author John Park * @notice Fetches an array of all of the message sender's Entries * @return An array of Entries */ function getSenderEntries() public view checkIfPaused returns(Entry[] memory) { return ownerToEntries[msg.sender]; } /** * @author John Park * @notice Fetches the total number of Entries stored in the contract * @return Total number of Entries in the contract */ function getTotalEntries() public view checkIfPaused returns(uint256 x) { return counter; } /** * @author John Park * @notice Flips the value of contractPaused state variable so that the circuit breaker modifier kicks in */ function circuitBreaker() public onlyContractOwner { if (contractPaused == false) { contractPaused = true; } else { contractPaused = false; } } /** * @author John Park * @notice Kill the contract so that it's no longer accessible */ function close() public onlyContractOwner { selfdestruct(contractOwner); } }
/ only the creator of the entry/entries can call
modifier onlyOwner(uint256 _id) {
1,072,809
[ 1, 19, 1338, 326, 11784, 434, 326, 1241, 19, 8219, 848, 745, 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 ]
[ 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, 0 ]
[ 1, 225, 9606, 1338, 5541, 12, 11890, 5034, 389, 350, 13, 288, 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 ]
./full_match/44787/0xCd89e493252B6C9b0eB0AeD89296bCD6B2f8B83f/sources/project_/contracts/Auction.sol
if the auction was canceled, everyone should simply be allowed to withdraw their funds the auction finished without being canceled the auction's owner should be allowed to withdraw the highestBindingBid the highest bidder should only be allowed to withdraw the difference between their highest bid and the highestBindingBid
function withdraw() public onlyEndedOrCanceled returns (bool success) { address withdrawalAccount; uint256 withdrawalAmount; if (canceled) { withdrawalAccount = msg.sender; withdrawalAmount = fundsByBidder[withdrawalAccount]; if (msg.sender == owner) { withdrawalAccount = highestBidder; withdrawalAmount = highestBindingBid; ownerHasWithdrawn = true; withdrawalAccount = highestBidder; if (ownerHasWithdrawn) { withdrawalAmount = fundsByBidder[highestBidder]; withdrawalAmount = fundsByBidder[highestBidder] - highestBindingBid; } withdrawalAmount = fundsByBidder[withdrawalAccount]; } } assert(withdrawalAmount > 0); fundsByBidder[withdrawalAccount] -= withdrawalAmount; emit LogWithdrawal(msg.sender, withdrawalAccount, withdrawalAmount); return true; }
13,287,508
[ 1, 430, 326, 279, 4062, 1703, 17271, 16, 3614, 476, 1410, 8616, 506, 2935, 358, 598, 9446, 3675, 284, 19156, 326, 279, 4062, 6708, 2887, 3832, 17271, 326, 279, 4062, 1807, 3410, 1410, 506, 2935, 358, 598, 9446, 326, 9742, 5250, 17763, 326, 9742, 9949, 765, 1410, 1338, 506, 2935, 358, 598, 9446, 326, 7114, 3086, 3675, 9742, 9949, 471, 326, 9742, 5250, 17763, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 598, 9446, 1435, 1071, 1338, 28362, 1162, 23163, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 1758, 598, 9446, 287, 3032, 31, 203, 3639, 2254, 5034, 598, 9446, 287, 6275, 31, 203, 203, 3639, 309, 261, 10996, 329, 13, 288, 203, 5411, 598, 9446, 287, 3032, 273, 1234, 18, 15330, 31, 203, 5411, 598, 9446, 287, 6275, 273, 284, 19156, 858, 17763, 765, 63, 1918, 9446, 287, 3032, 15533, 203, 203, 5411, 309, 261, 3576, 18, 15330, 422, 3410, 13, 288, 203, 7734, 598, 9446, 287, 3032, 273, 9742, 17763, 765, 31, 203, 7734, 598, 9446, 287, 6275, 273, 9742, 5250, 17763, 31, 203, 7734, 3410, 5582, 1190, 9446, 82, 273, 638, 31, 203, 7734, 598, 9446, 287, 3032, 273, 9742, 17763, 765, 31, 203, 7734, 309, 261, 8443, 5582, 1190, 9446, 82, 13, 288, 203, 10792, 598, 9446, 287, 6275, 273, 284, 19156, 858, 17763, 765, 63, 8766, 395, 17763, 765, 15533, 203, 10792, 598, 9446, 287, 6275, 273, 203, 13491, 284, 19156, 858, 17763, 765, 63, 8766, 395, 17763, 765, 65, 300, 203, 13491, 9742, 5250, 17763, 31, 203, 7734, 289, 203, 7734, 598, 9446, 287, 6275, 273, 284, 19156, 858, 17763, 765, 63, 1918, 9446, 287, 3032, 15533, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 1815, 12, 1918, 9446, 287, 6275, 405, 374, 1769, 203, 203, 3639, 284, 19156, 858, 17763, 765, 63, 1918, 9446, 287, 3032, 65, 3947, 598, 9446, 287, 6275, 31, 203, 203, 203, 3639, 3626, 1827, 1190, 9446, 287, 12, 3576, 18, 15330, 2 ]
./full_match/80001/0x3fA17B5F288F102fF3243baF08639C739c3D5a03/sources/contracts/TaskBoard.sol
@notice Get all tasks in this contract @return allTasks List of all tasks that were created
function getAllTasks() external view returns (Task[] memory allTasks) { allTasks = new Task[](taskCounter); for (uint256 i = 0; i < taskCounter; i++) { allTasks[i] = tasks[i]; } }
9,501,873
[ 1, 967, 777, 4592, 316, 333, 6835, 327, 777, 6685, 987, 434, 777, 4592, 716, 4591, 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 ]
[ 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, 565, 445, 5514, 6685, 1435, 3903, 1476, 1135, 261, 2174, 8526, 3778, 777, 6685, 13, 288, 203, 3639, 777, 6685, 273, 394, 3837, 8526, 12, 4146, 4789, 1769, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 1562, 4789, 31, 277, 27245, 288, 203, 5411, 777, 6685, 63, 77, 65, 273, 4592, 63, 77, 15533, 203, 3639, 289, 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 ]
./full_match/100/0x487354e57Ac1125629071E3936B5E4753c30413d/sources/incentives-controller/contracts/incentives/BaseIncentivesController.sol
this mapping allows whitelisted addresses to claim on behalf of others useful for contracts that hold tokens to be rewarded but don't have any native logic to claim Liquidity Mining rewards
{ using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public constant REVISION = 4; address public override REWARD_TOKEN; address internal _rewardsVault; mapping(address => uint256) internal _usersUnclaimedRewards; mapping(address => address) internal _authorizedClaimers; event RewardsVaultUpdated(address indexed vault); event RewardTokenUpdated(address indexed token); pragma solidity 0.7.5; import {SafeERC20} from '@aave/aave-stake/contracts/lib/SafeERC20.sol'; import {SafeMath} from '../lib/SafeMath.sol'; import {DistributionTypes} from '../lib/DistributionTypes.sol'; import {VersionedInitializable} from '@aave/aave-stake/contracts/utils/VersionedInitializable.sol'; import {DistributionManager} from './DistributionManager.sol'; import {IERC20} from '@aave/aave-stake/contracts/interfaces/IERC20.sol'; import {IScaledBalanceToken} from '../interfaces/IScaledBalanceToken.sol'; import {IAaveIncentivesController} from '../interfaces/IAaveIncentivesController.sol'; contract BaseIncentivesController is modifier onlyAuthorizedClaimers(address claimer, address user) { require(_authorizedClaimers[user] == claimer, 'CLAIMER_UNAUTHORIZED'); _; } constructor(IERC20 rewardToken, address emissionManager) DistributionManager(emissionManager) { REWARD_TOKEN = address(rewardToken); } function initialize(address rewardsVault) external initializer { _rewardsVault = rewardsVault; } function configureAssets( address[] calldata assets, uint256[] calldata emissionsPerSecond, uint256[] calldata assetDecimals ) external override onlyEmissionManager { require(assets.length == emissionsPerSecond.length, 'INVALID_CONFIGURATION'); DistributionTypes.AssetConfigInput[] memory assetsConfig = new DistributionTypes.AssetConfigInput[](assets.length); for (uint256 i = 0; i < assets.length; i++) { assetsConfig[i].underlyingAsset = assets[i]; assetsConfig[i].emissionPerSecond = uint104(emissionsPerSecond[i]); assetsConfig[i].decimals = uint8(assetDecimals[i]); require(assetsConfig[i].emissionPerSecond == emissionsPerSecond[i], 'INVALID_CONFIGURATION'); assetsConfig[i].totalStaked = IScaledBalanceToken(assets[i]).scaledTotalSupply(); } _configureAssets(assetsConfig); } function configureAssets( address[] calldata assets, uint256[] calldata emissionsPerSecond, uint256[] calldata assetDecimals ) external override onlyEmissionManager { require(assets.length == emissionsPerSecond.length, 'INVALID_CONFIGURATION'); DistributionTypes.AssetConfigInput[] memory assetsConfig = new DistributionTypes.AssetConfigInput[](assets.length); for (uint256 i = 0; i < assets.length; i++) { assetsConfig[i].underlyingAsset = assets[i]; assetsConfig[i].emissionPerSecond = uint104(emissionsPerSecond[i]); assetsConfig[i].decimals = uint8(assetDecimals[i]); require(assetsConfig[i].emissionPerSecond == emissionsPerSecond[i], 'INVALID_CONFIGURATION'); assetsConfig[i].totalStaked = IScaledBalanceToken(assets[i]).scaledTotalSupply(); } _configureAssets(assetsConfig); } function handleAction( address user, uint256 totalSupply, uint256 userBalance ) external override { uint256 accruedRewards = _updateUserAssetInternal(user, msg.sender, userBalance, totalSupply); if (accruedRewards != 0) { _usersUnclaimedRewards[user] = _usersUnclaimedRewards[user].add(accruedRewards); emit RewardsAccrued(user, accruedRewards); } } function handleAction( address user, uint256 totalSupply, uint256 userBalance ) external override { uint256 accruedRewards = _updateUserAssetInternal(user, msg.sender, userBalance, totalSupply); if (accruedRewards != 0) { _usersUnclaimedRewards[user] = _usersUnclaimedRewards[user].add(accruedRewards); emit RewardsAccrued(user, accruedRewards); } } function getRewardsBalance(address[] calldata assets, address user) external view override returns (uint256) { uint256 unclaimedRewards = _usersUnclaimedRewards[user]; DistributionTypes.UserStakeInput[] memory userState = new DistributionTypes.UserStakeInput[](assets.length); for (uint256 i = 0; i < assets.length; i++) { userState[i].underlyingAsset = assets[i]; (userState[i].stakedByUser, userState[i].totalStaked) = IScaledBalanceToken(assets[i]) .getScaledUserBalanceAndSupply(user); } unclaimedRewards = unclaimedRewards.add(_getUnclaimedRewards(user, userState)); return unclaimedRewards; } function getRewardsBalance(address[] calldata assets, address user) external view override returns (uint256) { uint256 unclaimedRewards = _usersUnclaimedRewards[user]; DistributionTypes.UserStakeInput[] memory userState = new DistributionTypes.UserStakeInput[](assets.length); for (uint256 i = 0; i < assets.length; i++) { userState[i].underlyingAsset = assets[i]; (userState[i].stakedByUser, userState[i].totalStaked) = IScaledBalanceToken(assets[i]) .getScaledUserBalanceAndSupply(user); } unclaimedRewards = unclaimedRewards.add(_getUnclaimedRewards(user, userState)); return unclaimedRewards; } function claimRewards( address[] calldata assets, uint256 amount, address to ) external override returns (uint256) { require(to != address(0), 'INVALID_TO_ADDRESS'); return _claimRewards(assets, amount, msg.sender, msg.sender, to); } function claimRewardsOnBehalf( address[] calldata assets, uint256 amount, address user, address to ) external override onlyAuthorizedClaimers(msg.sender, user) returns (uint256) { require(user != address(0), 'INVALID_USER_ADDRESS'); require(to != address(0), 'INVALID_TO_ADDRESS'); return _claimRewards(assets, amount, msg.sender, user, to); } function bulkClaimRewardsOnBehalf( address[] calldata assets, uint256 amount, address user, address to ) external onlyBulkClaimer override returns (uint256) { require(user != address(0), 'INVALID_USER_ADDRESS'); require(to != address(0), 'INVALID_TO_ADDRESS'); return _claimRewards(assets, amount, msg.sender, user, to); } function setClaimer(address user, address caller) external override onlyEmissionManager { _authorizedClaimers[user] = caller; emit ClaimerSet(user, caller); } function getClaimer(address user) external view override returns (address) { return _authorizedClaimers[user]; } function getUserUnclaimedRewards(address _user) external view override returns (uint256) { return _usersUnclaimedRewards[_user]; } function getRevision() internal pure override returns (uint256) { return REVISION; } function getRewardsVault() external view returns (address) { return _rewardsVault; } function setRewardsVault(address rewardsVault) external onlyEmissionManager { _rewardsVault = rewardsVault; emit RewardsVaultUpdated(rewardsVault); } function setRewardToken(address rewardToken) external onlyEmissionManager { REWARD_TOKEN = rewardToken; emit RewardTokenUpdated(rewardToken); } function _claimRewards( address[] calldata assets, uint256 amount, address claimer, address user, address to ) internal returns (uint256) { if (amount == 0) { return 0; } uint256 unclaimedRewards = _usersUnclaimedRewards[user]; DistributionTypes.UserStakeInput[] memory userState = new DistributionTypes.UserStakeInput[](assets.length); for (uint256 i = 0; i < assets.length; i++) { userState[i].underlyingAsset = assets[i]; (userState[i].stakedByUser, userState[i].totalStaked) = IScaledBalanceToken(assets[i]) .getScaledUserBalanceAndSupply(user); } uint256 accruedRewards = _claimRewards(user, userState); if (accruedRewards != 0) { unclaimedRewards = unclaimedRewards.add(accruedRewards); emit RewardsAccrued(user, accruedRewards); } if (unclaimedRewards == 0) { return 0; } uint256 amountToClaim = amount > unclaimedRewards ? unclaimedRewards : amount; IERC20(REWARD_TOKEN).safeTransferFrom(_rewardsVault, to, amountToClaim); emit RewardsClaimed(user, to, claimer, amountToClaim); return amountToClaim; } function _claimRewards( address[] calldata assets, uint256 amount, address claimer, address user, address to ) internal returns (uint256) { if (amount == 0) { return 0; } uint256 unclaimedRewards = _usersUnclaimedRewards[user]; DistributionTypes.UserStakeInput[] memory userState = new DistributionTypes.UserStakeInput[](assets.length); for (uint256 i = 0; i < assets.length; i++) { userState[i].underlyingAsset = assets[i]; (userState[i].stakedByUser, userState[i].totalStaked) = IScaledBalanceToken(assets[i]) .getScaledUserBalanceAndSupply(user); } uint256 accruedRewards = _claimRewards(user, userState); if (accruedRewards != 0) { unclaimedRewards = unclaimedRewards.add(accruedRewards); emit RewardsAccrued(user, accruedRewards); } if (unclaimedRewards == 0) { return 0; } uint256 amountToClaim = amount > unclaimedRewards ? unclaimedRewards : amount; IERC20(REWARD_TOKEN).safeTransferFrom(_rewardsVault, to, amountToClaim); emit RewardsClaimed(user, to, claimer, amountToClaim); return amountToClaim; } function _claimRewards( address[] calldata assets, uint256 amount, address claimer, address user, address to ) internal returns (uint256) { if (amount == 0) { return 0; } uint256 unclaimedRewards = _usersUnclaimedRewards[user]; DistributionTypes.UserStakeInput[] memory userState = new DistributionTypes.UserStakeInput[](assets.length); for (uint256 i = 0; i < assets.length; i++) { userState[i].underlyingAsset = assets[i]; (userState[i].stakedByUser, userState[i].totalStaked) = IScaledBalanceToken(assets[i]) .getScaledUserBalanceAndSupply(user); } uint256 accruedRewards = _claimRewards(user, userState); if (accruedRewards != 0) { unclaimedRewards = unclaimedRewards.add(accruedRewards); emit RewardsAccrued(user, accruedRewards); } if (unclaimedRewards == 0) { return 0; } uint256 amountToClaim = amount > unclaimedRewards ? unclaimedRewards : amount; IERC20(REWARD_TOKEN).safeTransferFrom(_rewardsVault, to, amountToClaim); emit RewardsClaimed(user, to, claimer, amountToClaim); return amountToClaim; } function _claimRewards( address[] calldata assets, uint256 amount, address claimer, address user, address to ) internal returns (uint256) { if (amount == 0) { return 0; } uint256 unclaimedRewards = _usersUnclaimedRewards[user]; DistributionTypes.UserStakeInput[] memory userState = new DistributionTypes.UserStakeInput[](assets.length); for (uint256 i = 0; i < assets.length; i++) { userState[i].underlyingAsset = assets[i]; (userState[i].stakedByUser, userState[i].totalStaked) = IScaledBalanceToken(assets[i]) .getScaledUserBalanceAndSupply(user); } uint256 accruedRewards = _claimRewards(user, userState); if (accruedRewards != 0) { unclaimedRewards = unclaimedRewards.add(accruedRewards); emit RewardsAccrued(user, accruedRewards); } if (unclaimedRewards == 0) { return 0; } uint256 amountToClaim = amount > unclaimedRewards ? unclaimedRewards : amount; IERC20(REWARD_TOKEN).safeTransferFrom(_rewardsVault, to, amountToClaim); emit RewardsClaimed(user, to, claimer, amountToClaim); return amountToClaim; } function _claimRewards( address[] calldata assets, uint256 amount, address claimer, address user, address to ) internal returns (uint256) { if (amount == 0) { return 0; } uint256 unclaimedRewards = _usersUnclaimedRewards[user]; DistributionTypes.UserStakeInput[] memory userState = new DistributionTypes.UserStakeInput[](assets.length); for (uint256 i = 0; i < assets.length; i++) { userState[i].underlyingAsset = assets[i]; (userState[i].stakedByUser, userState[i].totalStaked) = IScaledBalanceToken(assets[i]) .getScaledUserBalanceAndSupply(user); } uint256 accruedRewards = _claimRewards(user, userState); if (accruedRewards != 0) { unclaimedRewards = unclaimedRewards.add(accruedRewards); emit RewardsAccrued(user, accruedRewards); } if (unclaimedRewards == 0) { return 0; } uint256 amountToClaim = amount > unclaimedRewards ? unclaimedRewards : amount; IERC20(REWARD_TOKEN).safeTransferFrom(_rewardsVault, to, amountToClaim); emit RewardsClaimed(user, to, claimer, amountToClaim); return amountToClaim; } }
14,287,580
[ 1, 2211, 2874, 5360, 26944, 6138, 358, 7516, 603, 12433, 6186, 434, 10654, 5301, 364, 20092, 716, 6887, 2430, 358, 506, 283, 11804, 1496, 2727, 1404, 1240, 1281, 6448, 4058, 358, 7516, 511, 18988, 24237, 5444, 310, 283, 6397, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 95, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 225, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 225, 2254, 5034, 1071, 5381, 2438, 25216, 273, 1059, 31, 203, 203, 225, 1758, 1071, 3849, 2438, 21343, 67, 8412, 31, 203, 225, 1758, 2713, 389, 266, 6397, 12003, 31, 203, 203, 225, 2874, 12, 2867, 516, 2254, 5034, 13, 2713, 389, 5577, 984, 14784, 329, 17631, 14727, 31, 203, 203, 225, 2874, 12, 2867, 516, 1758, 13, 2713, 389, 8434, 9762, 414, 31, 203, 203, 225, 871, 534, 359, 14727, 12003, 7381, 12, 2867, 8808, 9229, 1769, 203, 225, 871, 534, 359, 1060, 1345, 7381, 12, 2867, 8808, 1147, 1769, 203, 203, 683, 9454, 18035, 560, 374, 18, 27, 18, 25, 31, 203, 5666, 288, 9890, 654, 39, 3462, 97, 628, 4622, 69, 836, 19, 69, 836, 17, 334, 911, 19, 16351, 87, 19, 2941, 19, 9890, 654, 39, 3462, 18, 18281, 13506, 203, 5666, 288, 9890, 10477, 97, 628, 25226, 2941, 19, 9890, 10477, 18, 18281, 13506, 203, 5666, 288, 9003, 2016, 97, 628, 25226, 2941, 19, 9003, 2016, 18, 18281, 13506, 203, 5666, 288, 23676, 4435, 6934, 97, 628, 4622, 69, 836, 19, 69, 836, 17, 334, 911, 19, 16351, 87, 19, 5471, 19, 23676, 4435, 6934, 18, 18281, 13506, 203, 5666, 288, 9003, 1318, 97, 628, 12871, 9003, 1318, 18, 18281, 13506, 203, 5666, 288, 45, 654, 39, 3462, 97, 628, 4622, 69, 836, 19, 69, 836, 17, 334, 911, 19, 16351, 87, 19, 15898, 2 ]
pragma solidity 0.5.17; // External Libraries import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol"; // Common import "../util/AddressArrayLib.sol"; import "../util/AddressLib.sol"; import "../base/TInitializable.sol"; // Contracts import "@openzeppelin/contracts-ethereum-package/contracts/access/roles/SignerRole.sol"; import "../base/BaseUpgradeable.sol"; // Interfaces import "./ATMGovernanceInterface.sol"; /*****************************************************************************************************/ /** WARNING **/ /** THIS CONTRACT IS UPGRADEABLE! **/ /** --------------------------------------------------------------------------------------------- **/ /** Do NOT change the order of or PREPEND any storage variables to this or new versions of this **/ /** contract as this will cause the the storage slots to be overwritten on the proxy contract!! **/ /** **/ /** Visit https://docs.openzeppelin.com/upgrades/2.6/proxies#upgrading-via-the-proxy-pattern for **/ /** more information. **/ /*****************************************************************************************************/ /** @notice This contract is used to modify Risk Settings, CRA or DataProviders for a specific ATM. @author [email protected] */ contract ATMGovernance is ATMGovernanceInterface, TInitializable, SignerRole, BaseUpgradeable { using AddressArrayLib for address[]; using AddressLib for address; using Address for address; /* Constants */ /* State Variables */ // List of general ATM settings. We don't accept settings equal to zero. // Example: supplyToDebtRatio => 5044 = percentage 50.44 // Example: supplyToDebtRatio => 1 = percentage 00.01 mapping(bytes32 => uint256) public generalSettings; // List of Market specific Asset settings on this ATM // Asset address => Asset setting name => Asset setting value // Example 1: USDC address => Risk Premium => 2500 (25%) // Example 2: DAI address => Risk Premium => 3500 (35%) mapping(address => mapping(bytes32 => uint256)) public assetMarketSettings; // List of ATM Data providers per data type mapping(uint8 => address[]) public dataProviders; // Unique CRA - Credit Risk Algorithm github hash to use in this ATM string public cra; /* External Functions */ /** @notice Adds a new General Setting to this ATM. @param settingName name of the setting to be added. @param settingValue value of the setting to be added. */ function addGeneralSetting(bytes32 settingName, uint256 settingValue) external onlySigner() isInitialized() { require(settingValue > 0, "GENERAL_SETTING_MUST_BE_POSITIVE"); require(settingName != "", "GENERAL_SETTING_MUST_BE_PROVIDED"); require(generalSettings[settingName] == 0, "GENERAL_SETTING_ALREADY_EXISTS"); generalSettings[settingName] = settingValue; emit GeneralSettingAdded(msg.sender, settingName, settingValue); } /** @notice Updates an existing General Setting on this ATM. @param settingName name of the setting to be modified. @param newValue new value to be set for this settingName. */ function updateGeneralSetting(bytes32 settingName, uint256 newValue) external onlySigner() isInitialized() { require(newValue > 0, "GENERAL_SETTING_MUST_BE_POSITIVE"); require(settingName != "", "GENERAL_SETTING_MUST_BE_PROVIDED"); uint256 oldValue = generalSettings[settingName]; require(oldValue != newValue, "GENERAL_SETTING_EQUAL_PREVIOUS"); generalSettings[settingName] = newValue; emit GeneralSettingUpdated(msg.sender, settingName, oldValue, newValue); } /** @notice Removes a General Setting from this ATM. @param settingName name of the setting to be removed. */ function removeGeneralSetting(bytes32 settingName) external onlySigner() isInitialized() { require(settingName != "", "GENERAL_SETTING_MUST_BE_PROVIDED"); require(generalSettings[settingName] > 0, "GENERAL_SETTING_NOT_FOUND"); uint256 previousValue = generalSettings[settingName]; delete generalSettings[settingName]; emit GeneralSettingRemoved(msg.sender, settingName, previousValue); } /** @notice Adds a new Asset Setting from a specific Market on this ATM. @param asset market specific asset address. @param settingName name of the setting to be added. @param settingValue value of the setting to be added. */ function addAssetMarketSetting( address asset, bytes32 settingName, uint256 settingValue ) external onlySigner() isInitialized() { asset.requireNotEmpty("ASSET_ADDRESS_IS_REQUIRED"); require(asset.isContract(), "ASSET_MUST_BE_A_CONTRACT"); require(settingValue > 0, "ASSET_SETTING_MUST_BE_POSITIVE"); require(settingName != "", "ASSET_SETTING_MUST_BE_PROVIDED"); require( assetMarketSettings[asset][settingName] == 0, "ASSET_SETTING_ALREADY_EXISTS" ); assetMarketSettings[asset][settingName] = settingValue; emit AssetMarketSettingAdded(msg.sender, asset, settingName, settingValue); } /** @notice Updates an existing Asset Setting from a specific Market on this ATM. @param asset market specific asset address. @param settingName name of the setting to be added. @param newValue value of the setting to be added. */ function updateAssetMarketSetting( address asset, bytes32 settingName, uint256 newValue ) external onlySigner() isInitialized() { require(settingName != "", "ASSET_SETTING_MUST_BE_PROVIDED"); require(assetMarketSettings[asset][settingName] > 0, "ASSET_SETTING_NOT_FOUND"); require( newValue != assetMarketSettings[asset][settingName], "NEW_VALUE_SAME_AS_OLD" ); uint256 oldValue = assetMarketSettings[asset][settingName]; assetMarketSettings[asset][settingName] = newValue; emit AssetMarketSettingUpdated( msg.sender, asset, settingName, oldValue, newValue ); } /** @notice Removes an existing Asset Setting from a specific Market on this ATM. @param asset market specific asset address. @param settingName name of the setting to be added. */ function removeAssetMarketSetting(address asset, bytes32 settingName) external onlySigner() isInitialized() { require(settingName != "", "ASSET_SETTING_MUST_BE_PROVIDED"); require(assetMarketSettings[asset][settingName] > 0, "ASSET_SETTING_NOT_FOUND"); uint256 oldValue = assetMarketSettings[asset][settingName]; delete assetMarketSettings[asset][settingName]; emit AssetMarketSettingRemoved(msg.sender, asset, settingName, oldValue); } /** @notice Adds a new Data Provider on a specific Data Type array. This function would accept duplicated data providers for the same data type. @param dataTypeIndex array index for this Data Type. @param dataProvider data provider address. */ function addDataProvider(uint8 dataTypeIndex, address dataProvider) external onlySigner() isInitialized() { require(dataProvider.isContract(), "DATA_PROVIDER_MUST_BE_A_CONTRACT"); dataProviders[dataTypeIndex].add(dataProvider); uint256 amountDataProviders = dataProviders[dataTypeIndex].length; emit DataProviderAdded( msg.sender, dataTypeIndex, amountDataProviders, dataProvider ); } /** @notice Updates an existing Data Provider on a specific Data Type array. @param dataTypeIndex array index for this Data Type. @param providerIndex previous data provider index. @param newProvider new data provider address. */ function updateDataProvider( uint8 dataTypeIndex, uint256 providerIndex, address newProvider ) external onlySigner() isInitialized() { require( dataProviders[dataTypeIndex].length > providerIndex, "DATA_PROVIDER_OUT_RANGE" ); require(newProvider.isContract(), "DATA_PROVIDER_MUST_BE_A_CONTRACT"); address oldProvider = dataProviders[dataTypeIndex][providerIndex]; require(oldProvider != newProvider, "DATA_PROVIDER_SAME_OLD"); dataProviders[dataTypeIndex][providerIndex] = newProvider; emit DataProviderUpdated( msg.sender, dataTypeIndex, providerIndex, oldProvider, newProvider ); } /** @notice Removes an existing Data Provider on a specific Data Type array. @param dataTypeIndex array index for this Data Type. @param dataProviderIndex data provider index. */ function removeDataProvider(uint8 dataTypeIndex, uint256 dataProviderIndex) external onlySigner() isInitialized() { require( dataProviders[dataTypeIndex].length > dataProviderIndex, "DATA_PROVIDER_OUT_RANGE" ); address oldDataProvider = dataProviders[dataTypeIndex][dataProviderIndex]; dataProviders[dataTypeIndex].removeAt(dataProviderIndex); emit DataProviderRemoved( msg.sender, dataTypeIndex, dataProviderIndex, oldDataProvider ); } /** @notice Sets the CRA - Credit Risk Algorithm to be used on this specific ATM. CRA is represented by a Github commit hash of the newly proposed algorithm. @param _cra Credit Risk Algorithm github commit hash. */ function setCRA(string calldata _cra) external onlySigner() isInitialized() { bytes memory tempEmptyStringTest = bytes(_cra); require(tempEmptyStringTest.length > 0, "CRA_CANT_BE_EMPTY"); require( keccak256(abi.encodePacked(cra)) != keccak256(abi.encodePacked(_cra)), "CRA_SAME_AS_OLD" ); cra = _cra; emit CRASet(msg.sender, cra); } /** @notice It initializes this ATM Governance instance. @param settingsAddress the initial settings address. @param ownerAddress the owner address for this ATM Governance. */ function initialize(address settingsAddress, address ownerAddress) external isNotInitialized() { _setSettings(settingsAddress); SignerRole.initialize(ownerAddress); TInitializable._initialize(); } /* External Constant functions */ /** @notice Returns a General Setting value from this ATM. @param settingName name of the setting to be returned. */ function getGeneralSetting(bytes32 settingName) external view returns (uint256) { return generalSettings[settingName]; } /** @notice Returns an existing Asset Setting value from a specific Market on this ATM. @param asset market specific asset address. @param settingName name of the setting to be returned. */ function getAssetMarketSetting(address asset, bytes32 settingName) external view returns (uint256) { return assetMarketSettings[asset][settingName]; } /** @notice Returns a Data Provider on a specific Data Type array. @param dataTypeIndex array index for this Data Type. @param dataProviderIndex data provider index number. */ function getDataProvider(uint8 dataTypeIndex, uint256 dataProviderIndex) external view returns (address) { if (dataProviders[dataTypeIndex].length > dataProviderIndex) { return dataProviders[dataTypeIndex][dataProviderIndex]; } return address(0x0); } /** @notice Returns current CRA - Credit Risk Algorithm that is being used on this specific ATM. CRA is represented by a Github commit hash of the newly proposed algorithm. */ function getCRA() external view returns (string memory) { return cra; } }
External Functions */*/
{ require(settingValue > 0, "GENERAL_SETTING_MUST_BE_POSITIVE"); require(settingName != "", "GENERAL_SETTING_MUST_BE_PROVIDED"); require(generalSettings[settingName] == 0, "GENERAL_SETTING_ALREADY_EXISTS"); generalSettings[settingName] = settingValue; emit GeneralSettingAdded(msg.sender, settingName, settingValue); } @param settingName name of the setting to be modified. @param newValue new value to be set for this settingName.
15,848,920
[ 1, 6841, 15486, 368, 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, 288, 203, 3639, 2583, 12, 8920, 620, 405, 374, 16, 315, 13990, 1013, 67, 1090, 12239, 67, 49, 5996, 67, 5948, 67, 7057, 16325, 8863, 203, 3639, 2583, 12, 8920, 461, 480, 23453, 315, 13990, 1013, 67, 1090, 12239, 67, 49, 5996, 67, 5948, 67, 3373, 15472, 2056, 8863, 203, 3639, 2583, 12, 12259, 2628, 63, 8920, 461, 65, 422, 374, 16, 315, 13990, 1013, 67, 1090, 12239, 67, 1013, 20305, 67, 21205, 8863, 203, 3639, 7470, 2628, 63, 8920, 461, 65, 273, 3637, 620, 31, 203, 3639, 3626, 9544, 5568, 8602, 12, 3576, 18, 15330, 16, 3637, 461, 16, 3637, 620, 1769, 203, 565, 289, 203, 203, 3639, 632, 891, 3637, 461, 508, 434, 326, 3637, 358, 506, 4358, 18, 203, 3639, 632, 891, 6129, 394, 460, 358, 506, 444, 364, 333, 3637, 461, 18, 7010, 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 ]
// File: https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router01.sol pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // File: https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/interfaces/IUniswapV2Router02.sol pragma solidity >=0.6.2; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // File: 4_deploy-defarm/Optimiser/SafeMath.sol pragma solidity ^0.6.12; // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a, 'SafeMath:INVALID_ADD'); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a, 'SafeMath:OVERFLOW_SUB'); c = a - b; } function mul(uint a, uint b, uint decimal) internal pure returns (uint) { uint dc = 10**decimal; uint c0 = a * b; require(a == 0 || c0 / a == b, "SafeMath: multiple overflow"); uint c1 = c0 + (dc / 2); require(c1 >= c0, "SafeMath: multiple overflow"); uint c2 = c1 / dc; return c2; } function div(uint256 a, uint256 b, uint decimal) internal pure returns (uint256) { require(b != 0, "SafeMath: division by zero"); uint dc = 10**decimal; uint c0 = a * dc; require(a == 0 || c0 / a == dc, "SafeMath: division internal"); uint c1 = c0 + (b / 2); require(c1 >= c0, "SafeMath: division internal"); uint c2 = c1 / b; return c2; } } // File: 4_deploy-defarm/Optimiser/TransferHelper.sol pragma solidity ^0.6.12; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } } // File: 4_deploy-defarm/Optimiser/UniformRandomNumber.sol /** Copyright 2019 PoolTogether LLC This file is part of PoolTogether. PoolTogether is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation under version 3 of the License. PoolTogether is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with PoolTogether. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.12; /** * @author Brendan Asselstine * @notice A library that uses entropy to select a random number within a bound. Compensates for modulo bias. * @dev Thanks to https://medium.com/hownetworks/dont-waste-cycles-with-modulo-bias-35b6fdafcf94 */ library UniformRandomNumber { /// @notice Select a random number without modulo bias using a random seed and upper bound /// @param _entropy The seed for randomness /// @param _upperBound The upper bound of the desired number /// @return A random number less than the _upperBound function uniform(uint256 _entropy, uint256 _upperBound) internal pure returns (uint256) { require(_upperBound > 0, "UniformRand/min-bound"); uint256 min = -_upperBound % _upperBound; uint256 random = _entropy; while (true) { if (random >= min) { break; } random = uint256(keccak256(abi.encodePacked(random))); } return random % _upperBound; } } // File: 4_deploy-defarm/Optimiser/SortitionSumTreeFactory.sol pragma solidity ^0.6.12; /** * @reviewers: [@clesaege, @unknownunknown1, @ferittuncer] * @auditors: [] * @bounties: [<14 days 10 ETH max payout>] * @deployments: [] */ /** * @title SortitionSumTreeFactory * @author Enrique Piqueras - <[email protected]> * @dev A factory of trees that keep track of staked values for sortition. */ library SortitionSumTreeFactory { /* Structs */ struct SortitionSumTree { uint K; // The maximum number of childs per node. // We use this to keep track of vacant positions in the tree after removing a leaf. This is for keeping the tree as balanced as possible without spending gas on moving nodes around. uint[] stack; uint[] nodes; // Two-way mapping of IDs to node indexes. Note that node index 0 is reserved for the root node, and means the ID does not have a node. mapping(bytes32 => uint) IDsToNodeIndexes; mapping(uint => bytes32) nodeIndexesToIDs; } /* Storage */ struct SortitionSumTrees { mapping(bytes32 => SortitionSumTree) sortitionSumTrees; } /* internal */ /** * @dev Create a sortition sum tree at the specified key. * @param _key The key of the new tree. * @param _K The number of children each node in the tree should have. */ function createTree(SortitionSumTrees storage self, bytes32 _key, uint _K) internal { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; require(tree.K == 0, "Tree already exists."); require(_K > 1, "K must be greater than one."); tree.K = _K; tree.stack = new uint[](0); tree.nodes = new uint[](0); tree.nodes.push(0); } /** * @dev Set a value of a tree. * @param _key The key of the tree. * @param _value The new value. * @param _ID The ID of the value. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function set(SortitionSumTrees storage self, bytes32 _key, uint _value, bytes32 _ID) internal { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (treeIndex == 0) { // No existing node. if (_value != 0) { // Non zero value. // Append. // Add node. if (tree.stack.length == 0) { // No vacant spots. // Get the index and append the value. treeIndex = tree.nodes.length; tree.nodes.push(_value); // Potentially append a new node and make the parent a sum node. if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child. uint parentIndex = treeIndex / tree.K; bytes32 parentID = tree.nodeIndexesToIDs[parentIndex]; uint newIndex = treeIndex + 1; tree.nodes.push(tree.nodes[parentIndex]); delete tree.nodeIndexesToIDs[parentIndex]; tree.IDsToNodeIndexes[parentID] = newIndex; tree.nodeIndexesToIDs[newIndex] = parentID; } } else { // Some vacant spot. // Pop the stack and append the value. treeIndex = tree.stack[tree.stack.length - 1]; tree.stack.pop(); tree.nodes[treeIndex] = _value; } // Add label. tree.IDsToNodeIndexes[_ID] = treeIndex; tree.nodeIndexesToIDs[treeIndex] = _ID; updateParents(self, _key, treeIndex, true, _value); } } else { // Existing node. if (_value == 0) { // Zero value. // Remove. // Remember value and set to 0. uint value = tree.nodes[treeIndex]; tree.nodes[treeIndex] = 0; // Push to stack. tree.stack.push(treeIndex); // Clear label. delete tree.IDsToNodeIndexes[_ID]; delete tree.nodeIndexesToIDs[treeIndex]; updateParents(self, _key, treeIndex, false, value); } else if (_value != tree.nodes[treeIndex]) { // New, non zero value. // Set. bool plusOrMinus = tree.nodes[treeIndex] <= _value; uint plusOrMinusValue = plusOrMinus ? _value - tree.nodes[treeIndex] : tree.nodes[treeIndex] - _value; tree.nodes[treeIndex] = _value; updateParents(self, _key, treeIndex, plusOrMinus, plusOrMinusValue); } } } /* internal Views */ /** * @dev Query the leaves of a tree. Note that if `startIndex == 0`, the tree is empty and the root node will be returned. * @param _key The key of the tree to get the leaves from. * @param _cursor The pagination cursor. * @param _count The number of items to return. * @return startIndex The index at which leaves start * @return values The values of the returned leaves * @return hasMore Whether there are more for pagination. * `O(n)` where * `n` is the maximum number of nodes ever appended. */ function queryLeafs( SortitionSumTrees storage self, bytes32 _key, uint _cursor, uint _count ) internal view returns(uint startIndex, uint[] memory values, bool hasMore) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; // Find the start index. for (uint i = 0; i < tree.nodes.length; i++) { if ((tree.K * i) + 1 >= tree.nodes.length) { startIndex = i; break; } } // Get the values. uint loopStartIndex = startIndex + _cursor; values = new uint[](loopStartIndex + _count > tree.nodes.length ? tree.nodes.length - loopStartIndex : _count); uint valuesIndex = 0; for (uint j = loopStartIndex; j < tree.nodes.length; j++) { if (valuesIndex < _count) { values[valuesIndex] = tree.nodes[j]; valuesIndex++; } else { hasMore = true; break; } } } /** * @dev Draw an ID from a tree using a number. Note that this function reverts if the sum of all values in the tree is 0. * @param _key The key of the tree. * @param _drawnNumber The drawn number. * @return ID The drawn ID. * `O(k * log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function draw(SortitionSumTrees storage self, bytes32 _key, uint _drawnNumber) internal view returns(bytes32 ID) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = 0; uint currentDrawnNumber = _drawnNumber % tree.nodes[0]; while ((tree.K * treeIndex) + 1 < tree.nodes.length) // While it still has children. for (uint i = 1; i <= tree.K; i++) { // Loop over children. uint nodeIndex = (tree.K * treeIndex) + i; uint nodeValue = tree.nodes[nodeIndex]; if (currentDrawnNumber >= nodeValue) currentDrawnNumber -= nodeValue; // Go to the next child. else { // Pick this child. treeIndex = nodeIndex; break; } } ID = tree.nodeIndexesToIDs[treeIndex]; } /** @dev Gets a specified ID's associated value. * @param _key The key of the tree. * @param _ID The ID of the value. * @return value The associated value. */ function stakeOf(SortitionSumTrees storage self, bytes32 _key, bytes32 _ID) internal view returns(uint value) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint treeIndex = tree.IDsToNodeIndexes[_ID]; if (treeIndex == 0) value = 0; else value = tree.nodes[treeIndex]; } function total(SortitionSumTrees storage self, bytes32 _key) internal view returns (uint) { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; if (tree.nodes.length == 0) { return 0; } else { return tree.nodes[0]; } } /* Private */ /** * @dev Update all the parents of a node. * @param _key The key of the tree to update. * @param _treeIndex The index of the node to start from. * @param _plusOrMinus Wether to add (true) or substract (false). * @param _value The value to add or substract. * `O(log_k(n))` where * `k` is the maximum number of childs per node in the tree, * and `n` is the maximum number of nodes ever appended. */ function updateParents(SortitionSumTrees storage self, bytes32 _key, uint _treeIndex, bool _plusOrMinus, uint _value) private { SortitionSumTree storage tree = self.sortitionSumTrees[_key]; uint parentIndex = _treeIndex; while (parentIndex != 0) { parentIndex = (parentIndex - 1) / tree.K; tree.nodes[parentIndex] = _plusOrMinus ? tree.nodes[parentIndex] + _value : tree.nodes[parentIndex] - _value; } } } // File: 4_deploy-defarm/Optimiser/Optimiser.sol pragma solidity 0.6.12; contract Optimiser { using SafeMath for uint; using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees; struct PoolInfo { uint total_weightage; uint rate_reward; } struct SessionInfo { uint total_reward; uint start_timestamp; uint end_timestamp; bool can_claim; // upon session ended, enable user to claim reward bool deposit_paused; // access control bool claim_paused; // access control } struct UserInfo { uint purchase_counter; } struct UserSessionInfo { uint tvl; uint num_of_ticket; uint first_deposit_timestamp; uint penalty_until_timestamp; bool has_purchased; // once purchased in the session, always is true bool has_claimed; // reward only can claim once } struct UserPoolInfo { uint weightage; uint num_of_ticket; bool claimed; } // mapping (session ID => session info) mapping(uint => SessionInfo) private session; // mapping (session ID => pool category => pool information) mapping(uint => mapping(uint => PoolInfo)) private pool; // mapping (user address => session ID => pool category => user purchased information) mapping(address => mapping(uint => mapping(uint => UserPoolInfo))) private user_pool; // mapping (user address => session ID => user info by session) mapping(address => mapping(uint => UserSessionInfo)) private user_session; // mapping (user address => user personal info) mapping(address => UserInfo) private user_info; // mapping (pool category ID => rate reward) master lookup mapping(uint => uint) public pool_reward_list; // mapping (pool category ID => chances of user enter the pool) lookup mapping(uint => uint) public pool_chances; mapping(address => bool) public access_permission; bool private initialized; bool public stop_next_session; // toggle for session will auto continue or not bool public swap_payment; // payment will swap to DEX and burn address public owner; // owner who deploy the contract address public tube; // TUBE2 token contract address public tube_chief; // TUBE Chief contract address public dev; // development address address public utility; // other usage purpose address public buyback; // upon user hit penalty, transfer for buyback address public uniswap_router; // dex router address address public signer; // website validation uint private preseed; // RNG seed uint public session_id; // current session ID uint public session_minute; // session duration uint public category_size; // current pool category size uint public eth_per_ticket; // how many ETH to buy 1 ticket uint public rate_buyback; // fund distribution for buyback TUBE uint public rate_dev; // fund distrubtion for dev team uint public rate_penalty; // claim penalty rate uint public penalty_base_minute; // claim penalty basis duration uint public DECIMAL; // ether unit decimal uint public PER_UNIT; // ether unit uint[] public multiplier_list; // multiplier list uint256 constant private MAX_TREE_LEAVES = 5; bytes32 constant private TREE_KEY = keccak256("JACKPOT"); SortitionSumTreeFactory.SortitionSumTrees private sortitionSumTrees; event PurchaseTicket(uint session_id, uint multiplier_rate, uint pool_index, uint eth_per_ticket, uint tvl, uint weightage, uint timestamp, address buyer); event Claim(uint session_id, uint claimable, uint actual_claimable, uint penalty_amount, uint timestamp, address buyer); event CompletePot(uint conclude_session, uint reward_amount, uint timestamp); event UpdateMultiplierList(uint[] multiplier_list); event UpdatePenaltySetting(uint rate_penalty, uint penalty_base_minute); event UpdateContracts(address tube, address tube_chief, address buyback, address dev, address utility, address uniswap_router, address signer); event UpdateRewardBySessionId(uint session_id, uint amount); event UpdateRewardPermission(address _address, bool status); event UpdateAccessPermission(address _address, bool status); event UpdatePoolCategory(uint new_max_category, uint[] reward_rates, uint[] chance_rates); event UpdateSessionEndTimestamp(uint end_timestamp); event UpdateStopNextSession(bool status); event UpdateSwapPayment(bool status); event UpdateSessionMinute(uint minute); event UpdatePaymentRateDistribution(uint rate_buyback, uint rate_dev); event UpdateToggleBySession(uint session_id, bool deposit_paused, bool claim_paused); event UpdateEthPerTicket(uint eth_per_ticket); event TransferOwner(address old_owner, address new_owner); modifier onlyOwner { require(msg.sender == owner); _; } modifier hasAccessPermission { require(access_permission[msg.sender], "no access permission"); _; } /* * init function after contract deployment */ function initialize() public { require(!initialized, "Contract instance has already been initialized"); initialized = true; sortitionSumTrees.createTree(TREE_KEY, MAX_TREE_LEAVES); owner = msg.sender; // constant value DECIMAL = 18; PER_UNIT = 1000000000000000000; // multipliers (1.5, 3, 6, 9) multiplier_list.push(1500000000000000000); multiplier_list.push(3000000000000000000); multiplier_list.push(6000000000000000000); multiplier_list.push(9000000000000000000); // reward distribution: P1[0] 33%, P2[1] 33%, P3[2] 33% // chances enter pool : P1[0] 50%, P2[1] 30%, P3[2] 20% category_size = 3; pool_reward_list[0] = 333333333333333333; pool_reward_list[1] = 333333333333333333; pool_reward_list[2] = 333333333333333333; _updatePoolChances(0, 500000000000000000); _updatePoolChances(1, 300000000000000000); _updatePoolChances(2, 200000000000000000); // per session duration 7 day session_minute = 10080; session_id = 2; // ticket price (0.2 ETH) eth_per_ticket = 200000000000000000; // payment received distribution (remaining 10% will for utility) rate_buyback = 700000000000000000; rate_dev = 200000000000000000; // penalty setting (30%, base lock up to 30 day) rate_penalty = 300000000000000000; penalty_base_minute = 43200; // contract linking tube = 0xdA86006036540822e0cd2861dBd2fD7FF9CAA0e8; tube_chief = 0x5fe65B1172E148d1Ac4F44fFc4777c2D4731ee8f; dev = 0xAd451FBEaee85D370ca953D2020bb0480c2Cfc45; buyback = 0x702b11a838429Edca4Ea0e80c596501F1a4F4c28; utility = 0x4679025788c92187d44BdA852e9fF97229e3109b; uniswap_router = 0x37D7f26405103C9Bc9D8F9352Cf32C5b655CBe02; signer = 0xd916731C0063E0c8D93552bE0a021c9Ae15ff183; // permission access_permission[msg.sender] = true; } /* * user purchase ticket and join current session jackpot * @params tvl - input from front end with signature validation */ function purchaseTicket(uint _tvl, uint counter, bytes memory signature) public payable { require(!session[session_id].deposit_paused, "deposit paused"); require(session[session_id].end_timestamp > block.timestamp, "jackpot ended"); require(msg.value == eth_per_ticket, "invalid payment"); require(counter > user_info[msg.sender].purchase_counter, 'EXPIRED COUNTER'); // prevent replay attack require(_verifySign(signer, msg.sender, _tvl, counter, signature), "invalid signature"); // replace user purchase counter number user_info[msg.sender].purchase_counter = counter; // uniform lowest bound number is 0 // result format is in array index so max upper bound number need to minus 1 uint mul_index = UniformRandomNumber.uniform(_rngSeed(), multiplier_list.length); uint pool_index = _pickPoolIndex(); // tvl should source from maximizer pool. (LP staked value * weightage) uint actual_weightage = _tvl.mul(multiplier_list[mul_index], DECIMAL); pool[session_id][pool_index].total_weightage = pool[session_id][pool_index].total_weightage.add(actual_weightage); user_pool[msg.sender][session_id][pool_index].weightage = user_pool[msg.sender][session_id][pool_index].weightage.add(actual_weightage); user_pool[msg.sender][session_id][pool_index].num_of_ticket = user_pool[msg.sender][session_id][pool_index].num_of_ticket.add(1); user_session[msg.sender][session_id].tvl = user_session[msg.sender][session_id].tvl.add(_tvl); user_session[msg.sender][session_id].num_of_ticket = user_session[msg.sender][session_id].num_of_ticket.add(1); user_session[msg.sender][session_id].has_purchased = true; if (swap_payment) { _paymentDistributionDex(msg.value); } else { _paymentDistributionBuyback(msg.value); } // withdrawal penalty set once // -> block.timestamp + 30 day + session(end - now) if (user_session[msg.sender][session_id].penalty_until_timestamp <= 0) { user_session[msg.sender][session_id].first_deposit_timestamp = block.timestamp; user_session[msg.sender][session_id].penalty_until_timestamp = session[session_id].end_timestamp.add(penalty_base_minute * 60); } emit PurchaseTicket(session_id, multiplier_list[mul_index], pool_index, eth_per_ticket, _tvl, actual_weightage, block.timestamp, msg.sender); } /* * user claim reward by session */ function claimReward(uint _session_id) public { require(session[_session_id].can_claim, "claim not enable"); require(!session[_session_id].claim_paused, "claim paused"); require(!user_session[msg.sender][_session_id].has_claimed, "reward claimed"); uint claimable = 0; for (uint pcategory = 0; pcategory < category_size; pcategory++) { claimable = claimable.add(_userReward(msg.sender, _session_id, pcategory, session[_session_id].total_reward)); } uint actual_claimable = _rewardAfterPenalty(msg.sender, claimable, _session_id); uint penalty_amount = claimable.sub(actual_claimable); // gas saving. transfer penalty amount for buyback if (claimable != actual_claimable) { TransferHelper.safeTransfer(tube, buyback, penalty_amount); } TransferHelper.safeTransfer(tube, msg.sender, actual_claimable); user_session[msg.sender][_session_id].has_claimed = true; emit Claim(_session_id, claimable, actual_claimable, penalty_amount, block.timestamp, msg.sender); } /* * get current session ended */ function getCurrentSessionEnded() public view returns(bool) { return (session[session_id].end_timestamp <= block.timestamp); } /* * get user in pool detail via pool category */ function getUserPoolInfo(address _address, uint _session_id, uint _pool_category) public view returns(uint, uint, bool) { return ( user_pool[_address][_session_id][_pool_category].weightage, user_pool[_address][_session_id][_pool_category].num_of_ticket, user_pool[_address][_session_id][_pool_category].claimed ); } /* * get user information */ function getUserInfo(address _address) public view returns(uint) { return (user_info[_address].purchase_counter); } /* * get user in the session */ function getUserSessionInfo(address _address, uint _session_id) public view returns(uint, uint, bool, bool, uint, uint) { return ( user_session[_address][_session_id].tvl, user_session[_address][_session_id].num_of_ticket, user_session[_address][_session_id].has_purchased, user_session[_address][_session_id].has_claimed, user_session[_address][_session_id].first_deposit_timestamp, user_session[_address][_session_id].penalty_until_timestamp ); } /* * get user has participant on current jackpot session or not */ function getCurrentSessionJoined(address _address) public view returns (bool) { return user_session[_address][session_id].has_purchased; } /* * get pool info */ function getPool(uint _session_id, uint _pool_category) public view returns(uint, uint) { return ( pool[_session_id][_pool_category].total_weightage, pool[_session_id][_pool_category].rate_reward ); } /* * get session info */ function getSession(uint _session_id) public view returns(uint, uint, uint, bool, bool, bool) { return ( session[_session_id].total_reward, session[_session_id].start_timestamp, session[_session_id].end_timestamp, session[_session_id].deposit_paused, session[_session_id].can_claim, session[_session_id].claim_paused ); } /* * get all pool reward by session ID */ function getPoolRewardBySession(uint _session_id) public view returns(uint, uint[] memory) { uint reward_tube = 0; if (_session_id == session_id) { reward_tube = reward_tube.add(ITubeChief(tube_chief).getJackpotReward()); } // local reward + pending tube chief reward uint reward_atm = reward_tube.add(session[_session_id].total_reward); uint[] memory pool_rewards = new uint[](category_size); for (uint pcategory = 0; pcategory < category_size; pcategory++) { pool_rewards[pcategory] = reward_atm.mul(pool[_session_id][pcategory].rate_reward, DECIMAL); } return (category_size, pool_rewards); } /* * get user reward by session ID */ function getUserRewardBySession(address _address, uint _session_id) public view returns (uint, uint) { uint reward_atm = session[_session_id].total_reward; if (_session_id == session_id) { reward_atm = reward_atm.add(ITubeChief(tube_chief).getJackpotReward()); } uint claimable = 0; for (uint pcategory = 0; pcategory < category_size; pcategory++) { claimable = claimable.add(_userReward(_address, _session_id, pcategory, reward_atm)); } uint max_claimable = claimable; claimable = _rewardAfterPenalty(_address, claimable, _session_id); return (max_claimable, claimable); } /* * start jackpot new session */ function initPot() public hasAccessPermission { _startPot(); } /* * update ticket prcing */ function updateEthPerTicket(uint _eth_per_ticket) public hasAccessPermission { eth_per_ticket = _eth_per_ticket; emit UpdateEthPerTicket(eth_per_ticket); } /* * update jackpot control toggle by session ID */ function updateToggleBySession(uint _session_id, bool _deposit_paused, bool _claim_paused) public hasAccessPermission { session[_session_id].deposit_paused = _deposit_paused; session[_session_id].claim_paused = _claim_paused; emit UpdateToggleBySession(_session_id, _deposit_paused, _claim_paused); } /* * update current session end timestamp */ function updateSessionEndTimestamp(uint end_timestamp) public hasAccessPermission { session[session_id].end_timestamp = end_timestamp; emit UpdateSessionEndTimestamp(end_timestamp); } /* * resetup pool category size and reward distribution * XX update will reflect immediately */ function updateMultiplierList(uint[] memory _multiplier_list) public hasAccessPermission { multiplier_list = _multiplier_list; emit UpdateMultiplierList(multiplier_list); } /* * update penatly setting */ function updatePenaltySetting(uint _rate_penalty, uint _penalty_base_minute) public hasAccessPermission { rate_penalty = _rate_penalty; penalty_base_minute = _penalty_base_minute; emit UpdatePenaltySetting(rate_penalty, penalty_base_minute); } /* * update payment rate distribution to each sectors * (!) rate utility will auto result in (1 - rate_buyback - rate_dev) */ function updatePaymentRateDistribution(uint _rate_buyback, uint _rate_dev) public hasAccessPermission { rate_buyback = _rate_buyback; rate_dev = _rate_dev; emit UpdatePaymentRateDistribution(rate_buyback, rate_dev); } /* * update contract addresses */ function updateContracts( address _tube, address _tube_chief, address _buyback, address _dev, address _utility, address _uniswap_router, address _signer ) public hasAccessPermission { tube = _tube; tube_chief = _tube_chief; buyback = _buyback; dev = _dev; utility = _utility; uniswap_router = _uniswap_router; signer = _signer; emit UpdateContracts(tube, tube_chief, buyback, dev, utility, uniswap_router, signer); } /* * resetup pool category size and reward distribution * @param new_max_category - total pool size * @param reward_rates - each pool reward distribution rate * @param chance_rates - change rate of user will enter the pool * XX pool reward rate update will reflect on next session * XX pool chance rate update will reflect now * XX may incur high gas fee */ function updatePoolCategory(uint new_max_category, uint[] memory reward_rates, uint[] memory chance_rates) public hasAccessPermission { require(reward_rates.length == category_size, "invalid input size"); // remove old setting for (uint i = 0; i < category_size; i++) { delete pool_reward_list[i]; delete pool_chances[i]; _updatePoolChances(i, 0); } // add new setting for (uint i = 0; i < new_max_category; i++) { pool_reward_list[i] = reward_rates[i]; _updatePoolChances(i, chance_rates[i]); } category_size = new_max_category; emit UpdatePoolCategory(new_max_category, reward_rates, chance_rates); } /* * update stop next session status */ function updateStopNextSession(bool status) public hasAccessPermission { stop_next_session = status; emit UpdateStopNextSession(status); } /* * update jackpot duration * XX update reflect on next session */ function updateSessionMinute(uint minute) public hasAccessPermission { session_minute = minute; emit UpdateSessionMinute(minute); } /* * update swap payment method */ function updateSwapPayment(bool status) public hasAccessPermission { swap_payment = status; emit UpdateSwapPayment(status); } /* * update access permission */ function updateAccessPermission(address _address, bool status) public onlyOwner { access_permission[_address] = status; emit UpdateAccessPermission(_address, status); } /* * conclude current session and start new session * - transferJackpot * - completePot */ function completePot() public hasAccessPermission { require(session[session_id].end_timestamp <= block.timestamp, "session not end"); /* * 1. main contract will transfer TUBE to this contract * 2. update the total reward amount for current session */ uint conclude_session = session_id; uint reward_amount = ITubeChief(tube_chief).transferJackpotReward(); session[conclude_session].total_reward = session[conclude_session].total_reward.add(reward_amount); session[conclude_session].can_claim = true; session_id = session_id.add(1); if (!stop_next_session) { _startPot(); } // if pool weightage is empty, transfer pool reward to buyback for (uint pcategory = 0; pcategory < category_size; pcategory++) { if (pool[conclude_session][pcategory].total_weightage > 0) { continue; } uint amount = session[conclude_session].total_reward.mul(pool[conclude_session][pcategory].rate_reward, DECIMAL); TransferHelper.safeTransfer(tube, buyback, amount); } emit CompletePot(conclude_session, reward_amount, block.timestamp); } /* * transfer ownership. proceed wisely. only owner executable */ function transferOwner(address new_owner) public onlyOwner { emit TransferOwner(owner, new_owner); owner = new_owner; } /* * emergency collect token from the contract. only owner executable */ function emergencyCollectToken(address token, uint amount) public onlyOwner { TransferHelper.safeTransfer(token, owner, amount); } /* * emergency collect eth from the contract. only owner executable */ function emergencyCollectEth(uint amount) public onlyOwner { address payable owner_address = payable(owner); TransferHelper.safeTransferETH(owner_address, amount); } function _userReward(address _address, uint _session_id, uint _pool_category, uint _total_reward) internal view returns (uint) { // (Z / Total Z of all users) x P1 / P2 / P3 TUBE2 = X amount of reward uint total_weight = pool[_session_id][_pool_category].total_weightage; if (total_weight <= 0 || user_pool[_address][_session_id][_pool_category].claimed) { return 0; } uint user_weight = user_pool[_address][_session_id][_pool_category].weightage; uint rate = pool[_session_id][_pool_category].rate_reward; return user_weight.div(total_weight, DECIMAL).mul(_total_reward, DECIMAL).mul(rate, DECIMAL); } function _startPot() internal { session[session_id].start_timestamp = block.timestamp; session[session_id].end_timestamp = block.timestamp.add(session_minute * 60); // init P1, P2, P3 for (uint i = 0; i < category_size; i++) { pool[session_id][i].rate_reward = pool_reward_list[i]; } } function _paymentDistributionDex(uint amount) internal { uint buyback_amount = amount.mul(rate_buyback, DECIMAL); uint dev_amount = amount.mul(rate_dev, DECIMAL); uint utility_amount = amount.sub(buyback_amount).sub(dev_amount); uint tube_swapped = _swapEthToTUBE(buyback_amount); TransferHelper.safeTransfer(tube, address(0), tube_swapped); TransferHelper.safeTransferETH(dev, dev_amount); TransferHelper.safeTransferETH(utility, utility_amount); } function _paymentDistributionBuyback(uint amount) internal { /* * distribution plan (initial) * buyback - 70% (buyback) * masternode - 20% (dev) * leaderboard - 10% (utility) */ uint buyback_amount = amount.mul(rate_buyback, DECIMAL); uint dev_amount = amount.mul(rate_dev, DECIMAL); uint utility_amount = amount.sub(buyback_amount).sub(dev_amount); TransferHelper.safeTransferETH(buyback, buyback_amount); TransferHelper.safeTransferETH(dev, dev_amount); TransferHelper.safeTransferETH(utility, utility_amount); } function _rngSeed() internal returns (uint) { uint seed = uint256(keccak256(abi.encode(block.number, msg.sender, preseed))); preseed = seed; return seed; } function _swapEthToTUBE(uint amount) internal returns (uint) { require(amount > 0, "empty swap amount"); TransferHelper.safeApprove(tube, uniswap_router, amount); address[] memory path = new address[](2); path[0] = IUniswapV2Router02(uniswap_router).WETH(); path[1] = tube; // lower down the receive expectation to prevent high failure uint buffer_rate = 980000000000000000; uint deadline = block.timestamp.add(60); uint[] memory amount_out_min = new uint[](2); amount_out_min = IUniswapV2Router02(uniswap_router).getAmountsOut(amount, path); amount_out_min[1] = amount_out_min[1].mul(buffer_rate, DECIMAL); uint[] memory swapped = IUniswapV2Router02(uniswap_router).swapExactETHForTokens{ value: amount }(amount_out_min[1], path, address(this), deadline); return swapped[1]; } function _rewardAfterPenalty(address _address, uint reward_amount, uint _session_id) internal view returns (uint) { /* * calculate the reward amount after penalty condition * * 1. get the withdrawable amount * 2. get the withdraw penalty rate * 3. get time ratio: (userPenaltyEndTime - now) / (penalty_base_minute * 60) * 4. result = [full reward] x [penalty rate] x [time ratio] */ if (user_session[_address][_session_id].penalty_until_timestamp >= block.timestamp) { uint end = user_session[_address][_session_id].penalty_until_timestamp; uint diff_now = end.sub(block.timestamp); uint time_ratio = diff_now.div(penalty_base_minute * 60, DECIMAL); uint penalty_amount = reward_amount.mul(rate_penalty, DECIMAL).mul(time_ratio, DECIMAL); reward_amount = reward_amount.sub(penalty_amount); } return reward_amount; } function _updatePoolChances(uint pool_index, uint chance_rate) internal { pool_chances[pool_index] = chance_rate; sortitionSumTrees.set(TREE_KEY, chance_rate, bytes32(uint256(pool_index))); } function _pickPoolIndex() internal returns (uint) { return uint256(sortitionSumTrees.draw(TREE_KEY, _rngSeed())); } /* * VerifySignature */ function _getMessageHash(address buyer, uint tvl, uint counter) internal pure returns (bytes32) { return keccak256(abi.encodePacked(buyer, tvl, counter)); } function _getEthSignedMessageHash(bytes32 _messageHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _messageHash)); } function _verifySign(address _signer, address buyer, uint tvl, uint counter, bytes memory signature) internal pure returns (bool) { bytes32 messageHash = _getMessageHash(buyer, tvl, counter); bytes32 ethSignedMessageHash = _getEthSignedMessageHash(messageHash); return _recoverSigner(ethSignedMessageHash, signature) == _signer; } function _recoverSigner(bytes32 _ethSignedMessageHash, bytes memory _signature) internal pure returns (address) { (bytes32 r, bytes32 s, uint8 v) = _splitSignature(_signature); return ecrecover(_ethSignedMessageHash, v, r, s); } function _splitSignature(bytes memory sig) internal pure returns (bytes32 r, bytes32 s, uint8 v) { require(sig.length == 65, "invalid signature length"); assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } } } interface ITubeChief { function getJackpotReward() external view returns (uint); function transferJackpotReward() external returns (uint); }
get user has participant on current jackpot session or not/
function getCurrentSessionJoined(address _address) public view returns (bool) { return user_session[_address][session_id].has_purchased; }
12,986,287
[ 1, 588, 729, 711, 14188, 603, 783, 525, 484, 13130, 1339, 578, 486, 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 ]
[ 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, 0, 0 ]
[ 1, 565, 445, 5175, 2157, 4572, 329, 12, 2867, 389, 2867, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 729, 67, 3184, 63, 67, 2867, 6362, 3184, 67, 350, 8009, 5332, 67, 12688, 343, 8905, 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 ]
./partial_match/1/0x79e6059BcBEE63b26E602830148584Fd71b5e2fD/sources/EIP20Gateway.sol
* Checks that contract is active. */
modifier isActive() { require( activated == true, "Gateway is not activated." ); _; } EIP20Interface _token, EIP20Interface _baseToken, StateRootInterface _stateRootProvider, uint256 _bounty, OrganizationInterface _organization, address _burner ) GatewayBase( _stateRootProvider, _bounty, _organization ) public
15,657,165
[ 1, 4081, 716, 6835, 353, 2695, 18, 342, 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, 9606, 15083, 1435, 288, 203, 3639, 2583, 12, 203, 5411, 14892, 422, 638, 16, 203, 5411, 315, 5197, 353, 486, 14892, 1199, 203, 3639, 11272, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 203, 3639, 512, 2579, 3462, 1358, 389, 2316, 16, 203, 3639, 512, 2579, 3462, 1358, 389, 1969, 1345, 16, 203, 3639, 3287, 2375, 1358, 389, 2019, 2375, 2249, 16, 203, 3639, 2254, 5034, 389, 70, 592, 93, 16, 203, 3639, 12046, 1358, 389, 15336, 16, 203, 3639, 1758, 389, 70, 321, 264, 203, 565, 262, 203, 3639, 11381, 2171, 12, 203, 5411, 389, 2019, 2375, 2249, 16, 203, 5411, 389, 70, 592, 93, 16, 203, 5411, 389, 15336, 203, 3639, 262, 203, 3639, 1071, 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 ]
// Sources flattened with hardhat v2.5.0 https://hardhat.org // File @openzeppelin/contracts/token/ERC20/[email protected] // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/libs/TransferHelper.sol // GPL-3.0-or-later pragma solidity ^0.8.6; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File contracts/libs/ABDKMath64x64.sol // BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.8.0; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { unchecked { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { unchecked { return int64 (x >> 64); } } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { unchecked { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (int256 (x << 64)); } } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { unchecked { require (x >= 0); return uint64 (uint128 (x >> 64)); } } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { unchecked { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { unchecked { return int256 (x) << 64; } } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { unchecked { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { unchecked { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (int256 (x)) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { unchecked { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { unchecked { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { unchecked { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return -x; } } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return x < 0 ? -x : x; } } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { unchecked { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { unchecked { return int128 ((int256 (x) + int256 (y)) >> 1); } } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { unchecked { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128 (x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x2 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x4 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x8 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require (absXShift < 64); if (y & 0x1 != 0) { absResult = absResult * absX >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = absX * absX >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require (resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256 (absResult) : int256 (absResult); require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { unchecked { require (x >= 0); return int128 (sqrtu (uint256 (int256 (x)) << 64)); } } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { unchecked { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { unchecked { require (x > 0); return int128 (int256 ( uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128)); } } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (int256 (63 - (x >> 64))); require (result <= uint256 (int256 (MAX_64x64))); return int128 (int256 (result)); } } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { unchecked { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x) private pure returns (uint128) { unchecked { if (x == 0) return 0; else { uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128 (r < r1 ? r : r1); } } } } // File contracts/interfaces/IHedgeOptions.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev 定义欧式期权接口 interface IHedgeOptions { // // 代币通道配置结构体 // struct Config { // // 波动率 // uint96 sigmaSQ; // // 64位二进制精度 // // 0.3/365/86400 = 9.512937595129377E-09 // // 175482725206 // int128 miu; // // 期权行权时间和当前时间的最小间隔 // uint32 minPeriod; // } /// @dev 期权信息 struct OptionView { uint index; address tokenAddress; uint strikePrice; bool orientation; uint exerciseBlock; uint balance; } /// @dev 新期权事件 /// @param tokenAddress 目标代币地址,0表示eth /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @param index 期权编号 event New(address tokenAddress, uint strikePrice, bool orientation, uint exerciseBlock, uint index); /// @dev 开仓事件 /// @param index 期权编号 /// @param dcuAmount 支付的dcu数量 /// @param owner 所有者 /// @param amount 买入份数 event Open( uint index, uint dcuAmount, address owner, uint amount ); /// @dev 行权事件 /// @param index 期权编号 /// @param amount 结算的期权分数 /// @param owner 所有者 /// @param gain 赢得的dcu数量 event Exercise(uint index, uint amount, address owner, uint gain); /// @dev 卖出事件 /// @param index 期权编号 /// @param amount 卖出份数 /// @param owner 所有者 /// @param dcuAmount 得到的dcu数量 event Sell(uint index, uint amount, address owner, uint dcuAmount); // /// @dev 修改指定代币通道的配置 // /// @param tokenAddress 目标代币地址 // /// @param config 配置对象 // function setConfig(address tokenAddress, Config calldata config) external; // /// @dev 获取指定代币通道的配置 // /// @param tokenAddress 目标代币地址 // /// @return 配置对象 // function getConfig(address tokenAddress) external view returns (Config memory); /// @dev 返回指定期权的余额 /// @param index 目标期权索引号 /// @param addr 目标地址 function balanceOf(uint index, address addr) external view returns (uint); /// @dev 查找目标账户的期权(倒序) /// @param start 从给定的合约地址对应的索引向前查询(不包含start对应的记录) /// @param count 最多返回的记录条数 /// @param maxFindCount 最多查找maxFindCount记录 /// @param owner 目标账户地址 /// @return optionArray 期权信息列表 function find( uint start, uint count, uint maxFindCount, address owner ) external view returns (OptionView[] memory optionArray); /// @dev 列出历史期权信息 /// @param offset Skip previous (offset) records /// @param count Return (count) records /// @param order Order. 0 reverse order, non-0 positive order /// @return optionArray 期权信息列表 function list(uint offset, uint count, uint order) external view returns (OptionView[] memory optionArray); /// @dev 获取已经开通的欧式期权代币数量 /// @return 已经开通的欧式期权代币数量 function getOptionCount() external view returns (uint); /// @dev 获取期权信息 /// @param tokenAddress 目标代币地址,0表示eth /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @return 期权信息 function getOptionInfo( address tokenAddress, uint strikePrice, bool orientation, uint exerciseBlock ) external view returns (OptionView memory); /// @dev 预估开仓可以买到的期权币数量 /// @param tokenAddress 目标代币地址,0表示eth /// @param oraclePrice 当前预言机价格价 /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @param dcuAmount 支付的dcu数量 /// @return amount 预估可以获得的期权币数量 function estimate( address tokenAddress, uint oraclePrice, uint strikePrice, bool orientation, uint exerciseBlock, uint dcuAmount ) external view returns (uint amount); /// @dev 开仓 /// @param tokenAddress 目标代币地址,0表示eth /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @param dcuAmount 支付的dcu数量 function open( address tokenAddress, uint strikePrice, bool orientation, uint exerciseBlock, uint dcuAmount ) external payable; /// @dev 行权 /// @param index 期权编号 /// @param amount 结算的期权分数 function exercise(uint index, uint amount) external payable; /// @dev 卖出期权 /// @param index 期权编号 /// @param amount 卖出的期权分数 function sell(uint index, uint amount) external payable; /// @dev 计算期权价格 /// @param tokenAddress 目标代币地址,0表示eth /// @param oraclePrice 当前预言机价格价 /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @return v 期权价格,需要除以18446744073709551616000000 function calcV( address tokenAddress, uint oraclePrice, uint strikePrice, bool orientation, uint exerciseBlock ) external view returns (uint v); } // File contracts/interfaces/INestPriceFacade.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines the methods for price call entry interface INestPriceFacade { /// @dev Find the price at block number /// @param tokenAddress Destination token address /// @param height Destination block number /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function findPrice( address tokenAddress, uint height, address paybackAddress ) external payable returns (uint blockNumber, uint price); /// @dev Get the latest trigger price /// @param tokenAddress Destination token address /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function triggeredPrice( address tokenAddress, address paybackAddress ) external payable returns (uint blockNumber, uint price); // /// @dev Price call entry configuration structure // struct Config { // // Single query fee(0.0001 ether, DIMI_ETHER). 100 // uint16 singleFee; // // Double query fee(0.0001 ether, DIMI_ETHER). 100 // uint16 doubleFee; // // The normal state flag of the call address. 0 // uint8 normalFlag; // } // /// @dev Modify configuration // /// @param config Configuration object // function setConfig(Config calldata config) external; // /// @dev Get configuration // /// @return Configuration object // function getConfig() external view returns (Config memory); // /// @dev Set the address flag. Only the address flag equals to config.normalFlag can the price be called // /// @param addr Destination address // /// @param flag Address flag // function setAddressFlag(address addr, uint flag) external; // /// @dev Get the flag. Only the address flag equals to config.normalFlag can the price be called // /// @param addr Destination address // /// @return Address flag // function getAddressFlag(address addr) external view returns(uint); // /// @dev Set INestQuery implementation contract address for token // /// @param tokenAddress Destination token address // /// @param nestQueryAddress INestQuery implementation contract address, 0 means delete // function setNestQuery(address tokenAddress, address nestQueryAddress) external; // /// @dev Get INestQuery implementation contract address for token // /// @param tokenAddress Destination token address // /// @return INestQuery implementation contract address, 0 means use default // function getNestQuery(address tokenAddress) external view returns (address); // /// @dev Get cached fee in fee channel // /// @param tokenAddress Destination token address // /// @return Cached fee in fee channel // function getTokenFee(address tokenAddress) external view returns (uint); // /// @dev Settle fee for charge fee channel // /// @param tokenAddress tokenAddress of charge fee channel // function settle(address tokenAddress) external; // /// @dev Get the latest trigger price // /// @param tokenAddress Destination token address // /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, // /// and the excess fees will be returned through this address // /// @return blockNumber The block number of price // /// @return price The token price. (1eth equivalent to (price) token) // function triggeredPrice( // address tokenAddress, // address paybackAddress // ) external payable returns (uint blockNumber, uint price); /// @dev Get the full information of latest trigger price /// @param tokenAddress Destination token address /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation /// assumes that the volatility cannot exceed 1. Correspondingly, when the return value is equal to /// 999999999999996447, it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo( address tokenAddress, address paybackAddress ) external payable returns (uint blockNumber, uint price, uint avgPrice, uint sigmaSQ); // /// @dev Find the price at block number // /// @param tokenAddress Destination token address // /// @param height Destination block number // /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, // /// and the excess fees will be returned through this address // /// @return blockNumber The block number of price // /// @return price The token price. (1eth equivalent to (price) token) // function findPrice( // address tokenAddress, // uint height, // address paybackAddress // ) external payable returns (uint blockNumber, uint price); /// @dev Get the latest effective price /// @param tokenAddress Destination token address /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function latestPrice( address tokenAddress, address paybackAddress ) external payable returns (uint blockNumber, uint price); // /// @dev Get the last (num) effective price // /// @param tokenAddress Destination token address // /// @param count The number of prices that want to return // /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, // /// and the excess fees will be returned through this address // /// @return An array which length is num * 2, each two element expresses one price like blockNumber|price // function lastPriceList( // address tokenAddress, // uint count, // address paybackAddress // ) external payable returns (uint[] memory); // /// @dev Returns the results of latestPrice() and triggeredPriceInfo() // /// @param tokenAddress Destination token address // /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, // /// and the excess fees will be returned through this address // /// @return latestPriceBlockNumber The block number of latest price // /// @return latestPriceValue The token latest price. (1eth equivalent to (price) token) // /// @return triggeredPriceBlockNumber The block number of triggered price // /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) // /// @return triggeredAvgPrice Average price // /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation // /// assumes that the volatility cannot exceed 1. Correspondingly, when the return value is equal to // /// 999999999999996447, it means that the volatility has exceeded the range that can be expressed // function latestPriceAndTriggeredPriceInfo(address tokenAddress, address paybackAddress) // external // payable // returns ( // uint latestPriceBlockNumber, // uint latestPriceValue, // uint triggeredPriceBlockNumber, // uint triggeredPriceValue, // uint triggeredAvgPrice, // uint triggeredSigmaSQ // ); /// @dev Returns lastPriceList and triggered price info /// @param tokenAddress Destination token address /// @param count The number of prices that want to return /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, /// and the excess fees will be returned through this address /// @return prices An array which length is num * 2, each two element expresses one price like blockNumber|price /// @return triggeredPriceBlockNumber The block number of triggered price /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// @return triggeredAvgPrice Average price /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation /// assumes that the volatility cannot exceed 1. Correspondingly, when the return value is equal to /// 999999999999996447, it means that the volatility has exceeded the range that can be expressed function lastPriceListAndTriggeredPriceInfo( address tokenAddress, uint count, address paybackAddress ) external payable returns ( uint[] memory prices, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ); // /// @dev Get the latest trigger price. (token and ntoken) // /// @param tokenAddress Destination token address // /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, // /// and the excess fees will be returned through this address // /// @return blockNumber The block number of price // /// @return price The token price. (1eth equivalent to (price) token) // /// @return ntokenBlockNumber The block number of ntoken price // /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) // function triggeredPrice2( // address tokenAddress, // address paybackAddress // ) external payable returns ( // uint blockNumber, // uint price, // uint ntokenBlockNumber, // uint ntokenPrice // ); // /// @dev Get the full information of latest trigger price. (token and ntoken) // /// @param tokenAddress Destination token address // /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, // /// and the excess fees will be returned through this address // /// @return blockNumber The block number of price // /// @return price The token price. (1eth equivalent to (price) token) // /// @return avgPrice Average price // /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that // /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, // /// it means that the volatility has exceeded the range that can be expressed // /// @return ntokenBlockNumber The block number of ntoken price // /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) // /// @return ntokenAvgPrice Average price of ntoken // /// @return ntokenSigmaSQ The square of the volatility (18 decimal places). The current implementation // /// assumes that the volatility cannot exceed 1. Correspondingly, when the return value is equal to // /// 999999999999996447, it means that the volatility has exceeded the range that can be expressed // function triggeredPriceInfo2( // address tokenAddress, // address paybackAddress // ) external payable returns ( // uint blockNumber, // uint price, // uint avgPrice, // uint sigmaSQ, // uint ntokenBlockNumber, // uint ntokenPrice, // uint ntokenAvgPrice, // uint ntokenSigmaSQ // ); // /// @dev Get the latest effective price. (token and ntoken) // /// @param tokenAddress Destination token address // /// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, // /// and the excess fees will be returned through this address // /// @return blockNumber The block number of price // /// @return price The token price. (1eth equivalent to (price) token) // /// @return ntokenBlockNumber The block number of ntoken price // /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) // function latestPrice2( // address tokenAddress, // address paybackAddress // ) external payable returns ( // uint blockNumber, // uint price, // uint ntokenBlockNumber, // uint ntokenPrice // ); } // File contracts/interfaces/IHedgeMapping.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev The interface defines methods for Hedge builtin contract address mapping interface IHedgeMapping { /// @dev Set the built-in contract address of the system /// @param dcuToken Address of dcu token contract /// @param hedgeDAO IHedgeDAO implementation contract address /// @param hedgeOptions IHedgeOptions implementation contract address /// @param hedgeFutures IHedgeFutures implementation contract address /// @param hedgeVaultForStaking IHedgeVaultForStaking implementation contract address /// @param nestPriceFacade INestPriceFacade implementation contract address function setBuiltinAddress( address dcuToken, address hedgeDAO, address hedgeOptions, address hedgeFutures, address hedgeVaultForStaking, address nestPriceFacade ) external; /// @dev Get the built-in contract address of the system /// @return dcuToken Address of dcu token contract /// @return hedgeDAO IHedgeDAO implementation contract address /// @return hedgeOptions IHedgeOptions implementation contract address /// @return hedgeFutures IHedgeFutures implementation contract address /// @return hedgeVaultForStaking IHedgeVaultForStaking implementation contract address /// @return nestPriceFacade INestPriceFacade implementation contract address function getBuiltinAddress() external view returns ( address dcuToken, address hedgeDAO, address hedgeOptions, address hedgeFutures, address hedgeVaultForStaking, address nestPriceFacade ); /// @dev Get address of dcu token contract /// @return Address of dcu token contract function getDCUTokenAddress() external view returns (address); /// @dev Get IHedgeDAO implementation contract address /// @return IHedgeDAO implementation contract address function getHedgeDAOAddress() external view returns (address); /// @dev Get IHedgeOptions implementation contract address /// @return IHedgeOptions implementation contract address function getHedgeOptionsAddress() external view returns (address); /// @dev Get IHedgeFutures implementation contract address /// @return IHedgeFutures implementation contract address function getHedgeFuturesAddress() external view returns (address); /// @dev Get IHedgeVaultForStaking implementation contract address /// @return IHedgeVaultForStaking implementation contract address function getHedgeVaultForStakingAddress() external view returns (address); /// @dev Get INestPriceFacade implementation contract address /// @return INestPriceFacade implementation contract address function getNestPriceFacade() external view returns (address); /// @dev Registered address. The address registered here is the address accepted by Hedge system /// @param key The key /// @param addr Destination address. 0 means to delete the registration information function registerAddress(string calldata key, address addr) external; /// @dev Get registered address /// @param key The key /// @return Destination address. 0 means empty function checkAddress(string calldata key) external view returns (address); } // File contracts/interfaces/IHedgeGovernance.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines the governance methods interface IHedgeGovernance is IHedgeMapping { /// @dev Set governance authority /// @param addr Destination address /// @param flag Weight. 0 means to delete the governance permission of the target address. Weight is not /// implemented in the current system, only the difference between authorized and unauthorized. /// Here, a uint96 is used to represent the weight, which is only reserved for expansion function setGovernance(address addr, uint flag) external; /// @dev Get governance rights /// @param addr Destination address /// @return Weight. 0 means to delete the governance permission of the target address. Weight is not /// implemented in the current system, only the difference between authorized and unauthorized. /// Here, a uint96 is used to represent the weight, which is only reserved for expansion function getGovernance(address addr) external view returns (uint); /// @dev Check whether the target address has governance rights for the given target /// @param addr Destination address /// @param flag Permission weight. The permission of the target address must be greater than this weight /// to pass the check /// @return True indicates permission function checkGovernance(address addr, uint flag) external view returns (bool); } // File contracts/interfaces/IHedgeDAO.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev This interface defines the DAO methods interface IHedgeDAO { /// @dev Application Flag Changed event /// @param addr DAO application contract address /// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization event ApplicationChanged(address addr, uint flag); /// @dev Set DAO application /// @param addr DAO application contract address /// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization function setApplication(address addr, uint flag) external; /// @dev Check DAO application flag /// @param addr DAO application contract address /// @return Authorization flag, 1 means authorization, 0 means cancel authorization function checkApplication(address addr) external view returns (uint); /// @dev Add reward /// @param pool Destination pool function addETHReward(address pool) external payable; /// @dev The function returns eth rewards of specified pool /// @param pool Destination pool function totalETHRewards(address pool) external view returns (uint); /// @dev Settlement /// @param pool Destination pool. Indicates which pool to pay with /// @param tokenAddress Token address of receiving funds (0 means ETH) /// @param to Address to receive /// @param value Amount to receive function settle(address pool, address tokenAddress, address to, uint value) external payable; } // File contracts/HedgeBase.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev Base contract of Hedge contract HedgeBase { /// @dev IHedgeGovernance implementation contract address address public _governance; /// @dev To support open-zeppelin/upgrades /// @param governance IHedgeGovernance implementation contract address function initialize(address governance) public virtual { require(_governance == address(0), "Hedge:!initialize"); _governance = governance; } /// @dev Rewritten in the implementation contract, for load other contract addresses. Call /// super.update(newGovernance) when overriding, and override method without onlyGovernance /// @param newGovernance IHedgeGovernance implementation contract address function update(address newGovernance) public virtual { address governance = _governance; require(governance == msg.sender || IHedgeGovernance(governance).checkGovernance(msg.sender, 0), "Hedge:!gov"); _governance = newGovernance; } /// @dev Migrate funds from current contract to HedgeDAO /// @param tokenAddress Destination token address.(0 means eth) /// @param value Migrate amount function migrate(address tokenAddress, uint value) external onlyGovernance { address to = IHedgeGovernance(_governance).getHedgeDAOAddress(); if (tokenAddress == address(0)) { IHedgeDAO(to).addETHReward { value: value } (address(0)); } else { TransferHelper.safeTransfer(tokenAddress, to, value); } } //---------modifier------------ modifier onlyGovernance() { require(IHedgeGovernance(_governance).checkGovernance(msg.sender, 0), "Hedge:!gov"); _; } modifier noContract() { require(msg.sender == tx.origin, "Hedge:!contract"); _; } } // File contracts/HedgeFrequentlyUsed.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev Base contract of Hedge contract HedgeFrequentlyUsed is HedgeBase { // Address of DCU contract address constant DCU_TOKEN_ADDRESS = 0xf56c6eCE0C0d6Fbb9A53282C0DF71dBFaFA933eF; // Address of NestPriceFacade contract address constant NEST_PRICE_FACADE_ADDRESS = 0xB5D2890c061c321A5B6A4a4254bb1522425BAF0A; // USDT代币地址 address constant USDT_TOKEN_ADDRESS = 0xdAC17F958D2ee523a2206206994597C13D831ec7; // USDT代币的基数 uint constant USDT_BASE = 1000000; } // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] // MIT pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File @openzeppelin/contracts/utils/[email protected] // MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/token/ERC20/[email protected] // MIT pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File contracts/DCU.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev DCU代币 contract DCU is HedgeBase, ERC20("Decentralized Currency Unit", "DCU") { // 保存挖矿权限地址 mapping(address=>uint) _minters; constructor() { } modifier onlyMinter { require(_minters[msg.sender] == 1, "DCU:not minter"); _; } /// @dev 设置挖矿权限 /// @param account 目标账号 /// @param flag 挖矿权限标记,只有1表示可以挖矿 function setMinter(address account, uint flag) external onlyGovernance { _minters[account] = flag; } /// @dev 检查挖矿权限 /// @param account 目标账号 /// @return flag 挖矿权限标记,只有1表示可以挖矿 function checkMinter(address account) external view returns (uint) { return _minters[account]; } /// @dev 铸币 /// @param to 接受地址 /// @param value 铸币数量 function mint(address to, uint value) external onlyMinter { _mint(to, value); } /// @dev 销毁 /// @param from 目标地址 /// @param value 销毁数量 function burn(address from, uint value) external onlyMinter { _burn(from, value); } } // File contracts/HedgeOptions.sol // GPL-3.0-or-later pragma solidity ^0.8.6; /// @dev 欧式期权 contract HedgeOptions is HedgeFrequentlyUsed, IHedgeOptions { /// @dev 期权结构 struct Option { address tokenAddress; uint56 strikePrice; bool orientation; uint32 exerciseBlock; //uint totalSupply; mapping(address=>uint) balances; } // 区块时间 uint constant BLOCK_TIME = 14; // 64位二进制精度的1 int128 constant ONE = 0x10000000000000000; // 64位二进制精度的50000 uint constant V50000 = 0x0C3500000000000000000; // 期权卖出价值比例,万分制。9750 uint constant SELL_RATE = 9500; // σ-usdt 0.00021368 波动率,每个币种独立设置(年化120%) uint constant SIGMA_SQ = 45659142400; // μ-usdt 0.000000025367 漂移系数,每个币种独立设置(年化80%) uint constant MIU = 467938556917; // 期权行权最小间隔 6000 区块数 行权时间和当前时间最小间隔区块数,统一设置 uint constant MIN_PERIOD = 180000; // 期权代币映射 mapping(uint=>uint) _optionMapping; // // 配置参数 // mapping(address=>Config) _configs; // 缓存代币的基数值 mapping(address=>uint) _bases; // 期权代币数组 Option[] _options; constructor() { } /// @dev To support open-zeppelin/upgrades /// @param governance IHedgeGovernance implementation contract address function initialize(address governance) public override { super.initialize(governance); _options.push(); } // /// @dev 修改指定代币通道的配置 // /// @param tokenAddress 目标代币地址 // /// @param config 配置对象 // function setConfig(address tokenAddress, Config calldata config) external override { // _configs[tokenAddress] = config; // } // /// @dev 获取指定代币通道的配置 // /// @param tokenAddress 目标代币地址 // /// @return 配置对象 // function getConfig(address tokenAddress) external view override returns (Config memory) { // return _configs[tokenAddress]; // } /// @dev 返回指定期权的余额 /// @param index 目标期权索引号 /// @param addr 目标地址 function balanceOf(uint index, address addr) external view override returns (uint) { return _options[index].balances[addr]; } /// @dev 查找目标账户的期权(倒序) /// @param start 从给定的合约地址对应的索引向前查询(不包含start对应的记录) /// @param count 最多返回的记录条数 /// @param maxFindCount 最多查找maxFindCount记录 /// @param owner 目标账户地址 /// @return optionArray 期权信息列表 function find( uint start, uint count, uint maxFindCount, address owner ) external view override returns (OptionView[] memory optionArray) { optionArray = new OptionView[](count); // 计算查找区间i和end Option[] storage options = _options; uint i = options.length; uint end = 0; if (start > 0) { i = start; } if (i > maxFindCount) { end = i - maxFindCount; } // 循环查找,将符合条件的记录写入缓冲区 for (uint index = 0; index < count && i > end;) { Option storage option = options[--i]; if (option.balances[owner] > 0) { optionArray[index++] = _toOptionView(option, i, owner); } } } /// @dev 列出历史期权信息 /// @param offset Skip previous (offset) records /// @param count Return (count) records /// @param order Order. 0 reverse order, non-0 positive order /// @return optionArray 期权信息列表 function list( uint offset, uint count, uint order ) external view override returns (OptionView[] memory optionArray) { // 加载代币数组 Option[] storage options = _options; // 创建结果数组 optionArray = new OptionView[](count); uint length = options.length; uint i = 0; // 倒序 if (order == 0) { uint index = length - offset; uint end = index > count ? index - count : 0; while (index > end) { Option storage option = options[--index]; optionArray[i++] = _toOptionView(option, index, msg.sender); } } // 正序 else { uint index = offset; uint end = index + count; if (end > length) { end = length; } while (index < end) { optionArray[i++] = _toOptionView(options[index], index, msg.sender); ++index; } } } /// @dev 获取已经开通的欧式期权代币数量 /// @return 已经开通的欧式期权代币数量 function getOptionCount() external view override returns (uint) { return _options.length; } /// @dev 获取期权信息 /// @param tokenAddress 目标代币地址,0表示eth /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @return 期权信息 function getOptionInfo( address tokenAddress, uint strikePrice, bool orientation, uint exerciseBlock ) external view override returns (OptionView memory) { uint index = _optionMapping[_getKey(tokenAddress, strikePrice, orientation, exerciseBlock)]; return _toOptionView(_options[index], index, msg.sender); } /// @dev 开仓 /// @param tokenAddress 目标代币地址,0表示eth /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @param dcuAmount 支付的dcu数量 function open( address tokenAddress, uint strikePrice, bool orientation, uint exerciseBlock, uint dcuAmount ) external payable override { // 1. 调用预言机获取价格 uint oraclePrice = _queryPrice(tokenAddress, msg.value, msg.sender); // 2. 计算可以买到的期权份数 uint amount = estimate(tokenAddress, oraclePrice, strikePrice, orientation, exerciseBlock, dcuAmount); // 3. 获取或创建期权代币 uint key = _getKey(tokenAddress, strikePrice, orientation, exerciseBlock); uint optionIndex = _optionMapping[key]; Option storage option = _options[optionIndex]; if (optionIndex == 0) { optionIndex = _options.length; option = _options.push(); option.tokenAddress = tokenAddress; option.strikePrice = _encodeFloat(strikePrice); option.orientation = orientation; option.exerciseBlock = uint32(exerciseBlock); // 将期权代币地址存入映射和数组,便于后面检索 _optionMapping[key] = optionIndex; // 新期权 //emit New(tokenAddress, strikePrice, orientation, exerciseBlock, optionIndex); } // 4. 销毁权利金 DCU(DCU_TOKEN_ADDRESS).burn(msg.sender, dcuAmount); // 5. 分发期权凭证 option.balances[msg.sender] += amount; // 开仓事件 emit Open(optionIndex, dcuAmount, msg.sender, amount); } /// @dev 预估开仓可以买到的期权币数量 /// @param tokenAddress 目标代币地址,0表示eth /// @param oraclePrice 当前预言机价格价 /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @param dcuAmount 支付的dcu数量 /// @return amount 预估可以获得的期权币数量 function estimate( address tokenAddress, uint oraclePrice, uint strikePrice, bool orientation, uint exerciseBlock, uint dcuAmount ) public view override returns (uint amount) { //Config memory config = _configs[tokenAddress]; //uint minPeriod = uint(config.minPeriod); require(exerciseBlock > block.number + MIN_PERIOD, "FEO:exerciseBlock to small"); // 1. 获取或创建期权代币 // 2. 调用预言机获取价格 // 3. 计算权利金(需要的dcu数量) // 按照平均每14秒出一个块计算 uint v = calcV( tokenAddress, oraclePrice, strikePrice, orientation, exerciseBlock ); if (orientation) { //v = _calcVc(config, oraclePrice, T, strikePrice); // Vc>=S0*1%; Vp>=K*1% // require(v * 100 >> 64 >= oraclePrice, "FEO:vc must greater than S0*1%"); if (v * 100 >> 64 < oraclePrice) { v = oraclePrice * 0x10000000000000000 / 100; } } else { //v = _calcVp(config, oraclePrice, T, strikePrice); // Vc>=S0*1%; Vp>=K*1% // require(v * 100 >> 64 >= strikePrice, "FEO:vp must greater than K*1%"); if (v * 100 >> 64 < strikePrice) { v = strikePrice * 0x10000000000000000 / 100; } } amount = (USDT_BASE << 64) * dcuAmount / v; } /// @dev 行权 /// @param index 期权编号 /// @param amount 结算的期权分数 function exercise(uint index, uint amount) external payable override { // 1. 获取期权信息 Option storage option = _options[index]; address tokenAddress = option.tokenAddress; uint strikePrice = _decodeFloat(option.strikePrice); bool orientation = option.orientation; uint exerciseBlock = uint(option.exerciseBlock); require(block.number >= exerciseBlock, "FEO:at maturity"); // 2. 销毁期权代币 option.balances[msg.sender] -= amount; // 3. 调用预言机获取价格,读取预言机在指定区块的价格 // 3.1. 获取token相对于eth的价格 uint tokenAmount = 1 ether; uint fee = msg.value; if (tokenAddress != address(0)) { fee = msg.value >> 1; (, tokenAmount) = INestPriceFacade(NEST_PRICE_FACADE_ADDRESS).findPrice { value: fee } (tokenAddress, exerciseBlock, msg.sender); } // 3.2. 获取usdt相对于eth的价格 (, uint usdtAmount) = INestPriceFacade(NEST_PRICE_FACADE_ADDRESS).findPrice { value: fee } (USDT_TOKEN_ADDRESS, exerciseBlock, msg.sender); // 将token价格转化为以usdt为单位计算的价格 uint oraclePrice = usdtAmount * _getBase(tokenAddress) / tokenAmount; // 4. 分情况计算用户可以获得的dcu数量 uint gain = 0; // 计算结算结果 // 看涨期权 if (orientation) { // 赌赢了 if (oraclePrice > strikePrice) { gain = amount * (oraclePrice - strikePrice) / USDT_BASE; } } // 看跌期权 else { // 赌赢了 if (oraclePrice < strikePrice) { gain = amount * (strikePrice - oraclePrice) / USDT_BASE; } } // 5. 用户赌赢了,给其增发赢得的dcu if (gain > 0) { DCU(DCU_TOKEN_ADDRESS).mint(msg.sender, gain); } // 行权事件 emit Exercise(index, amount, msg.sender, gain); } /// @dev 卖出期权 /// @param index 期权编号 /// @param amount 卖出的期权分数 function sell(uint index, uint amount) external payable override { // 期权卖出公式:vt=Max(ct(T,K)*0.975,0)其中ct(K,T)是按照定价公式计算的期权成本, // 注意,不是包含了不低于1%这个设定 // 1. 获取期权信息 Option storage option = _options[index]; address tokenAddress = option.tokenAddress; uint strikePrice = _decodeFloat(option.strikePrice); bool orientation = option.orientation; uint exerciseBlock = uint(option.exerciseBlock); // 2. 销毁期权代币 option.balances[msg.sender] -= amount; // 3. 调用预言机获取价格,读取预言机在指定区块的价格 uint oraclePrice = _queryPrice(tokenAddress, msg.value, msg.sender); // 4. 分情况计算当前情况下的期权价格 // 按照平均每14秒出一个块计算 uint dcuAmount = amount * calcV( tokenAddress, oraclePrice, strikePrice, orientation, exerciseBlock ) * SELL_RATE / (USDT_BASE * 10000 << 64); if (dcuAmount > 0) { DCU(DCU_TOKEN_ADDRESS).mint(msg.sender, dcuAmount); } // 卖出事件 emit Sell(index, amount, msg.sender, dcuAmount); } /// @dev 计算期权价格 /// @param tokenAddress 目标代币地址,0表示eth /// @param oraclePrice 当前预言机价格价 /// @param strikePrice 用户设置的行权价格,结算时系统会根据标的物当前价与行权价比较,计算用户盈亏 /// @param orientation 看涨/看跌两个方向。true:看涨,false:看跌 /// @param exerciseBlock 到达该日期后用户手动进行行权,日期在系统中使用区块号进行记录 /// @return v 期权价格,需要除以18446744073709551616000000 function calcV( address tokenAddress, uint oraclePrice, uint strikePrice, bool orientation, uint exerciseBlock ) public view override returns (uint v) { require(tokenAddress == address(0), "FEO:not allowed"); //Config memory config = _configs[tokenAddress]; //uint minPeriod = uint(config.minPeriod); //require(minPeriod > 0, "FEO:not allowed"); //require(exerciseBlock > block.number + minPeriod, "FEO:exerciseBlock to small"); // 1. 获取或创建期权代币 // 2. 调用预言机获取价格 // 3. 计算权利金(需要的dcu数量) // 按照平均每14秒出一个块计算 uint T = (exerciseBlock - block.number) * BLOCK_TIME; v = orientation ? _calcVc(oraclePrice, T, strikePrice) : _calcVp(oraclePrice, T, strikePrice); } // 转化位OptionView function _toOptionView( Option storage option, uint index, address owner ) private view returns (OptionView memory) { return OptionView( index, option.tokenAddress, _decodeFloat(option.strikePrice), option.orientation, uint(option.exerciseBlock), option.balances[owner] ); } // 根据期权信息获取索引key function _getKey( address tokenAddress, uint strikePrice, bool orientation, uint exerciseBlock ) private pure returns (uint) { //return keccak256(abi.encodePacked(tokenAddress, strikePrice, orientation, exerciseBlock)); require(exerciseBlock < 0x100000000, "FEO:exerciseBlock to large"); return (uint(uint160(tokenAddress)) << 96) | (uint(_encodeFloat(strikePrice)) << 40) | (exerciseBlock << 8) | (orientation ? 1 : 0); } // 获取代币的基数值 function _getBase(address tokenAddress) private returns (uint base) { if (tokenAddress == address(0)) { base = 1 ether; } else { base = _bases[tokenAddress]; if (base == 0) { base = 10 ** ERC20(tokenAddress).decimals(); _bases[tokenAddress] = base; } } } // 将18位十进制定点数转化为64位二级制定点数 function _d18TOb64(uint v) private pure returns (int128) { require(v < 0x6F05B59D3B200000000000000000000, "FEO:can't convert to 64bits"); return int128(int((v << 64) / 1 ether)); } // 将uint转化为int128 function _toInt128(uint v) private pure returns (int128) { require(v < 0x80000000000000000000000000000000, "FEO:can't convert to int128"); return int128(int(v)); } // 将int128转化为uint function _toUInt(int128 v) private pure returns (uint) { require(v >= 0, "FEO:can't convert to uint"); return uint(int(v)); } // 通过查表的方法计算标准正态分布函数 function _snd(int128 x) private pure returns (int128) { uint[28] memory table = [ /* */ ///////////////////// STANDARD NORMAL TABLE ////////////////////////// /* */ 0x174A15BF143412A8111C0F8F0E020C740AE6095807CA063B04AD031E018F0000, // ///// 0x2F8C2E0F2C912B1229922811268F250B23872202207D1EF61D6F1BE61A5D18D8, // /* */ 0x2F8C2E0F2C912B1229922811268F250B23872202207D1EF61D6F1BE61A5D18D4, // /* */ 0x46A2453C43D4426B41003F943E263CB63B4539D3385F36EA357333FB32823108, // /* */ 0x5C0D5AC5597B582F56E05590543E52EA5194503C4EE24D874C294ACA49694807, // /* */ 0x6F6C6E466D1F6BF56AC9699B686A6738660364CC6392625761195FD95E975D53, // /* */ 0x807E7F7F7E7D7D797C737B6A7A5F79517841772F761A750373E972CD71AF708E, // /* */ 0x8F2A8E518D768C998BB98AD789F2890B88218736864785568463836E8276817B, // /* */ 0x9B749AC19A0B9953989997DD971E965D959A94D4940C9342927591A690D49000, // /* */ 0xA57CA4ECA459A3C4A32EA295A1FAA15CA0BDA01C9F789ED29E2A9D809CD39C25, // ///// 0xA57CA4ECA459A3C4A32EA295A1FAA15DA0BDA01C9F789ED29E2A9D809CD39C25, // /* */ 0xAD78AD07AC93AC1EABA7AB2EAAB3AA36A9B8A937A8B5A830A7AAA721A697A60B, // /* */ 0xB3AAB353B2FAB2A0B245B1E7B189B128B0C6B062AFFDAF96AF2DAEC2AE56ADE8, // /* */ 0xB859B818B7D6B793B74EB708B6C0B678B62EB5E2B595B547B4F7B4A6B454B400, // /* */ 0xBBCDBB9EBB6EBB3CBB0ABAD7BAA2BA6DBA36B9FFB9C6B98CB951B915B8D8B899, // /* */ 0xBE49BE27BE05BDE2BDBEBD99BD74BD4DBD26BCFEBCD5BCACBC81BC56BC29BBFC, // /* */ 0xC006BFEEBFD7BFBEBFA5BF8CBF72BF57BF3CBF20BF03BEE6BEC8BEA9BE8ABE69, // /* */ 0xC135C126C116C105C0F4C0E3C0D1C0BFC0ACC099C086C072C05DC048C032C01C, // /* */ 0xC200C1F5C1EBC1E0C1D5C1C9C1BEC1B1C1A5C198C18BC17EC170C162C154C145, // /* */ 0xC283C27CC275C26EC267C260C258C250C248C240C238C22FC226C21DC213C20A, // /* */ 0xC2D6C2D2C2CDC2C9C2C5C2C0C2BBC2B6C2B1C2ACC2A7C2A1C29BC295C28FC289, // /* */ 0xC309C306C304C301C2FEC2FCC2F9C2F6C2F2C2EFC2ECC2E8C2E5C2E1C2DEC2DA, // /* */ 0xC328C326C325C323C321C320C31EC31CC31AC318C316C314C312C310C30EC30B, // /* */ 0xC33AC339C338C337C336C335C334C333C332C331C330C32EC32DC32CC32AC329, // /* */ 0xC344C343C343C342C342C341C341C340C33FC33FC33EC33DC33DC33CC33BC33A, // /* */ 0xC34AC349C349C349C348C348C348C348C347C347C346C346C346C345C345C344, // /* */ 0xC34DC34DC34CC34CC34CC34CC34CC34CC34BC34BC34BC34BC34BC34AC34AC34A, // /* */ 0xC34EC34EC34EC34EC34EC34EC34EC34EC34EC34EC34DC34DC34DC34DC34DC34D, // /* */ 0xC34FC34FC34FC34FC34FC34FC34FC34FC34FC34FC34FC34FC34FC34FC34EC34E, // /* */ 0xC350C350C350C350C350C350C34FC34FC34FC34FC34FC34FC34FC34FC34FC34F // /* */ //////////////////// MADE IN CHINA 2021-08-24 //////////////////////// ]; uint ux = uint(int(x < 0 ? -x : x)) * 100; uint i = ux >> 64; uint v = V50000; if (i < 447) { v = uint((table[i >> 4] >> ((i & 0xF) << 4)) & 0xFFFF) << 64; v = ( ( ( (uint((table[(i + 1) >> 4] >> (((i + 1) & 0xF) << 4)) & 0xFFFF) << 64) - v ) * (ux & 0xFFFFFFFFFFFFFFFF) //(ux - (i << 64)) ) >> 64 ) + v; } if (x > 0) { v = V50000 + v; } else { v = V50000 - v; } return int128(int(v / 100000)); } // 查询token价格 function _queryPrice(address tokenAddress, uint fee, address payback) private returns (uint oraclePrice) { // 1.1. 获取token相对于eth的价格 uint tokenAmount = 1 ether; //uint fee = msg.value; if (tokenAddress != address(0)) { fee >>= 1; (, tokenAmount) = INestPriceFacade(NEST_PRICE_FACADE_ADDRESS).latestPrice { value: fee } (tokenAddress, payback); } // 1.2. 获取usdt相对于eth的价格 (, uint usdtAmount) = INestPriceFacade(NEST_PRICE_FACADE_ADDRESS).latestPrice { value: fee } (USDT_TOKEN_ADDRESS, payback); // 1.3. 将token价格转化为以usdt为单位计算的价格 oraclePrice = usdtAmount * _getBase(tokenAddress) / tokenAmount; } // 计算看涨期权价格 function _calcVc(uint S0, uint T, uint K) private pure returns (uint vc) { int128 sigmaSQ_T = _d18TOb64(SIGMA_SQ * T); int128 miu_T = _toInt128(MIU * T); int128 sigma_t = ABDKMath64x64.sqrt(sigmaSQ_T); int128 D1 = _D1(S0, K, sigmaSQ_T, miu_T); int128 d = ABDKMath64x64.div(D1, sigma_t); uint left = _toUInt(ABDKMath64x64.mul( ABDKMath64x64.exp(miu_T), ABDKMath64x64.sub( ONE, _snd(ABDKMath64x64.sub(d, sigma_t)) ) )) * S0; uint right = _toUInt(ABDKMath64x64.sub(ONE, _snd(d))) * K; vc = left > right ? left - right : 0; } // 计算看跌期权价格 function _calcVp(uint S0, uint T, uint K) private pure returns (uint vp) { int128 sigmaSQ_T = _d18TOb64(SIGMA_SQ * T); int128 miu_T = _toInt128(MIU * T); int128 sigma_t = ABDKMath64x64.sqrt(sigmaSQ_T); int128 D1 = _D1(S0, K, sigmaSQ_T, miu_T); int128 d = ABDKMath64x64.div(D1, sigma_t); uint left = _toUInt(_snd(d)) * K; uint right = _toUInt(ABDKMath64x64.mul( ABDKMath64x64.exp(miu_T), _snd(ABDKMath64x64.sub(d, sigma_t)) )) * S0; vp = left > right ? left - right : 0; } // 计算公式种的d1,因为没有除以σ,所以命名为D1 function _D1(uint S0, uint K, int128 sigmaSQ_T, int128 miu_T) private pure returns (int128) { //require(K < 0x1000000000000000000000000000000000000000000000000, "FEO:K can't ROL 64bits"); return ABDKMath64x64.sub( ABDKMath64x64.add( ABDKMath64x64.ln(_toInt128(K * 0x10000000000000000 / S0)), sigmaSQ_T >> 1 ), miu_T ); } /// @dev Encode the uint value as a floating-point representation in the form of fraction * 16 ^ exponent /// @param value Destination uint value /// @return float format function _encodeFloat(uint value) private pure returns (uint56) { uint exponent = 0; while (value > 0x3FFFFFFFFFFFF) { value >>= 4; ++exponent; } return uint56((value << 6) | exponent); } /// @dev Decode the floating-point representation of fraction * 16 ^ exponent to uint /// @param floatValue fraction value /// @return decode format function _decodeFloat(uint56 floatValue) private pure returns (uint) { return (uint(floatValue) >> 6) << ((uint(floatValue) & 0x3F) << 2); } }
根据期权信息获取索引keyreturn keccak256(abi.encodePacked(tokenAddress, strikePrice, orientation, exerciseBlock));
function _getKey( address tokenAddress, uint strikePrice, bool orientation, uint exerciseBlock ) private pure returns (uint) { require(exerciseBlock < 0x100000000, "FEO:exerciseBlock to large"); return (uint(uint160(tokenAddress)) << 96) | (uint(_encodeFloat(strikePrice)) << 40) | (exerciseBlock << 8) | (orientation ? 1 : 0); }
482,494
[ 1, 167, 259, 122, 167, 240, 111, 167, 255, 258, 167, 256, 230, 165, 128, 99, 167, 228, 112, 169, 241, 120, 166, 242, 249, 168, 117, 100, 166, 125, 248, 856, 2463, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 2316, 1887, 16, 609, 2547, 5147, 16, 9820, 16, 24165, 1768, 10019, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 588, 653, 12, 203, 3639, 1758, 1147, 1887, 16, 7010, 3639, 2254, 609, 2547, 5147, 16, 7010, 3639, 1426, 9820, 16, 7010, 3639, 2254, 24165, 1768, 203, 565, 262, 3238, 16618, 1135, 261, 11890, 13, 288, 203, 3639, 2583, 12, 8913, 30708, 1768, 411, 374, 92, 21, 12648, 16, 315, 8090, 51, 30, 8913, 30708, 1768, 358, 7876, 8863, 203, 3639, 327, 261, 11890, 12, 11890, 16874, 12, 2316, 1887, 3719, 2296, 19332, 13, 7010, 7734, 571, 261, 11890, 24899, 3015, 4723, 12, 701, 2547, 5147, 3719, 2296, 8063, 13, 7010, 7734, 571, 261, 8913, 30708, 1768, 2296, 1725, 13, 203, 7734, 571, 261, 19235, 692, 404, 294, 374, 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 ]
./full_match/1/0xd2B8805735ed574B3db38c1663a64e833B8CFeA7/sources/contracts/traits/factory/UTAutographFactory.sol
Get the community data
(,address crAddr,) = COMMUNITY_LIST.communities(_inputTrait.communityId);
9,660,876
[ 1, 967, 326, 19833, 501, 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, 261, 16, 2867, 4422, 3178, 16, 13, 273, 5423, 49, 2124, 4107, 67, 7085, 18, 5702, 318, 1961, 24899, 2630, 15525, 18, 20859, 548, 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 ]
./partial_match/1/0x986A4010D6dF5754f66F72764487070615CBDE9A/sources/contracts/Ph101ppDailyPhoto.sol
Returns all period ranges.
function periodRanges() public view returns (string[] memory periods, uint256[] memory ranges) { return (_periods, _periodRanges); }
9,362,219
[ 1, 1356, 777, 3879, 7322, 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, 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, 3879, 9932, 1435, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 1080, 8526, 3778, 12777, 16, 2254, 5034, 8526, 3778, 7322, 13, 203, 565, 288, 203, 3639, 327, 261, 67, 20659, 16, 389, 6908, 9932, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.21; /** * @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)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title 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&#39;t hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conform * the base architecture for crowdsales. They are *not* intended to be modified / overriden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using &#39;super&#39; where appropiate to concatenate * behavior. */ contract Crowdsale { using SafeMath for uint256; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // How many token units a buyer gets per wei //uint256 public rate; // Amount of wei raised uint256 public weiRaised; // Amount of wei raised uint256 public tokensDistributed; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @param _wallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ function Crowdsale(address _wallet, ERC20 _token) public { require(_wallet != address(0)); require(_token != address(0)); wallet = _wallet; token = _token; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state weiRaised = weiRaised.add(weiAmount); tokensDistributed = tokensDistributed.add(tokens); _processPurchase(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); } // ----------------------------------------- // Internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(_beneficiary != address(0)); require(_weiAmount != 0); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.transferFrom(wallet, _beneficiary, _tokenAmount); //token.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { // must override } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } } /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public openingTime; uint256 public closingTime; /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { require(now >= openingTime && now <= closingTime); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime Crowdsale opening time * @param _closingTime Crowdsale closing time */ function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public { //require(_openingTime >= now); require(_closingTime >= _openingTime); openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { return now > closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen { super._preValidatePurchase(_beneficiary, _weiAmount); } } /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract&#39;s finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasClosed()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } /** * @title CappedCrowdsale * @dev Crowdsale with a limit for total contributions. */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param _cap Max amount of wei to be contributed */ function CappedCrowdsale(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised >= cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { super._preValidatePurchase(_beneficiary, _weiAmount); require(weiRaised.add(_weiAmount) <= cap); } } /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); /** * @param _wallet Vault address */ function RefundVault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } /** * @param investor Investor address */ function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { state = State.Closed; emit Closed(); wallet.transfer(address(this).balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @param investor Investor address */ function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); emit Refunded(investor, depositedValue); } } /** * @title RefundableCrowdsale * @dev Extension of Crowdsale contract that adds a funding goal, and * the possibility of users getting a refund if goal is not met. * Uses a RefundVault as the crowdsale&#39;s vault. */ contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund vault used to hold funds while crowdsale is running RefundVault public vault; /** * @dev Constructor, creates RefundVault. * @param _goal Funding goal */ function RefundableCrowdsale(uint256 _goal) public { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached() public view returns (bool) { return weiRaised >= goal; } /** * @dev vault finalization task, called when owner calls finalize() */ function finalization() internal { if (goalReached()) { vault.close(); } else { vault.transferOwnership(owner); } super.finalization(); } /** * @dev Overrides Crowdsale fund forwarding, sending funds to vault. */ function _forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } } /** * @title PostDeliveryCrowdsale * @dev Crowdsale that locks tokens from withdrawal until it ends. */ contract PostDeliveryCrowdsale is TimedCrowdsale, Ownable { using SafeMath for uint256; mapping(address => uint256) public balances; /** * @dev Overrides parent by storing balances instead of issuing tokens right away. * @param _beneficiary Token purchaser * @param _tokenAmount Amount of tokens purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { balances[_beneficiary] = balances[_beneficiary].add(_tokenAmount); } /** * @dev Withdraw tokens only after crowdsale ends. */ function withdrawTokens(address _beneficiary) public onlyOwner { require(hasClosed()); uint256 amount = balances[_beneficiary]; require(amount > 0); balances[_beneficiary] = 0; _deliverTokens(_beneficiary, amount); } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract CxNcontract is CappedCrowdsale, RefundableCrowdsale, PostDeliveryCrowdsale { // Only for testNet: //uint privSale1start = now; // Bounty hive address partnerAddress; // // 20 Mar 2018 07:00:00 PM CST uint privSale1start = 1521594000; // 10 Apr 2018 11:59:00 PM CST uint privSale1end = 1523426400; // 16 Apr 2018 07:00:00 PM CST uint privSale2start = 1523926800; // 07 May 2018 11:59:00 PM CST uint privSale2end = 1525759200; // 11 May 2018 07:00:00 PM CST uint saleStart = 1526086800; // 18 Jun 2018 11:59:00 PM CST uint saleEnd = 1526709600; function CxNcontract(uint256 _openingTime, uint256 _closingTime, address _wallet, uint256 _cap, ERC20 _token, uint256 _goal, address _partnerAddress) public payable Crowdsale(_wallet, _token) CappedCrowdsale(_cap) TimedCrowdsale(_openingTime, _closingTime) RefundableCrowdsale(_goal) { //As goal needs to be met for a successful crowdsale //the value needs to less or equal than a cap which is limit for accepted funds partnerAddress = _partnerAddress; require(_goal <= _cap); } function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal { require(checkValue(_weiAmount)); super._preValidatePurchase(_beneficiary, _weiAmount); } function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(getRate()); } function checkValue(uint256 amount) internal view returns (bool) { if (now > privSale1start && now < privSale1end) return (amount >= 5 ether); else if (now > privSale2start && now < privSale2end) return (amount >= 5 ether); else if (now > saleStart && now < saleEnd) return (amount >= 0.1 ether); return false; } function getRate() public view returns (uint256) { if (now > privSale1start && now < privSale1end) return 14375; // Stage I else if (now > privSale2start && now < privSale2end) return 13750; // Stage II else if (now > saleStart && now < saleEnd) return 12500; // Public Sale return 0; } function finalization() internal { uint256 tokensForPartners = 2800000 ether; uint256 tokensNeededToClose = tokensForPartners.add(tokensDistributed); require(token.balanceOf(wallet) >= tokensNeededToClose); token.transferFrom(wallet, partnerAddress, tokensForPartners); super.finalization(); } }
* @dev low level token purchase DO NOT OVERRIDE @param _beneficiary Address performing the token purchase/ calculate token amount to be created update state
function buyTokens(address _beneficiary) public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); uint256 tokens = _getTokenAmount(weiAmount); weiRaised = weiRaised.add(weiAmount); tokensDistributed = tokensDistributed.add(tokens); _processPurchase(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); }
10,577,288
[ 1, 821, 1801, 1147, 23701, 5467, 4269, 22577, 25382, 225, 389, 70, 4009, 74, 14463, 814, 5267, 14928, 326, 1147, 23701, 19, 4604, 1147, 3844, 358, 506, 2522, 1089, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 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, 225, 445, 30143, 5157, 12, 2867, 389, 70, 4009, 74, 14463, 814, 13, 1071, 8843, 429, 288, 203, 203, 565, 2254, 5034, 732, 77, 6275, 273, 1234, 18, 1132, 31, 203, 565, 389, 1484, 4270, 23164, 24899, 70, 4009, 74, 14463, 814, 16, 732, 77, 6275, 1769, 203, 203, 565, 2254, 5034, 2430, 273, 389, 588, 1345, 6275, 12, 1814, 77, 6275, 1769, 203, 203, 565, 732, 77, 12649, 5918, 273, 732, 77, 12649, 5918, 18, 1289, 12, 1814, 77, 6275, 1769, 203, 565, 2430, 1669, 11050, 273, 2430, 1669, 11050, 18, 1289, 12, 7860, 1769, 203, 203, 565, 389, 2567, 23164, 24899, 70, 4009, 74, 14463, 814, 16, 2430, 1769, 203, 565, 3626, 3155, 23164, 12, 3576, 18, 15330, 16, 389, 70, 4009, 74, 14463, 814, 16, 732, 77, 6275, 16, 2430, 1769, 203, 203, 565, 389, 2725, 10262, 343, 11730, 1119, 24899, 70, 4009, 74, 14463, 814, 16, 732, 77, 6275, 1769, 203, 203, 565, 389, 11565, 42, 19156, 5621, 203, 565, 389, 2767, 4270, 23164, 24899, 70, 4009, 74, 14463, 814, 16, 732, 77, 6275, 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 ]
/* Copyright 2019 Novera Capital Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity ^0.4.24; import "./SafeMath.sol"; //openzeppelin import "./Ownable.sol"; //openzeppelin import "./Fund.sol"; /// @title Novera Price Index /// @author Jose Miguel Herrera /// @notice You can use this contract to create a price oracle for a financial asset. Prices come from N registered price agents and averaged. /// @notice You can use this contract independently, or connected to a "fund" which reads the price and has an end price, at which the fund ends. /// @dev With mythX static analysis, you get warning SWC-128 (DoS With Block Gas Limit) due to the looping over connectedFundAddresses in reportPrice(). Since adding new funds is not a user facing function, there is no DoS threat... /// @dev ... However, this means that there IS an upper ceiling on how many funds can be connected to one price index. contract PriceIndex is Ownable { string public baseTicker; string public quoteTicker; mapping (address => FundInfo) public funds; address[] internal connectedFundAddresses; mapping (address => bool) internal isConnectedFund; uint256 public numberOfConnectedFunds; using SafeMath for uint; uint256 public masterPrice; address[] internal registeredPriceAgents; uint256 public numberOfRegisteredPriceAgents; uint256 public maxNumberPriceAgents; uint256 public decimals; mapping (address => bool) internal isRegisteredPriceAgent; mapping (address => priceReport) public PriceAgentReports; event LogPriceUpdate(uint256 _newPrice, uint256 timestamp); event changeInPriceAgents(uint _newNumberOfPriceAgents,address changer); event fundEndAlert(uint256 timestamp, uint256 endPrice, address fundAddress); /// @notice Creates a PriceIndex instance. /// @dev In the future, both the asset name and the currency used to track it will be included as parameters. /// @param initialPrice The initial price of the asset. /// @param initialPriceSource Where initialPrice is coming from. /// @param _maxNumberPriceAgents The max nnumber of price agents this price index will allow. /// @param _decimals The decimal precision used to represent the price of the asset. constructor(uint256 initialPrice, string initialPriceSource, uint _maxNumberPriceAgents,uint256 _decimals, string _baseTicker, string _quoteTicker) public { numberOfRegisteredPriceAgents=0; maxNumberPriceAgents=_maxNumberPriceAgents; registerPriceAgent(msg.sender); PriceAgentReports[msg.sender]=priceReport(initialPrice,now,initialPriceSource); masterPrice=initialPrice; numberOfConnectedFunds=0; decimals=_decimals; baseTicker=_baseTicker; quoteTicker=_quoteTicker; emit LogPriceUpdate(masterPrice,now); } /// @notice Connects a Fund to this price index - the fund starts tracking it. /// @notice Only callable by the contract owner. /// @dev Right now there's no way to disconnect a fund, this feature could be added in the future. /// @param fundAddress The address of the fund being created. function connectFund(address fundAddress) public onlyOwner { require(fundAddress!=0); require(!isConnectedFund[fundAddress]); require(Fund(fundAddress).decimals()==decimals); isConnectedFund[fundAddress]=true; connectedFundAddresses.push(fundAddress); funds[fundAddress]=FundInfo(Fund(fundAddress),false,0,0); funds[fundAddress].strikePrice=funds[fundAddress].fund.strikePrice(); numberOfConnectedFunds=numberOfConnectedFunds.add(1); //what if new connected fund here has reached max conditions already?? if(reachedMaxConditions(fundAddress)){ handleMaxConditionForFund(fundAddress); } } /// @notice Retrieves the address of one of the connected funds. /// @param index The index of the Ith connected fund. /// @return The address of the Ith connected fund. function getConnectedFundAddress(uint index) view public returns(address) { if(numberOfConnectedFunds==0 || index>connectedFundAddresses.length.sub(1)){ return 0; }else{ return connectedFundAddresses[index]; } } /// @notice Retrieves the address of one of the registered price agents. /// @param index The index of the Ith registered agent. /// @return The address of the Ith registered agent. function getRegisteredPriceAgent(uint index) view public returns(address) { if(numberOfRegisteredPriceAgents==0 || index>registeredPriceAgents.length.sub(1)){ return 0; }else{ return registeredPriceAgents[index]; } } /// @notice Retrieves the current price of the tracked asset. /// @dev Designed for the use of a Fund contract (external requests), but can be used publically (would be the same as calling masterPrice()) /// @return If called by Fund that has reached its end conditions, then returns the price that cuased the fund to end. Otherwise, returns CURRENT the price of the asset. function getPrice() view public returns(uint256){ //if I have a fund connected that has reached its end conditions, give it end price if(isConnectedFund[msg.sender] && funds[msg.sender].endPriceConditionsReached ){ return funds[msg.sender].endPrice; }else{ return masterPrice; } } /// @notice Updates current price of the tracked asset and handles the ending of funds. /// @param reportedPrice The reported price. /// @param reportedPriceSource Where reportedPrice comes from. /// @dev Currently averages the prices, future improvement to moving averages possible. /// @dev Analysis needs to be done on this function to see how gas usage increases with the growth of more connected fund addresses, as it may reach a point of self-inflicted DoS. /// @dev The above is an argument for having the ability to DISCONNECT funds. function reportPrice(uint256 reportedPrice,string reportedPriceSource ) public { require(isRegisteredPriceAgent[msg.sender]); //needs to be registered price agent PriceAgentReports[msg.sender]=priceReport(reportedPrice,now,reportedPriceSource); aggregatePrice(); checkAndUpdateFunds(); } /// @dev Internal function used to check if the current price, newly updated, causes the end of a fund. /// @param fundAddress The address of the fund that is being checked. /// @return true if the current price has caused the fund to reach its max/end conditions. False otherwise. function reachedMaxConditions(address fundAddress) internal view returns(bool){ require(isConnectedFund[fundAddress]); //modified so that price index asks a particular fund if it has reached its custom max conditions. return funds[fundAddress].fund.wouldReachEndConditions(masterPrice); } /// @dev Internal function used to handle when a price update causes the end of a fund. /// @param fundAddress The address of the fund that has ended due to a price update function handleMaxConditionForFund(address fundAddress) internal{ emit fundEndAlert(now,masterPrice,fundAddress); funds[fundAddress].endPriceConditionsReached=true; funds[fundAddress].endPrice=masterPrice; } /// @notice Checks if a connected fund has ended. /// @param fundAddress The address of the fund that is going to be checked. /// @return true if the fund has ended. false otherwise. function hasFundEnded(address fundAddress) public view returns(bool){ require(isConnectedFund[fundAddress]); return funds[fundAddress].endPriceConditionsReached; } /// @notice Retrieves the price that caused a fund to end. /// @param fundAddress The address of the fund that ended. /// @return the price that caused the fund to end. function getEndPrice(address fundAddress) public view returns(uint256){ require(hasFundEnded(fundAddress)); return funds[fundAddress].endPrice; } /// @dev Only callable by a Fund contract (external request) that has reached its end conditions/has ended. /// @dev Resets the end status of a fun and retreives the new strike price. function resetFundStatus() public { require(isConnectedFund[msg.sender] && funds[msg.sender].endPriceConditionsReached); funds[msg.sender].endPriceConditionsReached=false; funds[msg.sender].endPrice=0; funds[msg.sender].strikePrice=funds[msg.sender].fund.strikePrice(); } /// @dev Internal function that retrieves all current price reports and averages them, updating the master price. /// @dev This is where moving average functionality could be added instead of simple averaging. /// @dev Warning: does not work if there are no valid (have reported a price) reports/agents. This is enforced in the removal of agents. function aggregatePrice() private { uint256 aggPrice=0; uint256 numValidPrices=0; for (uint i=0; i<registeredPriceAgents.length; i=i.add(1)) { if(registeredPriceAgents[i]!=0 && PriceAgentReports[registeredPriceAgents[i]].timestamp!=0){ numValidPrices=numValidPrices.add(1); aggPrice=aggPrice.add(PriceAgentReports[registeredPriceAgents[i]].price); } } if(numValidPrices==0){ //THIS SHOULD NEVER HAPPEN, AND IS GUARANTEED BY THE REMOVE PRICE AGENT FUNC, THERE SHALL BE ALWAYS 1 AGENT revert("Price cannot be aggregated because there are no valid prices."); }else{ aggPrice = aggPrice.div(numValidPrices); } emit LogPriceUpdate(aggPrice,now); masterPrice=aggPrice; } /// @dev Internal function that checks if the previous price update would end a fund, and triggers the end process function checkAndUpdateFunds() private { for (uint i=0; i<connectedFundAddresses.length; i=i.add(1)) { if(isConnectedFund[connectedFundAddresses[i]] && !hasFundEnded(connectedFundAddresses[i]) && reachedMaxConditions(connectedFundAddresses[i])){ handleMaxConditionForFund(connectedFundAddresses[i]); } } } /// @notice Registers an address as a registered price agent for this price index. /// @notice Only callable by the contract owner. /// @param newAgent The address of the price agent to be registered. function registerPriceAgent(address newAgent) public onlyOwner { require(!isRegisteredPriceAgent[newAgent]); //prevent double registrations require(numberOfRegisteredPriceAgents<maxNumberPriceAgents); //no more than max isRegisteredPriceAgent[newAgent]=true; bool foundEmptySlot=false; for (uint i=0; i<registeredPriceAgents.length; i=i.add(1)) { if(registeredPriceAgents[i]==0){ registeredPriceAgents[i]=newAgent; //add agent in first free slot foundEmptySlot=true; break; } } if(!foundEmptySlot){ registeredPriceAgents.push(newAgent); } numberOfRegisteredPriceAgents=numberOfRegisteredPriceAgents.add(1); emit changeInPriceAgents(numberOfRegisteredPriceAgents,msg.sender); } /// @notice Removes an address as a registered price agent for this price index. Also removes the agent's price report, recalculating the master price. /// @notice Only callable by the contract owner. /// @dev Warning: you cannot remove the LAST valid (has reported a price) price reporting agent. /// @param agentToRemove The address of the price agent to be removed. function removePriceAgent(address agentToRemove) public onlyOwner { //require(agentToRemove!=owner()); //cannot remove contract owner (note: this is something that needs to be further discussed) //require(numberOfRegisteredPriceAgents>1); //above were previous attempts to prevent a bad state when the last valid agent was deleted, but now it's being done in aggregatePrice isRegisteredPriceAgent[agentToRemove]=false; delete PriceAgentReports[agentToRemove]; for (uint i=0; i<registeredPriceAgents.length; i=i.add(1)) { if(registeredPriceAgents[i]==agentToRemove){ delete registeredPriceAgents[i]; //leaves a gap of 0 } } aggregatePrice(); numberOfRegisteredPriceAgents=numberOfRegisteredPriceAgents.sub(1); emit changeInPriceAgents(numberOfRegisteredPriceAgents,msg.sender); } struct priceReport { uint256 price; uint256 timestamp; string source; } struct FundInfo{ Fund fund; bool endPriceConditionsReached; uint256 endPrice; uint256 strikePrice; } }
@notice Retrieves the price that caused a fund to end. @param fundAddress The address of the fund that ended. @return the price that caused the fund to end.
function getEndPrice(address fundAddress) public view returns(uint256){ require(hasFundEnded(fundAddress)); return funds[fundAddress].endPrice; }
15,789,459
[ 1, 6960, 326, 6205, 716, 15848, 279, 284, 1074, 358, 679, 18, 225, 284, 1074, 1887, 1021, 1758, 434, 326, 284, 1074, 716, 16926, 18, 327, 326, 6205, 716, 15848, 326, 284, 1074, 358, 679, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 9968, 5147, 12, 2867, 284, 1074, 1887, 13, 1071, 1476, 1135, 12, 11890, 5034, 15329, 203, 3639, 2583, 12, 5332, 42, 1074, 28362, 12, 74, 1074, 1887, 10019, 203, 3639, 327, 284, 19156, 63, 74, 1074, 1887, 8009, 409, 5147, 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 ]
./partial_match/56/0x0Fb22A54A749C3bABeEd908e04A99d27725A2FAe/sources/StrategyKebabLP.sol
* @dev Tokens Used: {wbnb, busd} - Required for liquidity routing when doing swaps. {kebab} - Token generated by staking our funds. In this case it's the KEBAB token. {bifi} - BeefyFinance token, used to send funds to the treasury. {lpPair} - Token that the strategy maximizes. The same token that users deposit in the vault. {lpToken0, lpToken1} - Tokens that the strategy maximizes. IUniswapV2Pair tokens/* @dev Third Party Contracts: {unirouter} - PancakeSwap unirouter {masterchef} - MasterChef contract {poolId} - MasterChef pool id/* @dev Beefy Contracts: {rewards} - Reward pool where the strategy fee earnings will go. {treasury} - Address of the BeefyFinance treasury {vault} - Address of the vault that controls the strategy's funds. {strategist} - Address of the strategy author/deployer where strategist fee will go./* @dev Distribution of fees earned. This allocations relative to the % implemented on doSplit(). Current implementation separates 4.5% for fees. {REWARDS_FEE} - 3% goes to BIFI holders through the {rewards} pool. {CALL_FEE} - 0.5% goes to whoever executes the harvest function as gas subsidy. {TREASURY_FEE} - 0.5% goes to the treasury. {STRATEGIST_FEE} - 0.5% goes to the strategist. {MAX_FEE} - Aux const used to safely calc the correct amounts. {WITHDRAWAL_FEE} - Fee taxed when a user withdraws funds. 10 === 0.1% fee. {WITHDRAWAL_MAX} - Aux const used to safely calc the correct amounts./* @dev Routes we take to swap tokens using PancakeSwap. {kebabToWbnbRoute} - Route we take to get from {kebab} into {wbnb}. {wbnbToBifiRoute} - Route we take to get from {wbnb} into {bifi}. {kebabToLp0Route} - Route we take to get from {kebab} into {lpToken0}. {kebabToLp1Route} - Route we take to get from {kebab} into {lpToken1}./* @dev Event that is fired each time someone harvests the strat./* @dev Initializes the strategy with the token to maximize./
constructor(address _lpPair, uint8 _poolId, address _vault, address _strategist) public { lpPair = _lpPair; lpToken0 = IUniswapV2Pair(lpPair).token0(); lpToken1 = IUniswapV2Pair(lpPair).token1(); poolId = _poolId; vault = _vault; strategist = _strategist; if (lpToken0 == wbnb) { kebabToLp0Route = [kebab, wbnb]; kebabToLp0Route = [kebab, busd]; kebabToLp0Route = [kebab, busd, lpToken0]; } if (lpToken1 == wbnb) { kebabToLp1Route = [kebab, wbnb]; kebabToLp1Route = [kebab, busd]; kebabToLp1Route = [kebab, busd, lpToken1]; } IERC20(lpPair).safeApprove(masterchef, uint(-1)); IERC20(kebab).safeApprove(unirouter, uint(-1)); IERC20(wbnb).safeApprove(unirouter, uint(-1)); IERC20(lpToken0).safeApprove(unirouter, 0); IERC20(lpToken0).safeApprove(unirouter, uint(-1)); IERC20(lpToken1).safeApprove(unirouter, 0); IERC20(lpToken1).safeApprove(unirouter, uint(-1)); }
11,110,464
[ 1, 5157, 10286, 30, 288, 9464, 6423, 16, 5766, 72, 97, 300, 10647, 364, 4501, 372, 24237, 7502, 1347, 9957, 1352, 6679, 18, 288, 4491, 70, 378, 97, 300, 3155, 4374, 635, 384, 6159, 3134, 284, 19156, 18, 657, 333, 648, 518, 1807, 326, 1475, 29258, 2090, 1147, 18, 288, 70, 704, 97, 300, 30830, 74, 93, 6187, 1359, 1147, 16, 1399, 358, 1366, 284, 19156, 358, 326, 9787, 345, 22498, 18, 288, 9953, 4154, 97, 300, 3155, 716, 326, 6252, 30547, 3128, 18, 1021, 1967, 1147, 716, 3677, 443, 1724, 316, 326, 9229, 18, 288, 9953, 1345, 20, 16, 12423, 1345, 21, 97, 300, 13899, 716, 326, 6252, 30547, 3128, 18, 467, 984, 291, 91, 438, 58, 22, 4154, 2430, 19, 225, 935, 6909, 6393, 93, 30131, 30, 288, 318, 77, 10717, 97, 300, 12913, 23780, 12521, 7738, 10717, 288, 7525, 343, 10241, 97, 300, 13453, 39, 580, 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, 3885, 12, 2867, 389, 9953, 4154, 16, 2254, 28, 389, 6011, 548, 16, 1758, 389, 26983, 16, 1758, 389, 701, 1287, 376, 13, 1071, 288, 203, 3639, 12423, 4154, 273, 389, 9953, 4154, 31, 203, 3639, 12423, 1345, 20, 273, 467, 984, 291, 91, 438, 58, 22, 4154, 12, 9953, 4154, 2934, 2316, 20, 5621, 203, 3639, 12423, 1345, 21, 273, 467, 984, 291, 91, 438, 58, 22, 4154, 12, 9953, 4154, 2934, 2316, 21, 5621, 203, 3639, 2845, 548, 273, 389, 6011, 548, 31, 203, 3639, 9229, 273, 389, 26983, 31, 203, 3639, 609, 1287, 376, 273, 389, 701, 1287, 376, 31, 203, 203, 3639, 309, 261, 9953, 1345, 20, 422, 17298, 6423, 13, 288, 203, 5411, 12519, 70, 378, 774, 48, 84, 20, 3255, 273, 306, 4491, 70, 378, 16, 17298, 6423, 15533, 203, 5411, 12519, 70, 378, 774, 48, 84, 20, 3255, 273, 306, 4491, 70, 378, 16, 5766, 72, 15533, 203, 5411, 12519, 70, 378, 774, 48, 84, 20, 3255, 273, 306, 4491, 70, 378, 16, 5766, 72, 16, 12423, 1345, 20, 15533, 203, 3639, 289, 203, 203, 3639, 309, 261, 9953, 1345, 21, 422, 17298, 6423, 13, 288, 203, 5411, 12519, 70, 378, 774, 48, 84, 21, 3255, 273, 306, 4491, 70, 378, 16, 17298, 6423, 15533, 203, 5411, 12519, 70, 378, 774, 48, 84, 21, 3255, 273, 306, 4491, 70, 378, 16, 5766, 72, 15533, 203, 5411, 12519, 70, 378, 774, 48, 84, 21, 3255, 273, 306, 4491, 70, 378, 16, 5766, 72, 16, 12423, 1345, 21, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; contract AutoCompoundFarm is ReentrancyGuard, Pausable, Ownable { using SafeMath for uint; using SafeERC20 for IERC20; struct UserInfo { uint amount; uint divisor; uint pastPending; } IERC20 public immutable krw; bool public multiplierIsMaxed; uint public dailyBlocks; uint public totalStaked; uint public totalPending; uint public multiplier; uint16 public fee; uint public targetDailyCompoundRate; uint public maxRewardsPerBlock; uint public rewardsPerBlock; uint public lastRewardBlock; uint public finalBlock; address public vault; mapping(address => UserInfo) public stakes; event Deposit(address indexed user, uint amount); event Withdraw(address indexed user, uint amount); event Claim(address indexed user, uint amount); event EmergencyWithdraw(address indexed user, uint amount); /** * @dev initialise the autocompounding farm. Fee defaults to zero * @param _krw contract address for krown * @param _vault address to send fees to * @param _maxRewardsPerBlock the maximum amount of krown rewards to be distributed per block * @param _targetDailyCompoundRate the daily compounding rate used to determine the amount of krown rewards per block */ constructor( address _krw, address _vault, uint _maxRewardsPerBlock, uint _targetDailyCompoundRate ) { krw = IERC20(_krw); multiplierIsMaxed = false; dailyBlocks = 1e18 * 20 * 60 * 24; // Based on 3 second per block on BSC totalStaked = 0; totalPending = 0; multiplier = 1e18; fee = 0; targetDailyCompoundRate = _targetDailyCompoundRate; maxRewardsPerBlock = _maxRewardsPerBlock; rewardsPerBlock = 0; lastRewardBlock = block.number; finalBlock = type(uint).max; vault = _vault; } /// @dev retrieves the amount deposited by the user function getDeposit(address account) external view returns(uint) { return stakes[account].amount; } /// @dev calculates and returns the APY function getAPY() external view returns(uint) { return totalStaked == 0 ? 0 : (rewardsPerBlock * dailyBlocks * 365) / (totalStaked + totalPending); } /// @dev updates the daily blocks variable /// @param _dailyBlocks the expected number of blocks to be mined per day function changeDailyBlocks(uint _dailyBlocks) external onlyOwner { dailyBlocks = _dailyBlocks; } /// @dev updates the final block variable /// @param _finalBlock the block number after which reward distribution will halt function changeFinalBlock(uint _finalBlock) external onlyOwner { finalBlock = _finalBlock; } /// @dev updates the fee variable /// @param _fee the % fee for depositing e.g. 100 = 1% function changeFee(uint16 _fee) public onlyOwner { require(_fee <= 10000, "Invalid fee"); fee = _fee; } /// @dev updates the maximum rewards per block variable /// @param _maxRewardsPerBlock the maximum amount of the token to be distributed per block function changeMaxRewardsPerBlock(uint _maxRewardsPerBlock) external onlyOwner { maxRewardsPerBlock = _maxRewardsPerBlock; } /// @dev updates the daily compound rate target variable /// @param _targetDailyCompoundRate the daily compounding rate used to determine the amount of krown rewards per block function changeTargetDailyCompoundRate(uint _targetDailyCompoundRate) external onlyOwner { require(_targetDailyCompoundRate > 1e18, "Target compound rate must be greater than 1 ether"); targetDailyCompoundRate = _targetDailyCompoundRate; } /// @dev updates the vault address variable /// @param _vault address to send fees to function changeVault(address _vault) external onlyOwner { vault = _vault; } /// @dev deposits tokens into the farm /// @param amount the amount of tokens to deposit function deposit(uint amount) external whenNotPaused nonReentrant { require(amount >= 1e18, "Must deposit at least 1 KRW"); update(); // distribute rewards krw.safeTransferFrom(msg.sender, address(this), amount); // subtract fee if (fee != 0) { uint feeAmount = (amount * fee) / 10000; krw.safeTransfer(address(vault), feeAmount); amount -= feeAmount; } // update user stake information UserInfo storage user = stakes[msg.sender]; user.pastPending = getPending(msg.sender); user.divisor = multiplier; user.amount += amount; totalStaked += amount; emit Deposit(msg.sender, amount); } /// @dev withdraw tokens from the farm /// @param amount the amount of tokens to withdraw function withdraw(uint amount) public nonReentrant { require(amount > 0, 'Amount must be larger than 0.'); require(stakes[msg.sender].amount >= amount, 'Amount cannot exceed balance.'); update(); // distribute rewards // send rewards to user uint pendingAmount = getPending(msg.sender); totalPending -= pendingAmount; krw.safeTransfer(msg.sender, pendingAmount); // remove amount from user stake UserInfo storage user = stakes[msg.sender]; totalStaked -= amount; user.amount -= amount; user.pastPending = 0; user.divisor = user.amount == 0 ? 0 : multiplier; // send amount to user krw.safeTransfer(msg.sender, amount); emit Withdraw(msg.sender, amount); } /// @dev withdraw all tokens from the farm function withdrawAll() external { withdraw(stakes[msg.sender].amount); } /// @dev withdraw all tokens from the farm, ignoring rewards function emergencyWithdraw() external nonReentrant { UserInfo storage user = stakes[msg.sender]; // remove user stake and clear rewards uint pendingAmount = getPending(msg.sender); totalStaked -= user.amount; totalPending -= pendingAmount; user.amount = 0; user.pastPending = 0; user.divisor = 0; // send tokens to user krw.safeTransfer(msg.sender, user.amount); emit EmergencyWithdraw(msg.sender, user.amount); } /// @dev claim rewards from the farm function claim() external nonReentrant { update(); // distribute rewards // clear rewards from user information UserInfo storage user = stakes[msg.sender]; uint pendingAmount = getPending( msg.sender); totalPending -= pendingAmount; user.divisor = multiplier; user.pastPending = 0; // send rewards to user krw.safeTransfer(msg.sender, pendingAmount); emit Claim(msg.sender, pendingAmount); } /// @dev updates the amount of rewards per block function updateRewardsPerBlock() internal { uint total = totalStaked + totalPending; rewardsPerBlock = ((targetDailyCompoundRate - 1e18) * total) / dailyBlocks; rewardsPerBlock = rewardsPerBlock < maxRewardsPerBlock ? rewardsPerBlock : maxRewardsPerBlock; } /// @dev distributes the rewards since update was last called function update() public whenNotPaused { if (totalStaked != 0) { updateRewardsPerBlock(); uint blocksSinceLastReward = block.number < finalBlock ? (block.number - lastRewardBlock) : 0; uint rewardsToDeliver = rewardsPerBlock * blocksSinceLastReward; uint total = totalStaked + totalPending; uint totalAfterRewards = total + rewardsToDeliver; // If the multiplier is going to overflow, then end the reward distribution // by setting the final block equal to the block number when rewards were last distributed. // Then return, so that no rewards are distributed. Using this mechanism, people will be // able to withdraw their stake and claim their rewards without any issues. if (type(uint).max / totalAfterRewards < multiplier) { multiplierIsMaxed = true; finalBlock = lastRewardBlock; return; } multiplier = (multiplier * totalAfterRewards) / total; totalPending += rewardsToDeliver; } lastRewardBlock = block.number; } /// @dev calculates the rewards /// @param account the account to calculate the rewards for /// @return the rewards for the account function getPending(address account) public view returns(uint) { UserInfo memory user = stakes[account]; uint totalAmount = user.amount + user.pastPending; return user.divisor == 0 ? 0 : (totalAmount * multiplier) / user.divisor - user.amount; } /// @dev pauses the farm function pause() external onlyOwner { _pause(); lastRewardBlock = block.number; } /// @dev resumes the farm function unpause() external onlyOwner { _unpause(); lastRewardBlock = block.number; } }
@dev pauses the farm
function pause() external onlyOwner { _pause(); lastRewardBlock = block.number; }
1,090,146
[ 1, 8774, 6117, 326, 284, 4610, 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, 11722, 1435, 3903, 1338, 5541, 288, 203, 3639, 389, 19476, 5621, 203, 3639, 1142, 17631, 1060, 1768, 273, 1203, 18, 2696, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x4eeF4C43734690ffe34a00A872234037676D7990/sources/contracts/Manager.sol
@param _raffleId Id of the raffle @param _player wallet of the player @return Claims data of the player on that raffle
function getClaimData(uint256 _raffleId, address _player) external view returns (ClaimStruct memory) { return claimsData[keccak256(abi.encode(_player, _raffleId))]; }
3,577,068
[ 1, 67, 354, 1403, 298, 548, 3124, 434, 326, 767, 1403, 298, 225, 389, 14872, 9230, 434, 326, 7291, 327, 28895, 501, 434, 326, 7291, 603, 716, 767, 1403, 298, 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, 565, 445, 13674, 4581, 751, 12, 11890, 5034, 389, 354, 1403, 298, 548, 16, 1758, 389, 14872, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 9762, 3823, 3778, 13, 203, 565, 288, 203, 3639, 327, 11955, 751, 63, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 24899, 14872, 16, 389, 354, 1403, 298, 548, 3719, 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 ]
//SPDX-License-Identifier: MIT pragma solidity 0.8.4; contract Mytoken{ string public constant name = "Saksham"; string public constant symbol = "SK"; uint8 public constant decimals = 18; //Event to listen on event Transfer(address indexed from, address indexed to, uint tokens); //Event for delegation approval event Approve(address indexed tokenOwner, address indexed spender, uint tokens ); //Address and balances mapping(address=>uint256) balances; //For delegation purpose mapping(address => mapping(address=>uint256)) allowed; //Owner of the smart contract address owner; uint256 totalSupply_; constructor(uint256 supply){ //Assigning the owner owner = msg.sender; totalSupply_ = supply; //Assigning the deployer all the token balances[msg.sender] = totalSupply_; } //Function to get the total total_supply function totalSupply() public view returns(uint256){ return totalSupply_; } //Function to get balance of the owner function balanceOf()public view returns(uint256){ return balances[owner]; } //Transfer ownership function transferOwnership(address toOwner) public returns(bool){ require(msg.sender == owner,"You do not have the privilege to transfer ownership"); owner = toOwner; return true; } //Transfer token to another account function transfer(address toAccount, uint256 amount) public returns(bool){ require(amount <= balances[msg.sender]); balances[toAccount] = balances[toAccount] + amount; //Incrementing balance balances[msg.sender] = balances[msg.sender] - amount; emit Transfer(msg.sender,toAccount,amount); return true; } //Delegation approval function approve(address delegate, uint256 tokens)public returns(bool) { //Allowing delegation ability to the address allowed[msg.sender][delegate] = tokens; emit Approve(msg.sender, delegate, tokens); return true; } //Function to get delegated amount to an address function allowance(address tokenOwner, address delegate) public view returns(uint){ return allowed[tokenOwner][delegate]; } //Transfer token by Delegated account function transferFrom(address tokenOwner,address destination, uint256 tokens)public returns(bool){ require(tokens <= balances[tokenOwner],"Insufficient balance"); require(tokens <= allowed[tokenOwner][msg.sender],"Token amount exceeds approved delgated amount"); balances[tokenOwner] = balances[tokenOwner] - tokens; allowed[tokenOwner][msg.sender] = allowed[tokenOwner][msg.sender] - tokens; balances[destination] = balances[destination] + tokens; emit Transfer(tokenOwner,destination,tokens); return true; } }
Event to listen onEvent for delegation approvalAddress and balancesFor delegation purposeOwner of the smart contract
contract Mytoken{ string public constant name = "Saksham"; string public constant symbol = "SK"; uint8 public constant decimals = 18; event Transfer(address indexed from, address indexed to, uint tokens); event Approve(address indexed tokenOwner, address indexed spender, uint tokens ); mapping(address=>uint256) balances; mapping(address => mapping(address=>uint256)) allowed; address owner; uint256 totalSupply_; pragma solidity 0.8.4; constructor(uint256 supply){ owner = msg.sender; totalSupply_ = supply; balances[msg.sender] = totalSupply_; } function totalSupply() public view returns(uint256){ return totalSupply_; } function balanceOf()public view returns(uint256){ return balances[owner]; } function transferOwnership(address toOwner) public returns(bool){ require(msg.sender == owner,"You do not have the privilege to transfer ownership"); owner = toOwner; return true; } function transfer(address toAccount, uint256 amount) public returns(bool){ require(amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender] - amount; emit Transfer(msg.sender,toAccount,amount); return true; } function approve(address delegate, uint256 tokens)public returns(bool) { allowed[msg.sender][delegate] = tokens; emit Approve(msg.sender, delegate, tokens); return true; } function allowance(address tokenOwner, address delegate) public view returns(uint){ return allowed[tokenOwner][delegate]; } function transferFrom(address tokenOwner,address destination, uint256 tokens)public returns(bool){ require(tokens <= balances[tokenOwner],"Insufficient balance"); require(tokens <= allowed[tokenOwner][msg.sender],"Token amount exceeds approved delgated amount"); balances[tokenOwner] = balances[tokenOwner] - tokens; allowed[tokenOwner][msg.sender] = allowed[tokenOwner][msg.sender] - tokens; balances[destination] = balances[destination] + tokens; emit Transfer(tokenOwner,destination,tokens); return true; } }
2,541,739
[ 1, 1133, 358, 6514, 603, 1133, 364, 23595, 23556, 1887, 471, 324, 26488, 1290, 23595, 13115, 5541, 434, 326, 13706, 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 ]
[ 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, 8005, 2316, 95, 203, 203, 565, 533, 1071, 5381, 508, 273, 315, 55, 581, 674, 301, 14432, 203, 565, 533, 1071, 5381, 3273, 273, 315, 11129, 14432, 203, 565, 2254, 28, 1071, 5381, 15105, 273, 6549, 31, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 2430, 1769, 203, 203, 565, 871, 1716, 685, 537, 12, 2867, 8808, 1147, 5541, 16, 1758, 8808, 17571, 264, 16, 2254, 2430, 11272, 203, 203, 203, 565, 2874, 12, 2867, 9207, 11890, 5034, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 9207, 11890, 5034, 3719, 2935, 31, 203, 203, 203, 565, 1758, 3410, 31, 203, 203, 565, 2254, 5034, 2078, 3088, 1283, 67, 31, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 24, 31, 203, 565, 3885, 12, 11890, 5034, 14467, 15329, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 3639, 2078, 3088, 1283, 67, 273, 14467, 31, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 2078, 3088, 1283, 67, 31, 203, 540, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 1135, 12, 11890, 5034, 15329, 203, 3639, 327, 2078, 3088, 1283, 67, 31, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 1435, 482, 1476, 1135, 12, 11890, 5034, 15329, 203, 3639, 327, 324, 26488, 63, 8443, 15533, 203, 565, 289, 203, 203, 565, 445, 7412, 5460, 12565, 12, 2867, 358, 5541, 13, 1071, 1135, 12, 6430, 15329, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 2 ]
// File: @openzeppelin/contracts/introspection/IERC165.sol // SPD-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // SPD-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Metadata.sol // SPD-License-Identifier: MIT pragma solidity ^0.6.2; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol // SPD-License-Identifier: MIT pragma solidity ^0.6.2; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/utils/Strings.sol // SPD-License-Identifier: MIT pragma solidity ^0.6.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--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // File: contracts/NFTLotteryURI.sol // SPD-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.6.8; /// @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); } } interface ILotteryInfo { function prizeAddress() external view returns (address); function prizeId() external view returns (uint256); function startDate() external view returns (uint64); function endDate() external view returns (uint64); function minTicketsToSell() external view returns (uint32); function maxTickets() external view returns (uint32); } interface IOwnable { function owner() external view returns (address); } interface ISVGCreator { function svg(address a) external view returns (bytes memory); } contract NFTLotteryURI { mapping(address => address) postLotterySVGCreator; string[] private hexAlphabet = ["0", "1","2","3","4","5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]; using Strings for uint256; function setPostLotterySVGCreator(address lottery, address svgCreator) external { require(msg.sender == IOwnable(lottery).owner(), "Not owner"); postLotterySVGCreator[lottery] = svgCreator; } function tokenURI(uint256 id) external view returns (string memory) { string memory name = getLotteryName(msg.sender); return string( abi.encodePacked( 'data:application/json;base64,', Base64.encode( bytes( abi.encodePacked( '{"name":"', name, ' ticket #', id.toString(), '", "description":"', 'A lottery ticket for ', name, '", "image": "', 'data:image/svg+xml;base64,', getSVG(msg.sender, id), '"}' ))))); } function getLotteryName(address a) public view returns (string memory) { ILotteryInfo lottery = ILotteryInfo(a); return string(abi.encodePacked(IERC721Metadata(lottery.prizeAddress()).name(), " #", lottery.prizeId().toString())); } function getSVG(address a, uint256 id) public view returns (string memory) { bytes memory svg; uint256 time = block.timestamp; if (time > ILotteryInfo(a).endDate()) { time = ILotteryInfo(a).endDate(); // If time is past, and we have a post-lottery SVG generator, then transform if (postLotterySVGCreator[a] != address(0)) { svg = ISVGCreator(postLotterySVGCreator[a]).svg(a); return Base64.encode(svg); } } uint256 supply = IERC721Enumerable(a).totalSupply(); if (IERC721Enumerable(a).totalSupply() > ILotteryInfo(a).minTicketsToSell()) { supply = ILotteryInfo(a).minTicketsToSell(); } svg = createTicket(a, id, time, supply); return Base64.encode(svg); } function createTicket(address a, uint256 id, uint256 time, uint256 supply) public view returns (bytes memory) { return abi.encodePacked('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000"><style>.big {font: bold 3rem monospace; } .small {font: bold 1.5rem monospace}</style><rect width="900" height="400" x="50" y="50" fill="#fff" stroke-width="20" stroke="black"/>', createGradient(a, id), '<text x="80" y="110" class="big">', getLotteryName(a), '</text>', createSaleBlock(a, supply), createTimeBlock(a, time), '</svg>' ); } function createSaleBlock(address a, uint256 supply) public view returns (string memory) { return string( abi.encodePacked( '<text x="80" y="170" class="small">Tickets sold:', IERC721Enumerable(a).totalSupply().toString(), '</text>', '<text x="450" y="170" class="small">Min:', uint256(ILotteryInfo(a).minTicketsToSell()).toString(), '</text>', '<text x="670" y="170" class="small">Max:', uint256(ILotteryInfo(a).maxTickets()).toString(), '</text>', '<rect width="', ((700 * supply) / ILotteryInfo(a).minTicketsToSell()).toString(), '" height="40" x="80" y="190" fill="url(#g)" />', '<text x="810" y="220" class="small">', (supply*100 / ILotteryInfo(a).minTicketsToSell()).toString(),'%</text>' )); } function createTimeBlock(address a, uint256 time) public view returns (string memory) { return string( abi.encodePacked( '<text x="80" y="300" class="small">Current time:', block.timestamp.toString(), '</text>', '<text x="500" y="300" class="small">End time:', uint256(ILotteryInfo(a).endDate()).toString(), '</text>', '<rect width="', ((700 * (time - ILotteryInfo(a).startDate())) / (ILotteryInfo(a).endDate() - ILotteryInfo(a).startDate())).toString(), '" height="40" x="80" y="320" fill="url(#g2)" />', '<text x="810" y="350" class="small">', ((time - ILotteryInfo(a).startDate())*100 / (ILotteryInfo(a).endDate() - ILotteryInfo(a).startDate())).toString(), '%</text>' )); } function randHex(uint256 rng) public view returns (string memory) { uint256 i1 = rng % 16; uint256 i2 = uint256(keccak256(abi.encodePacked(rng, i1))) % 16; uint256 i3 = uint256(keccak256(abi.encodePacked(rng, i2))) % 16; uint256 i4 = uint256(keccak256(abi.encodePacked(rng, i3))) % 16; uint256 i5 = uint256(keccak256(abi.encodePacked(rng, i4))) % 16; uint256 i6 = uint256(keccak256(abi.encodePacked(rng, i5))) % 16; return string(abi.encodePacked( hexAlphabet[i1], hexAlphabet[i2], hexAlphabet[i3], hexAlphabet[i4], hexAlphabet[i5], hexAlphabet[i6] )); } function createGradient(address a, uint256 id) public view returns (string memory) { uint256 color1 = uint256(keccak256(abi.encodePacked(a, id))); uint256 color2 = uint256(keccak256(abi.encodePacked(color1, a, id))); uint256 color3 = uint256(keccak256(abi.encodePacked(color2, a, id))); uint256 color4 = uint256(keccak256(abi.encodePacked(color3, a, id))); string memory svg = string(abi.encodePacked( '<defs>', gradientDef(randHex(color1), randHex(color2), randHex(color3), randHex(color4), "g", 4), gradientDef(randHex(color1*color2), randHex(color2*color3), randHex(color3*color4), randHex(color4*color1), "g2", 3), '</defs>' )); return svg; } function gradientDef(string memory color1, string memory color2, string memory color3, string memory color4, string memory gradientId, uint256 time) public pure returns (string memory) { return string(abi.encodePacked( '<linearGradient id="',gradientId,'"><stop offset="0%" stop-color="#', color1, '"><animate attributeName="stop-color" values="#',color1,';#',color2,';#',color1,'" dur="', time.toString(), 's" repeatCount="indefinite"/></stop><stop offset="100%" stop-color="#', color3, '"><animate attributeName="stop-color" values="#',color3,';#',color4,';#',color3,'" dur="', time.toString(), 's" repeatCount="indefinite"/></stop></linearGradient>' )); } }
If time is past, and we have a post-lottery SVG generator, then transform
function getSVG(address a, uint256 id) public view returns (string memory) { bytes memory svg; uint256 time = block.timestamp; if (time > ILotteryInfo(a).endDate()) { time = ILotteryInfo(a).endDate(); if (postLotterySVGCreator[a] != address(0)) { svg = ISVGCreator(postLotterySVGCreator[a]).svg(a); return Base64.encode(svg); } } uint256 supply = IERC721Enumerable(a).totalSupply(); if (IERC721Enumerable(a).totalSupply() > ILotteryInfo(a).minTicketsToSell()) { supply = ILotteryInfo(a).minTicketsToSell(); } svg = createTicket(a, id, time, supply); return Base64.encode(svg); }
14,421,812
[ 1, 2047, 813, 353, 8854, 16, 471, 732, 1240, 279, 1603, 17, 23372, 387, 93, 11281, 4456, 16, 1508, 2510, 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 ]
[ 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, 0 ]
[ 1, 225, 445, 1322, 9266, 12, 2867, 279, 16, 2254, 5034, 612, 13, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 565, 1731, 3778, 9804, 31, 203, 565, 2254, 5034, 813, 273, 1203, 18, 5508, 31, 203, 565, 309, 261, 957, 405, 467, 48, 352, 387, 93, 966, 12, 69, 2934, 409, 1626, 10756, 288, 203, 1377, 813, 273, 467, 48, 352, 387, 93, 966, 12, 69, 2934, 409, 1626, 5621, 203, 1377, 309, 261, 2767, 48, 352, 387, 93, 26531, 10636, 63, 69, 65, 480, 1758, 12, 20, 3719, 288, 203, 3639, 9804, 273, 4437, 9266, 10636, 12, 2767, 48, 352, 387, 93, 26531, 10636, 63, 69, 65, 2934, 11451, 12, 69, 1769, 203, 3639, 327, 3360, 1105, 18, 3015, 12, 11451, 1769, 203, 1377, 289, 203, 565, 289, 203, 565, 2254, 5034, 14467, 273, 467, 654, 39, 27, 5340, 3572, 25121, 12, 69, 2934, 4963, 3088, 1283, 5621, 203, 565, 309, 261, 45, 654, 39, 27, 5340, 3572, 25121, 12, 69, 2934, 4963, 3088, 1283, 1435, 405, 467, 48, 352, 387, 93, 966, 12, 69, 2934, 1154, 6264, 2413, 774, 55, 1165, 10756, 288, 203, 1377, 14467, 273, 467, 48, 352, 387, 93, 966, 12, 69, 2934, 1154, 6264, 2413, 774, 55, 1165, 5621, 203, 565, 289, 203, 565, 9804, 273, 752, 13614, 12, 69, 16, 612, 16, 813, 16, 14467, 1769, 203, 565, 327, 3360, 1105, 18, 3015, 12, 11451, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol pragma solidity ^0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/AddressUtils.sol pragma solidity ^0.4.24; /** * 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/upgradeability/EternalStorage.sol pragma solidity 0.4.24; /** * @title EternalStorage * @dev This contract holds all the necessary state variables to carry out the storage of any contract. */ contract EternalStorage { mapping(bytes32 => uint256) internal uintStorage; mapping(bytes32 => string) internal stringStorage; mapping(bytes32 => address) internal addressStorage; mapping(bytes32 => bytes) internal bytesStorage; mapping(bytes32 => bool) internal boolStorage; mapping(bytes32 => int256) internal intStorage; } // File: contracts/interfaces/IBridgeValidators.sol pragma solidity 0.4.24; interface IBridgeValidators { function isValidator(address _validator) external view returns (bool); function requiredSignatures() external view returns (uint256); function owner() external view returns (address); } // File: contracts/upgradeable_contracts/ValidatorStorage.sol pragma solidity 0.4.24; contract ValidatorStorage { bytes32 internal constant VALIDATOR_CONTRACT = 0x5a74bb7e202fb8e4bf311841c7d64ec19df195fee77d7e7ae749b27921b6ddfe; // keccak256(abi.encodePacked("validatorContract")) } // File: contracts/upgradeable_contracts/Validatable.sol pragma solidity 0.4.24; contract Validatable is EternalStorage, ValidatorStorage { function validatorContract() public view returns (IBridgeValidators) { return IBridgeValidators(addressStorage[VALIDATOR_CONTRACT]); } modifier onlyValidator() { require(validatorContract().isValidator(msg.sender)); /* solcov ignore next */ _; } function requiredSignatures() public view returns (uint256) { return validatorContract().requiredSignatures(); } } // File: contracts/libraries/Message.sol pragma solidity 0.4.24; library Message { function addressArrayContains(address[] array, address value) internal pure returns (bool) { for (uint256 i = 0; i < array.length; i++) { if (array[i] == value) { return true; } } return false; } // layout of message :: bytes: // offset 0: 32 bytes :: uint256 - message length // offset 32: 20 bytes :: address - recipient address // offset 52: 32 bytes :: uint256 - value // offset 84: 32 bytes :: bytes32 - transaction hash // offset 116: 20 bytes :: address - contract address to prevent double spending // mload always reads 32 bytes. // so we can and have to start reading recipient at offset 20 instead of 32. // if we were to read at 32 the address would contain part of value and be corrupted. // when reading from offset 20 mload will read 12 bytes (most of them zeros) followed // by the 20 recipient address bytes and correctly convert it into an address. // this saves some storage/gas over the alternative solution // which is padding address to 32 bytes and reading recipient at offset 32. // for more details see discussion in: // https://github.com/paritytech/parity-bridge/issues/61 function parseMessage(bytes message) internal pure returns (address recipient, uint256 amount, bytes32 txHash, address contractAddress) { require(isMessageValid(message)); assembly { recipient := mload(add(message, 20)) amount := mload(add(message, 52)) txHash := mload(add(message, 84)) contractAddress := mload(add(message, 104)) } } function isMessageValid(bytes _msg) internal pure returns (bool) { return _msg.length == requiredMessageLength(); } function requiredMessageLength() internal pure returns (uint256) { return 104; } function recoverAddressFromSignedMessage(bytes signature, bytes message, bool isAMBMessage) internal pure returns (address) { require(signature.length == 65); bytes32 r; bytes32 s; bytes1 v; assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := mload(add(signature, 0x60)) } require(uint8(v) == 27 || uint8(v) == 28); require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0); return ecrecover(hashMessage(message, isAMBMessage), uint8(v), r, s); } function hashMessage(bytes message, bool isAMBMessage) internal pure returns (bytes32) { bytes memory prefix = "\x19Ethereum Signed Message:\n"; if (isAMBMessage) { return keccak256(abi.encodePacked(prefix, uintToString(message.length), message)); } else { string memory msgLength = "104"; return keccak256(abi.encodePacked(prefix, msgLength, message)); } } /** * @dev Validates provided signatures, only first requiredSignatures() number * of signatures are going to be validated, these signatures should be from different validators. * @param _message bytes message used to generate signatures * @param _signatures bytes blob with signatures to be validated. * First byte X is a number of signatures in a blob, * next X bytes are v components of signatures, * next 32 * X bytes are r components of signatures, * next 32 * X bytes are s components of signatures. * @param _validatorContract contract, which conforms to the IBridgeValidators interface, * where info about current validators and required signatures is stored. * @param isAMBMessage true if _message is an AMB message with arbitrary length. */ function hasEnoughValidSignatures( bytes _message, bytes _signatures, IBridgeValidators _validatorContract, bool isAMBMessage ) internal view { require(isAMBMessage || isMessageValid(_message)); uint256 requiredSignatures = _validatorContract.requiredSignatures(); uint256 amount; assembly { amount := and(mload(add(_signatures, 1)), 0xff) } require(amount >= requiredSignatures); bytes32 hash = hashMessage(_message, isAMBMessage); address[] memory encounteredAddresses = new address[](requiredSignatures); for (uint256 i = 0; i < requiredSignatures; i++) { uint8 v; bytes32 r; bytes32 s; uint256 posr = 33 + amount + 32 * i; uint256 poss = posr + 32 * amount; assembly { v := mload(add(_signatures, add(2, i))) r := mload(add(_signatures, posr)) s := mload(add(_signatures, poss)) } address recoveredAddress = ecrecover(hash, v, r, s); require(_validatorContract.isValidator(recoveredAddress)); require(!addressArrayContains(encounteredAddresses, recoveredAddress)); encounteredAddresses[i] = recoveredAddress; } } function uintToString(uint256 i) internal pure returns (string) { if (i == 0) return "0"; uint256 j = i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length - 1; while (i != 0) { bstr[k--] = bytes1(48 + (i % 10)); i /= 10; } return string(bstr); } } // File: contracts/upgradeable_contracts/MessageRelay.sol pragma solidity 0.4.24; contract MessageRelay is EternalStorage { function relayedMessages(bytes32 _txHash) public view returns (bool) { return boolStorage[keccak256(abi.encodePacked("relayedMessages", _txHash))]; } function setRelayedMessages(bytes32 _txHash, bool _status) internal { boolStorage[keccak256(abi.encodePacked("relayedMessages", _txHash))] = _status; } } // File: contracts/interfaces/IUpgradeabilityOwnerStorage.sol pragma solidity 0.4.24; interface IUpgradeabilityOwnerStorage { function upgradeabilityOwner() external view returns (address); } // File: contracts/upgradeable_contracts/Upgradeable.sol pragma solidity 0.4.24; contract Upgradeable { // Avoid using onlyUpgradeabilityOwner name to prevent issues with implementation from proxy contract modifier onlyIfUpgradeabilityOwner() { require(msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner()); /* solcov ignore next */ _; } } // File: contracts/upgradeable_contracts/Initializable.sol pragma solidity 0.4.24; contract Initializable is EternalStorage { bytes32 internal constant INITIALIZED = 0x0a6f646cd611241d8073675e00d1a1ff700fbf1b53fcf473de56d1e6e4b714ba; // keccak256(abi.encodePacked("isInitialized")) function setInitialize() internal { boolStorage[INITIALIZED] = true; } function isInitialized() public view returns (bool) { return boolStorage[INITIALIZED]; } } // File: contracts/upgradeable_contracts/InitializableBridge.sol pragma solidity 0.4.24; contract InitializableBridge is Initializable { bytes32 internal constant DEPLOYED_AT_BLOCK = 0xb120ceec05576ad0c710bc6e85f1768535e27554458f05dcbb5c65b8c7a749b0; // keccak256(abi.encodePacked("deployedAtBlock")) function deployedAtBlock() external view returns (uint256) { return uintStorage[DEPLOYED_AT_BLOCK]; } } // File: contracts/upgradeable_contracts/Ownable.sol pragma solidity 0.4.24; /** * @title Ownable * @dev This contract has an owner address providing basic authorization control */ contract Ownable is EternalStorage { bytes4 internal constant UPGRADEABILITY_OWNER = 0x6fde8202; // upgradeabilityOwner() /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event OwnershipTransferred(address previousOwner, address newOwner); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner()); /* solcov ignore next */ _; } /** * @dev Throws if called by any account other than contract itself or owner. */ modifier onlyRelevantSender() { // proxy owner if used through proxy, address(0) otherwise require( !address(this).call(abi.encodeWithSelector(UPGRADEABILITY_OWNER)) || // covers usage without calling through storage proxy msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner() || // covers usage through regular proxy calls msg.sender == address(this) // covers calls through upgradeAndCall proxy method ); /* solcov ignore next */ _; } bytes32 internal constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; // keccak256(abi.encodePacked("owner")) /** * @dev Tells the address of the owner * @return the address of the owner */ function owner() public view returns (address) { return addressStorage[OWNER]; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner the address to transfer ownership to. */ function transferOwnership(address newOwner) external onlyOwner { _setOwner(newOwner); } /** * @dev Sets a new owner address */ function _setOwner(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(owner(), newOwner); addressStorage[OWNER] = newOwner; } } // File: contracts/upgradeable_contracts/Sacrifice.sol pragma solidity 0.4.24; contract Sacrifice { constructor(address _recipient) public payable { selfdestruct(_recipient); } } // File: contracts/libraries/Address.sol pragma solidity 0.4.24; /** * @title Address * @dev Helper methods for Address type. */ library Address { /** * @dev Try to send native tokens to the address. If it fails, it will force the transfer by creating a selfdestruct contract * @param _receiver address that will receive the native tokens * @param _value the amount of native tokens to send */ function safeSendValue(address _receiver, uint256 _value) internal { if (!_receiver.send(_value)) { (new Sacrifice).value(_value)(_receiver); } } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: contracts/interfaces/ERC677.sol pragma solidity 0.4.24; contract ERC677 is ERC20 { event Transfer(address indexed from, address indexed to, uint256 value, bytes data); function transferAndCall(address, uint256, bytes) external returns (bool); function increaseAllowance(address spender, uint256 addedValue) public returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool); } contract LegacyERC20 { function transfer(address _spender, uint256 _value) public; // returns (bool); function transferFrom(address _owner, address _spender, uint256 _value) public; // returns (bool); } // File: contracts/libraries/SafeERC20.sol pragma solidity 0.4.24; /** * @title SafeERC20 * @dev Helper methods for safe token transfers. * Functions perform additional checks to be sure that token transfer really happened. */ library SafeERC20 { using SafeMath for uint256; /** * @dev Same as ERC20.transfer(address,uint256) but with extra consistency checks. * @param _token address of the token contract * @param _to address of the receiver * @param _value amount of tokens to send */ function safeTransfer(address _token, address _to, uint256 _value) internal { LegacyERC20(_token).transfer(_to, _value); assembly { if returndatasize { returndatacopy(0, 0, 32) if iszero(mload(0)) { revert(0, 0) } } } } /** * @dev Same as ERC20.transferFrom(address,address,uint256) but with extra consistency checks. * @param _token address of the token contract * @param _from address of the sender * @param _value amount of tokens to send */ function safeTransferFrom(address _token, address _from, uint256 _value) internal { LegacyERC20(_token).transferFrom(_from, address(this), _value); assembly { if returndatasize { returndatacopy(0, 0, 32) if iszero(mload(0)) { revert(0, 0) } } } } } // File: contracts/upgradeable_contracts/Claimable.sol pragma solidity 0.4.24; /** * @title Claimable * @dev Implementation of the claiming utils that can be useful for withdrawing accidentally sent tokens that are not used in bridge operations. */ contract Claimable { using SafeERC20 for address; /** * Throws if a given address is equal to address(0) */ modifier validAddress(address _to) { require(_to != address(0)); /* solcov ignore next */ _; } /** * @dev Withdraws the erc20 tokens or native coins from this contract. * Caller should additionally check that the claimed token is not a part of bridge operations (i.e. that token != erc20token()). * @param _token address of the claimed token or address(0) for native coins. * @param _to address of the tokens/coins receiver. */ function claimValues(address _token, address _to) internal validAddress(_to) { if (_token == address(0)) { claimNativeCoins(_to); } else { claimErc20Tokens(_token, _to); } } /** * @dev Internal function for withdrawing all native coins from the contract. * @param _to address of the coins receiver. */ function claimNativeCoins(address _to) internal { uint256 value = address(this).balance; Address.safeSendValue(_to, value); } /** * @dev Internal function for withdrawing all tokens of ssome particular ERC20 contract from this contract. * @param _token address of the claimed ERC20 token. * @param _to address of the tokens receiver. */ function claimErc20Tokens(address _token, address _to) internal { ERC20Basic token = ERC20Basic(_token); uint256 balance = token.balanceOf(this); _token.safeTransfer(_to, balance); } } // File: contracts/upgradeable_contracts/VersionableBridge.sol pragma solidity 0.4.24; contract VersionableBridge { function getBridgeInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) { return (6, 1, 0); } /* solcov ignore next */ function getBridgeMode() external pure returns (bytes4); } // File: contracts/upgradeable_contracts/DecimalShiftBridge.sol pragma solidity 0.4.24; contract DecimalShiftBridge is EternalStorage { using SafeMath for uint256; bytes32 internal constant DECIMAL_SHIFT = 0x1e8ecaafaddea96ed9ac6d2642dcdfe1bebe58a930b1085842d8fc122b371ee5; // keccak256(abi.encodePacked("decimalShift")) /** * @dev Internal function for setting the decimal shift for bridge operations. * Decimal shift can be positive, negative, or equal to zero. * It has the following meaning: N tokens in the foreign chain are equivalent to N * pow(10, shift) tokens on the home side. * @param _shift new value of decimal shift. */ function _setDecimalShift(int256 _shift) internal { // since 1 wei * 10**77 > 2**255, it does not make any sense to use higher values require(_shift > -77 && _shift < 77); uintStorage[DECIMAL_SHIFT] = uint256(_shift); } /** * @dev Returns the value of foreign-to-home decimal shift. * @return decimal shift. */ function decimalShift() public view returns (int256) { return int256(uintStorage[DECIMAL_SHIFT]); } /** * @dev Converts the amount of home tokens into the equivalent amount of foreign tokens. * @param _value amount of home tokens. * @return equivalent amount of foreign tokens. */ function _unshiftValue(uint256 _value) internal view returns (uint256) { return _shiftUint(_value, -decimalShift()); } /** * @dev Converts the amount of foreign tokens into the equivalent amount of home tokens. * @param _value amount of foreign tokens. * @return equivalent amount of home tokens. */ function _shiftValue(uint256 _value) internal view returns (uint256) { return _shiftUint(_value, decimalShift()); } /** * @dev Calculates _value * pow(10, _shift). * @param _value amount of tokens. * @param _shift decimal shift to apply. * @return shifted value. */ function _shiftUint(uint256 _value, int256 _shift) private pure returns (uint256) { if (_shift == 0) { return _value; } if (_shift > 0) { return _value.mul(10**uint256(_shift)); } return _value.div(10**uint256(-_shift)); } } // File: contracts/upgradeable_contracts/BasicBridge.sol pragma solidity 0.4.24; contract BasicBridge is InitializableBridge, Validatable, Ownable, Upgradeable, Claimable, VersionableBridge, DecimalShiftBridge { event GasPriceChanged(uint256 gasPrice); event RequiredBlockConfirmationChanged(uint256 requiredBlockConfirmations); bytes32 internal constant GAS_PRICE = 0x55b3774520b5993024893d303890baa4e84b1244a43c60034d1ced2d3cf2b04b; // keccak256(abi.encodePacked("gasPrice")) bytes32 internal constant REQUIRED_BLOCK_CONFIRMATIONS = 0x916daedf6915000ff68ced2f0b6773fe6f2582237f92c3c95bb4d79407230071; // keccak256(abi.encodePacked("requiredBlockConfirmations")) /** * @dev Public setter for fallback gas price value. Only bridge owner can call this method. * @param _gasPrice new value for the gas price. */ function setGasPrice(uint256 _gasPrice) external onlyOwner { _setGasPrice(_gasPrice); } function gasPrice() external view returns (uint256) { return uintStorage[GAS_PRICE]; } function setRequiredBlockConfirmations(uint256 _blockConfirmations) external onlyOwner { _setRequiredBlockConfirmations(_blockConfirmations); } function _setRequiredBlockConfirmations(uint256 _blockConfirmations) internal { require(_blockConfirmations > 0); uintStorage[REQUIRED_BLOCK_CONFIRMATIONS] = _blockConfirmations; emit RequiredBlockConfirmationChanged(_blockConfirmations); } function requiredBlockConfirmations() external view returns (uint256) { return uintStorage[REQUIRED_BLOCK_CONFIRMATIONS]; } /** * @dev Internal function for updating fallback gas price value. * @param _gasPrice new value for the gas price, zero gas price is allowed. */ function _setGasPrice(uint256 _gasPrice) internal { uintStorage[GAS_PRICE] = _gasPrice; emit GasPriceChanged(_gasPrice); } } // File: contracts/upgradeable_contracts/BasicTokenBridge.sol pragma solidity 0.4.24; contract BasicTokenBridge is EternalStorage, Ownable, DecimalShiftBridge { using SafeMath for uint256; event DailyLimitChanged(uint256 newLimit); event ExecutionDailyLimitChanged(uint256 newLimit); bytes32 internal constant MIN_PER_TX = 0xbbb088c505d18e049d114c7c91f11724e69c55ad6c5397e2b929e68b41fa05d1; // keccak256(abi.encodePacked("minPerTx")) bytes32 internal constant MAX_PER_TX = 0x0f8803acad17c63ee38bf2de71e1888bc7a079a6f73658e274b08018bea4e29c; // keccak256(abi.encodePacked("maxPerTx")) bytes32 internal constant DAILY_LIMIT = 0x4a6a899679f26b73530d8cf1001e83b6f7702e04b6fdb98f3c62dc7e47e041a5; // keccak256(abi.encodePacked("dailyLimit")) bytes32 internal constant EXECUTION_MAX_PER_TX = 0xc0ed44c192c86d1cc1ba51340b032c2766b4a2b0041031de13c46dd7104888d5; // keccak256(abi.encodePacked("executionMaxPerTx")) bytes32 internal constant EXECUTION_DAILY_LIMIT = 0x21dbcab260e413c20dc13c28b7db95e2b423d1135f42bb8b7d5214a92270d237; // keccak256(abi.encodePacked("executionDailyLimit")) function totalSpentPerDay(uint256 _day) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _day))]; } function totalExecutedPerDay(uint256 _day) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _day))]; } function dailyLimit() public view returns (uint256) { return uintStorage[DAILY_LIMIT]; } function executionDailyLimit() public view returns (uint256) { return uintStorage[EXECUTION_DAILY_LIMIT]; } function maxPerTx() public view returns (uint256) { return uintStorage[MAX_PER_TX]; } function executionMaxPerTx() public view returns (uint256) { return uintStorage[EXECUTION_MAX_PER_TX]; } function minPerTx() public view returns (uint256) { return uintStorage[MIN_PER_TX]; } function withinLimit(uint256 _amount) public view returns (bool) { uint256 nextLimit = totalSpentPerDay(getCurrentDay()).add(_amount); return dailyLimit() >= nextLimit && _amount <= maxPerTx() && _amount >= minPerTx(); } function withinExecutionLimit(uint256 _amount) public view returns (bool) { uint256 nextLimit = totalExecutedPerDay(getCurrentDay()).add(_amount); return executionDailyLimit() >= nextLimit && _amount <= executionMaxPerTx(); } function getCurrentDay() public view returns (uint256) { return now / 1 days; } function addTotalSpentPerDay(uint256 _day, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _day))] = totalSpentPerDay(_day).add(_value); } function addTotalExecutedPerDay(uint256 _day, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _day))] = totalExecutedPerDay(_day).add(_value); } function setDailyLimit(uint256 _dailyLimit) external onlyOwner { require(_dailyLimit > maxPerTx() || _dailyLimit == 0); uintStorage[DAILY_LIMIT] = _dailyLimit; emit DailyLimitChanged(_dailyLimit); } function setExecutionDailyLimit(uint256 _dailyLimit) external onlyOwner { require(_dailyLimit > executionMaxPerTx() || _dailyLimit == 0); uintStorage[EXECUTION_DAILY_LIMIT] = _dailyLimit; emit ExecutionDailyLimitChanged(_dailyLimit); } function setExecutionMaxPerTx(uint256 _maxPerTx) external onlyOwner { require(_maxPerTx < executionDailyLimit()); uintStorage[EXECUTION_MAX_PER_TX] = _maxPerTx; } function setMaxPerTx(uint256 _maxPerTx) external onlyOwner { require(_maxPerTx == 0 || (_maxPerTx > minPerTx() && _maxPerTx < dailyLimit())); uintStorage[MAX_PER_TX] = _maxPerTx; } function setMinPerTx(uint256 _minPerTx) external onlyOwner { require(_minPerTx > 0 && _minPerTx < dailyLimit() && _minPerTx < maxPerTx()); uintStorage[MIN_PER_TX] = _minPerTx; } /** * @dev Retrieves maximum available bridge amount per one transaction taking into account maxPerTx() and dailyLimit() parameters. * @return minimum of maxPerTx parameter and remaining daily quota. */ function maxAvailablePerTx() public view returns (uint256) { uint256 _maxPerTx = maxPerTx(); uint256 _dailyLimit = dailyLimit(); uint256 _spent = totalSpentPerDay(getCurrentDay()); uint256 _remainingOutOfDaily = _dailyLimit > _spent ? _dailyLimit - _spent : 0; return _maxPerTx < _remainingOutOfDaily ? _maxPerTx : _remainingOutOfDaily; } function _setLimits(uint256[3] _limits) internal { require( _limits[2] > 0 && // minPerTx > 0 _limits[1] > _limits[2] && // maxPerTx > minPerTx _limits[0] > _limits[1] // dailyLimit > maxPerTx ); uintStorage[DAILY_LIMIT] = _limits[0]; uintStorage[MAX_PER_TX] = _limits[1]; uintStorage[MIN_PER_TX] = _limits[2]; emit DailyLimitChanged(_limits[0]); } function _setExecutionLimits(uint256[2] _limits) internal { require(_limits[1] < _limits[0]); // foreignMaxPerTx < foreignDailyLimit uintStorage[EXECUTION_DAILY_LIMIT] = _limits[0]; uintStorage[EXECUTION_MAX_PER_TX] = _limits[1]; emit ExecutionDailyLimitChanged(_limits[0]); } } // File: contracts/upgradeable_contracts/BasicForeignBridge.sol pragma solidity 0.4.24; contract BasicForeignBridge is EternalStorage, Validatable, BasicBridge, BasicTokenBridge, MessageRelay { /// triggered when relay of deposit from HomeBridge is complete event RelayedMessage(address recipient, uint256 value, bytes32 transactionHash); event UserRequestForAffirmation(address recipient, uint256 value); /** * @dev Validates provided signatures and relays a given message * @param message bytes to be relayed * @param signatures bytes blob with signatures to be validated */ function executeSignatures(bytes message, bytes signatures) external { Message.hasEnoughValidSignatures(message, signatures, validatorContract(), false); address recipient; uint256 amount; bytes32 txHash; address contractAddress; (recipient, amount, txHash, contractAddress) = Message.parseMessage(message); if (withinExecutionLimit(amount)) { require(contractAddress == address(this)); require(!relayedMessages(txHash)); setRelayedMessages(txHash, true); require(onExecuteMessage(recipient, amount, txHash)); emit RelayedMessage(recipient, amount, txHash); } else { onFailedMessage(recipient, amount, txHash); } } /** * @dev Internal function for updating fallback gas price value. * @param _gasPrice new value for the gas price, zero gas price is not allowed. */ function _setGasPrice(uint256 _gasPrice) internal { require(_gasPrice > 0); super._setGasPrice(_gasPrice); } /* solcov ignore next */ function onExecuteMessage(address, uint256, bytes32) internal returns (bool); /* solcov ignore next */ function onFailedMessage(address, uint256, bytes32) internal; } // File: contracts/upgradeable_contracts/ERC20Bridge.sol pragma solidity 0.4.24; contract ERC20Bridge is BasicForeignBridge { bytes32 internal constant ERC20_TOKEN = 0x15d63b18dbc21bf4438b7972d80076747e1d93c4f87552fe498c90cbde51665e; // keccak256(abi.encodePacked("erc20token")) function erc20token() public view returns (ERC20) { return ERC20(addressStorage[ERC20_TOKEN]); } function setErc20token(address _token) internal { require(AddressUtils.isContract(_token)); addressStorage[ERC20_TOKEN] = _token; } function relayTokens(address _receiver, uint256 _amount) external { require(_receiver != address(0)); require(_receiver != address(this)); require(_amount > 0); require(withinLimit(_amount)); addTotalSpentPerDay(getCurrentDay(), _amount); erc20token().transferFrom(msg.sender, address(this), _amount); emit UserRequestForAffirmation(_receiver, _amount); } } // File: contracts/upgradeable_contracts/OtherSideBridgeStorage.sol pragma solidity 0.4.24; contract OtherSideBridgeStorage is EternalStorage { bytes32 internal constant BRIDGE_CONTRACT = 0x71483949fe7a14d16644d63320f24d10cf1d60abecc30cc677a340e82b699dd2; // keccak256(abi.encodePacked("bridgeOnOtherSide")) function _setBridgeContractOnOtherSide(address _bridgeContract) internal { require(_bridgeContract != address(0)); addressStorage[BRIDGE_CONTRACT] = _bridgeContract; } function bridgeContractOnOtherSide() internal view returns (address) { return addressStorage[BRIDGE_CONTRACT]; } } // File: contracts/upgradeable_contracts/erc20_to_native/ForeignBridgeErcToNative.sol pragma solidity 0.4.24; contract ForeignBridgeErcToNative is ERC20Bridge, OtherSideBridgeStorage { function initialize( address _validatorContract, address _erc20token, uint256 _requiredBlockConfirmations, uint256 _gasPrice, uint256[3] _dailyLimitMaxPerTxMinPerTxArray, // [ 0 = _dailyLimit, 1 = _maxPerTx, 2 = _minPerTx ] uint256[2] _homeDailyLimitHomeMaxPerTxArray, //[ 0 = _homeDailyLimit, 1 = _homeMaxPerTx ] address _owner, int256 _decimalShift, address _bridgeOnOtherSide ) external onlyRelevantSender returns (bool) { require(!isInitialized()); require(AddressUtils.isContract(_validatorContract)); addressStorage[VALIDATOR_CONTRACT] = _validatorContract; setErc20token(_erc20token); uintStorage[DEPLOYED_AT_BLOCK] = block.number; _setRequiredBlockConfirmations(_requiredBlockConfirmations); _setGasPrice(_gasPrice); _setLimits(_dailyLimitMaxPerTxMinPerTxArray); _setExecutionLimits(_homeDailyLimitHomeMaxPerTxArray); _setDecimalShift(_decimalShift); _setOwner(_owner); _setBridgeContractOnOtherSide(_bridgeOnOtherSide); setInitialize(); return isInitialized(); } function getBridgeMode() external pure returns (bytes4 _data) { return 0x18762d46; // bytes4(keccak256(abi.encodePacked("erc-to-native-core"))) } /** * @dev Withdraws the erc20 tokens or native coins from this contract. * @param _token address of the claimed token or address(0) for native coins. * @param _to address of the tokens/coins receiver. */ function claimTokens(address _token, address _to) external onlyIfUpgradeabilityOwner { // Since bridged tokens are locked at this contract, it is not allowed to claim them with the use of claimTokens function require(_token != address(erc20token())); claimValues(_token, _to); } function onExecuteMessage( address _recipient, uint256 _amount, bytes32 /*_txHash*/ ) internal returns (bool) { addTotalExecutedPerDay(getCurrentDay(), _amount); return erc20token().transfer(_recipient, _unshiftValue(_amount)); } function onFailedMessage(address, uint256, bytes32) internal { revert(); } function relayTokens(address _receiver, uint256 _amount) external { require(_receiver != bridgeContractOnOtherSide()); require(_receiver != address(0)); require(_receiver != address(this)); require(_amount > 0); require(withinLimit(_amount)); addTotalSpentPerDay(getCurrentDay(), _amount); erc20token().transferFrom(msg.sender, address(this), _amount); emit UserRequestForAffirmation(_receiver, _amount); } } // File: contracts/interfaces/IInterestReceiver.sol pragma solidity 0.4.24; interface IInterestReceiver { function onInterestReceived(address _token) external; } // File: contracts/upgradeable_contracts/erc20_to_native/InterestConnector.sol pragma solidity 0.4.24; /** * @title InterestConnector * @dev This contract gives an abstract way of receiving interest on locked tokens. */ contract InterestConnector is Ownable, ERC20Bridge { event PaidInterest(address indexed token, address to, uint256 value); /** * @dev Throws if interest is bearing not enabled. * @param token address, for which interest should be enabled. */ modifier interestEnabled(address token) { require(isInterestEnabled(token)); /* solcov ignore next */ _; } /** * @dev Ensures that caller is an EOA. * Functions with such modifier cannot be called from other contract (as well as from GSN-like approaches) */ modifier onlyEOA { // solhint-disable-next-line avoid-tx-origin require(msg.sender == tx.origin); /* solcov ignore next */ _; } /** * @dev Tells if interest earning was enabled for particular token. * @return true, if interest bearing is enabled. */ function isInterestEnabled(address _token) public view returns (bool) { return boolStorage[keccak256(abi.encodePacked("interestEnabled", _token))]; } /** * @dev Initializes interest receiving functionality. * Only owner can call this method. * @param _token address of the token for interest earning. * @param _minCashThreshold minimum amount of underlying tokens that are not invested. * @param _minInterestPaid minimum amount of interest that can be paid in a single call. */ function initializeInterest( address _token, uint256 _minCashThreshold, uint256 _minInterestPaid, address _interestReceiver ) external onlyOwner { require(_isInterestSupported(_token)); require(!isInterestEnabled(_token)); _setInterestEnabled(_token, true); _setMinCashThreshold(_token, _minCashThreshold); _setMinInterestPaid(_token, _minInterestPaid); _setInterestReceiver(_token, _interestReceiver); } /** * @dev Sets minimum amount of tokens that cannot be invested. * Only owner can call this method. * @param _token address of the token contract. * @param _minCashThreshold minimum amount of underlying tokens that are not invested. */ function setMinCashThreshold(address _token, uint256 _minCashThreshold) external onlyOwner { _setMinCashThreshold(_token, _minCashThreshold); } /** * @dev Tells minimum amount of tokens that are not being invested. * @param _token address of the invested token contract. * @return amount of tokens. */ function minCashThreshold(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("minCashThreshold", _token))]; } /** * @dev Sets lower limit for the paid interest amount. * Only owner can call this method. * @param _token address of the token contract. * @param _minInterestPaid minimum amount of interest paid in a single call. */ function setMinInterestPaid(address _token, uint256 _minInterestPaid) external onlyOwner { _setMinInterestPaid(_token, _minInterestPaid); } /** * @dev Tells minimum amount of paid interest in a single call. * @param _token address of the invested token contract. * @return paid interest minimum limit. */ function minInterestPaid(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("minInterestPaid", _token))]; } /** * @dev Internal function that disables interest for locked funds. * Only owner can call this method. * @param _token of token to disable interest for. */ function disableInterest(address _token) external onlyOwner { _withdraw(_token, uint256(-1)); _setInterestEnabled(_token, false); } /** * @dev Tells configured address of the interest receiver. * @param _token address of the invested token contract. * @return address of the interest receiver. */ function interestReceiver(address _token) public view returns (address) { return addressStorage[keccak256(abi.encodePacked("interestReceiver", _token))]; } /** * Updates the interest receiver address. * Only owner can call this method. * @param _token address of the invested token contract. * @param _receiver new receiver address. */ function setInterestReceiver(address _token, address _receiver) external onlyOwner { _setInterestReceiver(_token, _receiver); } /** * @dev Pays collected interest for the specific underlying token. * Requires interest for the given token to be enabled. * @param _token address of the token contract. */ function payInterest(address _token) external onlyEOA interestEnabled(_token) { uint256 interest = interestAmount(_token); require(interest >= minInterestPaid(_token)); uint256 redeemed = _safeWithdrawTokens(_token, interest); _transferInterest(_token, redeemed); } /** * @dev Tells the amount of underlying tokens that are currently invested. * @param _token address of the token contract. * @return amount of underlying tokens. */ function investedAmount(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("investedAmount", _token))]; } /** * @dev Invests all excess tokens. * Requires interest for the given token to be enabled. * @param _token address of the token contract considered. */ function invest(address _token) public interestEnabled(_token) { uint256 balance = _selfBalance(_token); uint256 minCash = minCashThreshold(_token); require(balance > minCash); uint256 amount = balance - minCash; _setInvestedAmount(_token, investedAmount(_token).add(amount)); _invest(_token, amount); } /** * @dev Internal function for transferring interest. * Calls a callback on the receiver, if it is a contract. * @param _token address of the underlying token contract. * @param _amount amount of collected tokens that should be sent. */ function _transferInterest(address _token, uint256 _amount) internal { address receiver = interestReceiver(_token); require(receiver != address(0)); ERC20(_token).transfer(receiver, _amount); if (AddressUtils.isContract(receiver)) { IInterestReceiver(receiver).onInterestReceived(_token); } emit PaidInterest(_token, receiver, _amount); } /** * @dev Internal function for setting interest enabled flag for some token. * @param _token address of the token contract. * @param _enabled true to enable interest earning, false to disable. */ function _setInterestEnabled(address _token, bool _enabled) internal { boolStorage[keccak256(abi.encodePacked("interestEnabled", _token))] = _enabled; } /** * @dev Internal function for setting the amount of underlying tokens that are currently invested. * @param _token address of the token contract. * @param _amount new amount of invested tokens. */ function _setInvestedAmount(address _token, uint256 _amount) internal { uintStorage[keccak256(abi.encodePacked("investedAmount", _token))] = _amount; } /** * @dev Internal function for withdrawing some amount of the invested tokens. * Reverts if given amount cannot be withdrawn. * @param _token address of the token contract withdrawn. * @param _amount amount of requested tokens to be withdrawn. */ function _withdraw(address _token, uint256 _amount) internal { if (_amount == 0) return; uint256 invested = investedAmount(_token); uint256 withdrawal = _amount > invested ? invested : _amount; uint256 redeemed = _safeWithdrawTokens(_token, withdrawal); _setInvestedAmount(_token, invested > redeemed ? invested - redeemed : 0); } /** * @dev Internal function for safe withdrawal of invested tokens. * Reverts if given amount cannot be withdrawn. * Additionally verifies that at least _amount of tokens were withdrawn. * @param _token address of the token contract withdrawn. * @param _amount amount of requested tokens to be withdrawn. */ function _safeWithdrawTokens(address _token, uint256 _amount) private returns (uint256) { uint256 balance = _selfBalance(_token); _withdrawTokens(_token, _amount); uint256 redeemed = _selfBalance(_token) - balance; require(redeemed >= _amount); return redeemed; } /** * @dev Internal function for setting minimum amount of tokens that cannot be invested. * @param _token address of the token contract. * @param _minCashThreshold minimum amount of underlying tokens that are not invested. */ function _setMinCashThreshold(address _token, uint256 _minCashThreshold) internal { uintStorage[keccak256(abi.encodePacked("minCashThreshold", _token))] = _minCashThreshold; } /** * @dev Internal function for setting lower limit for paid interest amount. * @param _token address of the token contract. * @param _minInterestPaid minimum amount of interest paid in a single call. */ function _setMinInterestPaid(address _token, uint256 _minInterestPaid) internal { uintStorage[keccak256(abi.encodePacked("minInterestPaid", _token))] = _minInterestPaid; } /** * @dev Internal function for setting interest receiver address. * @param _token address of the invested token contract. * @param _receiver address of the interest receiver. */ function _setInterestReceiver(address _token, address _receiver) internal { require(_receiver != address(this)); addressStorage[keccak256(abi.encodePacked("interestReceiver", _token))] = _receiver; } /** * @dev Tells this contract balance of some specific token contract * @param _token address of the token contract. * @return contract balance. */ function _selfBalance(address _token) internal view returns (uint256) { return ERC20(_token).balanceOf(address(this)); } function _isInterestSupported(address _token) internal pure returns (bool); function _invest(address _token, uint256 _amount) internal; function _withdrawTokens(address _token, uint256 _amount) internal; function interestAmount(address _token) public view returns (uint256); } // File: contracts/interfaces/ICToken.sol pragma solidity 0.4.24; interface ICToken { function mint(uint256 mintAmount) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function balanceOf(address account) external view returns (uint256); function balanceOfUnderlying(address account) external view returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 borrowAmount) external returns (uint256); } // File: contracts/interfaces/IComptroller.sol pragma solidity 0.4.24; interface IComptroller { function claimComp(address[] holders, address[] cTokens, bool borrowers, bool suppliers) external; } // File: contracts/upgradeable_contracts/erc20_to_native/CompoundConnector.sol pragma solidity 0.4.24; /** * @title CompoundConnector * @dev This contract allows to partially invest locked Dai tokens into Compound protocol. */ contract CompoundConnector is InterestConnector { uint256 internal constant SUCCESS = 0; /** * @dev Tells the address of the DAI token in the Ethereum Mainnet. */ function daiToken() public pure returns (ERC20) { return ERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); } /** * @dev Tells the address of the cDAI token in the Ethereum Mainnet. */ function cDaiToken() public pure returns (ICToken) { return ICToken(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643); } /** * @dev Tells the address of the Comptroller contract in the Ethereum Mainnet. */ function comptroller() public pure returns (IComptroller) { return IComptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); } /** * @dev Tells the address of the COMP token in the Ethereum Mainnet. */ function compToken() public pure returns (ERC20) { return ERC20(0xc00e94Cb662C3520282E6f5717214004A7f26888); } /** * @dev Tells the current earned interest amount. * @param _token address of the underlying token contract. * @return total amount of interest that can be withdrawn now. */ function interestAmount(address _token) public view returns (uint256) { uint256 underlyingBalance = cDaiToken().balanceOfUnderlying(address(this)); // 1 DAI is reserved for possible truncation/round errors uint256 invested = investedAmount(_token) + 1 ether; return underlyingBalance > invested ? underlyingBalance - invested : 0; } /** * @dev Tells if interest earning is supported for the specific token contract. * @param _token address of the token contract. * @return true, if interest earning is supported. */ function _isInterestSupported(address _token) internal pure returns (bool) { return _token == address(daiToken()); } /** * @dev Invests the given amount of tokens to the Compound protocol. * Converts _amount of TOKENs into X cTOKENs. * @param _token address of the token contract. * @param _amount amount of tokens to invest. */ function _invest(address _token, uint256 _amount) internal { (_token); daiToken().approve(address(cDaiToken()), _amount); require(cDaiToken().mint(_amount) == SUCCESS); } /** * @dev Withdraws at least the given amount of tokens from the Compound protocol. * Converts X cTOKENs into _amount of TOKENs. * @param _token address of the token contract. * @param _amount minimal amount of tokens to withdraw. */ function _withdrawTokens(address _token, uint256 _amount) internal { (_token); require(cDaiToken().redeemUnderlying(_amount) == SUCCESS); } /** * @dev Claims Comp token and transfers it to the associated interest receiver. */ function claimCompAndPay() external onlyEOA { address[] memory holders = new address[](1); holders[0] = address(this); address[] memory markets = new address[](1); markets[0] = address(cDaiToken()); comptroller().claimComp(holders, markets, false, true); address comp = address(compToken()); uint256 interest = _selfBalance(comp); require(interest >= minInterestPaid(comp)); _transferInterest(comp, interest); } } // File: contracts/gsn/interfaces/IRelayRecipient.sol // SPDX-License-Identifier:MIT pragma solidity 0.4.24; /** * a contract must implement this interface in order to support relayed transaction. * It is better to inherit the BaseRelayRecipient as its implementation. */ contract IRelayRecipient { /** * return if the forwarder is trusted to forward relayed transactions to us. * the forwarder is required to verify the sender's signature, and verify * the call is not a replay. */ function isTrustedForwarder(address forwarder) public view returns (bool); /** * return the sender of this call. * if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes * of the msg.data. * otherwise, return `msg.sender` * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal view returns (address); /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise, return `msg.data` * should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly * signing or hashing the */ function _msgData() internal view returns (bytes memory); function versionRecipient() external view returns (string memory); } // File: contracts/gsn/BaseRelayRecipient.sol // SPDX-License-Identifier:MIT // solhint-disable no-inline-assembly pragma solidity 0.4.24; /** * A base contract to be inherited by any contract that want to receive relayed transactions * A subclass must use "_msgSender()" instead of "msg.sender" */ contract BaseRelayRecipient is IRelayRecipient { /** * return the sender of this call. * if the call came through our trusted forwarder, return the original sender. * otherwise, return `msg.sender`. * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal view returns (address ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // so we trust that the last bytes of msg.data are the verified sender address. // extract sender address from the end of msg.data assembly { ret := shr(96, calldataload(sub(calldatasize, 20))) } } else { return msg.sender; } } /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise, return `msg.data` * should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly * signing or hashing the */ function _msgData() internal view returns (bytes memory ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // we copy the msg.data , except the last 20 bytes (and update the total length) assembly { let ptr := mload(0x40) // copy only size-20 bytes let size := sub(calldatasize, 20) // structure RLP data as <offset> <length> <bytes> mstore(ptr, 0x20) mstore(add(ptr, 32), size) calldatacopy(add(ptr, 64), 0, size) return(ptr, add(size, 64)) } } else { return msg.data; } } } // File: contracts/gsn/interfaces/IKnowForwarderAddress.sol // SPDX-License-Identifier:MIT pragma solidity 0.4.24; interface IKnowForwarderAddress { /** * return the forwarder we trust to forward relayed transactions to us. * the forwarder is required to verify the sender's signature, and verify * the call is not a replay. */ function getTrustedForwarder() external view returns (address); } // File: contracts/upgradeable_contracts/GSNForeignERC20Bridge.sol pragma solidity 0.4.24; contract GSNForeignERC20Bridge is BasicForeignBridge, ERC20Bridge, BaseRelayRecipient, IKnowForwarderAddress { bytes32 internal constant PAYMASTER = 0xfefcc139ed357999ed60c6a013947328d52e7d9751e93fd0274a2bfae5cbcb12; // keccak256(abi.encodePacked("paymaster")) bytes32 internal constant TRUSTED_FORWARDER = 0x222cb212229f0f9bcd249029717af6845ea3d3a84f22b54e5744ac25ef224c92; // keccak256(abi.encodePacked("trustedForwarder")) function versionRecipient() external view returns (string memory) { return "1.0.1"; } function getTrustedForwarder() external view returns (address) { return addressStorage[TRUSTED_FORWARDER]; } function setTrustedForwarder(address _trustedForwarder) public onlyOwner { addressStorage[TRUSTED_FORWARDER] = _trustedForwarder; } function isTrustedForwarder(address forwarder) public view returns (bool) { return forwarder == addressStorage[TRUSTED_FORWARDER]; } function setPayMaster(address _paymaster) public onlyOwner { addressStorage[PAYMASTER] = _paymaster; } /** * @param message same as in `executeSignatures` * @param signatures same as in `executeSignatures` * @param maxTokensFee maximum amount of foreign tokens that user allows to take * as a commission */ function executeSignaturesGSN(bytes message, bytes signatures, uint256 maxTokensFee) external { // Allow only forwarder calls require(isTrustedForwarder(msg.sender), "invalid forwarder"); Message.hasEnoughValidSignatures(message, signatures, validatorContract(), false); address recipient; uint256 amount; bytes32 txHash; address contractAddress; (recipient, amount, txHash, contractAddress) = Message.parseMessage(message); if (withinExecutionLimit(amount)) { require(maxTokensFee <= amount); require(contractAddress == address(this)); require(!relayedMessages(txHash)); setRelayedMessages(txHash, true); require(onExecuteMessageGSN(recipient, amount, maxTokensFee)); emit RelayedMessage(recipient, amount, txHash); } else { onFailedMessage(recipient, amount, txHash); } } function onExecuteMessageGSN(address recipient, uint256 amount, uint256 fee) internal returns (bool) { addTotalExecutedPerDay(getCurrentDay(), amount); // Send maxTokensFee to paymaster ERC20 token = erc20token(); bool first = token.transfer(addressStorage[PAYMASTER], fee); bool second = token.transfer(recipient, amount - fee); return first && second; } } // File: contracts/upgradeable_contracts/erc20_to_native/XDaiForeignBridge.sol pragma solidity 0.4.24; contract XDaiForeignBridge is ForeignBridgeErcToNative, CompoundConnector, GSNForeignERC20Bridge { function initialize( address _validatorContract, address _erc20token, uint256 _requiredBlockConfirmations, uint256 _gasPrice, uint256[3] _dailyLimitMaxPerTxMinPerTxArray, // [ 0 = _dailyLimit, 1 = _maxPerTx, 2 = _minPerTx ] uint256[2] _homeDailyLimitHomeMaxPerTxArray, //[ 0 = _homeDailyLimit, 1 = _homeMaxPerTx ] address _owner, int256 _decimalShift, address _bridgeOnOtherSide ) external onlyRelevantSender returns (bool) { require(!isInitialized()); require(AddressUtils.isContract(_validatorContract)); require(_erc20token == address(daiToken())); require(_decimalShift == 0); addressStorage[VALIDATOR_CONTRACT] = _validatorContract; uintStorage[DEPLOYED_AT_BLOCK] = block.number; _setRequiredBlockConfirmations(_requiredBlockConfirmations); _setGasPrice(_gasPrice); _setLimits(_dailyLimitMaxPerTxMinPerTxArray); _setExecutionLimits(_homeDailyLimitHomeMaxPerTxArray); _setOwner(_owner); _setBridgeContractOnOtherSide(_bridgeOnOtherSide); setInitialize(); return isInitialized(); } function erc20token() public view returns (ERC20) { return daiToken(); } // selector 6a641d80 function migrateTo_6_1_0(address _interestReceiver) external { bytes32 upgradeStorage = 0x6a641d806674d4ce5e98c8fdab48e66c563660255f099d81d45fa2fe8ed9cc1d; // keccak256(abi.encodePacked('migrateTo_6_1_0(address)')) require(!boolStorage[upgradeStorage]); address dai = address(daiToken()); address comp = address(compToken()); _setInterestEnabled(dai, true); _setMinCashThreshold(dai, 1000000 ether); _setMinInterestPaid(dai, 1000 ether); _setInterestReceiver(dai, _interestReceiver); _setMinInterestPaid(comp, 1 ether); _setInterestReceiver(comp, _interestReceiver); invest(dai); boolStorage[upgradeStorage] = true; } function investDai() external { invest(address(daiToken())); } /** * @dev Withdraws the erc20 tokens or native coins from this contract. * @param _token address of the claimed token or address(0) for native coins. * @param _to address of the tokens/coins receiver. */ function claimTokens(address _token, address _to) external onlyIfUpgradeabilityOwner { // Since bridged tokens are locked at this contract, it is not allowed to claim them with the use of claimTokens function address bridgedToken = address(daiToken()); require(_token != address(bridgedToken)); require(_token != address(cDaiToken()) || !isInterestEnabled(bridgedToken)); require(_token != address(compToken()) || !isInterestEnabled(bridgedToken)); claimValues(_token, _to); } function onExecuteMessage( address _recipient, uint256 _amount, bytes32 /*_txHash*/ ) internal returns (bool) { addTotalExecutedPerDay(getCurrentDay(), _amount); ERC20 token = daiToken(); ensureEnoughTokens(token, _amount); return token.transfer(_recipient, _amount); } function onExecuteMessageGSN(address recipient, uint256 amount, uint256 fee) internal returns (bool) { ensureEnoughTokens(daiToken(), amount); return super.onExecuteMessageGSN(recipient, amount, fee); } function ensureEnoughTokens(ERC20 token, uint256 amount) internal { uint256 currentBalance = token.balanceOf(address(this)); if (currentBalance < amount) { uint256 withdrawAmount = (amount - currentBalance).add(minCashThreshold(address(token))); _withdraw(address(token), withdrawAmount); } } }
* return the msg.data of this call. if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes of the msg.data - so this method will strip those 20 bytes off. otherwise, return `msg.data` should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly signing or hashing the/ At this point we know that the sender is a trusted forwarder, we copy the msg.data , except the last 20 bytes (and update the total length) copy only size-20 bytes structure RLP data as <offset> <length> <bytes>
function _msgData() internal view returns (bytes memory ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { assembly { let ptr := mload(0x40) let size := sub(calldatasize, 20) mstore(ptr, 0x20) mstore(add(ptr, 32), size) calldatacopy(add(ptr, 64), 0, size) return(ptr, add(size, 64)) } return msg.data; } }
1,093,446
[ 1, 2463, 326, 1234, 18, 892, 434, 333, 745, 18, 309, 326, 745, 22497, 3059, 3134, 13179, 364, 20099, 16, 1508, 326, 2863, 5793, 1703, 12317, 487, 326, 1142, 4200, 1731, 434, 326, 1234, 18, 892, 300, 1427, 333, 707, 903, 2569, 5348, 4200, 1731, 3397, 18, 3541, 16, 327, 1375, 3576, 18, 892, 68, 1410, 506, 1399, 316, 326, 6835, 3560, 434, 1234, 18, 892, 16, 1625, 326, 7114, 4834, 5432, 261, 73, 18, 75, 18, 1347, 8122, 10611, 578, 24641, 326, 19, 2380, 333, 1634, 732, 5055, 716, 326, 5793, 353, 279, 13179, 364, 20099, 16, 732, 1610, 326, 1234, 18, 892, 269, 1335, 326, 1142, 4200, 1731, 261, 464, 1089, 326, 2078, 769, 13, 1610, 1338, 963, 17, 3462, 1731, 3695, 534, 14461, 501, 487, 411, 3348, 34, 411, 2469, 34, 411, 3890, 34, 2, 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, 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 ]
[ 1, 565, 445, 389, 3576, 751, 1435, 2713, 1476, 1135, 261, 3890, 3778, 325, 13, 288, 203, 3639, 309, 261, 3576, 18, 892, 18, 2469, 1545, 4248, 597, 353, 16950, 30839, 12, 3576, 18, 15330, 3719, 288, 203, 5411, 19931, 288, 203, 7734, 2231, 6571, 519, 312, 945, 12, 20, 92, 7132, 13, 203, 7734, 2231, 963, 519, 720, 12, 1991, 13178, 554, 16, 4200, 13, 203, 7734, 312, 2233, 12, 6723, 16, 374, 92, 3462, 13, 203, 7734, 312, 2233, 12, 1289, 12, 6723, 16, 3847, 3631, 963, 13, 203, 7734, 745, 892, 3530, 12, 1289, 12, 6723, 16, 5178, 3631, 374, 16, 963, 13, 203, 7734, 327, 12, 6723, 16, 527, 12, 1467, 16, 5178, 3719, 203, 5411, 289, 203, 5411, 327, 1234, 18, 892, 31, 203, 3639, 289, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "./erc677/IERC677Receiver.sol"; import "./access/HasCrunchParent.sol"; import "./CrunchToken.sol"; /** * DataCrunch Staking contract for the CRUNCH token. * * To start staking, use the {CrunchStaking-deposit(address)} method, but this require an allowance from your account. * Another method is to do a {CrunchToken-transferAndCall(address, uint256, bytes)} to avoid doing 2 transactions. (as per ERC-677 standart) * * Withdrawing will withdraw everything. There is currently no method to only withdraw a specific amount. * * @author Enzo CACERES * @author Arnaud CASTILLO */ contract CrunchStaking is HasCrunchParent, IERC677Receiver { event Withdrawed( address indexed to, uint256 reward, uint256 staked, uint256 totalAmount ); event EmergencyWithdrawed(address indexed to, uint256 staked); event Deposited(address indexed sender, uint256 amount); event RewardPerDayUpdated(uint256 rewardPerDay, uint256 totalDebt); struct Holder { /** Index in `addresses`, used for faster lookup in case of a remove. */ uint256 index; /** When does an holder stake for the first time (set to `block.timestamp`). */ uint256 start; /** Total amount staked by the holder. */ uint256 totalStaked; /** When the reward per day is updated, the reward debt is updated to ensure that the previous reward they could have got isn't lost. */ uint256 rewardDebt; /** Individual stakes. */ Stake[] stakes; } struct Stake { /** How much the stake is. */ uint256 amount; /** When does the stakes 'start' is. When created it is `block.timestamp`, and is updated when the `reward per day` is updated. */ uint256 start; } /** The `reward per day` is the amount of tokens rewarded for 1 million CRUNCHs staked over a 1 day period. */ uint256 public rewardPerDay; /** List of all currently staking addresses. Used for looping. */ address[] public addresses; /** address to Holder mapping. */ mapping(address => Holder) public holders; /** Currently total staked amount by everyone. It is incremented when someone deposit token, and decremented when someone withdraw. This value does not include the rewards. */ uint256 public totalStaked; /** @dev Initializes the contract by specifying the parent `crunch` and the initial `rewardPerDay`. */ constructor(CrunchToken crunch, uint256 _rewardPerDay) HasCrunchParent(crunch) { rewardPerDay = _rewardPerDay; } /** * @dev Deposit an `amount` of tokens from your account to this contract. * * This will start the staking with the provided amount. * The implementation call {IERC20-transferFrom}, so the caller must have previously {IERC20-approve} the `amount`. * * Emits a {Deposited} event. * * Requirements: * - `amount` cannot be the zero address. * - `caller` must have a balance of at least `amount`. * * @param amount amount to reposit. */ function deposit(uint256 amount) external { crunch.transferFrom(_msgSender(), address(this), amount); _deposit(_msgSender(), amount); } /** * Withdraw the staked tokens with the reward. * * Emits a {Withdrawed} event. * * Requirements: * - `caller` to be staking. */ function withdraw() external { _withdraw(_msgSender()); } /** * Returns the current reserve for rewards. * * @return the contract balance - the total staked. */ function reserve() public view returns (uint256) { uint256 balance = contractBalance(); if (totalStaked > balance) { revert( "Staking: the balance has less CRUNCH than the total staked" ); } return balance - totalStaked; } /** * Test if the caller is currently staking. * * @return `true` if the caller is staking, else if not. */ function isCallerStaking() external view returns (bool) { return isStaking(_msgSender()); } /** * Test if an address is currently staking. * * @param `addr` address to test. * @return `true` if the address is staking, else if not. */ function isStaking(address addr) public view returns (bool) { return _isStaking(holders[addr]); } /** * Get the current balance in CRUNCH of this smart contract. * * @return The current staking contract's balance in CRUNCH. */ function contractBalance() public view returns (uint256) { return crunch.balanceOf(address(this)); } /** * Returns the sum of the specified `addr` staked amount. * * @param addr address to check. * @return the total staked of the holder. */ function totalStakedOf(address addr) external view returns (uint256) { return holders[addr].totalStaked; } /** * Returns the computed reward of everyone. * * @return total the computed total reward of everyone. */ function totalReward() public view returns (uint256 total) { uint256 length = addresses.length; for (uint256 index = 0; index < length; index++) { address addr = addresses[index]; total += totalRewardOf(addr); } } /** * Compute the reward of the specified `addr`. * * @param addr address to test. * @return the reward the address would get. */ function totalRewardOf(address addr) public view returns (uint256) { Holder storage holder = holders[addr]; return _computeRewardOf(holder); } /** * Sum the reward debt of everyone. * * @return total the sum of all `Holder.rewardDebt`. */ function totalRewardDebt() external view returns (uint256 total) { uint256 length = addresses.length; for (uint256 index = 0; index < length; index++) { address addr = addresses[index]; total += rewardDebtOf(addr); } } /** * Get the reward debt of an holder. * * @param addr holder's address. * @return the reward debt of the holder. */ function rewardDebtOf(address addr) public view returns (uint256) { return holders[addr].rewardDebt; } /** * Test if the reserve is sufficient to cover the `{totalReward()}`. * * @return whether the reserve has enough CRUNCH to give to everyone. */ function isReserveSufficient() external view returns (bool) { return _isReserveSufficient(totalReward()); } /** * Test if the reserve is sufficient to cover the `{totalRewardOf(address)}` of the specified address. * * @param addr address to test. * @return whether the reserve has enough CRUNCH to give to this address. */ function isReserveSufficientFor(address addr) external view returns (bool) { return _isReserveSufficient(totalRewardOf(addr)); } /** * Get the number of address current staking. * * @return the length of the `addresses` array. */ function stakerCount() external view returns (uint256) { return addresses.length; } /** * Get the stakes array of an holder. * * @param addr address to get the stakes array. * @return the holder's stakes array. */ function stakesOf(address addr) external view returns (Stake[] memory) { return holders[addr].stakes; } /** * Get the stakes array length of an holder. * * @param addr address to get the stakes array length. * @return the length of the `stakes` array. */ function stakesCountOf(address addr) external view returns (uint256) { return holders[addr].stakes.length; } /** * @dev ONLY FOR EMERGENCY!! * * Force an address to withdraw. * * @dev Should only be called if a {CrunchStaking-destroy()} would cost too much gas to be executed. * * @param addr address to withdraw. */ function forceWithdraw(address addr) external onlyOwner { _withdraw(addr); } /** * @dev ONLY FOR EMERGENCY!! * * Emergency withdraw. * * All rewards are discarded. Only initial staked amount will be transfered back! * * Emits a {EmergencyWithdrawed} event. * * Requirements: * - `caller` to be staking. */ function emergencyWithdraw() external { _emergencyWithdraw(_msgSender()); } /** * @dev ONLY FOR EMERGENCY!! * * Force an address to emergency withdraw. * * @dev Should only be called if a {CrunchStaking-emergencyDestroy()} would cost too much gas to be executed. * * @param addr address to emergency withdraw. */ function forceEmergencyWithdraw(address addr) external onlyOwner { _emergencyWithdraw(addr); } /** * Update the reward per day. * * This will recompute a reward debt with the previous reward per day value. * The debt is used to make sure that everyone will keep their rewarded tokens using the previous reward per day value for the calculation. * * Emits a {RewardPerDayUpdated} event. * * Requirements: * - `to` must not be the same as the reward per day. * - `to` must be below or equal to 15000. * * @param to new reward per day value. */ function setRewardPerDay(uint256 to) external onlyOwner { require( rewardPerDay != to, "Staking: reward per day value must be different" ); require( to <= 15000, "Staking: reward per day must be below 15000/1M token/day" ); uint256 debt = _updateDebts(); rewardPerDay = to; emit RewardPerDayUpdated(rewardPerDay, debt); } /** * @dev ONLY FOR EMERGENCY!! * * Empty the reserve if there is a problem. */ function emptyReserve() external onlyOwner { uint256 amount = reserve(); require(amount != 0, "Staking: reserve is empty"); crunch.transfer(owner(), amount); } /** * Destroy the contact after withdrawing everyone. * * @dev If the reserve is not zero after the withdraw, the remaining will be sent back to the contract's owner. */ function destroy() external onlyOwner { uint256 usable = reserve(); uint256 length = addresses.length; for (uint256 index = 0; index < length; index++) { address addr = addresses[index]; Holder storage holder = holders[addr]; uint256 reward = _computeRewardOf(holder); require(usable >= reward, "Staking: reserve does not have enough"); uint256 total = holder.totalStaked + reward; crunch.transfer(addr, total); } _transferRemainingAndSelfDestruct(); } /** * @dev ONLY FOR EMERGENCY!! * * Destroy the contact after emergency withdrawing everyone, avoiding the reward computation to save gas. * * If the reserve is not zero after the withdraw, the remaining will be sent back to the contract's owner. */ function emergencyDestroy() external onlyOwner { uint256 length = addresses.length; for (uint256 index = 0; index < length; index++) { address addr = addresses[index]; Holder storage holder = holders[addr]; crunch.transfer(addr, holder.totalStaked); } _transferRemainingAndSelfDestruct(); } /** * @dev ONLY FOR CRITICAL EMERGENCY!! * * Destroy the contact without withdrawing anyone. * Only use this function if the code has a fatal bug and its not possible to do otherwise. */ function criticalDestroy() external onlyOwner { _transferRemainingAndSelfDestruct(); } /** @dev Internal function called when the {IERC677-transferAndCall} is used. */ function onTokenTransfer( address sender, uint256 value, bytes memory data ) external override onlyCrunchParent { data; /* silence unused */ _deposit(sender, value); } /** * Deposit. * * @dev If the depositor is not currently holding, the `Holder.start` is set and his address is added to the addresses list. * * @param from depositor address. * @param amount amount to deposit. */ function _deposit(address from, uint256 amount) internal { require(amount != 0, "cannot deposit zero"); Holder storage holder = holders[from]; if (!_isStaking(holder)) { holder.start = block.timestamp; holder.index = addresses.length; addresses.push(from); } holder.totalStaked += amount; holder.stakes.push(Stake({amount: amount, start: block.timestamp})); totalStaked += amount; emit Deposited(from, amount); } /** * Withdraw. * * @dev This will remove the `Holder` from the `holders` mapping and the address from the `addresses` array. * * Requirements: * - `addr` must be staking. * - the reserve must have enough token. * * @param addr address to withdraw. */ function _withdraw(address addr) internal { Holder storage holder = holders[addr]; require(_isStaking(holder), "Staking: no stakes"); uint256 reward = _computeRewardOf(holder); require( _isReserveSufficient(reward), "Staking: the reserve does not have enough token" ); uint256 staked = holder.totalStaked; uint256 total = staked + reward; crunch.transfer(addr, total); totalStaked -= staked; _deleteAddress(holder.index); delete holders[addr]; emit Withdrawed(addr, reward, staked, total); } /** * Emergency withdraw. * * This is basically the same as {CrunchStaking-_withdraw(address)}, but without the reward. * This function must only be used for emergencies as it consume less gas and does not have the check for the reserve. * * @dev This will remove the `Holder` from the `holders` mapping and the address from the `addresses` array. * * Requirements: * - `addr` must be staking. * * @param addr address to withdraw. */ function _emergencyWithdraw(address addr) internal { Holder storage holder = holders[addr]; require(_isStaking(holder), "Staking: no stakes"); uint256 staked = holder.totalStaked; crunch.transfer(addr, staked); totalStaked -= staked; _deleteAddress(holder.index); delete holders[addr]; emit EmergencyWithdrawed(addr, staked); } /** * Test if the `reserve` is sufficiant for a specified reward. * * @param reward value to test. * @return if the reserve is bigger or equal to the `reward` parameter. */ function _isReserveSufficient(uint256 reward) private view returns (bool) { return reserve() >= reward; } /** * Test if an holder struct is currently staking. * * @dev Its done by testing if the stake array length is equal to zero. Since its not possible, it mean that the holder is not currently staking and the struct is only zero. * * @param holder holder struct. * @return `true` if the holder is staking, `false` otherwise. */ function _isStaking(Holder storage holder) internal view returns (bool) { return holder.stakes.length != 0; } /** * Update the reward debt of all holders. * * @dev Usually called before a `reward per day` update. * * @return total total debt updated. */ function _updateDebts() internal returns (uint256 total) { uint256 length = addresses.length; for (uint256 index = 0; index < length; index++) { address addr = addresses[index]; Holder storage holder = holders[addr]; uint256 debt = _updateDebtsOf(holder); holder.rewardDebt += debt; total += debt; } } /** * Update the reward debt of a specified `holder`. * * @param holder holder struct to update. * @return total sum of debt added. */ function _updateDebtsOf(Holder storage holder) internal returns (uint256 total) { uint256 length = holder.stakes.length; for (uint256 index = 0; index < length; index++) { Stake storage stake = holder.stakes[index]; total += _computeStakeReward(stake); stake.start = block.timestamp; } } /** * Compute the reward for every holder. * * @return total the total of all of the reward for all of the holders. */ function _computeTotalReward() internal view returns (uint256 total) { uint256 length = addresses.length; for (uint256 index = 0; index < length; index++) { address addr = addresses[index]; Holder storage holder = holders[addr]; total += _computeRewardOf(holder); } } /** * Compute all stakes reward for an holder. * * @param holder the holder struct. * @return total total reward for the holder (including the debt). */ function _computeRewardOf(Holder storage holder) internal view returns (uint256 total) { uint256 length = holder.stakes.length; for (uint256 index = 0; index < length; index++) { Stake storage stake = holder.stakes[index]; total += _computeStakeReward(stake); } total += holder.rewardDebt; } /** * Compute the reward of a single stake. * * @param stake the stake struct. * @return the token rewarded (does not include the debt). */ function _computeStakeReward(Stake storage stake) internal view returns (uint256) { uint256 numberOfDays = ((block.timestamp - stake.start) / 1 days); return (stake.amount * numberOfDays * rewardPerDay) / 1_000_000; } /** * Delete an address from the `addresses` array. * * @dev To avoid holes, the last value will replace the deleted address. * * @param index address's index to delete. */ function _deleteAddress(uint256 index) internal { uint256 length = addresses.length; require( length != 0, "Staking: cannot remove address if array length is zero" ); uint256 last = length - 1; if (last != index) { address addr = addresses[last]; addresses[index] = addr; holders[addr].index = index; } addresses.pop(); } /** * Transfer the remaining tokens back to the current contract owner and then self destruct. * * @dev This function must only be called for destruction!! * @dev If the balance is 0, the `CrunchToken#transfer(address, uint256)` is not called. */ function _transferRemainingAndSelfDestruct() internal { uint256 remaining = contractBalance(); if (remaining != 0) { crunch.transfer(owner(), remaining); } selfdestruct(payable(owner())); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; import "./erc677/ERC677.sol"; contract CrunchToken is ERC677, ERC20Burnable { constructor() ERC20("Crunch Token", "CRUNCH") { _mint(msg.sender, 10765163 * 10**decimals()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.2; import "@openzeppelin/contracts/access/Ownable.sol"; import "../CrunchToken.sol"; contract HasCrunchParent is Ownable { event ParentUpdated(address from, address to); CrunchToken public crunch; constructor(CrunchToken _crunch) { crunch = _crunch; emit ParentUpdated(address(0), address(crunch)); } modifier onlyCrunchParent() { require( address(crunch) == _msgSender(), "HasCrunchParent: caller is not the crunch token" ); _; } function setCrunch(CrunchToken _crunch) public onlyOwner { require(address(crunch) != address(_crunch), "useless to update to same crunch token"); emit ParentUpdated(address(crunch), address(_crunch)); crunch = _crunch; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./ERC677.sol"; import "./IERC677.sol"; import "./IERC677Receiver.sol"; abstract contract ERC677 is IERC677, ERC20 { function transferAndCall( address recipient, uint256 amount, bytes memory data ) public virtual override returns (bool success) { super.transfer(recipient, amount); emit TransferAndCall(msg.sender, recipient, amount, data); if (isContract(recipient)) { IERC677Receiver receiver = IERC677Receiver(recipient); receiver.onTokenTransfer(msg.sender, amount, data); } return true; } function isContract(address addr) private view returns (bool hasCode) { uint256 length; assembly { length := extcodesize(addr) } return length > 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; interface IERC677 is IERC20 { /** * @dev transfer token to a contract address with additional data if the recipient is a contact. * @param recipient The address to transfer to. * @param amount The amount to be transferred. * @param data The extra data to be passed to the receiving contract. */ function transferAndCall( address recipient, uint256 amount, bytes memory data ) external returns (bool success); event TransferAndCall( address indexed from, address indexed to, uint256 value, bytes data ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IERC677Receiver { function onTokenTransfer( address sender, uint256 value, bytes memory data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../utils/Context.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; } }
* Withdraw. @dev This will remove the `Holder` from the `holders` mapping and the address from the `addresses` array. Requirements: - `addr` must be staking. - the reserve must have enough token. @param addr address to withdraw./
function _withdraw(address addr) internal { Holder storage holder = holders[addr]; require(_isStaking(holder), "Staking: no stakes"); uint256 reward = _computeRewardOf(holder); require( _isReserveSufficient(reward), "Staking: the reserve does not have enough token" ); uint256 staked = holder.totalStaked; uint256 total = staked + reward; crunch.transfer(addr, total); totalStaked -= staked; _deleteAddress(holder.index); delete holders[addr]; emit Withdrawed(addr, reward, staked, total); }
1,587,812
[ 1, 1190, 9446, 18, 225, 1220, 903, 1206, 326, 1375, 6064, 68, 628, 326, 1375, 9000, 68, 2874, 471, 326, 1758, 628, 326, 1375, 13277, 68, 526, 18, 29076, 30, 300, 1375, 4793, 68, 1297, 506, 384, 6159, 18, 300, 326, 20501, 1297, 1240, 7304, 1147, 18, 225, 3091, 1758, 358, 598, 9446, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 1918, 9446, 12, 2867, 3091, 13, 2713, 288, 203, 3639, 670, 1498, 2502, 10438, 273, 366, 4665, 63, 4793, 15533, 203, 203, 3639, 2583, 24899, 291, 510, 6159, 12, 4505, 3631, 315, 510, 6159, 30, 1158, 384, 3223, 8863, 203, 203, 3639, 2254, 5034, 19890, 273, 389, 9200, 17631, 1060, 951, 12, 4505, 1769, 203, 203, 3639, 2583, 12, 203, 5411, 389, 291, 607, 6527, 55, 11339, 12, 266, 2913, 3631, 203, 5411, 315, 510, 6159, 30, 326, 20501, 1552, 486, 1240, 7304, 1147, 6, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 384, 9477, 273, 10438, 18, 4963, 510, 9477, 31, 203, 3639, 2254, 5034, 2078, 273, 384, 9477, 397, 19890, 31, 203, 3639, 276, 2681, 343, 18, 13866, 12, 4793, 16, 2078, 1769, 203, 203, 3639, 2078, 510, 9477, 3947, 384, 9477, 31, 203, 203, 3639, 389, 3733, 1887, 12, 4505, 18, 1615, 1769, 203, 3639, 1430, 366, 4665, 63, 4793, 15533, 203, 203, 3639, 3626, 3423, 9446, 329, 12, 4793, 16, 19890, 16, 384, 9477, 16, 2078, 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 ]
./full_match/137/0xC2EAD235451db0a037a6dAedE2377FffEECdC90C/sources/project_/contracts/market/ERC721Bids.sol
* @dev remove bid from storage/ Step 1: delete the bid and the address Step 2: if no bid left
function _removeBid( address erc721Address, uint256 tokenId, address bidder ) private { if (_erc721Bids[erc721Address].bids[tokenId].bidders.contains(bidder)) { delete _erc721Bids[erc721Address].bids[tokenId].bids[bidder]; _erc721Bids[erc721Address].bids[tokenId].bidders.remove(bidder); if ( _erc721Bids[erc721Address].bids[tokenId].bidders.length() == 0 ) { _erc721Bids[erc721Address].tokenIds.remove(tokenId); } } }
4,668,789
[ 1, 4479, 9949, 628, 2502, 19, 8693, 404, 30, 1430, 326, 9949, 471, 326, 1758, 8693, 576, 30, 309, 1158, 9949, 2002, 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, 389, 4479, 17763, 12, 203, 3639, 1758, 6445, 71, 27, 5340, 1887, 16, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 1758, 9949, 765, 203, 565, 262, 3238, 288, 203, 3639, 309, 261, 67, 12610, 27, 5340, 38, 2232, 63, 12610, 27, 5340, 1887, 8009, 70, 2232, 63, 2316, 548, 8009, 70, 1873, 414, 18, 12298, 12, 19773, 765, 3719, 288, 203, 5411, 1430, 389, 12610, 27, 5340, 38, 2232, 63, 12610, 27, 5340, 1887, 8009, 70, 2232, 63, 2316, 548, 8009, 70, 2232, 63, 19773, 765, 15533, 203, 5411, 389, 12610, 27, 5340, 38, 2232, 63, 12610, 27, 5340, 1887, 8009, 70, 2232, 63, 2316, 548, 8009, 70, 1873, 414, 18, 4479, 12, 19773, 765, 1769, 203, 203, 5411, 309, 261, 203, 7734, 389, 12610, 27, 5340, 38, 2232, 63, 12610, 27, 5340, 1887, 8009, 70, 2232, 63, 2316, 548, 8009, 70, 1873, 414, 18, 2469, 1435, 422, 374, 203, 5411, 262, 288, 203, 7734, 389, 12610, 27, 5340, 38, 2232, 63, 12610, 27, 5340, 1887, 8009, 2316, 2673, 18, 4479, 12, 2316, 548, 1769, 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, -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.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol"; import "./interfaces/IAliumGaming1155.sol"; import "./interfaces/INFTRewardPool.sol"; /** * @title NFTRewardPool - Special NFT reward pool for SHP alium users and * gamers. */ contract NFTRewardPool is INFTRewardPool, Ownable, IERC1155Receiver, ERC1155Holder { struct Reward { uint256 tokenId; uint256 amount; } struct InputReward { Reward[] rewards; } bool public status; IAliumGaming1155 public rewardToken; address public shp; bool public initialized; mapping(uint256 => Reward[]) internal _rewards; // pool id -> withdraw position -> counter mapping(address => mapping(uint256 => uint256)) internal _logs; // account -> tokenId -> amount mapping(address => mapping(uint256 => uint256)) internal _balances; event Logged(address, uint256); event ErrorLog(bytes); event Initialized(); event RewardUpdated(uint256 poolId); /** * @dev Initialize contract. * * Permission: Owner */ function initialize(IAliumGaming1155 _rewardToken, address _shp) external onlyOwner { require(!initialized, "Reward pool: initialized"); require(address(_rewardToken) != address(0), "Reward zero address"); require(_shp != address(0), "SHP zero address"); require( ERC165Checker.supportsERC165(address(_rewardToken)), "ERC165 unsupported token" ); require( ERC165Checker.supportsInterface( address(_rewardToken), type(IAliumGaming1155).interfaceId ), "ERC1155 unsupported token" ); rewardToken = _rewardToken; shp = _shp; initialized = true; emit Initialized(); } /** * @dev Write to log `_caller` and `_withdrawPosition`. * * Permission: SHP */ function log(address _caller, uint256 _withdrawPosition) external override onlySHP { require(_caller != address(0), "Log zero address"); _logs[_caller][_withdrawPosition] += 1; emit Logged(_caller, _withdrawPosition); } /** * @dev Claim available reward. */ function claim() external { Reward memory reward; uint256[101] memory _userLogs = getLogs(msg.sender); for (uint256 i; i <= 100; i++) { if (_userLogs[i] != 0) { // clear log data delete _logs[msg.sender][i]; uint256 ll = _rewards[i].length; for (uint256 ii; ii < ll; ii++) { reward = _rewards[i][ii]; rewardToken.mint( address(this), reward.tokenId, reward.amount, "" ); try rewardToken.safeTransferFrom( address(this), msg.sender, reward.tokenId, reward.amount, "" ) { // } catch (bytes memory error) { _balances[msg.sender][reward.tokenId] += reward.amount; emit ErrorLog(error); } } } } } /** * @dev Withdraw available tokens by `_tokenId`. */ function withdraw(uint256 _tokenId) external { _withdraw( msg.sender, msg.sender, _tokenId, _balances[msg.sender][_tokenId] ); } /** * @dev Withdraw to account `_to` amount `_tokenAmount` tokens with `_tokenId`. */ function withdrawTo( address _to, uint256 _tokenId, uint256 _tokenAmount ) external { _withdraw(msg.sender, _to, _tokenId, _tokenAmount); } /** * @dev Returns `_account` balance by `_tokenId`. */ function getBalance(address _account, uint256 _tokenId) external view returns (uint256) { return _balances[_account][_tokenId]; } /** * @dev Returns `_account` log by `_withdrawPosition`. */ function getLog(address _account, uint256 _withdrawPosition) external view returns (uint256 res) { res = _logs[_account][_withdrawPosition]; } /** * @dev Returns reward by `_withdrawPosition`. */ function getReward(uint256 _withdrawPosition) external view returns (Reward[] memory) { return _rewards[_withdrawPosition]; } /** * @dev Set `_rewardsList` for current `_withdrawPosition`. * * Permission: owner * * @notice Reward will be overwritten */ function setReward(uint256 _position, Reward[] memory _rewardsList) external onlyOwner { uint256 l = _rewardsList.length; uint256 i = 0; delete _rewards[_position]; for (i; i < l; i++) { require(_rewardsList[i].amount != 0, "Zero reward amount"); _rewards[_position].push(_rewardsList[i]); } emit RewardUpdated(_position); } /** * @dev Set `_rewardsLists` for selected `_positions`. * * Permission: owner * * @notice Reward will be overwritten */ function setRewards( uint256[] memory _positions, InputReward[] memory _rewardsLists ) external onlyOwner { uint256 l = _positions.length; require(l == _rewardsLists.length, "Incorrect length input data"); uint256 i; uint256 ll; for (i; i < l; i++) { if (_positions[i] > 100 || _positions[i] == 0) { require(false, "Wrong position index set"); } } i = 0; for (i; i < l; i++) { if (_rewards[_positions[i]].length != 0) { delete _rewards[_positions[i]]; } ll = _rewardsLists[i].rewards.length; for (uint256 ii; ii < ll; ii++) { _rewards[_positions[i]].push(_rewardsLists[i].rewards[ii]); } emit RewardUpdated(_positions[i]); } } /** * @dev Returns `_account` logs. */ function getLogs(address _account) public view returns (uint256[101] memory res) { uint256 l = 100; uint256 i = 1; for (i; i <= l; i++) { res[i] = _logs[_account][i]; } } function _withdraw( address _from, address _to, uint256 _tokenId, uint256 _tokenAmount ) private { require( _from != address(0) && _to != address(0), "Transfer to or from zero address" ); uint256 balance = _balances[_from][_tokenId]; require(balance > 0, "Withdraw empty balance"); require(_tokenAmount >= balance, "Not enough token balance"); _balances[_from][_tokenId] -= _tokenAmount; rewardToken.safeTransferFrom(address(this), _to, _tokenId, balance, ""); } modifier onlySHP() { require(msg.sender == shp, "Only SHP contract"); _; } }
* @dev Withdraw to account `_to` amount `_tokenAmount` tokens with `_tokenId`./
function withdrawTo( address _to, uint256 _tokenId, uint256 _tokenAmount ) external { _withdraw(msg.sender, _to, _tokenId, _tokenAmount); }
13,034,326
[ 1, 1190, 9446, 358, 2236, 1375, 67, 869, 68, 3844, 1375, 67, 2316, 6275, 68, 2430, 598, 1375, 67, 2316, 548, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 445, 598, 9446, 774, 12, 203, 3639, 1758, 389, 869, 16, 203, 3639, 2254, 5034, 389, 2316, 548, 16, 203, 3639, 2254, 5034, 389, 2316, 6275, 203, 565, 262, 3903, 288, 203, 3639, 389, 1918, 9446, 12, 3576, 18, 15330, 16, 389, 869, 16, 389, 2316, 548, 16, 389, 2316, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x6F9e33E225485Af4874FAC060F65ff60693ab4b8/sources/contracts/interfaces/internal/routes/INFTCollectionFactoryDrops.sol
* @title Interface for routing calls to the NFT Collection Factory to create drop collections. @author reggieag/
interface INFTCollectionFactoryDrops { function createNFTDropCollection( string calldata name, string calldata symbol, string calldata baseURI, bool isRevealed, uint32 maxTokenId, address approvedMinter, uint96 nonce ) external returns (address collection); function createNFTDropCollectionWithPaymentFactory( string calldata name, string calldata symbol, string calldata baseURI, bool isRevealed, uint32 maxTokenId, address approvedMinter, uint96 nonce, CallWithoutValue calldata paymentAddressFactoryCall ) external returns (address collection); pragma solidity ^0.8.18; }
15,980,481
[ 1, 1358, 364, 7502, 4097, 358, 326, 423, 4464, 2200, 7822, 358, 752, 3640, 6980, 18, 225, 960, 75, 1385, 346, 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 ]
[ 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, 5831, 2120, 4464, 2532, 1733, 40, 16703, 288, 203, 225, 445, 752, 50, 4464, 7544, 2532, 12, 203, 565, 533, 745, 892, 508, 16, 203, 565, 533, 745, 892, 3273, 16, 203, 565, 533, 745, 892, 1026, 3098, 16, 203, 565, 1426, 28627, 537, 18931, 16, 203, 565, 2254, 1578, 943, 1345, 548, 16, 203, 565, 1758, 20412, 49, 2761, 16, 203, 565, 2254, 10525, 7448, 203, 225, 262, 3903, 1135, 261, 2867, 1849, 1769, 203, 203, 225, 445, 752, 50, 4464, 7544, 2532, 1190, 6032, 1733, 12, 203, 565, 533, 745, 892, 508, 16, 203, 565, 533, 745, 892, 3273, 16, 203, 565, 533, 745, 892, 1026, 3098, 16, 203, 565, 1426, 28627, 537, 18931, 16, 203, 565, 2254, 1578, 943, 1345, 548, 16, 203, 565, 1758, 20412, 49, 2761, 16, 203, 565, 2254, 10525, 7448, 16, 203, 565, 3049, 8073, 620, 745, 892, 5184, 1887, 1733, 1477, 203, 225, 262, 3903, 1135, 261, 2867, 1849, 1769, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 2643, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.6; import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import "@chainlink/contracts/src/v0.6/VRFConsumerBase.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract Lottery is VRFConsumerBase, Ownable { address payable[] public players; uint256 public entryFee; address payable public recentWinner; uint256 public randomness; enum LOTTERY_STATE { OPEN, CLOSED, CALCULATING_WINNER } LOTTERY_STATE public lottery_state; bytes32 public keyHash; uint256 public fee; event RequestedRandomness(bytes32 requestId); AggregatorV3Interface internal priceFeed; constructor( address _priceFeedAddress, address _vrfCoordinator, address _link, uint256 _fee, bytes32 _keyHash ) public VRFConsumerBase(_vrfCoordinator, _link) { entryFee = 50 * (10**18); //in wei priceFeed = AggregatorV3Interface(_priceFeedAddress); lottery_state = LOTTERY_STATE.CLOSED; // 1 fee = _fee; keyHash = _keyHash; } function enter() public payable { // minimum price check require( lottery_state == LOTTERY_STATE.OPEN, "Lottery is Not Open yet!" ); require(msg.value >= getEntranceFee(), "Not Enough Eth"); players.push(msg.sender); } function getEntranceFee() public view returns (uint256) { (, int256 price, , , ) = priceFeed.latestRoundData(); uint256 adjustedPrice = uint256(price) * (10**10); // setting the price uint256 costToEnter = (entryFee * 10**18) / adjustedPrice; return costToEnter; } function startLottery() public onlyOwner { require( lottery_state == LOTTERY_STATE.CLOSED, "Can't start a new lottery yet!" ); lottery_state = LOTTERY_STATE.OPEN; } function endLottery() public onlyOwner { lottery_state = LOTTERY_STATE.CALCULATING_WINNER; bytes32 requestId = requestRandomness(keyHash, fee); emit RequestedRandomness(requestId); } /** * Callback function used by VRF Coordinator */ function fulfillRandomness(bytes32 _requestId, uint256 _randomness) internal override { require( lottery_state == LOTTERY_STATE.CALCULATING_WINNER, "Wait For it!" ); require(_randomness > 0, "Random Not Found!"); uint256 indexOfWinner = _randomness % players.length; recentWinner = players[indexOfWinner]; recentWinner.transfer(address(this).balance); //Reset players = new address payable[](0); lottery_state = LOTTERY_STATE.CLOSED; randomness = _randomness; } }
* Callback function used by VRF Coordinator/Reset
function fulfillRandomness(bytes32 _requestId, uint256 _randomness) internal override { require( lottery_state == LOTTERY_STATE.CALCULATING_WINNER, "Wait For it!" ); require(_randomness > 0, "Random Not Found!"); uint256 indexOfWinner = _randomness % players.length; recentWinner = players[indexOfWinner]; recentWinner.transfer(address(this).balance); players = new address payable[](0); lottery_state = LOTTERY_STATE.CLOSED; randomness = _randomness; }
7,269,982
[ 1, 2428, 445, 1399, 635, 776, 12918, 10320, 4240, 19, 7013, 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, 22290, 8529, 4496, 12, 3890, 1578, 389, 2293, 548, 16, 2254, 5034, 389, 9188, 4496, 13, 203, 3639, 2713, 203, 3639, 3849, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 17417, 387, 93, 67, 2019, 422, 1806, 1470, 8404, 67, 7998, 18, 7913, 39, 1506, 28054, 67, 24572, 12196, 16, 203, 5411, 315, 5480, 2457, 518, 4442, 203, 3639, 11272, 203, 3639, 2583, 24899, 9188, 4496, 405, 374, 16, 315, 8529, 2288, 10750, 4442, 1769, 203, 3639, 2254, 5034, 3133, 59, 7872, 273, 389, 9188, 4496, 738, 18115, 18, 2469, 31, 203, 3639, 8399, 59, 7872, 273, 18115, 63, 31806, 59, 7872, 15533, 203, 3639, 8399, 59, 7872, 18, 13866, 12, 2867, 12, 2211, 2934, 12296, 1769, 203, 540, 203, 3639, 18115, 273, 394, 1758, 8843, 429, 8526, 12, 20, 1769, 203, 3639, 17417, 387, 93, 67, 2019, 273, 1806, 1470, 8404, 67, 7998, 18, 28475, 31, 203, 3639, 2744, 4496, 273, 389, 9188, 4496, 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 ]
pragma solidity ^0.7.3; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract TorNFT is ERC721, Ownable { using Counters for Counters.Counter; Counters.Counter private _tokenIds; constructor() public ERC721("TheOsunRiver", "TOR") {} function createNFT(address receiver, string memory tokenURI) public onlyOwner returns (uint256) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(receiver, newItemId); _setTokenURI(newItemId, tokenURI); // returns the id for the newly created token return newItemId; } }
returns the id for the newly created token
{ _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(receiver, newItemId); _setTokenURI(newItemId, tokenURI); return newItemId; }
5,353,030
[ 1, 6154, 326, 612, 364, 326, 10894, 2522, 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, 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, 288, 203, 3639, 389, 2316, 2673, 18, 15016, 5621, 203, 203, 3639, 2254, 5034, 394, 17673, 273, 389, 2316, 2673, 18, 2972, 5621, 203, 3639, 389, 81, 474, 12, 24454, 16, 394, 17673, 1769, 203, 3639, 389, 542, 1345, 3098, 12, 2704, 17673, 16, 1147, 3098, 1769, 203, 203, 3639, 327, 394, 17673, 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 ]
./full_match/5/0xD26f1F080168294777419e30C8bFCa71C4AB6722/sources/contracts/MafiaNuts.sol
get tokenURI for a specific token. If collection is not revealed, return the defaultURI
function tokenURI(uint256 _tokenId) public view override returns (string memory){ require( _exists(_tokenId), "ERC721Metadata: URI query for nonexistent token" ); return isRevealed ? string(abi.encodePacked(baseTokenURI, _tokenId.toString())) : defaultURI; }
1,951,737
[ 1, 588, 1147, 3098, 364, 279, 2923, 1147, 18, 971, 1849, 353, 486, 283, 537, 18931, 16, 327, 326, 805, 3098, 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, 565, 445, 1147, 3098, 12, 11890, 5034, 389, 2316, 548, 13, 1071, 1476, 3849, 1135, 261, 1080, 3778, 15329, 203, 3639, 2583, 12, 203, 5411, 389, 1808, 24899, 2316, 548, 3631, 203, 2398, 315, 654, 39, 27, 5340, 2277, 30, 3699, 843, 364, 1661, 19041, 1147, 6, 203, 3639, 11272, 203, 3639, 327, 28627, 537, 18931, 692, 533, 12, 21457, 18, 3015, 4420, 329, 12, 1969, 1345, 3098, 16, 389, 2316, 548, 18, 10492, 1435, 3719, 294, 805, 3098, 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 ]
./partial_match/42/0x9736db9CE5747AAC473d68695a8E242AE2607e1D/sources/compoundFarmer.sol
4. Wrap ETH - amount input variable 4.1 send ETH to WETH mycontract 4.2 approve mycontract to control WETH balance 4.4 transfer WETH to mycontract
function Wrap (uint256 amount) internal { WETH.call.gas(200000).value(amount)(""); IWETH_Contract.approve(address(this), amount); IWETH_Contract.transfer(address(this), amount); }
3,339,490
[ 1, 24, 18, 4266, 512, 2455, 300, 3844, 810, 2190, 225, 1059, 18, 21, 1366, 512, 2455, 358, 678, 1584, 44, 3399, 16351, 225, 1059, 18, 22, 6617, 537, 3399, 16351, 358, 3325, 678, 1584, 44, 11013, 225, 1059, 18, 24, 7412, 678, 1584, 44, 358, 3399, 16351, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 4266, 261, 11890, 5034, 3844, 13, 2713, 225, 288, 203, 203, 3639, 678, 1584, 44, 18, 1991, 18, 31604, 12, 22, 11706, 2934, 1132, 12, 8949, 13, 2932, 8863, 203, 540, 203, 3639, 467, 59, 1584, 44, 67, 8924, 18, 12908, 537, 12, 2867, 12, 2211, 3631, 3844, 1769, 203, 540, 203, 3639, 467, 59, 1584, 44, 67, 8924, 18, 13866, 12, 2867, 12, 2211, 3631, 3844, 1769, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xDC750c9a411e3BfA0fB0Dd1248251D5831321352/sources/cache/solpp-generated-contracts/Bytes.sol
NOTE: theoretically possible overflow of (_start + 0x20)
function bytesToBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32 r) { uint256 offset = _start + 0x20; require(_bytes.length >= offset, "btb32"); assembly { r := mload(add(_bytes, offset)) } }
749,288
[ 1, 17857, 30, 326, 479, 88, 6478, 3323, 9391, 434, 261, 67, 1937, 397, 374, 92, 3462, 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 ]
[ 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, 0 ]
[ 1, 565, 445, 1731, 21033, 1578, 12, 3890, 3778, 389, 3890, 16, 2254, 5034, 389, 1937, 13, 2713, 16618, 1135, 261, 3890, 1578, 436, 13, 288, 203, 3639, 2254, 5034, 1384, 273, 389, 1937, 397, 374, 92, 3462, 31, 203, 3639, 2583, 24899, 3890, 18, 2469, 1545, 1384, 16, 315, 70, 18587, 1578, 8863, 203, 3639, 19931, 288, 203, 5411, 436, 519, 312, 945, 12, 1289, 24899, 3890, 16, 1384, 3719, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x31EaFefAda2c68C6476b344bd7c9E8B4260879AA/sources/BigBang.sol
Add a new lp to the pool. Can only be called by the owner. XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accRigelPerShare: 0 })); }
15,703,373
[ 1, 986, 279, 394, 12423, 358, 326, 2845, 18, 4480, 1338, 506, 2566, 635, 326, 3410, 18, 11329, 5467, 4269, 527, 326, 1967, 511, 52, 1147, 1898, 2353, 3647, 18, 534, 359, 14727, 903, 506, 15216, 730, 731, 309, 1846, 741, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 527, 12, 11890, 5034, 389, 9853, 2148, 16, 467, 654, 39, 3462, 389, 9953, 1345, 16, 1426, 389, 1918, 1891, 13, 1071, 1338, 5541, 288, 203, 3639, 309, 261, 67, 1918, 1891, 13, 288, 203, 5411, 8039, 1891, 16639, 5621, 203, 3639, 289, 203, 3639, 2254, 5034, 1142, 17631, 1060, 1768, 273, 1203, 18, 2696, 405, 787, 1768, 692, 1203, 18, 2696, 294, 787, 1768, 31, 203, 3639, 2078, 8763, 2148, 273, 2078, 8763, 2148, 18, 1289, 24899, 9853, 2148, 1769, 203, 3639, 2845, 966, 18, 6206, 12, 2864, 966, 12590, 203, 5411, 12423, 1345, 30, 389, 9953, 1345, 16, 203, 5411, 4767, 2148, 30, 389, 9853, 2148, 16, 203, 5411, 1142, 17631, 1060, 1768, 30, 1142, 17631, 1060, 1768, 16, 203, 5411, 4078, 54, 360, 292, 2173, 9535, 30, 374, 203, 3639, 289, 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 ]
./full_match/1/0xC6eda45cC5b2e6E5E962D8bC33e6b785E3754477/sources/ERC20.sol
* @dev @dev Destroys `amount` tokens from msg.sender, reducing the total supply. Requirements: - msg.sender must have at least `value` tokens./
function burn(uint256 value) external { _burn(msg.sender, value); }
3,188,066
[ 1, 9378, 28599, 1375, 8949, 68, 2430, 628, 1234, 18, 15330, 16, 9299, 2822, 326, 2078, 14467, 18, 29076, 30, 300, 1234, 18, 15330, 1297, 1240, 622, 4520, 1375, 1132, 68, 2430, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 18305, 12, 11890, 5034, 460, 13, 3903, 288, 203, 3639, 389, 70, 321, 12, 3576, 18, 15330, 16, 460, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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; // This contract is a fork of Dr. Todd Proebsting's parimutuel contract. https://programtheblockchain.com/posts/2018/05/08/writing-a-parimutuel-wager-contract/ // Additional gas guzzling shitcoding by Woody Deck. contract WhatDoesNadiaThink { address public owner; string public question; string public questionType; string public answerHash; bytes32[] public responses; uint256 public marketClosureTime; uint256 public timeout; uint256 public integrityFee; uint256 public integrityPercentage; uint256 public winningAnswer; uint256 public total; event AddressandAnswer(address indexed _from, uint256 indexed _result, uint _value); constructor(string _question, bytes32[] _responses, string _questionType, string _answerHash, uint256 _timeQuestionIsOpen) public payable { owner = msg.sender; question = _question; responses = _responses; marketClosureTime = now + _timeQuestionIsOpen; // The time in seconds that the market is open. After this time, the answer() function will revert all incoming transactions // until close() is executed by the owner. The frontend of the Dapp will check if the question is open for answer by seeing if the closure time has passed. Transacting // manually outside of the Dapp will mean you need to calculate this time yourself. timeout = now + _timeQuestionIsOpen + 1209600; // The contract function cancel() can be executed by anyone after 14 days after market closure (1,209,600 seconds is 14 days). // This is to allow for refunds if the answer is not posted in a timely manner. The market can still be resolved normally if the contract owner posts the result after // 14 days, but before anyone calls cancel(). questionType = _questionType; // Categories are art, fact, and opinion. answerHash = _answerHash; // Hash of correct answer to verify integrity of the posted answer. integrityPercentage = 5; // The market integrity fee (5% of the total) goes to the contract owner. It is to strongly encourage answer secrecy and fair play. The amount is about double what could be realistically stolen via insider trading without being easily detected forensically. winningAnswer = 1234; // Set initially to 1234 (all possible answers) so the frontend can recognize when the market is closed, but not yet resolved with an answer. The variable winningAnswer is purely statistical in nature. total = msg.value; // This contract version is payable so the market can be seeded with free Ether to incentivize answers. } enum States { Open, Resolved, Cancelled } States state = States.Open; mapping(address => mapping(uint256 => uint256)) public answerAmount; mapping(uint256 => uint256) public totalPerResponse; uint256 winningResponse; function answer(uint256 result) public payable { if (now > marketClosureTime) { revert(); // Prevents answers after the market closes. } require(state == States.Open); answerAmount[msg.sender][result] += msg.value; totalPerResponse[result] += msg.value; total += msg.value; require(total < 2 ** 128); // Avoid overflow possibility. emit AddressandAnswer(msg.sender, result, msg.value); } function resolve(uint256 _winningResponse) public { require(now > marketClosureTime && state == States.Open); // States of smart contracts are updated only when someone transacts with them. The answer function looks up the Unix time that is converted on the front end to see if the market is still open. The state doesn't change until resolved, so both cases must be true in order to use the resolve() function, otherwise the owner could resolve early or change the answer after. ' require(msg.sender == owner); winningResponse = _winningResponse; // This is the internally used integer, as arrays in Solidity start from 0. winningAnswer = winningResponse + 1; // Publically posts the correct answer. The '+ 1' addition is for the frontend and to avoid layman confusion with arrays that start from zero. if (totalPerResponse[winningResponse] == 0) { state = States.Cancelled; // If nobody bet on the winning answer, the market is cancelled, else it is resolved. Losing bets will be refunded. } else { state = States.Resolved; integrityFee = total * integrityPercentage/100; // Only collect the integrityFee if the market resolves. It would be a mess to take upfront in case of cancel() being executed. msg.sender.transfer(integrityFee); // The integrityFee goes to the owner. } } function claim() public { require(state == States.Resolved); uint256 amount = answerAmount[msg.sender][winningResponse] * (total - integrityFee) / totalPerResponse[winningResponse]; // Subtract the integrityFee from the total before paying out winners. answerAmount[msg.sender][winningResponse] = 0; msg.sender.transfer(amount); } function cancel() public { require(state != States.Resolved); require(msg.sender == owner || now > timeout); state = States.Cancelled; } function refund(uint256 result) public { require(state == States.Cancelled); uint256 amount = answerAmount[msg.sender][result]; // You have to manually choose which answer you bet on because every answer is now entitled to a refund. Please when manually requesting a refund outside of the Dapp that Answer 1 is 0, Answer 2 is 1, Answer is 3, and Answer 4 is 3 as arrays start from 0. There is nothing bad that happens if you screw this up except a waste of gas. answerAmount[msg.sender][result] = 0; msg.sender.transfer(amount); } }
until close() is executed by the owner. The frontend of the Dapp will check if the question is open for answer by seeing if the closure time has passed. Transacting manually outside of the Dapp will mean you need to calculate this time yourself. This is to allow for refunds if the answer is not posted in a timely manner. The market can still be resolved normally if the contract owner posts the result after 14 days, but before anyone calls cancel().
{ owner = msg.sender; question = _question; responses = _responses; } States state = States.Open; mapping(address => mapping(uint256 => uint256)) public answerAmount; mapping(uint256 => uint256) public totalPerResponse; uint256 winningResponse;
12,695,950
[ 1, 12198, 1746, 1435, 353, 7120, 635, 326, 3410, 18, 1021, 15442, 434, 326, 463, 2910, 903, 866, 309, 326, 5073, 353, 1696, 364, 5803, 635, 2621, 310, 309, 326, 7213, 813, 711, 2275, 18, 2604, 621, 310, 10036, 8220, 434, 326, 463, 2910, 903, 3722, 1846, 1608, 358, 4604, 333, 813, 3433, 2890, 18, 1220, 353, 358, 1699, 364, 16255, 87, 309, 326, 5803, 353, 486, 23082, 316, 279, 1658, 2357, 21296, 18, 1021, 13667, 848, 4859, 506, 4640, 15849, 309, 326, 6835, 3410, 10775, 326, 563, 1839, 5045, 4681, 16, 1496, 1865, 1281, 476, 4097, 3755, 7675, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 288, 203, 3639, 3410, 273, 1234, 18, 15330, 31, 203, 3639, 5073, 273, 389, 4173, 31, 203, 3639, 7220, 273, 389, 11822, 31, 203, 565, 289, 203, 203, 565, 29577, 919, 273, 29577, 18, 3678, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 11890, 5034, 516, 2254, 5034, 3719, 1071, 5803, 6275, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 1071, 2078, 2173, 1064, 31, 203, 203, 203, 565, 2254, 5034, 5657, 2093, 1064, 31, 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 ]
/** *Submitted for verification at Etherscan.io on 2020-08-23 */ // File: contracts/spec_interfaces/IContractRegistry.sol pragma solidity 0.5.16; interface IContractRegistry { event ContractAddressUpdated(string contractName, address addr); /// @dev updates the contracts address and emits a corresponding event function set(string calldata contractName, address addr) external /* onlyGovernor */; /// @dev returns the current address of the function get(string calldata contractName) external view returns (address); } // File: contracts/spec_interfaces/ICertification.sol pragma solidity 0.5.16; /// @title Elections contract interface interface ICertification /* is Ownable */ { event GuardianCertificationUpdate(address guardian, bool isCertified); /* * External methods */ /// @dev Called by a guardian as part of the automatic vote unready flow /// Used by the Election contract function isGuardianCertified(address addr) external view returns (bool isCertified); /// @dev Called by a guardian as part of the automatic vote unready flow /// Used by the Election contract function setGuardianCertification(address addr, bool isCertified) external /* Owner only */ ; /* * Governance */ /// @dev Updates the address calldata of the contract registry function setContractRegistry(IContractRegistry _contractRegistry) external /* onlyMigrationOwner */; } // File: contracts/spec_interfaces/IProtocol.sol pragma solidity 0.5.16; interface IProtocol { event ProtocolVersionChanged(string deploymentSubset, uint256 currentVersion, uint256 nextVersion, uint256 fromTimestamp); /* * External methods */ /// @dev returns true if the given deployment subset exists (i.e - is registered with a protocol version) function deploymentSubsetExists(string calldata deploymentSubset) external view returns (bool); /// @dev returns the current protocol version for the given deployment subset. function getProtocolVersion(string calldata deploymentSubset) external view returns (uint256); /* * Governor methods */ /// @dev create a new deployment subset. function createDeploymentSubset(string calldata deploymentSubset, uint256 initialProtocolVersion) external /* onlyFunctionalOwner */; /// @dev schedules a protocol version upgrade for the given deployment subset. function setProtocolVersion(string calldata deploymentSubset, uint256 nextVersion, uint256 fromTimestamp) external /* onlyFunctionalOwner */; } // File: contracts/spec_interfaces/ICommittee.sol pragma solidity 0.5.16; /// @title Elections contract interface interface ICommittee { event GuardianCommitteeChange(address addr, uint256 weight, bool certification, bool inCommittee); event CommitteeSnapshot(address[] addrs, uint256[] weights, bool[] certification); // No external functions /* * Methods restricted to other Orbs contracts */ /// @dev Called by: Elections contract /// Notifies a weight change for sorting to a relevant committee member. /// weight = 0 indicates removal of the member from the committee (for exmaple on unregister, voteUnready, voteOut) function memberWeightChange(address addr, uint256 weight) external returns (bool committeeChanged) /* onlyElectionContract */; /// @dev Called by: Elections contract /// Notifies a guardian certification change function memberCertificationChange(address addr, bool isCertified) external returns (bool committeeChanged) /* onlyElectionsContract */; /// @dev Called by: Elections contract /// Notifies a a member removal for exampl e due to voteOut / voteUnready function removeMember(address addr) external returns (bool committeeChanged) /* onlyElectionContract */; /// @dev Called by: Elections contract /// Notifies a new member applicable for committee (due to registration, unbanning, certification change) function addMember(address addr, uint256 weight, bool isCertified) external returns (bool committeeChanged) /* onlyElectionsContract */; /// @dev Called by: Elections contract /// Returns the committee members and their weights function getCommittee() external view returns (address[] memory addrs, uint256[] memory weights, bool[] memory certification); /* * Governance */ function setMaxTimeBetweenRewardAssignments(uint32 maxTimeBetweenRewardAssignments) external /* onlyFunctionalOwner onlyWhenActive */; function setMaxCommittee(uint8 maxCommitteeSize) external /* onlyFunctionalOwner onlyWhenActive */; event MaxTimeBetweenRewardAssignmentsChanged(uint32 newValue, uint32 oldValue); event MaxCommitteeSizeChanged(uint8 newValue, uint8 oldValue); /// @dev Updates the address calldata of the contract registry function setContractRegistry(IContractRegistry _contractRegistry) external /* onlyMigrationOwner */; /* * Getters */ /// @dev returns the current committee /// used also by the rewards and fees contracts function getCommitteeInfo() external view returns (address[] memory addrs, uint256[] memory weights, address[] memory orbsAddrs, bool[] memory certification, bytes4[] memory ips); /// @dev returns the current settings of the committee contract function getSettings() external view returns (uint32 maxTimeBetweenRewardAssignments, uint8 maxCommitteeSize); } // File: contracts/IStakeChangeNotifier.sol pragma solidity 0.5.16; /// @title An interface for notifying of stake change events (e.g., stake, unstake, partial unstake, restate, etc.). interface IStakeChangeNotifier { /// @dev Notifies of stake change event. /// @param _stakeOwner address The address of the subject stake owner. /// @param _amount uint256 The difference in the total staked amount. /// @param _sign bool The sign of the added (true) or subtracted (false) amount. /// @param _updatedStake uint256 The updated total staked amount. function stakeChange(address _stakeOwner, uint256 _amount, bool _sign, uint256 _updatedStake) external; /// @dev Notifies of multiple stake change events. /// @param _stakeOwners address[] The addresses of subject stake owners. /// @param _amounts uint256[] The differences in total staked amounts. /// @param _signs bool[] The signs of the added (true) or subtracted (false) amounts. /// @param _updatedStakes uint256[] The updated total staked amounts. function stakeChangeBatch(address[] calldata _stakeOwners, uint256[] calldata _amounts, bool[] calldata _signs, uint256[] calldata _updatedStakes) external; /// @dev Notifies of stake migration event. /// @param _stakeOwner address The address of the subject stake owner. /// @param _amount uint256 The migrated amount. function stakeMigration(address _stakeOwner, uint256 _amount) external; } // File: contracts/interfaces/IElections.sol pragma solidity 0.5.16; /// @title Elections contract interface interface IElections /* is IStakeChangeNotifier */ { // Election state change events event GuardianVotedUnready(address guardian); event GuardianVotedOut(address guardian); // Function calls event VoteUnreadyCasted(address voter, address subject); event VoteOutCasted(address voter, address subject); event StakeChanged(address addr, uint256 selfStake, uint256 delegated_stake, uint256 effective_stake); event GuardianStatusUpdated(address addr, bool readyToSync, bool readyForCommittee); // Governance event VoteUnreadyTimeoutSecondsChanged(uint32 newValue, uint32 oldValue); event MinSelfStakePercentMilleChanged(uint32 newValue, uint32 oldValue); event VoteOutPercentageThresholdChanged(uint8 newValue, uint8 oldValue); event VoteUnreadyPercentageThresholdChanged(uint8 newValue, uint8 oldValue); /* * External methods */ /// @dev Called by a guardian as part of the automatic vote-out flow function voteUnready(address subject_addr) external; /// @dev casts a voteOut vote by the sender to the given address function voteOut(address subjectAddr) external; /// @dev Called by a guardian when ready to start syncing with other nodes function readyToSync() external; /// @dev Called by a guardian when ready to join the committee, typically after syncing is complete or after being voted out function readyForCommittee() external; /* * Methods restricted to other Orbs contracts */ /// @dev Called by: delegation contract /// Notifies a delegated stake change event /// total_delegated_stake = 0 if addr delegates to another guardian function delegatedStakeChange(address addr, uint256 selfStake, uint256 delegatedStake, uint256 totalDelegatedStake) external /* onlyDelegationContract */; /// @dev Called by: guardian registration contract /// Notifies a new guardian was registered function guardianRegistered(address addr) external /* onlyGuardiansRegistrationContract */; /// @dev Called by: guardian registration contract /// Notifies a new guardian was unregistered function guardianUnregistered(address addr) external /* onlyGuardiansRegistrationContract */; /// @dev Called by: guardian registration contract /// Notifies on a guardian certification change function guardianCertificationChanged(address addr, bool isCertified) external /* onlyCertificationContract */; /* * Governance */ /// @dev Updates the address of the contract registry function setContractRegistry(IContractRegistry _contractRegistry) external /* onlyMigrationOwner */; function setVoteUnreadyTimeoutSeconds(uint32 voteUnreadyTimeoutSeconds) external /* onlyFunctionalOwner onlyWhenActive */; function setMinSelfStakePercentMille(uint32 minSelfStakePercentMille) external /* onlyFunctionalOwner onlyWhenActive */; function setVoteOutPercentageThreshold(uint8 voteUnreadyPercentageThreshold) external /* onlyFunctionalOwner onlyWhenActive */; function setVoteUnreadyPercentageThreshold(uint8 voteUnreadyPercentageThreshold) external /* onlyFunctionalOwner onlyWhenActive */; function getSettings() external view returns ( uint32 voteUnreadyTimeoutSeconds, uint32 minSelfStakePercentMille, uint8 voteUnreadyPercentageThreshold, uint8 voteOutPercentageThreshold ); } // File: contracts/spec_interfaces/IGuardiansRegistration.sol pragma solidity 0.5.16; /// @title Elections contract interface interface IGuardiansRegistration { event GuardianRegistered(address addr); event GuardianDataUpdated(address addr, bytes4 ip, address orbsAddr, string name, string website, string contact); event GuardianUnregistered(address addr); event GuardianMetadataChanged(address addr, string key, string newValue, string oldValue); /* * External methods */ /// @dev Called by a participant who wishes to register as a guardian function registerGuardian(bytes4 ip, address orbsAddr, string calldata name, string calldata website, string calldata contact) external; /// @dev Called by a participant who wishes to update its propertires function updateGuardian(bytes4 ip, address orbsAddr, string calldata name, string calldata website, string calldata contact) external; /// @dev Called by a participant who wishes to update its IP address (can be call by both main and Orbs addresses) function updateGuardianIp(bytes4 ip) external /* onlyWhenActive */; /// @dev Called by a participant to update additional guardian metadata properties. function setMetadata(string calldata key, string calldata value) external; /// @dev Called by a participant to get additional guardian metadata properties. function getMetadata(address addr, string calldata key) external view returns (string memory); /// @dev Called by a participant who wishes to unregister function unregisterGuardian() external; /// @dev Returns a guardian's data /// Used also by the Election contract function getGuardianData(address addr) external view returns (bytes4 ip, address orbsAddr, string memory name, string memory website, string memory contact, uint registration_time, uint last_update_time); /// @dev Returns the Orbs addresses of a list of guardians /// Used also by the committee contract function getGuardiansOrbsAddress(address[] calldata addrs) external view returns (address[] memory orbsAddrs); /// @dev Returns a guardian's ip /// Used also by the Election contract function getGuardianIp(address addr) external view returns (bytes4 ip); /// @dev Returns guardian ips function getGuardianIps(address[] calldata addr) external view returns (bytes4[] memory ips); /// @dev Returns true if the given address is of a registered guardian /// Used also by the Election contract function isRegistered(address addr) external view returns (bool); /* * Methods restricted to other Orbs contracts */ /// @dev Translates a list guardians Ethereum addresses to Orbs addresses /// Used by the Election contract function getOrbsAddresses(address[] calldata ethereumAddrs) external view returns (address[] memory orbsAddr); /// @dev Translates a list guardians Orbs addresses to Ethereum addresses /// Used by the Election contract function getEthereumAddresses(address[] calldata orbsAddrs) external view returns (address[] memory ethereumAddr); /// @dev Resolves the ethereum address for a guardian, given an Ethereum/Orbs address function resolveGuardianAddress(address ethereumOrOrbsAddress) external view returns (address mainAddress); } // File: contracts/spec_interfaces/ISubscriptions.sol pragma solidity 0.5.16; /// @title Subscriptions contract interface interface ISubscriptions { event SubscriptionChanged(uint256 vcid, uint256 genRefTime, uint256 expiresAt, string tier, string deploymentSubset); event Payment(uint256 vcid, address by, uint256 amount, string tier, uint256 rate); event VcConfigRecordChanged(uint256 vcid, string key, string value); event SubscriberAdded(address subscriber); event VcCreated(uint256 vcid, address owner); // TODO what about isCertified, deploymentSubset? event VcOwnerChanged(uint256 vcid, address previousOwner, address newOwner); /* * Methods restricted to other Orbs contracts */ /// @dev Called by: authorized subscriber (plan) contracts /// Creates a new VC function createVC(string calldata tier, uint256 rate, uint256 amount, address owner, bool isCertified, string calldata deploymentSubset) external returns (uint, uint); /// @dev Called by: authorized subscriber (plan) contracts /// Extends the subscription of an existing VC. function extendSubscription(uint256 vcid, uint256 amount, address payer) external; /// @dev called by VC owner to set a VC config record. Emits a VcConfigRecordChanged event. function setVcConfigRecord(uint256 vcid, string calldata key, string calldata value) external /* onlyVcOwner */; /// @dev returns the value of a VC config record function getVcConfigRecord(uint256 vcid, string calldata key) external view returns (string memory); /// @dev Transfers VC ownership to a new owner (can only be called by the current owner) function setVcOwner(uint256 vcid, address owner) external /* onlyVcOwner */; /// @dev Returns the genesis ref time delay function getGenesisRefTimeDelay() external view returns (uint256); /* * Governance methods */ /// @dev Called by the owner to authorize a subscriber (plan) function addSubscriber(address addr) external /* onlyFunctionalOwner */; /// @dev Called by the owner to set the genesis ref time delay function setGenesisRefTimeDelay(uint256 newGenesisRefTimeDelay) external /* onlyFunctionalOwner */; /// @dev Updates the address of the contract registry function setContractRegistry(IContractRegistry _contractRegistry) external /* onlyMigrationOwner */; } // File: contracts/spec_interfaces/IDelegation.sol pragma solidity 0.5.16; /// @title Elections contract interface interface IDelegations /* is IStakeChangeNotifier */ { // Delegation state change events event DelegatedStakeChanged(address indexed addr, uint256 selfDelegatedStake, uint256 delegatedStake, address[] delegators, uint256[] delegatorTotalStakes); // Function calls event Delegated(address indexed from, address indexed to); /* * External methods */ /// @dev Stake delegation function delegate(address to) external /* onlyWhenActive */; function refreshStakeNotification(address addr) external /* onlyWhenActive */; /* * Governance */ /// @dev Updates the address calldata of the contract registry function setContractRegistry(IContractRegistry _contractRegistry) external /* onlyMigrationOwner */; function importDelegations(address[] calldata from, address[] calldata to, bool notifyElections) external /* onlyMigrationOwner onlyDuringDelegationImport */; function finalizeDelegationImport() external /* onlyMigrationOwner onlyDuringDelegationImport */; event DelegationsImported(address[] from, address[] to, bool notifiedElections); event DelegationImportFinalized(); /* * Getters */ function getDelegatedStakes(address addr) external view returns (uint256); function getSelfDelegatedStake(address addr) external view returns (uint256); function getDelegation(address addr) external view returns (address); function getTotalDelegatedStake() external view returns (uint256) ; } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/IMigratableStakingContract.sol pragma solidity 0.5.16; /// @title An interface for staking contracts which support stake migration. interface IMigratableStakingContract { /// @dev Returns the address of the underlying staked token. /// @return IERC20 The address of the token. function getToken() external view returns (IERC20); /// @dev Stakes ORBS tokens on behalf of msg.sender. This method assumes that the user has already approved at least /// the required amount using ERC20 approve. /// @param _stakeOwner address The specified stake owner. /// @param _amount uint256 The number of tokens to stake. function acceptMigration(address _stakeOwner, uint256 _amount) external; event AcceptedMigration(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); } // File: contracts/IStakingContract.sol pragma solidity 0.5.16; /// @title An interface for staking contracts. interface IStakingContract { /// @dev Stakes ORBS tokens on behalf of msg.sender. This method assumes that the user has already approved at least /// the required amount using ERC20 approve. /// @param _amount uint256 The amount of tokens to stake. function stake(uint256 _amount) external; /// @dev Unstakes ORBS tokens from msg.sender. If successful, this will start the cooldown period, after which /// msg.sender would be able to withdraw all of his tokens. /// @param _amount uint256 The amount of tokens to unstake. function unstake(uint256 _amount) external; /// @dev Requests to withdraw all of staked ORBS tokens back to msg.sender. Stake owners can withdraw their ORBS /// tokens only after previously unstaking them and after the cooldown period has passed (unless the contract was /// requested to release all stakes). function withdraw() external; /// @dev Restakes unstaked ORBS tokens (in or after cooldown) for msg.sender. function restake() external; /// @dev Distributes staking rewards to a list of addresses by directly adding rewards to their stakes. This method /// assumes that the user has already approved at least the required amount using ERC20 approve. Since this is a /// convenience method, we aren't concerned about reaching block gas limit by using large lists. We assume that /// callers will be able to properly batch/paginate their requests. /// @param _totalAmount uint256 The total amount of rewards to distributes. /// @param _stakeOwners address[] The addresses of the stake owners. /// @param _amounts uint256[] The amounts of the rewards. function distributeRewards(uint256 _totalAmount, address[] calldata _stakeOwners, uint256[] calldata _amounts) external; /// @dev Returns the stake of the specified stake owner (excluding unstaked tokens). /// @param _stakeOwner address The address to check. /// @return uint256 The total stake. function getStakeBalanceOf(address _stakeOwner) external view returns (uint256); /// @dev Returns the total amount staked tokens (excluding unstaked tokens). /// @return uint256 The total staked tokens of all stake owners. function getTotalStakedTokens() external view returns (uint256); /// @dev Returns the time that the cooldown period ends (or ended) and the amount of tokens to be released. /// @param _stakeOwner address The address to check. /// @return cooldownAmount uint256 The total tokens in cooldown. /// @return cooldownEndTime uint256 The time when the cooldown period ends (in seconds). function getUnstakeStatus(address _stakeOwner) external view returns (uint256 cooldownAmount, uint256 cooldownEndTime); /// @dev Migrates the stake of msg.sender from this staking contract to a new approved staking contract. /// @param _newStakingContract IMigratableStakingContract The new staking contract which supports stake migration. /// @param _amount uint256 The amount of tokens to migrate. function migrateStakedTokens(IMigratableStakingContract _newStakingContract, uint256 _amount) external; event Staked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event Unstaked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event Withdrew(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event Restaked(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); event MigratedStake(address indexed stakeOwner, uint256 amount, uint256 totalStakedAmount); } // File: contracts/interfaces/IRewards.sol pragma solidity 0.5.16; /// @title Rewards contract interface interface IRewards { function assignRewards() external; function assignRewardsToCommittee(address[] calldata generalCommittee, uint256[] calldata generalCommitteeWeights, bool[] calldata certification) external /* onlyCommitteeContract */; // staking event StakingRewardsDistributed(address indexed distributer, uint256 fromBlock, uint256 toBlock, uint split, uint txIndex, address[] to, uint256[] amounts); event StakingRewardsAssigned(address[] assignees, uint256[] amounts); // todo balance? event StakingRewardsAddedToPool(uint256 added, uint256 total); event MaxDelegatorsStakingRewardsChanged(uint32 maxDelegatorsStakingRewardsPercentMille); /// @return Returns the currently unclaimed orbs token reward balance of the given address. function getStakingRewardBalance(address addr) external view returns (uint256 balance); /// @dev Distributes msg.sender's orbs token rewards to a list of addresses, by transferring directly into the staking contract. /// @dev `to[0]` must be the sender's main address /// @dev Total delegators reward (`to[1:n]`) must be less then maxDelegatorsStakingRewardsPercentMille of total amount function distributeOrbsTokenStakingRewards(uint256 totalAmount, uint256 fromBlock, uint256 toBlock, uint split, uint txIndex, address[] calldata to, uint256[] calldata amounts) external; /// @dev Transfers the given amount of orbs tokens form the sender to this contract an update the pool. function topUpStakingRewardsPool(uint256 amount) external; /* * Reward-governor methods */ /// @dev Assigns rewards and sets a new monthly rate for the pro-rata pool. function setAnnualStakingRewardsRate(uint256 annual_rate_in_percent_mille, uint256 annual_cap) external /* onlyFunctionalOwner */; // fees event FeesAssigned(uint256 generalGuardianAmount, uint256 certifiedGuardianAmount); event FeesWithdrawn(address guardian, uint256 amount); event FeesWithdrawnFromBucket(uint256 bucketId, uint256 withdrawn, uint256 total, bool isCertified); event FeesAddedToBucket(uint256 bucketId, uint256 added, uint256 total, bool isCertified); /* * External methods */ /// @return Returns the currently unclaimed orbs token reward balance of the given address. function getFeeBalance(address addr) external view returns (uint256 balance); /// @dev Transfer all of msg.sender's outstanding balance to their account function withdrawFeeFunds() external; /// @dev Called by: subscriptions contract /// Top-ups the certification fee pool with the given amount at the given rate (typically called by the subscriptions contract) function fillCertificationFeeBuckets(uint256 amount, uint256 monthlyRate, uint256 fromTimestamp) external; /// @dev Called by: subscriptions contract /// Top-ups the general fee pool with the given amount at the given rate (typically called by the subscriptions contract) function fillGeneralFeeBuckets(uint256 amount, uint256 monthlyRate, uint256 fromTimestamp) external; function getTotalBalances() external view returns (uint256 feesTotalBalance, uint256 stakingRewardsTotalBalance, uint256 bootstrapRewardsTotalBalance); // bootstrap event BootstrapRewardsAssigned(uint256 generalGuardianAmount, uint256 certifiedGuardianAmount); event BootstrapAddedToPool(uint256 added, uint256 total); event BootstrapRewardsWithdrawn(address guardian, uint256 amount); /* * External methods */ /// @return Returns the currently unclaimed bootstrap balance of the given address. function getBootstrapBalance(address addr) external view returns (uint256 balance); /// @dev Transfer all of msg.sender's outstanding balance to their account function withdrawBootstrapFunds() external; /// @return The timestamp of the last reward assignment. function getLastRewardAssignmentTime() external view returns (uint256 time); /// @dev Transfers the given amount of bootstrap tokens form the sender to this contract and update the pool. /// Assumes the tokens were approved for transfer function topUpBootstrapPool(uint256 amount) external; /* * Reward-governor methods */ /// @dev Assigns rewards and sets a new monthly rate for the geenral commitee bootstrap. function setGeneralCommitteeAnnualBootstrap(uint256 annual_amount) external /* onlyFunctionalOwner */; /// @dev Assigns rewards and sets a new monthly rate for the certification commitee bootstrap. function setCertificationCommitteeAnnualBootstrap(uint256 annual_amount) external /* onlyFunctionalOwner */; event EmergencyWithdrawal(address addr); function emergencyWithdraw() external /* onlyMigrationManager */; /* * General governance */ /// @dev Updates the address of the contract registry function setContractRegistry(IContractRegistry _contractRegistry) external /* onlyMigrationOwner */; } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/WithClaimableMigrationOwnership.sol pragma solidity 0.5.16; /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract WithClaimableMigrationOwnership is Context{ address private _migrationOwner; address pendingMigrationOwner; event MigrationOwnershipTransferred(address indexed previousMigrationOwner, address indexed newMigrationOwner); /** * @dev Initializes the contract setting the deployer as the initial migrationMigrationOwner. */ constructor () internal { address msgSender = _msgSender(); _migrationOwner = msgSender; emit MigrationOwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current migrationOwner. */ function migrationOwner() public view returns (address) { return _migrationOwner; } /** * @dev Throws if called by any account other than the migrationOwner. */ modifier onlyMigrationOwner() { require(isMigrationOwner(), "WithClaimableMigrationOwnership: caller is not the migrationOwner"); _; } /** * @dev Returns true if the caller is the current migrationOwner. */ function isMigrationOwner() public view returns (bool) { return _msgSender() == _migrationOwner; } /** * @dev Leaves the contract without migrationOwner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current migrationOwner. * * NOTE: Renouncing migrationOwnership will leave the contract without an migrationOwner, * thereby removing any functionality that is only available to the migrationOwner. */ function renounceMigrationOwnership() public onlyMigrationOwner { emit MigrationOwnershipTransferred(_migrationOwner, address(0)); _migrationOwner = address(0); } /** * @dev Transfers migrationOwnership of the contract to a new account (`newOwner`). */ function _transferMigrationOwnership(address newMigrationOwner) internal { require(newMigrationOwner != address(0), "MigrationOwner: new migrationOwner is the zero address"); emit MigrationOwnershipTransferred(_migrationOwner, newMigrationOwner); _migrationOwner = newMigrationOwner; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingMigrationOwner() { require(msg.sender == pendingMigrationOwner, "Caller is not the pending migrationOwner"); _; } /** * @dev Allows the current migrationOwner to set the pendingOwner address. * @param newMigrationOwner The address to transfer migrationOwnership to. */ function transferMigrationOwnership(address newMigrationOwner) public onlyMigrationOwner { pendingMigrationOwner = newMigrationOwner; } /** * @dev Allows the pendingMigrationOwner address to finalize the transfer. */ function claimMigrationOwnership() external onlyPendingMigrationOwner { _transferMigrationOwnership(pendingMigrationOwner); pendingMigrationOwner = address(0); } } // File: contracts/Lockable.sol pragma solidity 0.5.16; /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Lockable is WithClaimableMigrationOwnership { bool public locked; event Locked(); event Unlocked(); function lock() external onlyMigrationOwner { locked = true; emit Locked(); } function unlock() external onlyMigrationOwner { locked = false; emit Unlocked(); } modifier onlyWhenActive() { require(!locked, "contract is locked for this operation"); _; } } // File: contracts/spec_interfaces/IProtocolWallet.sol pragma solidity 0.5.16; pragma solidity 0.5.16; /// @title Protocol Wallet interface interface IProtocolWallet { event FundsAddedToPool(uint256 added, uint256 total); event ClientSet(address client); event MaxAnnualRateSet(uint256 maxAnnualRate); event EmergencyWithdrawal(address addr); /// @dev Returns the address of the underlying staked token. /// @return IERC20 The address of the token. function getToken() external view returns (IERC20); /// @dev Returns the address of the underlying staked token. /// @return IERC20 The address of the token. function getBalance() external view returns (uint256 balance); /// @dev Transfers the given amount of orbs tokens form the sender to this contract an update the pool. function topUp(uint256 amount) external; /// @dev Withdraw from pool to a the sender's address, limited by the pool's MaxRate. /// A maximum of MaxRate x time period since the last Orbs transfer may be transferred out. /// Flow: /// PoolWallet.approveTransfer(amount); /// ERC20.transferFrom(PoolWallet, client, amount) function withdraw(uint256 amount) external; /* onlyClient */ /* Governance */ /// @dev Sets a new transfer rate for the Orbs pool. function setMaxAnnualRate(uint256 annual_rate) external; /* onlyMigrationManager */ /// @dev transfer the entire pool's balance to a new wallet. function emergencyWithdraw() external; /* onlyMigrationManager */ /// @dev sets the address of the new contract function setClient(address client) external; /* onlyFunctionalManager */ } // File: contracts/ContractRegistryAccessor.sol pragma solidity 0.5.16; contract ContractRegistryAccessor is WithClaimableMigrationOwnership { IContractRegistry contractRegistry; event ContractRegistryAddressUpdated(address addr); function setContractRegistry(IContractRegistry _contractRegistry) external onlyMigrationOwner { contractRegistry = _contractRegistry; emit ContractRegistryAddressUpdated(address(_contractRegistry)); } function getProtocolContract() public view returns (IProtocol) { return IProtocol(contractRegistry.get("protocol")); } function getRewardsContract() public view returns (IRewards) { return IRewards(contractRegistry.get("rewards")); } function getCommitteeContract() public view returns (ICommittee) { return ICommittee(contractRegistry.get("committee")); } function getElectionsContract() public view returns (IElections) { return IElections(contractRegistry.get("elections")); } function getDelegationsContract() public view returns (IDelegations) { return IDelegations(contractRegistry.get("delegations")); } function getGuardiansRegistrationContract() public view returns (IGuardiansRegistration) { return IGuardiansRegistration(contractRegistry.get("guardiansRegistration")); } function getCertificationContract() public view returns (ICertification) { return ICertification(contractRegistry.get("certification")); } function getStakingContract() public view returns (IStakingContract) { return IStakingContract(contractRegistry.get("staking")); } function getSubscriptionsContract() public view returns (ISubscriptions) { return ISubscriptions(contractRegistry.get("subscriptions")); } function getStakingRewardsWallet() public view returns (IProtocolWallet) { return IProtocolWallet(contractRegistry.get("stakingRewardsWallet")); } function getBootstrapRewardsWallet() public view returns (IProtocolWallet) { return IProtocolWallet(contractRegistry.get("bootstrapRewardsWallet")); } } // File: contracts/WithClaimableFunctionalOwnership.sol pragma solidity 0.5.16; /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract WithClaimableFunctionalOwnership is Context{ address private _functionalOwner; address pendingFunctionalOwner; event FunctionalOwnershipTransferred(address indexed previousFunctionalOwner, address indexed newFunctionalOwner); /** * @dev Initializes the contract setting the deployer as the initial functionalFunctionalOwner. */ constructor () internal { address msgSender = _msgSender(); _functionalOwner = msgSender; emit FunctionalOwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current functionalOwner. */ function functionalOwner() public view returns (address) { return _functionalOwner; } /** * @dev Throws if called by any account other than the functionalOwner. */ modifier onlyFunctionalOwner() { require(isFunctionalOwner(), "WithClaimableFunctionalOwnership: caller is not the functionalOwner"); _; } /** * @dev Returns true if the caller is the current functionalOwner. */ function isFunctionalOwner() public view returns (bool) { return _msgSender() == _functionalOwner; } /** * @dev Leaves the contract without functionalOwner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current functionalOwner. * * NOTE: Renouncing functionalOwnership will leave the contract without an functionalOwner, * thereby removing any functionality that is only available to the functionalOwner. */ function renounceFunctionalOwnership() public onlyFunctionalOwner { emit FunctionalOwnershipTransferred(_functionalOwner, address(0)); _functionalOwner = address(0); } /** * @dev Transfers functionalOwnership of the contract to a new account (`newOwner`). */ function _transferFunctionalOwnership(address newFunctionalOwner) internal { require(newFunctionalOwner != address(0), "FunctionalOwner: new functionalOwner is the zero address"); emit FunctionalOwnershipTransferred(_functionalOwner, newFunctionalOwner); _functionalOwner = newFunctionalOwner; } /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingFunctionalOwner() { require(msg.sender == pendingFunctionalOwner, "Caller is not the pending functionalOwner"); _; } /** * @dev Allows the current functionalOwner to set the pendingOwner address. * @param newFunctionalOwner The address to transfer functionalOwnership to. */ function transferFunctionalOwnership(address newFunctionalOwner) public onlyFunctionalOwner { pendingFunctionalOwner = newFunctionalOwner; } /** * @dev Allows the pendingFunctionalOwner address to finalize the transfer. */ function claimFunctionalOwnership() external onlyPendingFunctionalOwner { _transferFunctionalOwnership(pendingFunctionalOwner); pendingFunctionalOwner = address(0); } } // File: ../contracts/Certification.sol pragma solidity 0.5.16; contract Certification is ICertification, ContractRegistryAccessor, WithClaimableFunctionalOwnership, Lockable { mapping (address => bool) guardianCertification; /* * External methods */ function isGuardianCertified(address addr) external view returns (bool isCertified) { return guardianCertification[addr]; } function setGuardianCertification(address addr, bool isCertified) external onlyFunctionalOwner onlyWhenActive { guardianCertification[addr] = isCertified; emit GuardianCertificationUpdate(addr, isCertified); getElectionsContract().guardianCertificationChanged(addr, isCertified); } }
* @dev Throws if called by any account other than the functionalOwner./
modifier onlyFunctionalOwner() { require(isFunctionalOwner(), "WithClaimableFunctionalOwnership: caller is not the functionalOwner"); _; }
947,817
[ 1, 21845, 309, 2566, 635, 1281, 2236, 1308, 2353, 326, 18699, 5541, 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 ]
[ 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, 0, 0 ]
[ 1, 565, 9606, 1338, 2083, 287, 5541, 1435, 288, 203, 3639, 2583, 12, 291, 2083, 287, 5541, 9334, 315, 1190, 9762, 429, 2083, 287, 5460, 12565, 30, 4894, 353, 486, 326, 18699, 5541, 8863, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.7.0; import '@openzeppelin/contracts/math/SafeMath.sol'; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol'; import './libraries/UniswapV2Library.sol'; import './interfaces/IFeeSplitter.sol'; import './interfaces/ILockedLiquidityEvent.sol'; import './interfaces/ITDAO.sol'; contract FeeController { using SafeMath for uint256; address public pairWETH; address public pairWBTC; address public pairUSDC; address public pairMUSD; address public WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public WBTC = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; address public USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public MUSD = 0xe2f2a5C287993345a840Db3B0845fbC70f5935a5; address public pair; address public tdao; address public feeSplitter; address public lle; uint256 public fee = 100; // max 1000 = 10% artificial clamp uint256 public constant BASE = 10000; // fee/base => 100/10000 => 0.01 => 1.0% mapping(address => bool) private _noFeeList; mapping(address => bool) private _blockList; modifier onlyTDAO() { require(msg.sender == tdao, 'FeeController: Function call not allowed.'); _; } constructor( address _tdao, address _addressTokenB, address _addressFactory, address _feeSplitter ) public { tdao = _tdao; pair = IUniswapV2Factory(_addressFactory).getPair(_addressTokenB, tdao); feeSplitter = _feeSplitter; lle = address(ITDAO(tdao).lockedLiquidityEvent()); require( lle != address(0), 'FeeController: Must first deploy and set LockedLiquidityEvent' ); pairWETH = UniswapV2Library.pairFor(_addressFactory, WETH, tdao); pairWBTC = UniswapV2Library.pairFor(_addressFactory, WBTC, tdao); pairUSDC = UniswapV2Library.pairFor(_addressFactory, USDC, tdao); pairMUSD = UniswapV2Library.pairFor(_addressFactory, MUSD, tdao); _editNoFeeList(pairWETH, true); _editNoFeeList(pairWBTC, true); _editNoFeeList(pairUSDC, true); _editNoFeeList(pairMUSD, true); _editNoFeeList(pair, true); _editNoFeeList(lle, true); _editNoFeeList(feeSplitter, true); _editNoFeeList(_treasuryVault(), true); // Reward Vaults must be whitelisted to avoid fee infinite loops. _editNoFeeList(IFeeSplitter(feeSplitter).nftRewardsVault(), true); _editNoFeeList(IFeeSplitter(feeSplitter).trigRewardsVault(), true); } function isPaused() external view returns (bool) { return _isPaused(); } function isFeeless(address account) external view returns (bool) { return _noFeeList[account]; } function isBlocked(address account) external view returns (bool) { return _blockList[account]; } function setFee(uint256 _fee) external onlyTDAO { require( _fee >= 10 && _fee <= 1000, 'FeeController: Fee must be in between 10 and 1000' ); fee = _fee; } function editNoFeeList(address _address, bool _noFee) external onlyTDAO { require( _address != feeSplitter, 'FeeController: Cannot charge fees to fee splitter.' ); require( _address != _treasuryVault(), 'FeeController: Cannot charge fees to treasury.' ); require( _address != IFeeSplitter(feeSplitter).nftRewardsVault(), 'FeeController: Cannot charge fees to NFT reward vault.' ); require( _address != IFeeSplitter(feeSplitter).trigRewardsVault(), 'FeeController: Cannot charge fees to Trig reward vault.' ); _editNoFeeList(_address, _noFee); } function editBlockList(address _address, bool _block) external onlyTDAO { require(_address != pair, 'FeeController: Cannot block main Uniswap pair.'); require( _address != _treasuryVault(), 'FeeController: Cannot block treasury.' ); require( _address != feeSplitter, 'FeeController: Cannot block fee splitter.' ); require( _address != IFeeSplitter(feeSplitter).nftRewardsVault(), 'FeeController: Cannot block NFT reward vault.' ); require( _address != IFeeSplitter(feeSplitter).trigRewardsVault(), 'FeeController: Cannot block Trig reward vault.' ); _editBlockList(_address, _block); } function applyFee( address sender, address recipient, uint256 amount ) external view returns (uint256 transferToRecipientAmount, uint256 transferToFeeAmount) { require(!_blockList[sender], 'FeeController: Sender account is blocked.'); require( !_blockList[recipient], 'FeeController: Recipient account is blocked.' ); if (recipient != pair) { require(!_isPaused(), 'FeeController: Trading has not started.'); } if (_noFeeList[sender]) { // Do not charge a fee when vault is sending. Avoid infinite loop. // Do not charge a fee when pair is sending. No fees on buy. transferToFeeAmount = 0; transferToRecipientAmount = amount; } else { transferToFeeAmount = amount.mul(fee).div(BASE); transferToRecipientAmount = amount.sub(transferToFeeAmount); } } function _treasuryVault() internal view returns (address) { return IFeeSplitter(feeSplitter).treasuryVault(); } function _isPaused() internal view returns (bool) { return block.timestamp < ILockedLiquidityEvent(lle).startTradingTime(); } function _editNoFeeList(address _address, bool _noFee) internal { _noFeeList[_address] = _noFee; } function _editBlockList(address _address, bool _block) internal { _blockList[_address] = _block; } }
Do not charge a fee when vault is sending. Avoid infinite loop. Do not charge a fee when pair is sending. No fees on buy.
function applyFee( address sender, address recipient, uint256 amount ) external view returns (uint256 transferToRecipientAmount, uint256 transferToFeeAmount) { require(!_blockList[sender], 'FeeController: Sender account is blocked.'); require( !_blockList[recipient], 'FeeController: Recipient account is blocked.' ); if (recipient != pair) { require(!_isPaused(), 'FeeController: Trading has not started.'); } if (_noFeeList[sender]) { transferToFeeAmount = 0; transferToRecipientAmount = amount; transferToFeeAmount = amount.mul(fee).div(BASE); transferToRecipientAmount = amount.sub(transferToFeeAmount); } }
6,383,220
[ 1, 3244, 486, 13765, 279, 14036, 1347, 9229, 353, 5431, 18, 17843, 14853, 2798, 18, 2256, 486, 13765, 279, 14036, 1347, 3082, 353, 5431, 18, 2631, 1656, 281, 603, 30143, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 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, 225, 445, 2230, 14667, 12, 203, 565, 1758, 5793, 16, 203, 565, 1758, 8027, 16, 203, 565, 2254, 5034, 3844, 203, 225, 262, 203, 565, 3903, 203, 565, 1476, 203, 565, 1135, 261, 11890, 5034, 7412, 774, 18241, 6275, 16, 2254, 5034, 7412, 774, 14667, 6275, 13, 203, 225, 288, 203, 565, 2583, 12, 5, 67, 2629, 682, 63, 15330, 6487, 296, 14667, 2933, 30, 15044, 2236, 353, 14547, 1093, 1769, 203, 565, 2583, 12, 203, 1377, 401, 67, 2629, 682, 63, 20367, 6487, 203, 1377, 296, 14667, 2933, 30, 23550, 2236, 353, 14547, 1093, 203, 565, 11272, 203, 203, 565, 309, 261, 20367, 480, 3082, 13, 288, 203, 1377, 2583, 12, 5, 67, 291, 28590, 9334, 296, 14667, 2933, 30, 2197, 7459, 711, 486, 5746, 1093, 1769, 203, 565, 289, 203, 203, 565, 309, 261, 67, 2135, 14667, 682, 63, 15330, 5717, 288, 203, 1377, 7412, 774, 14667, 6275, 273, 374, 31, 203, 1377, 7412, 774, 18241, 6275, 273, 3844, 31, 203, 1377, 7412, 774, 14667, 6275, 273, 3844, 18, 16411, 12, 21386, 2934, 2892, 12, 8369, 1769, 203, 1377, 7412, 774, 18241, 6275, 273, 3844, 18, 1717, 12, 13866, 774, 14667, 6275, 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 ]
pragma solidity ^0.4.24; //Swap Deployer functions - descriptions can be found in Deployer.sol interface Deployer_Interface { function newContract(address _party, address user_contract, uint _start_date) external payable returns (address); } //Slightly modified SafeMath library - includes a min function library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } function min(uint a, uint b) internal pure returns (uint256) { return a < b ? a : b; } } //Swap factory functions - descriptions can be found in Factory.sol interface Factory_Interface { function createToken(uint _supply, address _party, uint _start_date) external returns (address,address, uint); function payToken(address _party, address _token_add) external; function deployContract(uint _start_date) external payable returns (address); function getBase() external view returns(address); function getVariables() external view returns (address, uint, uint, address,uint); function isWhitelisted(address _member) external view returns (bool); } /** *The DRCTLibrary contains the reference code used in the DRCT_Token (an ERC20 compliant token *representing the payout of the swap contract specified in the Factory contract). */ library DRCTLibrary{ using SafeMath for uint256; /*Structs*/ /** *@dev Keeps track of balance amounts in the balances array */ struct Balance { address owner; uint amount; } struct TokenStorage{ //This is the factory contract that the token is standardized at address factory_contract; //Total supply of outstanding tokens in the contract uint total_supply; //Mapping from: swap address -> user balance struct (index for a particular user&#39;s balance can be found in swap_balances_index) mapping(address => Balance[]) swap_balances; //Mapping from: swap address -> user -> swap_balances index mapping(address => mapping(address => uint)) swap_balances_index; //Mapping from: user -> dynamic array of swap addresses (index for a particular swap can be found in user_swaps_index) mapping(address => address[]) user_swaps; //Mapping from: user -> swap address -> user_swaps index mapping(address => mapping(address => uint)) user_swaps_index; //Mapping from: user -> total balance accross all entered swaps mapping(address => uint) user_total_balances; //Mapping from: owner -> spender -> amount allowed mapping(address => mapping(address => uint)) allowed; } /*Events*/ /** *@dev events for transfer and approvals */ event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); event CreateToken(address _from, uint _value); /*Functions*/ /** *@dev Constructor - sets values for token name and token supply, as well as the *factory_contract, the swap. *@param _factory */ function startToken(TokenStorage storage self,address _factory) public { self.factory_contract = _factory; } /** *@dev ensures the member is whitelisted *@param _member is the member address that is chekced agaist the whitelist */ function isWhitelisted(TokenStorage storage self,address _member) internal view returns(bool){ Factory_Interface _factory = Factory_Interface(self.factory_contract); return _factory.isWhitelisted(_member); } /** *@dev gets the factory address */ function getFactoryAddress(TokenStorage storage self) external view returns(address){ return self.factory_contract; } /** *@dev Token Creator - This function is called by the factory contract and creates new tokens *for the user *@param _supply amount of DRCT tokens created by the factory contract for this swap *@param _owner address *@param _swap address */ function createToken(TokenStorage storage self,uint _supply, address _owner, address _swap) public{ require(msg.sender == self.factory_contract); //Update total supply of DRCT Tokens self.total_supply = self.total_supply.add(_supply); //Update the total balance of the owner self.user_total_balances[_owner] = self.user_total_balances[_owner].add(_supply); //If the user has not entered any swaps already, push a zeroed address to their user_swaps mapping to prevent default value conflicts in user_swaps_index if (self.user_swaps[_owner].length == 0) self.user_swaps[_owner].push(address(0x0)); //Add a new swap index for the owner self.user_swaps_index[_owner][_swap] = self.user_swaps[_owner].length; //Push a new swap address to the owner&#39;s swaps self.user_swaps[_owner].push(_swap); //Push a zeroed Balance struct to the swap balances mapping to prevent default value conflicts in swap_balances_index self.swap_balances[_swap].push(Balance({ owner: 0, amount: 0 })); //Add a new owner balance index for the swap self.swap_balances_index[_swap][_owner] = 1; //Push the owner&#39;s balance to the swap self.swap_balances[_swap].push(Balance({ owner: _owner, amount: _supply })); emit CreateToken(_owner,_supply); } /** *@dev Called by the factory contract, and pays out to a _party *@param _party being paid *@param _swap address */ function pay(TokenStorage storage self,address _party, address _swap) public{ require(msg.sender == self.factory_contract); uint party_balance_index = self.swap_balances_index[_swap][_party]; require(party_balance_index > 0); uint party_swap_balance = self.swap_balances[_swap][party_balance_index].amount; //reduces the users totals balance by the amount in that swap self.user_total_balances[_party] = self.user_total_balances[_party].sub(party_swap_balance); //reduces the total supply by the amount of that users in that swap self.total_supply = self.total_supply.sub(party_swap_balance); //sets the partys balance to zero for that specific swaps party balances self.swap_balances[_swap][party_balance_index].amount = 0; } /** *@dev Returns the users total balance (sum of tokens in all swaps the user has tokens in) *@param _owner user address *@return user total balance */ function balanceOf(TokenStorage storage self,address _owner) public constant returns (uint balance) { return self.user_total_balances[_owner]; } /** *@dev Getter for the total_supply of tokens in the contract *@return total supply */ function totalSupply(TokenStorage storage self) public constant returns (uint _total_supply) { return self.total_supply; } /** *@dev Removes the address from the swap balances for a swap, and moves the last address in the *swap into their place *@param _remove address of prevous owner *@param _swap address used to get last addrss of the swap to replace the removed address */ function removeFromSwapBalances(TokenStorage storage self,address _remove, address _swap) internal { uint last_address_index = self.swap_balances[_swap].length.sub(1); address last_address = self.swap_balances[_swap][last_address_index].owner; //If the address we want to remove is the final address in the swap if (last_address != _remove) { uint remove_index = self.swap_balances_index[_swap][_remove]; //Update the swap&#39;s balance index of the last address to that of the removed address index self.swap_balances_index[_swap][last_address] = remove_index; //Set the swap&#39;s Balance struct at the removed index to the Balance struct of the last address self.swap_balances[_swap][remove_index] = self.swap_balances[_swap][last_address_index]; } //Remove the swap_balances index for this address delete self.swap_balances_index[_swap][_remove]; //Finally, decrement the swap balances length self.swap_balances[_swap].length = self.swap_balances[_swap].length.sub(1); } /** *@dev This is the main function to update the mappings when a transfer happens *@param _from address to send funds from *@param _to address to send funds to *@param _amount amount of token to send */ function transferHelper(TokenStorage storage self,address _from, address _to, uint _amount) internal { //Get memory copies of the swap arrays for the sender and reciever address[] memory from_swaps = self.user_swaps[_from]; //Iterate over sender&#39;s swaps in reverse order until enough tokens have been transferred for (uint i = from_swaps.length.sub(1); i > 0; i--) { //Get the index of the sender&#39;s balance for the current swap uint from_swap_user_index = self.swap_balances_index[from_swaps[i]][_from]; Balance memory from_user_bal = self.swap_balances[from_swaps[i]][from_swap_user_index]; //If the current swap will be entirely depleted - we remove all references to it for the sender if (_amount >= from_user_bal.amount) { _amount -= from_user_bal.amount; //If this swap is to be removed, we know it is the (current) last swap in the user&#39;s user_swaps list, so we can simply decrement the length to remove it self.user_swaps[_from].length = self.user_swaps[_from].length.sub(1); //Remove the user swap index for this swap delete self.user_swaps_index[_from][from_swaps[i]]; //If the _to address already holds tokens from this swap if (self.user_swaps_index[_to][from_swaps[i]] != 0) { //Get the index of the _to balance in this swap uint to_balance_index = self.swap_balances_index[from_swaps[i]][_to]; assert(to_balance_index != 0); //Add the _from tokens to _to self.swap_balances[from_swaps[i]][to_balance_index].amount = self.swap_balances[from_swaps[i]][to_balance_index].amount.add(from_user_bal.amount); //Remove the _from address from this swap&#39;s balance array removeFromSwapBalances(self,_from, from_swaps[i]); } else { //Prepare to add a new swap by assigning the swap an index for _to if (self.user_swaps[_to].length == 0){ self.user_swaps[_to].push(address(0x0)); } self.user_swaps_index[_to][from_swaps[i]] = self.user_swaps[_to].length; //Add the new swap to _to self.user_swaps[_to].push(from_swaps[i]); //Give the reciever the sender&#39;s balance for this swap self.swap_balances[from_swaps[i]][from_swap_user_index].owner = _to; //Give the reciever the sender&#39;s swap balance index for this swap self.swap_balances_index[from_swaps[i]][_to] = self.swap_balances_index[from_swaps[i]][_from]; //Remove the swap balance index from the sending party delete self.swap_balances_index[from_swaps[i]][_from]; } //If there is no more remaining to be removed, we break out of the loop if (_amount == 0) break; } else { //The amount in this swap is more than the amount we still need to transfer uint to_swap_balance_index = self.swap_balances_index[from_swaps[i]][_to]; //If the _to address already holds tokens from this swap if (self.user_swaps_index[_to][from_swaps[i]] != 0) { //Because both addresses are in this swap, and neither will be removed, we simply update both swap balances self.swap_balances[from_swaps[i]][to_swap_balance_index].amount = self.swap_balances[from_swaps[i]][to_swap_balance_index].amount.add(_amount); } else { //Prepare to add a new swap by assigning the swap an index for _to if (self.user_swaps[_to].length == 0){ self.user_swaps[_to].push(address(0x0)); } self.user_swaps_index[_to][from_swaps[i]] = self.user_swaps[_to].length; //And push the new swap self.user_swaps[_to].push(from_swaps[i]); //_to is not in this swap, so we give this swap a new balance index for _to self.swap_balances_index[from_swaps[i]][_to] = self.swap_balances[from_swaps[i]].length; //And push a new balance for _to self.swap_balances[from_swaps[i]].push(Balance({ owner: _to, amount: _amount })); } //Finally, update the _from user&#39;s swap balance self.swap_balances[from_swaps[i]][from_swap_user_index].amount = self.swap_balances[from_swaps[i]][from_swap_user_index].amount.sub(_amount); //Because we have transferred the last of the amount to the reciever, we break; break; } } } /** *@dev ERC20 compliant transfer function *@param _to Address to send funds to *@param _amount Amount of token to send *@return true for successful */ function transfer(TokenStorage storage self, address _to, uint _amount) public returns (bool) { require(isWhitelisted(self,_to)); uint balance_owner = self.user_total_balances[msg.sender]; if ( _to == msg.sender || _to == address(0) || _amount == 0 || balance_owner < _amount ) return false; transferHelper(self,msg.sender, _to, _amount); self.user_total_balances[msg.sender] = self.user_total_balances[msg.sender].sub(_amount); self.user_total_balances[_to] = self.user_total_balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); return true; } /** *@dev ERC20 compliant transferFrom function *@param _from address to send funds from (must be allowed, see approve function) *@param _to address to send funds to *@param _amount amount of token to send *@return true for successful */ function transferFrom(TokenStorage storage self, address _from, address _to, uint _amount) public returns (bool) { require(isWhitelisted(self,_to)); uint balance_owner = self.user_total_balances[_from]; uint sender_allowed = self.allowed[_from][msg.sender]; if ( _to == _from || _to == address(0) || _amount == 0 || balance_owner < _amount || sender_allowed < _amount ) return false; transferHelper(self,_from, _to, _amount); self.user_total_balances[_from] = self.user_total_balances[_from].sub(_amount); self.user_total_balances[_to] = self.user_total_balances[_to].add(_amount); self.allowed[_from][msg.sender] = self.allowed[_from][msg.sender].sub(_amount); emit Transfer(_from, _to, _amount); return true; } /** *@dev ERC20 compliant approve function *@param _spender party that msg.sender approves for transferring funds *@param _amount amount of token to approve for sending *@return true for successful */ function approve(TokenStorage storage self, address _spender, uint _amount) public returns (bool) { self.allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** *@dev Counts addresses involved in the swap based on the length of balances array for _swap *@param _swap address *@return the length of the balances array for the swap */ function addressCount(TokenStorage storage self, address _swap) public constant returns (uint) { return self.swap_balances[_swap].length; } /** *@dev Gets the owner address and amount by specifying the swap address and index *@param _ind specified index in the swap *@param _swap specified swap address *@return the owner address associated with a particular index in a particular swap *@return the amount to transfer associated with a particular index in a particular swap */ function getBalanceAndHolderByIndex(TokenStorage storage self, uint _ind, address _swap) public constant returns (uint, address) { return (self.swap_balances[_swap][_ind].amount, self.swap_balances[_swap][_ind].owner); } /** *@dev Gets the index by specifying the swap and owner addresses *@param _owner specifed address *@param _swap specified swap address *@return the index associated with the _owner address in a particular swap */ function getIndexByAddress(TokenStorage storage self, address _owner, address _swap) public constant returns (uint) { return self.swap_balances_index[_swap][_owner]; } /** *@dev Look up how much the spender or contract is allowed to spend? *@param _owner *@param _spender party approved for transfering funds *@return the allowed amount _spender can spend of _owner&#39;s balance */ function allowance(TokenStorage storage self, address _owner, address _spender) public constant returns (uint) { return self.allowed[_owner][_spender]; } } /** *The DRCT_Token is an ERC20 compliant token representing the payout of the swap contract *specified in the Factory contract. *Each Factory contract is specified one DRCT Token and the token address can contain many *different swap contracts that are standardized at the Factory level. *The logic for the functions in this contract is housed in the DRCTLibary.sol. */ contract DRCT_Token { using DRCTLibrary for DRCTLibrary.TokenStorage; /*Variables*/ DRCTLibrary.TokenStorage public drct; /*Functions*/ /** *@dev Constructor - sets values for token name and token supply, as well as the *factory_contract, the swap. *@param _factory */ constructor() public { drct.startToken(msg.sender); } /** *@dev Token Creator - This function is called by the factory contract and creates new tokens *for the user *@param _supply amount of DRCT tokens created by the factory contract for this swap *@param _owner address *@param _swap address */ function createToken(uint _supply, address _owner, address _swap) public{ drct.createToken(_supply,_owner,_swap); } /** *@dev gets the factory address */ function getFactoryAddress() external view returns(address){ return drct.getFactoryAddress(); } /** *@dev Called by the factory contract, and pays out to a _party *@param _party being paid *@param _swap address */ function pay(address _party, address _swap) public{ drct.pay(_party,_swap); } /** *@dev Returns the users total balance (sum of tokens in all swaps the user has tokens in) *@param _owner user address *@return user total balance */ function balanceOf(address _owner) public constant returns (uint balance) { return drct.balanceOf(_owner); } /** *@dev Getter for the total_supply of tokens in the contract *@return total supply */ function totalSupply() public constant returns (uint _total_supply) { return drct.totalSupply(); } /** *ERC20 compliant transfer function *@param _to Address to send funds to *@param _amount Amount of token to send *@return true for successful */ function transfer(address _to, uint _amount) public returns (bool) { return drct.transfer(_to,_amount); } /** *@dev ERC20 compliant transferFrom function *@param _from address to send funds from (must be allowed, see approve function) *@param _to address to send funds to *@param _amount amount of token to send *@return true for successful transfer */ function transferFrom(address _from, address _to, uint _amount) public returns (bool) { return drct.transferFrom(_from,_to,_amount); } /** *@dev ERC20 compliant approve function *@param _spender party that msg.sender approves for transferring funds *@param _amount amount of token to approve for sending *@return true for successful */ function approve(address _spender, uint _amount) public returns (bool) { return drct.approve(_spender,_amount); } /** *@dev Counts addresses involved in the swap based on the length of balances array for _swap *@param _swap address *@return the length of the balances array for the swap */ function addressCount(address _swap) public constant returns (uint) { return drct.addressCount(_swap); } /** *@dev Gets the owner address and amount by specifying the swap address and index *@param _ind specified index in the swap *@param _swap specified swap address *@return the amount to transfer associated with a particular index in a particular swap *@return the owner address associated with a particular index in a particular swap */ function getBalanceAndHolderByIndex(uint _ind, address _swap) public constant returns (uint, address) { return drct.getBalanceAndHolderByIndex(_ind,_swap); } /** *@dev Gets the index by specifying the swap and owner addresses *@param _owner specifed address *@param _swap specified swap address *@return the index associated with the _owner address in a particular swap */ function getIndexByAddress(address _owner, address _swap) public constant returns (uint) { return drct.getIndexByAddress(_owner,_swap); } /** *@dev Look up how much the spender or contract is allowed to spend? *@param _owner address *@param _spender party approved for transfering funds *@return the allowed amount _spender can spend of _owner&#39;s balance */ function allowance(address _owner, address _spender) public constant returns (uint) { return drct.allowance(_owner,_spender); } } //ERC20 function interface with create token and withdraw interface Wrapped_Ether_Interface { function totalSupply() external constant returns (uint); function balanceOf(address _owner) external constant returns (uint); function transfer(address _to, uint _amount) external returns (bool); function transferFrom(address _from, address _to, uint _amount) external returns (bool); function approve(address _spender, uint _amount) external returns (bool); function allowance(address _owner, address _spender) external constant returns (uint); function withdraw(uint _value) external; function createToken() external; } interface Membership_Interface { function getMembershipType(address _member) external constant returns(uint); } /** *The Factory contract sets the standardized variables and also deploys new contracts based on *these variables for the user. */ contract Factory { using SafeMath for uint256; /*Variables*/ //Addresses of the Factory owner and oracle. For oracle information, //check www.github.com/DecentralizedDerivatives/Oracles address public owner; address public oracle_address; //Address of the user contract address public user_contract; //Address of the deployer contract address internal deployer_address; Deployer_Interface internal deployer; address public token; //A fee for creating a swap in wei. Plan is for this to be zero, however can be raised to prevent spam uint public fee; //swap fee uint public swapFee; //Duration of swap contract in days uint public duration; //Multiplier of reference rate. 2x refers to a 50% move generating a 100% move in the contract payout values uint public multiplier; //Token_ratio refers to the number of DRCT Tokens a party will get based on the number of base tokens. As an example, 1e15 indicates that a party will get 1000 DRCT Tokens based upon 1 ether of wrapped wei. uint public token_ratio; //Array of deployed contracts address[] public contracts; uint[] public startDates; address public memberContract; mapping(uint => bool) whitelistedTypes; mapping(address => uint) public created_contracts; mapping(address => uint) public token_dates; mapping(uint => address) public long_tokens; mapping(uint => address) public short_tokens; mapping(address => uint) public token_type; //1=short 2=long /*Events*/ //Emitted when a Swap is created event ContractCreation(address _sender, address _created); /*Modifiers*/ modifier onlyOwner() { require(msg.sender == owner); _; } /*Functions*/ /** *@dev Constructor - Sets owner */ constructor() public { owner = msg.sender; } /** *@dev constructor function for cloned factory */ function init(address _owner) public{ require(owner == address(0)); owner = _owner; } /** *@dev Sets the Membership contract address *@param _memberContract The new membership address */ function setMemberContract(address _memberContract) public onlyOwner() { memberContract = _memberContract; } /** *@dev Sets the member types/permissions for those whitelisted *@param _memberTypes is the list of member types */ function setWhitelistedMemberTypes(uint[] _memberTypes) public onlyOwner(){ whitelistedTypes[0] = false; for(uint i = 0; i<_memberTypes.length;i++){ whitelistedTypes[_memberTypes[i]] = true; } } /** *@dev Checks the membership type/permissions for whitelisted members *@param _member address to get membership type from */ function isWhitelisted(address _member) public view returns (bool){ Membership_Interface Member = Membership_Interface(memberContract); return whitelistedTypes[Member.getMembershipType(_member)]; } /** *@dev Gets long and short token addresses based on specified date *@param _date *@return short and long tokens&#39; addresses */ function getTokens(uint _date) public view returns(address, address){ return(long_tokens[_date],short_tokens[_date]); } /** *@dev Gets the type of Token (long and short token) for the specifed *token address *@param _token address *@return token type short = 1 and long = 2 */ function getTokenType(address _token) public view returns(uint){ return(token_type[_token]); } /** *@dev Updates the fee amount *@param _fee is the new fee amount */ function setFee(uint _fee) public onlyOwner() { fee = _fee; } /** *@dev Updates the swap fee amount *@param _swapFee is the new swap fee amount */ function setSwapFee(uint _swapFee) public onlyOwner() { swapFee = _swapFee; } /** *@dev Sets the deployer address *@param _deployer is the new deployer address */ function setDeployer(address _deployer) public onlyOwner() { deployer_address = _deployer; deployer = Deployer_Interface(_deployer); } /** *@dev Sets the user_contract address *@param _userContract is the new userContract address */ function setUserContract(address _userContract) public onlyOwner() { user_contract = _userContract; } /** *@dev Sets token ratio, swap duration, and multiplier variables for a swap. *@param _token_ratio the ratio of the tokens *@param _duration the duration of the swap, in days *@param _multiplier the multiplier used for the swap *@param _swapFee the swap fee */ function setVariables(uint _token_ratio, uint _duration, uint _multiplier, uint _swapFee) public onlyOwner() { require(_swapFee < 10000); token_ratio = _token_ratio; duration = _duration; multiplier = _multiplier; swapFee = _swapFee; } /** *@dev Sets the address of the base tokens used for the swap *@param _token The address of a token to be used as collateral */ function setBaseToken(address _token) public onlyOwner() { token = _token; } /** *@dev Allows a user to deploy a new swap contract, if they pay the fee *@param _start_date the contract start date *@return new_contract address for he newly created swap address and calls *event &#39;ContractCreation&#39; */ function deployContract(uint _start_date) public payable returns (address) { require(msg.value >= fee && isWhitelisted(msg.sender)); require(_start_date % 86400 == 0); address new_contract = deployer.newContract(msg.sender, user_contract, _start_date); contracts.push(new_contract); created_contracts[new_contract] = _start_date; emit ContractCreation(msg.sender,new_contract); return new_contract; } /** *@dev Deploys DRCT tokens for given start date *@param _start_date of contract */ function deployTokenContract(uint _start_date) public{ address _token; require(_start_date % 86400 == 0); require(long_tokens[_start_date] == address(0) && short_tokens[_start_date] == address(0)); _token = new DRCT_Token(); token_dates[_token] = _start_date; long_tokens[_start_date] = _token; token_type[_token]=2; _token = new DRCT_Token(); token_type[_token]=1; short_tokens[_start_date] = _token; token_dates[_token] = _start_date; startDates.push(_start_date); } /** *@dev Deploys new tokens on a DRCT_Token contract -- called from within a swap *@param _supply The number of tokens to create *@param _party the address to send the tokens to *@param _start_date the start date of the contract *@returns ltoken the address of the created DRCT long tokens *@returns stoken the address of the created DRCT short tokens *@returns token_ratio The ratio of the created DRCT token */ function createToken(uint _supply, address _party, uint _start_date) public returns (address, address, uint) { require(created_contracts[msg.sender] == _start_date); address ltoken = long_tokens[_start_date]; address stoken = short_tokens[_start_date]; require(ltoken != address(0) && stoken != address(0)); DRCT_Token drct_interface = DRCT_Token(ltoken); drct_interface.createToken(_supply.div(token_ratio), _party,msg.sender); drct_interface = DRCT_Token(stoken); drct_interface.createToken(_supply.div(token_ratio), _party,msg.sender); return (ltoken, stoken, token_ratio); } /** *@dev Allows the owner to set a new oracle address *@param _new_oracle_address */ function setOracleAddress(address _new_oracle_address) public onlyOwner() { oracle_address = _new_oracle_address; } /** *@dev Allows the owner to set a new owner address *@param _new_owner the new owner address */ function setOwner(address _new_owner) public onlyOwner() { owner = _new_owner; } /** *@dev Allows the owner to pull contract creation fees *@return the withdrawal fee _val and the balance where is the return function? */ function withdrawFees() public onlyOwner(){ Wrapped_Ether_Interface token_interface = Wrapped_Ether_Interface(token); uint _val = token_interface.balanceOf(address(this)); if(_val > 0){ token_interface.withdraw(_val); } owner.transfer(address(this).balance); } /** *@dev fallback function */ function() public payable { } /** *@dev Returns a tuple of many private variables. *The variables from this function are pass through to the TokenLibrary.getVariables function *@returns oracle_adress is the address of the oracle *@returns duration is the duration of the swap *@returns multiplier is the multiplier for the swap *@returns token is the address of token *@returns _swapFee is the swap fee */ function getVariables() public view returns (address, uint, uint, address,uint){ return (oracle_address,duration, multiplier, token,swapFee); } /** *@dev Pays out to a DRCT token *@param _party is the address being paid *@param _token_add token to pay out */ function payToken(address _party, address _token_add) public { require(created_contracts[msg.sender] > 0); DRCT_Token drct_interface = DRCT_Token(_token_add); drct_interface.pay(_party, msg.sender); } /** *@dev Counts number of contacts created by this factory *@return the number of contracts */ function getCount() public constant returns(uint) { return contracts.length; } /** *@dev Counts number of start dates in this factory *@return the number of active start dates */ function getDateCount() public constant returns(uint) { return startDates.length; } } /** *This contracts helps clone factories and swaps through the Deployer.sol and MasterDeployer.sol. *The address of the targeted contract to clone has to be provided. */ contract CloneFactory { /*Variables*/ address internal owner; /*Events*/ event CloneCreated(address indexed target, address clone); /*Modifiers*/ modifier onlyOwner() { require(msg.sender == owner); _; } /*Functions*/ constructor() public{ owner = msg.sender; } /** *@dev Allows the owner to set a new owner address *@param _owner the new owner address */ function setOwner(address _owner) public onlyOwner(){ owner = _owner; } /** *@dev Creates factory clone *@param _target is the address being cloned *@return address for clone */ function createClone(address target) internal returns (address result) { bytes memory clone = hex"600034603b57603080600f833981f36000368180378080368173bebebebebebebebebebebebebebebebebebebebe5af43d82803e15602c573d90f35b3d90fd"; bytes20 targetBytes = bytes20(target); for (uint i = 0; i < 20; i++) { clone[26 + i] = targetBytes[i]; } assembly { let len := mload(clone) let data := add(clone, 0x20) result := create(0, data, len) } } } /** *This contract deploys a factory contract and uses CloneFactory to clone the factory *specified. */ contract MasterDeployer is CloneFactory{ using SafeMath for uint256; /*Variables*/ address[] factory_contracts; address private factory; mapping(address => uint) public factory_index; /*Events*/ event NewFactory(address _factory); /*Functions*/ /** *@dev Initiates the factory_contract array with address(0) */ constructor() public { factory_contracts.push(address(0)); } /** *@dev Set factory address to clone *@param _factory address to clone */ function setFactory(address _factory) public onlyOwner(){ factory = _factory; } /** *@dev creates a new factory by cloning the factory specified in setFactory. *@return _new_fac which is the new factory address */ function deployFactory() public onlyOwner() returns(address){ address _new_fac = createClone(factory); factory_index[_new_fac] = factory_contracts.length; factory_contracts.push(_new_fac); Factory(_new_fac).init(msg.sender); emit NewFactory(_new_fac); return _new_fac; } /** *@dev Removes the factory specified *@param _factory address to remove */ function removeFactory(address _factory) public onlyOwner(){ require(_factory != address(0) && factory_index[_factory] != 0); uint256 fIndex = factory_index[_factory]; uint256 lastFactoryIndex = factory_contracts.length.sub(1); address lastFactory = factory_contracts[lastFactoryIndex]; factory_contracts[fIndex] = lastFactory; factory_index[lastFactory] = fIndex; factory_contracts.length--; factory_index[_factory] = 0; } /** *@dev Counts the number of factories *@returns the number of active factories */ function getFactoryCount() public constant returns(uint){ return factory_contracts.length - 1; } /** *@dev Returns the factory address for the specified index *@param _index for factory to look up in the factory_contracts array *@return factory address for the index specified */ function getFactorybyIndex(uint _index) public constant returns(address){ return factory_contracts[_index]; } }
*@dev Sets the address of the base tokens used for the swap@param _token The address of a token to be used as collateral/
function setBaseToken(address _token) public onlyOwner() { token = _token; }
2,080,671
[ 1, 2785, 326, 1758, 434, 326, 1026, 2430, 1399, 364, 326, 7720, 389, 2316, 1021, 1758, 434, 279, 1147, 358, 506, 1399, 225, 487, 4508, 2045, 287, 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 ]
[ 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 26435, 1345, 12, 2867, 389, 2316, 13, 1071, 1338, 5541, 1435, 288, 203, 3639, 1147, 273, 389, 2316, 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 ]
pragma solidity >=0.5.11; //Represents the money being traded in this program contract Money { int amount; //Amount that this Money object holds constructor(int amt) public { amount = amt; } //Add additional Money function mergeMoney(Money m) public { amount = amount + m.getAmount(); } //Returns the amount of this Money function getAmount() public view returns (int) { return amount; } // DANGER: for internal use only! function addAmount(int amt) public { amount += amt; } //Use some amount of this Money function splitMoneyInto(int amt, Money otherMoney) public { if (amt > amount) { revert ("Can't split out more money than is available in a given Money object."); } else { amount = amount - amt; otherMoney.addAmount(amt); } } } //Represents the bet prediction of a Bettor contract BetPrediction { string public predictedOutcome; //the Bettor's prediction of the winning outcome int public betAmount; //the amount of money the Bettor put down on this BetPrediction constructor(string memory predOut, int amount) public { predictedOutcome = predOut; betAmount = amount; } } //Represents a person betting on a game contract Bettor { Money money; //Total Money the Bettor owns constructor(Money m) public { money = m; } //Take some Money out of the Bettor's total money function withdrawMoney(int amount) public returns (Money) { Money newMoney = new Money(0); money.splitMoneyInto(amount, newMoney); return newMoney; } //Adds Money to the Bettor's total money function receiveMoney(Money m) public { money.mergeMoney(m); } } //Represents a single bet contract Bet { Bettor public bettor; //The Bettor making the bet BetPrediction public prediction; //The BetPrediction for the winner constructor(Bettor b, BetPrediction p) public { bettor = b; prediction = p; } } //Represents a container of Bets contract BetList { Bet[] bets; //Add a new Bet to the end of the list function append(Bet newB) public { bets.push(newB); } //remove a Bet with a given Bettor reference, and return that Bet function popSpecific(Bettor bettor) public returns (Bet) { for (uint i = 0; i < bets.length; i++) { if (bets[i].bettor() == bettor) { Bet result = bets[i]; bets[i] = bets[bets.length - 1]; delete bets[bets.length - 1]; bets.length--; return result; } } revert("No matching bets in list"); } //returns true if a Bet has been placed by a Bettor function contains(Bettor bettor) public view returns (bool) { for (uint i = 0; i < bets.length; i++) { if (bets[i].bettor() == bettor) { return true; } } } } //Represents a generic game contract Game { enum State { BeforePlay, Playing, FinishedPlaying} State state; constructor() public { state = State.BeforePlay; } //Start the game function startPlaying() public { require(state == State.BeforePlay, "Wrong initial state."); state = State.Playing; } //Finish the game function finishPlaying() public { require(state == State.Playing, "Wrong initial state."); state = State.FinishedPlaying; } //Returns the outcome of the game function calculateOutcome() public view returns (string memory) { require(state == State.FinishedPlaying, "Wrong initial state."); //... return ""; //Always returns empty string for now } }
remove a Bet with a given Bettor reference, and return that Bet
function popSpecific(Bettor bettor) public returns (Bet) { for (uint i = 0; i < bets.length; i++) { if (bets[i].bettor() == bettor) { Bet result = bets[i]; bets[i] = bets[bets.length - 1]; delete bets[bets.length - 1]; bets.length--; return result; } } revert("No matching bets in list"); }
12,673,736
[ 1, 4479, 279, 605, 278, 598, 279, 864, 605, 278, 13039, 2114, 16, 471, 327, 716, 605, 278, 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 ]
[ 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, 0 ]
[ 1, 565, 445, 1843, 9969, 12, 38, 278, 13039, 2701, 13039, 13, 1071, 1135, 261, 38, 278, 13, 288, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 324, 2413, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 70, 2413, 63, 77, 8009, 70, 278, 13039, 1435, 422, 2701, 13039, 13, 288, 203, 7734, 605, 278, 563, 273, 324, 2413, 63, 77, 15533, 203, 7734, 324, 2413, 63, 77, 65, 273, 324, 2413, 63, 70, 2413, 18, 2469, 300, 404, 15533, 203, 7734, 1430, 324, 2413, 63, 70, 2413, 18, 2469, 300, 404, 15533, 203, 7734, 324, 2413, 18, 2469, 413, 31, 203, 7734, 327, 563, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 15226, 2932, 2279, 3607, 324, 2413, 316, 666, 8863, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "../interfaces/IReservoir.sol"; /** * @title MasterChef */ contract MasterChef is Ownable { using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of rewardTokens // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accRewardPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accRewardPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. rewardTokens to distribute per block. uint256 lastRewardBlock; // Last block number that rewardTokens distribution occurs. uint256 accRewardPerShare; // Accumulated rewardTokens per share, times 1e18. See below. } // The REWARD TOKEN! IERC20 public rewardToken; // rewardTokens created per block. uint256 public rewardPerBlock; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when rewardToken mining starts. uint256 public startBlock; // Token reservoir. IReservoir public rewardReservoir; // Checking already added LP tokens. mapping(address => bool) private lpTokens; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event SetRewardReservoir(address reservoir); // Set reward reservoir event. event SetRewardPerBlock(uint256 rewardPerBlock); // Set rewardPerBlock event. constructor( IERC20 _rewardToken, IReservoir _rewardReservoir, uint256 _rewardPerBlock, uint256 _startBlock ) { require(address(_rewardToken) != address(0), "MasterChef: rewardToken cannot be zero address"); rewardToken = _rewardToken; rewardReservoir = _rewardReservoir; rewardPerBlock = _rewardPerBlock; startBlock = _startBlock; } // ** EXTERNAL VIEW functions ** function poolLength() external view returns (uint256) { return poolInfo.length; } // View function to see pending rewardTokens on frontend. function pendingReward(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accRewardPerShare = pool.accRewardPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = _getMultiplier(pool.lastRewardBlock, block.number); uint256 tokenReward = multiplier * rewardPerBlock * pool.allocPoint / totalAllocPoint; tokenReward = _availableReward(tokenReward); // amount available on rewardReservoir accRewardPerShare = accRewardPerShare + (tokenReward * 1e18 / lpSupply); } return (user.amount * accRewardPerShare / 1e18) - user.rewardDebt; } // ** POOL PUBLIC functions ** // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = _getMultiplier(pool.lastRewardBlock, block.number); uint256 tokenReward = multiplier * rewardPerBlock * pool.allocPoint / totalAllocPoint; tokenReward = rewardReservoir.drip(tokenReward); // transfer tokens from rewardReservoir pool.accRewardPerShare = pool.accRewardPerShare + (tokenReward * 1e18 / lpSupply); pool.lastRewardBlock = block.number; } // ** USER EXTERNAL functions ** // Deposit LP tokens to MasterChef for rewardToken allocation. function deposit(uint256 _pid, uint256 _amount) external { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = (user.amount * pool.accRewardPerShare / 1e18) - user.rewardDebt; if (pending > 0) { _safeRewardTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount += _amount; } user.rewardDebt = user.amount * pool.accRewardPerShare / 1e18; emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) external { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "MasterChef: amount exceeds balance"); updatePool(_pid); uint256 pending = (user.amount * pool.accRewardPerShare / 1e18) - user.rewardDebt; if (pending > 0) { _safeRewardTransfer(msg.sender, pending); } if (_amount > 0) { user.amount -= _amount; pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount * pool.accRewardPerShare / 1e18; emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // ** ONLY OWNER functions ** // Add a new lp to the pool. Can only be called by the owner. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) external onlyOwner { // Trying to add the same LP token more than once. require(!lpTokens[address(_lpToken)], "MasterChef: LP token has already been added"); lpTokens[address(_lpToken)] = true; // Trying to add rewardToken as LP token. require(address(_lpToken) != address(rewardToken), "MasterChef: reward token cannot be LP token"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = (block.number > startBlock) ? block.number : startBlock; totalAllocPoint += _allocPoint; poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accRewardPerShare: 0 })); } // Update the given pool's rewardToken allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) external onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint - poolInfo[_pid].allocPoint + _allocPoint; require(totalAllocPoint > 0, "MasterChef: totalAllocPoint cannot be zero"); poolInfo[_pid].allocPoint = _allocPoint; } // Set reward per block. Can only be called by the owner. function setRewardPerBlock(uint256 _rewardPerBlock, bool _withUpdate) external onlyOwner { if (_withUpdate) { massUpdatePools(); } rewardPerBlock = _rewardPerBlock; emit SetRewardPerBlock(_rewardPerBlock); } // Set rewardReservoir. Can only be called by the owner. function setRewardReservoir(IReservoir _rewardReservoir) external onlyOwner { rewardReservoir = _rewardReservoir; emit SetRewardReservoir(address(_rewardReservoir)); } // ** INTERNAL functions ** // Return reward multiplier over the given _from to _to block. function _getMultiplier(uint256 _from, uint256 _to) internal pure returns (uint256) { return (_to - _from); } // Return available reward on rewardReservoir. function _availableReward(uint256 _requestedTokens) internal view returns (uint256) { uint256 reservoirBalance = rewardToken.balanceOf(address(rewardReservoir)); return (_requestedTokens > reservoirBalance) ? reservoirBalance : _requestedTokens; } // Safe rewardToken transfer function, just in case if rounding error causes pool to not have enough rewardTokens. function _safeRewardTransfer(address _to, uint256 _amount) internal { uint256 rewardBal = rewardToken.balanceOf(address(this)); if (_amount > rewardBal) { rewardToken.safeTransfer(_to, rewardBal); } else { rewardToken.safeTransfer(_to, _amount); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) 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() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.4; /** * @dev Interface of Reservoir contract. */ interface IReservoir { function drip(uint256 requestedTokens) external returns (uint256 sentTokens); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
transfer tokens from rewardReservoir
tokenReward = rewardReservoir.drip(tokenReward);
6,435,737
[ 1, 13866, 2430, 628, 19890, 607, 264, 31238, 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, 1147, 17631, 1060, 273, 19890, 607, 264, 31238, 18, 72, 21335, 12, 2316, 17631, 1060, 1769, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.11; import "./base/Controllable.sol"; import "sol-temple/src/tokens/ERC1155.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; /// @title Ape Runners Serum /// @author naomsa <https://twitter.com/naomsa666> contract ApeRunnersSerum is Ownable, Pausable, Controllable, ERC1155 { using Strings for uint256; /* -------------------------------------------------------------------------- */ /* Sale Details */ /* -------------------------------------------------------------------------- */ /// @notice Utility token contract address. IRUN public utilityToken; /* -------------------------------------------------------------------------- */ /* Metadata Details */ /* -------------------------------------------------------------------------- */ /// @notice Base metadata uri. string public baseURI; /// @notice Base metadata uri extension. string public baseExtension; constructor( string memory newBaseURI, string memory newBaseExtension, address newUtilityToken ) { // Set variables baseURI = newBaseURI; baseExtension = newBaseExtension; utilityToken = IRUN(newUtilityToken); } /* -------------------------------------------------------------------------- */ /* Sale Logic */ /* -------------------------------------------------------------------------- */ /// @notice Buy one or more serums. /// @param serum Serum id to buy. /// @param amount Amount to buy. function buy(uint256 serum, uint256 amount) external { require( serum == 1 || serum == 2 || serum == 3, "Query for nonexisting serum" ); require( totalSupply[serum] + amount <= maxSuppply(serum), "Serum max supply exceeded" ); require(amount > 0, "Invalid buy amount"); utilityToken.burn(msg.sender, price(serum) * amount); _mint(msg.sender, serum, amount, ""); } /// @notice Retrieve serum cost. /// @param serum Serum 1, 2 or 3. function price(uint256 serum) public pure returns (uint256) { if (serum == 1) return 300 ether; else if (serum == 2) return 900 ether; else if (serum == 3) return 3000 ether; else revert("Query for nonexisting serum"); } /// @notice Retrieve serum max supply. /// @param serum Serum 1, 2 or 3. function maxSuppply(uint256 serum) public pure returns (uint256) { if (serum == 1) return 4500; else if (serum == 2) return 490; else if (serum == 3) return 10; else revert("Query for nonexisting serum"); } /* -------------------------------------------------------------------------- */ /* Owner Logic */ /* -------------------------------------------------------------------------- */ /// @notice Set baseURI to `newBaseURI`. /// @param newBaseURI New base uri. function setBaseURI(string memory newBaseURI) external onlyOwner { baseURI = newBaseURI; } /// @notice Set baseExtension to `newBaseExtension`. /// @param newBaseExtension New base uri. function setBaseExtension(string memory newBaseExtension) external onlyOwner { baseExtension = newBaseExtension; } /// @notice Set utilityToken to `newUtilityToken`. /// @param newUtilityToken New utility token. function setUtilityToken(address newUtilityToken) external onlyOwner { utilityToken = IRUN(newUtilityToken); } /// @notice Toggle if the contract is paused. function togglePaused() external onlyOwner { if (paused()) _unpause(); else _pause(); } /* -------------------------------------------------------------------------- */ /* ERC-1155 Logic */ /* -------------------------------------------------------------------------- */ /// @notice Mint new tokens with `ids` at `amounts` to `to`. /// @param to Address of the recipient. /// @param ids Array of token ids. /// @param amounts Array of amounts. function mint( address to, uint256[] calldata ids, uint256[] calldata amounts ) external onlyController { _mintBatch(to, ids, amounts, ""); } /// @notice Burn tokens with `ids` at `amounts` from `from`. /// @param from Address of the owner. /// @param ids Array of token ids. /// @param amounts Array of amounts. function burn( address from, uint256[] calldata ids, uint256[] calldata amounts ) external onlyController { _burnBatch(from, ids, amounts); } /// @notice See {ERC1155-uri}. function uri(uint256 id) public view override returns (string memory) { require(super.exists(id), "Query for nonexisting serum"); return string(abi.encodePacked(baseURI, id.toString(), baseExtension)); } /// @notice See {ERC1155-_beforeTokenTransfer}. /// @dev Overriden to block transactions while the contract is paused (avoiding bugs). function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override { require(!super.paused() || msg.sender == super.owner(), "Pausable: paused"); super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } } interface IRUN { function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.11; /// @title Controllable abstract contract Controllable { /// @notice address => is controller. mapping(address => bool) private _isController; /// @notice Require the caller to be a controller. modifier onlyController() { require( _isController[msg.sender], "Controllable: Caller is not a controller" ); _; } /// @notice Check if `addr` is a controller. function isController(address addr) public view returns (bool) { return _isController[addr]; } /// @notice Set the `addr` controller status to `status`. function _setController(address addr, bool status) internal { _isController[addr] = status; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.8.0 <0.9.0; import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol"; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @title ERC1155 * @author naomsa <https://twitter.com/naomsa666> * @notice A complete ERC1155 implementation including supply tracking and * enumerable functions. Completely gas optimized and extensible. */ abstract contract ERC1155 is IERC165, IERC1155, IERC1155MetadataURI { /* _ _ */ /* ( )_ ( )_ */ /* ___ | ,_) _ _ | ,_) __ */ /* /',__)| | /'_` )| | /'__`\ */ /* \__, \| |_ ( (_| || |_ ( ___/ */ /* (____/`\__)`\__,_)`\__)`\____) */ /// @notice See {ERC1155-balanceOf}. mapping(address => mapping(uint256 => uint256)) public balanceOf; /// @notice See {ERC1155-isApprovedForAll}. mapping(address => mapping(address => bool)) public isApprovedForAll; /// @notice Tracker for tokens in circulation by Id. mapping(uint256 => uint256) public totalSupply; /* _ */ /* (_ ) _ */ /* | | _ __ (_) ___ */ /* | | /'_`\ /'_ `\| | /'___) */ /* | | ( (_) )( (_) || |( (___ */ /* (___)`\___/'`\__ |(_)`\____) */ /* ( )_) | */ /* \___/' */ /// @notice See {ERC1155Metadata_URI-uri}. function uri(uint256) public view virtual returns (string memory); /// @notice See {ERC1155-balanceOfBatch}. function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; i++) batchBalances[i] = balanceOf[accounts[i]][ids[i]]; return batchBalances; } /// @notice See {ERC1155-setApprovalForAll}. function setApprovalForAll(address operator, bool approved) public virtual { _setApprovalForAll(msg.sender, operator, approved); } /// @notice See {ERC1155-safeTransferFrom}. function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual { require(from == msg.sender || isApprovedForAll[from][msg.sender], "ERC1155: caller is not owner nor approved"); _safeTransferFrom(from, to, id, amount, data); } /// @notice See {ERC1155-safeBatchTransferFrom}. function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual { require( from == msg.sender || isApprovedForAll[from][msg.sender], "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /// @notice Indicates whether any token exist with a given id, or not./ function exists(uint256 id) public view virtual returns (bool) { return totalSupply[id] > 0; } /* _ _ */ /* _ ( )_ (_ ) */ /* (_) ___ | ,_) __ _ __ ___ _ _ | | */ /* | |/' _ `\| | /'__`\( '__)/' _ `\ /'_` ) | | */ /* | || ( ) || |_ ( ___/| | | ( ) |( (_| | | | */ /* (_)(_) (_)`\__)`\____)(_) (_) (_)`\__,_)(___) */ /// @notice Transfers `amount` tokens of token type `id` from `from` to `to`. function _safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); _trackSupplyBeforeTransfer(from, to, _asSingletonArray(id), _asSingletonArray(amount)); _beforeTokenTransfer(msg.sender, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); require(balanceOf[from][id] >= amount, "ERC1155: insufficient balance for transfer"); unchecked { balanceOf[from][id] -= amount; } balanceOf[to][id] += amount; emit TransferSingle(msg.sender, from, to, id, amount); _checkOnERC1155Received(msg.sender, from, to, id, amount, data); _afterTokenTransfer(msg.sender, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); } /// @notice Safe version of the batchTransferFrom function. function _safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); _trackSupplyBeforeTransfer(from, to, ids, amounts); _beforeTokenTransfer(msg.sender, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { require(balanceOf[from][ids[i]] >= amounts[i], "ERC1155: insufficient balance for transfer"); unchecked { balanceOf[from][ids[i]] -= amounts[i]; balanceOf[to][ids[i]] += amounts[i]; } } emit TransferBatch(msg.sender, from, to, ids, amounts); _checkOnERC1155BatchReceived(msg.sender, from, to, ids, amounts, data); _afterTokenTransfer(msg.sender, from, to, ids, amounts, data); } /// @notice Creates `amount` tokens of token type `id`, and assigns them to `to`. function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); _trackSupplyBeforeTransfer(address(0), to, _asSingletonArray(id), _asSingletonArray(amount)); _beforeTokenTransfer(msg.sender, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); balanceOf[to][id] += amount; emit TransferSingle(msg.sender, address(0), to, id, amount); _checkOnERC1155Received(msg.sender, address(0), to, id, amount, data); _afterTokenTransfer(msg.sender, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); } /// @notice Batch version of {mint}. function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); _trackSupplyBeforeTransfer(address(0), to, ids, amounts); _beforeTokenTransfer(msg.sender, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { balanceOf[to][ids[i]] += amounts[i]; } emit TransferBatch(msg.sender, address(0), to, ids, amounts); _checkOnERC1155BatchReceived(msg.sender, address(0), to, ids, amounts, data); _afterTokenTransfer(msg.sender, address(0), to, ids, amounts, data); } /// @notice Destroys `amount` tokens of token type `id` from `from` function _burn( address from, uint256 id, uint256 amount ) internal virtual { _trackSupplyBeforeTransfer(from, address(0), _asSingletonArray(id), _asSingletonArray(amount)); _beforeTokenTransfer(msg.sender, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); require(balanceOf[from][id] >= amount, "ERC1155: burn amount exceeds balance"); unchecked { balanceOf[from][id] -= amount; } emit TransferSingle(msg.sender, from, address(0), id, amount); _afterTokenTransfer(msg.sender, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); } /// @notice Batch version of {burn}. function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); _trackSupplyBeforeTransfer(from, address(0), ids, amounts); _beforeTokenTransfer(msg.sender, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { require(balanceOf[from][ids[i]] >= amounts[i], "ERC1155: burn amount exceeds balance"); unchecked { balanceOf[from][ids[i]] -= amounts[i]; } } emit TransferBatch(msg.sender, from, address(0), ids, amounts); _afterTokenTransfer(msg.sender, from, address(0), ids, amounts, ""); } /// @notice Approve `operator` to operate on all of `owner` tokens function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); isApprovedForAll[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /// @notice Hook that is called before any token transfer. function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} /// @notice Hook that is called after any token transfer. function _afterTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} /// @notice Internal helper for tracking token supply before transfers. function _trackSupplyBeforeTransfer( address from, address to, uint256[] memory ids, uint256[] memory amounts ) private { if (from == address(0)) { for (uint256 i = 0; i < ids.length; i++) { totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; i++) { totalSupply[ids[i]] -= amounts[i]; } } } /// @notice ERC1155Receiver callback checking and calling helper for single transfers. function _checkOnERC1155Received( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.code.length > 0) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 returnValue) { require(returnValue == 0xf23a6e61, "ERC1155: transfer to non ERC1155Receiver implementer"); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } /// @notice ERC1155Receiver callback checking and calling helper for batch transfers. function _checkOnERC1155BatchReceived( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.code.length > 0) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 returnValue) { require(returnValue == 0xbc197c81, "ERC1155: transfer to non ERC1155Receiver implementer"); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } /// @notice Helper for single item arrays. function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } /* ___ _ _ _ _ __ _ __ */ /* /',__)( ) ( )( '_`\ /'__`\( '__) */ /* \__, \| (_) || (_) )( ___/| | */ /* (____/`\___/'| ,__/'`\____)(_) */ /* | | */ /* (_) */ /// @notice See {ERC165-supportsInterface}. function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) { return interfaceId == type(IERC1155).interfaceId || // ERC1155 interfaceId == type(IERC1155MetadataURI).interfaceId || // ERC1155MetadataURI interfaceId == type(IERC165).interfaceId; // ERC165 } } interface IERC1155Receiver { function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) 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() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) 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 // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface 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 // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface 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 // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
@notice See {ERC1155-_beforeTokenTransfer}. @dev Overriden to block transactions while the contract is paused (avoiding bugs).
function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal override { require(!super.paused() || msg.sender == super.owner(), "Pausable: paused"); super._beforeTokenTransfer(operator, from, to, ids, amounts, data); }
1,689,737
[ 1, 9704, 288, 654, 39, 2499, 2539, 17, 67, 5771, 1345, 5912, 5496, 225, 531, 1107, 17951, 358, 1203, 8938, 1323, 326, 6835, 353, 17781, 261, 842, 839, 310, 22398, 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, 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, 225, 445, 389, 5771, 1345, 5912, 12, 203, 565, 1758, 3726, 16, 203, 565, 1758, 628, 16, 203, 565, 1758, 358, 16, 203, 565, 2254, 5034, 8526, 3778, 3258, 16, 203, 565, 2254, 5034, 8526, 3778, 30980, 16, 203, 565, 1731, 3778, 501, 203, 225, 262, 2713, 3849, 288, 203, 565, 2583, 12, 5, 9565, 18, 8774, 3668, 1435, 747, 1234, 18, 15330, 422, 2240, 18, 8443, 9334, 315, 16507, 16665, 30, 17781, 8863, 203, 565, 2240, 6315, 5771, 1345, 5912, 12, 9497, 16, 628, 16, 358, 16, 3258, 16, 30980, 16, 501, 1769, 203, 225, 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 ]
./partial_match/1/0xC851A4aDb98697CDbE95d880B1cA3c342Ec99629/sources/src/L1/ResourceMetering.sol
@notice Virtual function that returns the resource config. Contracts that inherit this contract must implement this function. @return ResourceConfig @notice Sets initial resource parameter values. This function must either be called by the initializer function of an upgradeable child contract. solhint-disable-next-line func-name-mixedcase
function _resourceConfig() internal virtual returns (ResourceConfig memory); function __ResourceMetering_init() internal onlyInitializing { }
16,035,361
[ 1, 6466, 445, 716, 1135, 326, 1058, 642, 18, 540, 30131, 716, 6811, 333, 6835, 1297, 2348, 333, 445, 18, 327, 2591, 809, 225, 11511, 2172, 1058, 1569, 924, 18, 540, 1220, 445, 1297, 3344, 506, 2566, 635, 326, 12562, 445, 434, 392, 8400, 429, 540, 1151, 6835, 18, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 1326, 17, 529, 17, 19562, 3593, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 3146, 809, 1435, 2713, 5024, 1135, 261, 1420, 809, 3778, 1769, 203, 203, 565, 445, 1001, 1420, 16935, 310, 67, 2738, 1435, 2713, 1338, 29782, 288, 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 ]
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 result = a * b; assert(a == 0 || result / a == b); return result; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 result = a / b; return result; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 result = a + b; assert(result >= a); return result; } function getAllValuesSum(uint256[] values) internal pure returns(uint256) { uint256 result = 0; for (uint i = 0; i < values.length; i++){ result = add(result, values[i]); } return result; } } contract Ownable { constructor() public { ownerAddress = msg.sender; } event TransferOwnership( address indexed previousOwner, address indexed newOwner ); address public ownerAddress; //wallet that can change owner address internal masterKey = 0x819466D9C043DBb7aB4E1168aB8E014c3dCAA470; function transferOwnership(address newOwner) public returns(bool); modifier onlyOwner() { require(msg.sender == ownerAddress); _; } // Prevents user to send transaction on his own address modifier notSender(address owner){ require(msg.sender != owner); _; } } contract ERC20Basic { event Transfer( address indexed from, address indexed to, uint256 value ); uint256 public totalSupply; function balanceOf(address who) public view returns(uint256); function transfer(address to, uint256 value) public returns(bool); } contract BasicToken is ERC20Basic, Ownable { using SafeMath for uint256; struct WalletData { uint256 tokensAmount; uint256 freezedAmount; bool canFreezeTokens; } mapping(address => WalletData) wallets; function transfer(address to, uint256 value) public notSender(to) returns(bool) { require(to != address(0) && wallets[msg.sender].tokensAmount >= value && (wallets[msg.sender].canFreezeTokens && checkIfCanUseTokens(msg.sender, value))); uint256 amount = wallets[msg.sender].tokensAmount.sub(value); wallets[msg.sender].tokensAmount = amount; wallets[to].tokensAmount = wallets[to].tokensAmount.add(value); emit Transfer(msg.sender, to, value); return true; } function balanceOf(address owner) public view returns(uint256 balance) { return wallets[owner].tokensAmount; } // Check wallet on unfreeze tokens amount function checkIfCanUseTokens( address owner, uint256 amount ) internal view returns(bool) { uint256 unfreezedAmount = wallets[owner].tokensAmount - wallets[owner].freezedAmount; return amount <= unfreezedAmount; } } contract FreezableToken is BasicToken { event AllowFreeze(address indexed who); event DissallowFreeze(address indexed who); event FreezeTokens(address indexed who, uint256 freezeAmount); event UnfreezeTokens(address indexed who, uint256 unfreezeAmount); uint256 public freezeTokensAmount = 0; // Give permission to a wallet for freeze tokens. function allowFreezing(address owner) public onlyOwner returns(bool) { require(!wallets[owner].canFreezeTokens); wallets[owner].canFreezeTokens = true; emit AllowFreeze(owner); return true; } function dissalowFreezing(address owner) public onlyOwner returns(bool) { require(wallets[owner].canFreezeTokens); wallets[owner].canFreezeTokens = false; wallets[owner].freezedAmount = 0; emit DissallowFreeze(owner); return true; } function freezeAllowance(address owner) public view returns(bool) { return wallets[owner].canFreezeTokens; } // Freeze tokens on sender wallet if have permission. function freezeTokens( uint256 amount ) public isFreezeAllowed returns(bool) { uint256 freezedAmount = wallets[msg.sender].freezedAmount.add(amount); require(wallets[msg.sender].tokensAmount >= freezedAmount); wallets[msg.sender].freezedAmount = freezedAmount; emit FreezeTokens(msg.sender, amount); return true; } function showFreezedTokensAmount(address owner) public view returns(uint256) { return wallets[owner].freezedAmount; } function unfreezeTokens( uint256 amount ) public isFreezeAllowed returns(bool) { uint256 freezeAmount = wallets[msg.sender].freezedAmount.sub(amount); wallets[msg.sender].freezedAmount = freezeAmount; emit UnfreezeTokens(msg.sender, amount); return true; } function getUnfreezedTokens(address owner) internal view returns(uint256) { return wallets[owner].tokensAmount - wallets[owner].freezedAmount; } modifier isFreezeAllowed() { require(freezeAllowance(msg.sender)); _; } } contract MultisendableToken is FreezableToken { using SafeMath for uint256; function massTransfer( address[] addresses, uint[] values ) public onlyOwner returns(bool) { for (uint i = 0; i < addresses.length; i++){ transferFromOwner(addresses[i], values[i]); } return true; } function transferFromOwner( address to, uint256 value ) internal onlyOwner { require(to != address(0) && wallets[ownerAddress].tokensAmount >= value && (freezeAllowance(ownerAddress) && checkIfCanUseTokens(ownerAddress, value))); uint256 freezeAmount = wallets[ownerAddress].tokensAmount.sub(value); wallets[ownerAddress].tokensAmount = freezeAmount; wallets[to].tokensAmount = wallets[to].tokensAmount.add(value); emit Transfer(ownerAddress, to, value); } } contract Airdropper is MultisendableToken { using SafeMath for uint256[]; event Airdrop(uint256 tokensDropped, uint256 airdropCount); event AirdropFinished(); uint256 public airdropsCount = 0; uint256 public airdropTotalSupply = 0; uint256 public distributedTokensAmount = 0; bool public airdropFinished = false; function airdropToken( address[] addresses, uint256[] values ) public onlyOwner returns(bool) { uint256 result = distributedTokensAmount + values.getAllValuesSum(); require(!airdropFinished && result <= airdropTotalSupply); distributedTokensAmount = result; airdropsCount++; emit Airdrop(values.getAllValuesSum(), airdropsCount); return massTransfer(addresses, values); } function finishAirdrops() public onlyOwner { // Can&#39;t finish airdrop before send all tokens for airdrop. require(distributedTokensAmount == airdropTotalSupply); airdropFinished = true; emit AirdropFinished(); } } contract CryptosoulToken is Airdropper { event Mint(address indexed to, uint256 value); event AllowMinting(); event Burn(address indexed from, uint256 value); string constant public name = "CryptoSoul"; string constant public symbol = "SOUL"; uint constant public decimals = 6; uint256 constant public START_TOKENS = 500000000 * 10**decimals; //500M start uint256 constant public MINT_AMOUNT = 1360000 * 10**decimals; uint32 constant public MINT_INTERVAL_SEC = 1 days; // 24 hours uint256 constant private MAX_BALANCE_VALUE = 2**256 - 1; uint constant public startMintingData = 1538352000; uint public nextMintPossibleTime = 0; bool public canMint = false; constructor() public { wallets[ownerAddress].tokensAmount = START_TOKENS; wallets[ownerAddress].canFreezeTokens = true; totalSupply = START_TOKENS; airdropTotalSupply = 200000000 * 10**decimals; emit Mint(ownerAddress, START_TOKENS); } function allowMinting() public onlyOwner { // Can start minting token after 01.10.2018 require(now >= startMintingData); nextMintPossibleTime = now; canMint = true; emit AllowMinting(); } function mint() public onlyOwner returns(bool) { require(canMint && totalSupply + MINT_AMOUNT <= MAX_BALANCE_VALUE && now >= nextMintPossibleTime); nextMintPossibleTime = nextMintPossibleTime.add(MINT_INTERVAL_SEC); uint256 freezeAmount = wallets[ownerAddress].tokensAmount.add(MINT_AMOUNT); wallets[ownerAddress].tokensAmount = freezeAmount; totalSupply = totalSupply.add(MINT_AMOUNT); emit Mint(ownerAddress, MINT_AMOUNT); return true; } function burn(uint256 value) public onlyOwner returns(bool) { require(checkIfCanUseTokens(ownerAddress, value) && wallets[ownerAddress].tokensAmount >= value); uint256 freezeAmount = wallets[ownerAddress].tokensAmount.sub(value); wallets[ownerAddress].tokensAmount = freezeAmount; totalSupply = totalSupply.sub(value); emit Burn(ownerAddress, value); return true; } function transferOwnership(address newOwner) public returns(bool) { require(msg.sender == masterKey && newOwner != address(0)); // Transfer token data from old owner to new. wallets[newOwner].tokensAmount = wallets[ownerAddress].tokensAmount; wallets[newOwner].canFreezeTokens = true; wallets[newOwner].freezedAmount = wallets[ownerAddress].freezedAmount; wallets[ownerAddress].freezedAmount = 0; wallets[ownerAddress].tokensAmount = 0; wallets[ownerAddress].canFreezeTokens = false; emit TransferOwnership(ownerAddress, newOwner); ownerAddress = newOwner; return true; } function() public payable { revert(); } }
Transfer token data from old owner to new.
function transferOwnership(address newOwner) public returns(bool) { require(msg.sender == masterKey && newOwner != address(0)); wallets[newOwner].tokensAmount = wallets[ownerAddress].tokensAmount; wallets[newOwner].canFreezeTokens = true; wallets[newOwner].freezedAmount = wallets[ownerAddress].freezedAmount; wallets[ownerAddress].freezedAmount = 0; wallets[ownerAddress].tokensAmount = 0; wallets[ownerAddress].canFreezeTokens = false; emit TransferOwnership(ownerAddress, newOwner); ownerAddress = newOwner; return true; }
7,683,450
[ 1, 5912, 1147, 501, 628, 1592, 3410, 358, 394, 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, 565, 445, 7412, 5460, 12565, 12, 2867, 394, 5541, 13, 7010, 3639, 1071, 203, 3639, 1135, 12, 6430, 13, 203, 565, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 4171, 653, 597, 394, 5541, 480, 1758, 12, 20, 10019, 203, 3639, 17662, 2413, 63, 2704, 5541, 8009, 7860, 6275, 273, 17662, 2413, 63, 8443, 1887, 8009, 7860, 6275, 31, 203, 3639, 17662, 2413, 63, 2704, 5541, 8009, 4169, 9194, 8489, 5157, 273, 638, 31, 203, 3639, 17662, 2413, 63, 2704, 5541, 8009, 9156, 94, 329, 6275, 273, 17662, 2413, 63, 8443, 1887, 8009, 9156, 94, 329, 6275, 31, 203, 3639, 17662, 2413, 63, 8443, 1887, 8009, 9156, 94, 329, 6275, 273, 374, 31, 203, 3639, 17662, 2413, 63, 8443, 1887, 8009, 7860, 6275, 273, 374, 31, 203, 3639, 17662, 2413, 63, 8443, 1887, 8009, 4169, 9194, 8489, 5157, 273, 629, 31, 203, 3639, 3626, 12279, 5460, 12565, 12, 8443, 1887, 16, 394, 5541, 1769, 203, 3639, 3410, 1887, 273, 394, 5541, 31, 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 ]
./full_match/1/0x0Ac846AF10fF07c7db7c02Cdf06daf3554660e09/sources/contracts/token/ERC721/ERC721.sol
* @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"); }
8,295,812
[ 1, 26946, 2357, 29375, 1375, 2316, 548, 68, 1147, 628, 1375, 2080, 68, 358, 1375, 869, 9191, 6728, 1122, 716, 6835, 12045, 854, 18999, 434, 326, 4232, 39, 27, 5340, 1771, 358, 5309, 2430, 628, 3832, 21238, 8586, 18, 1375, 67, 892, 68, 353, 3312, 501, 16, 518, 711, 1158, 1269, 740, 471, 518, 353, 3271, 316, 745, 358, 1375, 869, 8338, 1220, 2713, 445, 353, 7680, 358, 288, 4626, 5912, 1265, 5779, 471, 848, 506, 1399, 358, 425, 18, 75, 18, 2348, 10355, 1791, 28757, 358, 3073, 1147, 7412, 16, 4123, 487, 3372, 17, 12261, 18, 29076, 30, 300, 1375, 2080, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 869, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 2316, 548, 68, 1147, 1297, 1005, 471, 506, 16199, 635, 1375, 2080, 8338, 300, 971, 1375, 869, 68, 21368, 358, 279, 13706, 6835, 16, 518, 1297, 2348, 288, 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, 389, 4626, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 1731, 3778, 389, 892, 203, 565, 262, 2713, 5024, 95, 203, 3639, 389, 13866, 12, 2080, 16, 358, 16, 1147, 548, 1769, 203, 3639, 2583, 24899, 1893, 1398, 654, 39, 27, 5340, 8872, 12, 2080, 16, 358, 16, 1147, 548, 16, 389, 892, 3631, 315, 654, 39, 27, 5340, 30, 7412, 358, 1661, 4232, 39, 27, 5340, 12952, 2348, 264, 8863, 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 ]
pragma solidity ^0.4.20; /** * @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; require(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; 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) { require(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; require(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)); owner = newOwner; OwnershipTransferred(owner, newOwner); } } contract CutdownTokenInterface { //ERC20 function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); //ERC677 function tokenFallback(address from, uint256 amount, bytes data) public returns (bool); } /** * @title Eco Value Coin * @dev Burnable ERC20 + ERC677 token with initial transfers blocked */ contract EcoValueCoin is Ownable { using SafeMath for uint256; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Burn(address indexed _burner, uint256 _value); event TransfersEnabled(); event TransferRightGiven(address indexed _to); event TransferRightCancelled(address indexed _from); event WithdrawnERC20Tokens(address indexed _tokenContract, address indexed _owner, uint256 _balance); event WithdrawnEther(address indexed _owner, uint256 _balance); string public constant name = "Eco Value Coin"; string public constant symbol = "EVC"; uint256 public constant decimals = 18; uint256 public constant initialSupply = 3300000000 * (10 ** decimals); uint256 public totalSupply; mapping(address => uint256) public balances; mapping(address => mapping (address => uint256)) internal allowed; //This mapping is used for the token owner and crowdsale contract to //transfer tokens before they are transferable mapping(address => bool) public transferGrants; //This flag controls the global token transfer bool public transferable; /** * @dev Modifier to check if tokens can be transfered. */ modifier canTransfer() { require(transferable || transferGrants[msg.sender]); _; } /** * @dev The constructor sets the original `owner` of the contract * to the sender account and assigns them all tokens. */ function EcoValueCoin() public { owner = msg.sender; totalSupply = initialSupply; balances[owner] = totalSupply; transferGrants[owner] = true; } /** * @dev This contract does not accept any ether. * Any forced ether can be withdrawn with `withdrawEther()` by the owner. */ function () payable public { revert(); } /** * @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 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) canTransfer 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 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) canTransfer 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) canTransfer 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) canTransfer 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) canTransfer 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) canTransfer 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; } /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } /** * @dev Enables the transfer of tokens for everyone */ function enableTransfers() onlyOwner public { require(!transferable); transferable = true; TransfersEnabled(); } /** * @dev Assigns the special transfer right, before transfers are enabled * @param _to The address receiving the transfer grant */ function grantTransferRight(address _to) onlyOwner public { require(!transferable); require(!transferGrants[_to]); require(_to != address(0)); transferGrants[_to] = true; TransferRightGiven(_to); } /** * @dev Removes the special transfer right, before transfers are enabled * @param _from The address that the transfer grant is removed from */ function cancelTransferRight(address _from) onlyOwner public { require(!transferable); require(transferGrants[_from]); transferGrants[_from] = false; TransferRightCancelled(_from); } /** * @dev Allows to transfer out the balance of arbitrary ERC20 tokens from the contract. * @param _tokenContract The contract address of the ERC20 token. */ function withdrawERC20Tokens(address _tokenContract) onlyOwner public { CutdownTokenInterface token = CutdownTokenInterface(_tokenContract); uint256 totalBalance = token.balanceOf(address(this)); token.transfer(owner, totalBalance); WithdrawnERC20Tokens(_tokenContract, owner, totalBalance); } /** * @dev Allows to transfer out the ether balance that was forced into this contract, e.g with `selfdestruct` */ function withdrawEther() public onlyOwner { uint256 totalBalance = this.balance; require(totalBalance > 0); owner.transfer(totalBalance); WithdrawnEther(owner, totalBalance); } }
* @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) { require(b <= a); return a - b; }
57,615
[ 1, 1676, 2876, 87, 2795, 5600, 16, 1216, 603, 9391, 261, 77, 18, 73, 18, 309, 720, 2033, 25710, 353, 6802, 2353, 1131, 89, 409, 2934, 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 ]
[ 1, 1, 1, 1, 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, 720, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 565, 2583, 12, 70, 1648, 279, 1769, 203, 565, 327, 279, 300, 324, 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 ]
./full_match/3/0xEae2757A6a84760B3affa69e71207E464C32c5e6/sources/browser/bettex3.sol
react to int values by some paths _id status._id periods.ft.home periods.ft.away
function parseEventResult(bytes memory input) public { uint64 eventid = 0; uint statusid = 0; uint periods_ft_home = 0; uint periods_ft_away = 0; uint state = STATE_VALUE; uint depth = 0; uint stringStart; bytes32[] memory path = new bytes32[](10); for (uint p = 0; p < input.length; p++) { byte c = input[p]; require(depth >= 0, "depth underflow"); require(depth < 10, "depth overflow"); if (state == STATE_ORDVALUE) { if ((c == " ") || (c == ":")) { continue; } if (path[1] == keccak_id) { eventid = bytes2uint(input, stringStart, p); } else if ((depth == 2) && (path[1] == keccak_status) && (path[2] == keccak_id)) { statusid = bytes2uint(input, stringStart, p); if (path[3] == keccak_home) { periods_ft_home = bytes2uint(input, stringStart, p); periods_ft_away = bytes2uint(input, stringStart, p); } } state = STATE_LIST; depth--; } continue; } }
14,153,883
[ 1, 17056, 358, 509, 924, 635, 2690, 2953, 389, 350, 1267, 6315, 350, 12777, 18, 1222, 18, 8712, 12777, 18, 1222, 18, 26718, 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, 445, 1109, 1133, 1253, 12, 3890, 3778, 810, 13, 1071, 288, 203, 3639, 2254, 1105, 871, 350, 273, 374, 31, 203, 3639, 2254, 1267, 350, 273, 374, 31, 203, 3639, 2254, 12777, 67, 1222, 67, 8712, 273, 374, 31, 203, 3639, 2254, 12777, 67, 1222, 67, 26718, 273, 374, 31, 203, 203, 3639, 2254, 919, 273, 7442, 67, 4051, 31, 203, 3639, 2254, 3598, 273, 374, 31, 203, 3639, 2254, 533, 1685, 31, 203, 3639, 1731, 1578, 8526, 3778, 589, 273, 394, 1731, 1578, 8526, 12, 2163, 1769, 203, 203, 3639, 364, 261, 11890, 293, 273, 374, 31, 293, 411, 810, 18, 2469, 31, 293, 27245, 288, 203, 5411, 1160, 276, 273, 810, 63, 84, 15533, 203, 5411, 2583, 12, 5979, 1545, 374, 16, 315, 5979, 3613, 2426, 8863, 203, 5411, 2583, 12, 5979, 411, 1728, 16, 315, 5979, 9391, 8863, 203, 5411, 309, 261, 2019, 422, 7442, 67, 916, 40, 4051, 13, 288, 203, 7734, 309, 14015, 71, 422, 315, 9369, 747, 261, 71, 422, 6153, 3719, 288, 203, 10792, 1324, 31, 203, 7734, 289, 203, 10792, 309, 261, 803, 63, 21, 65, 422, 417, 24410, 581, 67, 350, 13, 288, 203, 13491, 871, 350, 273, 1731, 22, 11890, 12, 2630, 16, 533, 1685, 16, 293, 1769, 203, 10792, 289, 203, 10792, 469, 309, 14015, 5979, 422, 576, 13, 597, 261, 803, 63, 21, 65, 422, 417, 24410, 581, 67, 2327, 13, 597, 261, 803, 63, 22, 65, 422, 417, 24410, 581, 67, 350, 3719, 288, 203, 13491, 1267, 350, 273, 1731, 2 ]
// SPDX-License-Identifier: MIT // Smart Contract Written by: imnotFuzzyHat <Ian Olson> pragma solidity ^0.8.4; pragma abicoder v2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./rarible/library/LibPart.sol"; import "./rarible/library/LibRoyaltiesV2.sol"; import "./rarible/RoyaltiesV2.sol"; contract Dot is Ownable, ERC721Enumerable, RoyaltiesV2 { using SafeMath for uint256; // --- // Constants // --- uint256 constant public royaltyFeeBps = 1000; // 10% bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; bytes4 private constant _INTERFACE_ID_EIP2981 = 0x2a55205a; // --- // Properties // --- uint256 public nextTokenId = 0; string private contractUri; address public payoutAddress; // --- // Mappings // --- mapping(address => bool) private isAdmin; mapping(uint256 => string) private metadataByTokenId; // --- // Security // --- modifier onlyValidTokenId(uint256 tokenId) { require(_exists(tokenId), "Token ID does not exist."); _; } modifier onlyAdmin() { require(isAdmin[msg.sender], "Only admins."); _; } // --- // Constructor // --- constructor() ERC721("dot", "dot") { isAdmin[msg.sender] = true; payoutAddress = msg.sender; contractUri = "ipfs://QmQXsHZXKN5SKfdE2oTUL9BRkWtCpsB4bCR9fgQL2nzZ6N"; // Initial Mints mintToken("ipfs://QmUfpKFdmcJCyop6TSWqQDUCGfTCqW8Rom5fwKEKYqWaeq"); // Token 0 mintToken("ipfs://QmSYqy7DcU4CGo1gMrvkdmrHrQqzywBuzqgJyCdFybb31r"); // Token 1 mintToken("ipfs://QmT8DJKGyTMnpLMmAaL6i92Cav2naRxNbiXyyujdJKaQXc"); // Token 2 mintToken("ipfs://QmaEWr6xsbYSU2FfoDmpfHkvtNw741BCLMtmErf8R85XSw"); // Token 3 mintToken("ipfs://QmNocN1JLzLvMvkj4yrP6xNxBn2MCYabRau77nuC8jwfSD"); // Token 4 mintToken("ipfs://QmXDUgpBAxE4GsiLeXcDLwvQ82uBYnbsaL3RaK43UEHjye"); // Token 5 } // --- // Supported Interfaces // --- function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == _INTERFACE_ID_ERC165 || interfaceId == LibRoyaltiesV2._INTERFACE_ID_ROYALTIES || interfaceId == _INTERFACE_ID_ERC721 || interfaceId == _INTERFACE_ID_ERC721_METADATA || interfaceId == _INTERFACE_ID_ERC721_ENUMERABLE || interfaceId == _INTERFACE_ID_EIP2981 || super.supportsInterface(interfaceId); } // --- // Minting // --- function mintToken(string memory metadataUri) public onlyAdmin returns (uint256 tokenId) { tokenId = nextTokenId; nextTokenId = nextTokenId.add(1); _mint(msg.sender, tokenId); metadataByTokenId[tokenId] = metadataUri; } // --- // Burning // --- function burn(uint256 tokenId) public virtual onlyAdmin { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "Only approved or token owners can burn."); _burn(tokenId); } // --- // Update Functions // --- function addAdmin(address adminAddress) public onlyAdmin { isAdmin[adminAddress] = true; } function removeAdmin(address adminAddress) public onlyAdmin { require((msg.sender != adminAddress), "Cannot remove self."); isAdmin[adminAddress] = false; } function updateContractUri(string memory updatedContractUri) public onlyAdmin { contractUri = updatedContractUri; } function updatePayoutAddress(address newPayoutAddress) public onlyAdmin { payoutAddress = newPayoutAddress; } function updateTokenMetadata(uint256 tokenId, string memory metadataUri) public onlyAdmin onlyValidTokenId(tokenId) { metadataByTokenId[tokenId] = metadataUri; } // --- // Contract Retrieve Functions // --- function tokenURI(uint256 tokenId) public view override virtual onlyValidTokenId(tokenId) returns (string memory) { return metadataByTokenId[tokenId]; } function contractURI() public view virtual returns (string memory) { return contractUri; } function getTokensOfOwner(address walletAddress) public view returns (uint256[] memory tokenIds) { uint256 tokenCount = balanceOf(walletAddress); if (tokenCount == 0) { tokenIds = new uint256[](0); } else { tokenIds = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { tokenIds[index] = tokenOfOwnerByIndex(walletAddress, index); } } return tokenIds; } // --- // Secondary Marketplace Functions // --- /* Rarible Royalties V2 */ function getRaribleV2Royalties(uint256 id) external view override onlyValidTokenId(id) returns (LibPart.Part[] memory) { LibPart.Part[] memory royalties = new LibPart.Part[](1); royalties[0] = LibPart.Part({ account: payable(payoutAddress), value: uint96(royaltyFeeBps) }); return royalties; } /* EIP-2981 */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view onlyValidTokenId(tokenId) returns (address receiver, uint256 amount) { uint256 fivePercent = SafeMath.div(SafeMath.mul(salePrice, royaltyFeeBps), 10000); return (payoutAddress, fivePercent); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library LibRoyaltiesV2 { /* * bytes4(keccak256('getRaribleV2Royalties(uint256)')) == 0xcad96cca */ bytes4 constant _INTERFACE_ID_ROYALTIES = 0xcad96cca; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library LibPart { bytes32 public constant TYPE_HASH = keccak256("Part(address account,uint96 value)"); struct Part { address payable account; uint96 value; } function hash(Part memory part) internal pure returns (bytes32) { return keccak256(abi.encode(TYPE_HASH, part.account, part.value)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "./library/LibPart.sol"; interface RoyaltiesV2 { event RoyaltiesSet(uint256 tokenId, LibPart.Part[] royalties); function getRaribleV2Royalties(uint256 id) external view returns (LibPart.Part[] memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev 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; 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; 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); } }
--- Constructor --- Initial Mints
constructor() ERC721("dot", "dot") { isAdmin[msg.sender] = true; payoutAddress = msg.sender; }
14,518,071
[ 1, 6062, 11417, 9948, 10188, 490, 28142, 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, 3885, 1435, 4232, 39, 27, 5340, 2932, 9811, 3113, 315, 9811, 7923, 288, 203, 3639, 23467, 63, 3576, 18, 15330, 65, 273, 638, 31, 203, 3639, 293, 2012, 1887, 273, 1234, 18, 15330, 31, 203, 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 ]
// Contracts by dYdX Foundation. Individual files are released under different licenses. // // https://dydx.community // https://github.com/dydxfoundation/governance-contracts // // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../dependencies/open-zeppelin/SafeERC20.sol'; import { IERC20 } from '../../interfaces/IERC20.sol'; import { SM1Admin } from '../v1_1/impl/SM1Admin.sol'; import { SM1Getters } from '../v1_1/impl/SM1Getters.sol'; import { SM1Operators } from '../v1_1/impl/SM1Operators.sol'; import { SM1Slashing } from '../v1_1/impl/SM1Slashing.sol'; import { SM1Staking } from '../v1_1/impl/SM1Staking.sol'; /** * @title SafetyModuleV2 * @author dYdX * * @notice Contract for staking tokens, which may be slashed by the permissioned slasher. * * NOTE: Most functions will revert if epoch zero has not started. */ contract SafetyModuleV2 is SM1Slashing, SM1Operators, SM1Admin, SM1Getters { using SafeERC20 for IERC20; // ============ Constants ============ string public constant EIP712_DOMAIN_NAME = 'dYdX Safety Module'; string public constant EIP712_DOMAIN_VERSION = '1'; bytes32 public constant EIP712_DOMAIN_SCHEMA_HASH = keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ); // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) SM1Staking(stakedToken, rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ External Functions ============ /** * @notice Initializer for v2, intended to fix the deployment bug that affected v1. * * Responsible for the following: * * 1. Funds recovery and staker compensation: * - Transfer all Safety Module DYDX to the recovery contract. * - Transfer compensation amount from the rewards treasury to the recovery contract. * * 2. Storage recovery and cleanup: * - Set the _EXCHANGE_RATE_ to EXCHANGE_RATE_BASE. * - Clean up invalid storage values at slots 115 and 125. * * @param recoveryContract The address of the contract which will distribute * recovered funds to stakers. * @param recoveryCompensationAmount Amount to transfer out of the rewards treasury, for staker * compensation, on top of the return of staked funds. */ function initialize( address recoveryContract, uint256 recoveryCompensationAmount ) external initializer { // Funds recovery and staker compensation. uint256 balance = STAKED_TOKEN.balanceOf(address(this)); STAKED_TOKEN.safeTransfer(recoveryContract, balance); REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, recoveryContract, recoveryCompensationAmount); // Storage recovery and cleanup. __SM1ExchangeRate_init(); // solhint-disable-next-line no-inline-assembly assembly { sstore(115, 0) sstore(125, 0) } } // ============ Internal Functions ============ /** * @dev Returns the revision of the implementation contract. * * @return The revision number. */ function getRevision() internal pure override returns (uint256) { return 2; } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import { IERC20 } from '../../interfaces/IERC20.sol'; import { SafeMath } from './SafeMath.sol'; import { Address } from './Address.sol'; /** * @title SafeERC20 * @dev From https://github.com/OpenZeppelin/openzeppelin-contracts * 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)); } 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 callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), 'SafeERC20: call to non-contract'); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, 'SafeERC20: low-level call failed'); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed'); } } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; /** * @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: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Roles } from './SM1Roles.sol'; import { SM1StakedBalances } from './SM1StakedBalances.sol'; /** * @title SM1Admin * @author dYdX * * @dev Admin-only functions. */ abstract contract SM1Admin is SM1StakedBalances, SM1Roles { using SafeMath for uint256; // ============ External Functions ============ /** * @notice Set the parameters defining the function from timestamp to epoch number. * * The formula used is `n = floor((t - b) / a)` where: * - `n` is the epoch number * - `t` is the timestamp (in seconds) * - `b` is a non-negative offset, indicating the start of epoch zero (in seconds) * - `a` is the length of an epoch, a.k.a. the interval (in seconds) * * Reverts if epoch zero already started, and the new parameters would change the current epoch. * Reverts if epoch zero has not started, but would have had started under the new parameters. * * @param interval The length `a` of an epoch, in seconds. * @param offset The offset `b`, i.e. the start of epoch zero, in seconds. */ function setEpochParameters( uint256 interval, uint256 offset ) external onlyRole(EPOCH_PARAMETERS_ROLE) nonReentrant { if (!hasEpochZeroStarted()) { require( block.timestamp < offset, 'SM1Admin: Started epoch zero' ); _setEpochParameters(interval, offset); return; } // We must settle the total active balance to ensure the index is recorded at the epoch // boundary as needed, before we make any changes to the epoch formula. _settleTotalActiveBalance(); // Update the epoch parameters. Require that the current epoch number is unchanged. uint256 originalCurrentEpoch = getCurrentEpoch(); _setEpochParameters(interval, offset); uint256 newCurrentEpoch = getCurrentEpoch(); require( originalCurrentEpoch == newCurrentEpoch, 'SM1Admin: Changed epochs' ); } /** * @notice Set the blackout window, during which one cannot request withdrawals of staked funds. */ function setBlackoutWindow( uint256 blackoutWindow ) external onlyRole(EPOCH_PARAMETERS_ROLE) nonReentrant { _setBlackoutWindow(blackoutWindow); } /** * @notice Set the emission rate of rewards. * * @param emissionPerSecond The new number of rewards tokens given out per second. */ function setRewardsPerSecond( uint256 emissionPerSecond ) external onlyRole(REWARDS_RATE_ROLE) nonReentrant { uint256 totalStaked = 0; if (hasEpochZeroStarted()) { // We must settle the total active balance to ensure the index is recorded at the epoch // boundary as needed, before we make any changes to the emission rate. totalStaked = _settleTotalActiveBalance(); } _setRewardsPerSecond(emissionPerSecond, totalStaked); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { Math } from '../../../utils/Math.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1Getters * @author dYdX * * @dev Some external getter functions. */ abstract contract SM1Getters is SM1Storage { using SafeMath for uint256; // ============ External Functions ============ /** * @notice The parameters specifying the function from timestamp to epoch number. * * @return The parameters struct with `interval` and `offset` fields. */ function getEpochParameters() external view returns (SM1Types.EpochParameters memory) { return _EPOCH_PARAMETERS_; } /** * @notice The period of time at the end of each epoch in which withdrawals cannot be requested. * * @return The blackout window duration, in seconds. */ function getBlackoutWindow() external view returns (uint256) { return _BLACKOUT_WINDOW_; } /** * @notice Get the domain separator used for EIP-712 signatures. * * @return The EIP-712 domain separator. */ function getDomainSeparator() external view returns (bytes32) { return _DOMAIN_SEPARATOR_; } /** * @notice The value of one underlying token, in the units used for staked balances, denominated * as a mutiple of EXCHANGE_RATE_BASE for additional precision. * * To convert from an underlying amount to a staked amount, multiply by the exchange rate. * * @return The exchange rate. */ function getExchangeRate() external view returns (uint256) { return _EXCHANGE_RATE_; } /** * @notice Get an exchange rate snapshot. * * @param index The index number of the exchange rate snapshot. * * @return The snapshot struct with `blockNumber` and `value` fields. */ function getExchangeRateSnapshot( uint256 index ) external view returns (SM1Types.Snapshot memory) { return _EXCHANGE_RATE_SNAPSHOTS_[index]; } /** * @notice Get the number of exchange rate snapshots. * * @return The number of snapshots that have been taken of the exchange rate. */ function getExchangeRateSnapshotCount() external view returns (uint256) { return _EXCHANGE_RATE_SNAPSHOT_COUNT_; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SM1Roles } from './SM1Roles.sol'; import { SM1Staking } from './SM1Staking.sol'; /** * @title SM1Operators * @author dYdX * * @dev Actions which may be called by authorized operators, nominated by the contract owner. * * There are two types of operators. These should be smart contracts, which can be used to * provide additional functionality to users: * * STAKE_OPERATOR_ROLE: * * This operator is allowed to request withdrawals and withdraw funds on behalf of stakers. This * role could be used by a smart contract to provide a staking interface with additional * features, for example, optional lock-up periods that pay out additional rewards (from a * separate rewards pool). * * CLAIM_OPERATOR_ROLE: * * This operator is allowed to claim rewards on behalf of stakers. This role could be used by a * smart contract to provide an interface for claiming rewards from multiple incentive programs * at once. */ abstract contract SM1Operators is SM1Staking, SM1Roles { using SafeMath for uint256; // ============ Events ============ event OperatorStakedFor( address indexed staker, uint256 amount, address operator ); event OperatorWithdrawalRequestedFor( address indexed staker, uint256 amount, address operator ); event OperatorWithdrewStakeFor( address indexed staker, address recipient, uint256 amount, address operator ); event OperatorClaimedRewardsFor( address indexed staker, address recipient, uint256 claimedRewards, address operator ); // ============ External Functions ============ /** * @notice Request a withdrawal on behalf of a staker. * * Reverts if we are currently in the blackout window. * * @param staker The staker whose stake to request a withdrawal for. * @param stakeAmount The amount of stake to move from the active to the inactive balance. */ function requestWithdrawalFor( address staker, uint256 stakeAmount ) external onlyRole(STAKE_OPERATOR_ROLE) nonReentrant { _requestWithdrawal(staker, stakeAmount); emit OperatorWithdrawalRequestedFor(staker, stakeAmount, msg.sender); } /** * @notice Withdraw a staker's stake, and send to the specified recipient. * * @param staker The staker whose stake to withdraw. * @param recipient The address that should receive the funds. * @param stakeAmount The amount of stake to withdraw from the staker's inactive balance. */ function withdrawStakeFor( address staker, address recipient, uint256 stakeAmount ) external onlyRole(STAKE_OPERATOR_ROLE) nonReentrant { _withdrawStake(staker, recipient, stakeAmount); emit OperatorWithdrewStakeFor(staker, recipient, stakeAmount, msg.sender); } /** * @notice Claim rewards on behalf of a staker, and send them to the specified recipient. * * @param staker The staker whose rewards to claim. * @param recipient The address that should receive the funds. * * @return The number of rewards tokens claimed. */ function claimRewardsFor( address staker, address recipient ) external onlyRole(CLAIM_OPERATOR_ROLE) nonReentrant returns (uint256) { uint256 rewards = _settleAndClaimRewards(staker, recipient); // Emits an event internally. emit OperatorClaimedRewardsFor(staker, recipient, rewards, msg.sender); return rewards; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Roles } from './SM1Roles.sol'; import { SM1Staking } from './SM1Staking.sol'; /** * @title SM1Slashing * @author dYdX * * @dev Provides the slashing function for removing funds from the contract. * * SLASHING: * * All funds in the contract, active or inactive, are slashable. Slashes are recorded by updating * the exchange rate, and to simplify the technical implementation, we disallow full slashes. * To reduce the possibility of overflow in the exchange rate, we place an upper bound on the * fraction of funds that may be slashed in a single slash. * * Warning: Slashing is not possible if the slash would cause the exchange rate to overflow. * * REWARDS AND GOVERNANCE POWER ACCOUNTING: * * Since all slashes are accounted for by a global exchange rate, slashes do not require any * update to staked balances. The earning of rewards is unaffected by slashes. * * Governance power takes slashes into account by using snapshots of the exchange rate inside * the getPowerAtBlock() function. Note that getPowerAtBlock() returns the governance power as of * the end of the specified block. */ abstract contract SM1Slashing is SM1Staking, SM1Roles { using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Constants ============ /// @notice The maximum fraction of funds that may be slashed in a single slash (numerator). uint256 public constant MAX_SLASH_NUMERATOR = 95; /// @notice The maximum fraction of funds that may be slashed in a single slash (denominator). uint256 public constant MAX_SLASH_DENOMINATOR = 100; // ============ Events ============ event Slashed( uint256 amount, address recipient, uint256 newExchangeRate ); // ============ External Functions ============ /** * @notice Slash staked token balances and withdraw those funds to the specified address. * * @param requestedSlashAmount The request slash amount, denominated in the underlying token. * @param recipient The address to receive the slashed tokens. * * @return The amount slashed, denominated in the underlying token. */ function slash( uint256 requestedSlashAmount, address recipient ) external onlyRole(SLASHER_ROLE) nonReentrant returns (uint256) { uint256 underlyingBalance = STAKED_TOKEN.balanceOf(address(this)); if (underlyingBalance == 0) { return 0; } // Get the slash amount and remaining amount. Note that remainingAfterSlash is nonzero. uint256 maxSlashAmount = underlyingBalance.mul(MAX_SLASH_NUMERATOR).div(MAX_SLASH_DENOMINATOR); uint256 slashAmount = Math.min(requestedSlashAmount, maxSlashAmount); uint256 remainingAfterSlash = underlyingBalance.sub(slashAmount); if (slashAmount == 0) { return 0; } // Update the exchange rate. // // Warning: Can revert if the max exchange rate is exceeded. uint256 newExchangeRate = updateExchangeRate(underlyingBalance, remainingAfterSlash); // Transfer the slashed token. STAKED_TOKEN.safeTransfer(recipient, slashAmount); emit Slashed(slashAmount, recipient, newExchangeRate); return slashAmount; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1ERC20 } from './SM1ERC20.sol'; import { SM1StakedBalances } from './SM1StakedBalances.sol'; /** * @title SM1Staking * @author dYdX * * @dev External functions for stakers. See SM1StakedBalances for details on staker accounting. * * UNDERLYING AND STAKED AMOUNTS: * * We distinguish between underlying amounts and stake amounts. An underlying amount is denoted * in the original units of the token being staked. A stake amount is adjusted by the exchange * rate, which can increase due to slashing. Before any slashes have occurred, the exchange rate * is equal to one. */ abstract contract SM1Staking is SM1StakedBalances, SM1ERC20 { using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Events ============ event Staked( address indexed staker, address spender, uint256 underlyingAmount, uint256 stakeAmount ); event WithdrawalRequested( address indexed staker, uint256 stakeAmount ); event WithdrewStake( address indexed staker, address recipient, uint256 underlyingAmount, uint256 stakeAmount ); // ============ Constants ============ IERC20 public immutable STAKED_TOKEN; // ============ Constructor ============ constructor( IERC20 stakedToken, IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) SM1StakedBalances(rewardsToken, rewardsTreasury, distributionStart, distributionEnd) { STAKED_TOKEN = stakedToken; } // ============ External Functions ============ /** * @notice Deposit and stake funds. These funds are active and start earning rewards immediately. * * @param underlyingAmount The amount of underlying token to stake. */ function stake( uint256 underlyingAmount ) external nonReentrant { _stake(msg.sender, underlyingAmount); } /** * @notice Deposit and stake on behalf of another address. * * @param staker The staker who will receive the stake. * @param underlyingAmount The amount of underlying token to stake. */ function stakeFor( address staker, uint256 underlyingAmount ) external nonReentrant { _stake(staker, underlyingAmount); } /** * @notice Request to withdraw funds. Starting in the next epoch, the funds will be “inactive” * and available for withdrawal. Inactive funds do not earn rewards. * * Reverts if we are currently in the blackout window. * * @param stakeAmount The amount of stake to move from the active to the inactive balance. */ function requestWithdrawal( uint256 stakeAmount ) external nonReentrant { _requestWithdrawal(msg.sender, stakeAmount); } /** * @notice Withdraw the sender's inactive funds, and send to the specified recipient. * * @param recipient The address that should receive the funds. * @param stakeAmount The amount of stake to withdraw from the sender's inactive balance. */ function withdrawStake( address recipient, uint256 stakeAmount ) external nonReentrant { _withdrawStake(msg.sender, recipient, stakeAmount); } /** * @notice Withdraw the max available inactive funds, and send to the specified recipient. * * This is less gas-efficient than querying the max via eth_call and calling withdrawStake(). * * @param recipient The address that should receive the funds. * * @return The withdrawn amount. */ function withdrawMaxStake( address recipient ) external nonReentrant returns (uint256) { uint256 stakeAmount = getStakeAvailableToWithdraw(msg.sender); _withdrawStake(msg.sender, recipient, stakeAmount); return stakeAmount; } /** * @notice Settle and claim all rewards, and send them to the specified recipient. * * Call this function with eth_call to query the claimable rewards balance. * * @param recipient The address that should receive the funds. * * @return The number of rewards tokens claimed. */ function claimRewards( address recipient ) external nonReentrant returns (uint256) { return _settleAndClaimRewards(msg.sender, recipient); // Emits an event internally. } // ============ Public Functions ============ /** * @notice Get the amount of stake available for a given staker to withdraw. * * @param staker The address whose balance to check. * * @return The staker's stake amount that is inactive and available to withdraw. */ function getStakeAvailableToWithdraw( address staker ) public view returns (uint256) { // Note that the next epoch inactive balance is always at least that of the current epoch. return getInactiveBalanceCurrentEpoch(staker); } // ============ Internal Functions ============ function _stake( address staker, uint256 underlyingAmount ) internal { // Convert using the exchange rate. uint256 stakeAmount = stakeAmountFromUnderlyingAmount(underlyingAmount); // Update staked balances and delegate snapshots. _increaseCurrentAndNextActiveBalance(staker, stakeAmount); _moveDelegatesForTransfer(address(0), staker, stakeAmount); // Transfer token from the sender. STAKED_TOKEN.safeTransferFrom(msg.sender, address(this), underlyingAmount); emit Staked(staker, msg.sender, underlyingAmount, stakeAmount); emit Transfer(address(0), msg.sender, stakeAmount); } function _requestWithdrawal( address staker, uint256 stakeAmount ) internal { require( !inBlackoutWindow(), 'SM1Staking: Withdraw requests restricted in the blackout window' ); // Get the staker's requestable amount and revert if there is not enough to request withdrawal. uint256 requestableBalance = getActiveBalanceNextEpoch(staker); require( stakeAmount <= requestableBalance, 'SM1Staking: Withdraw request exceeds next active balance' ); // Move amount from active to inactive in the next epoch. _moveNextBalanceActiveToInactive(staker, stakeAmount); emit WithdrawalRequested(staker, stakeAmount); } function _withdrawStake( address staker, address recipient, uint256 stakeAmount ) internal { // Get staker withdrawable balance and revert if there is not enough to withdraw. uint256 withdrawableBalance = getInactiveBalanceCurrentEpoch(staker); require( stakeAmount <= withdrawableBalance, 'SM1Staking: Withdraw amount exceeds staker inactive balance' ); // Update staked balances and delegate snapshots. _decreaseCurrentAndNextInactiveBalance(staker, stakeAmount); _moveDelegatesForTransfer(staker, address(0), stakeAmount); // Convert using the exchange rate. uint256 underlyingAmount = underlyingAmountFromStakeAmount(stakeAmount); // Transfer token to the recipient. STAKED_TOKEN.safeTransfer(recipient, underlyingAmount); emit Transfer(msg.sender, address(0), stakeAmount); emit WithdrewStake(staker, recipient, underlyingAmount, stakeAmount); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // 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. */ 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.7.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev 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'); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; library SM1Types { /** * @dev The parameters used to convert a timestamp to an epoch number. */ struct EpochParameters { uint128 interval; uint128 offset; } /** * @dev Snapshot of a value at a specific block, used to track historical governance power. */ struct Snapshot { uint256 blockNumber; uint256 value; } /** * @dev A balance, possibly with a change scheduled for the next epoch. * * @param currentEpoch The epoch in which the balance was last updated. * @param currentEpochBalance The balance at epoch `currentEpoch`. * @param nextEpochBalance The balance at epoch `currentEpoch + 1`. */ struct StoredBalance { uint16 currentEpoch; uint240 currentEpochBalance; uint240 nextEpochBalance; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1Roles * @author dYdX * * @dev Defines roles used in the SafetyModuleV1 contract. The hierarchy of roles and powers * of each role are described below. * * Roles: * * OWNER_ROLE * | -> May add or remove addresses from any of the roles below. * | * +-- SLASHER_ROLE * | -> Can slash staked token balances and withdraw those funds. * | * +-- EPOCH_PARAMETERS_ROLE * | -> May set epoch parameters such as the interval, offset, and blackout window. * | * +-- REWARDS_RATE_ROLE * | -> May set the emission rate of rewards. * | * +-- CLAIM_OPERATOR_ROLE * | -> May claim rewards on behalf of a user. * | * +-- STAKE_OPERATOR_ROLE * -> May manipulate user's staked funds (e.g. perform withdrawals on behalf of a user). */ abstract contract SM1Roles is SM1Storage { bytes32 public constant OWNER_ROLE = keccak256('OWNER_ROLE'); bytes32 public constant SLASHER_ROLE = keccak256('SLASHER_ROLE'); bytes32 public constant EPOCH_PARAMETERS_ROLE = keccak256('EPOCH_PARAMETERS_ROLE'); bytes32 public constant REWARDS_RATE_ROLE = keccak256('REWARDS_RATE_ROLE'); bytes32 public constant CLAIM_OPERATOR_ROLE = keccak256('CLAIM_OPERATOR_ROLE'); bytes32 public constant STAKE_OPERATOR_ROLE = keccak256('STAKE_OPERATOR_ROLE'); function __SM1Roles_init() internal { // Assign roles to the sender. // // The STAKE_OPERATOR_ROLE and CLAIM_OPERATOR_ROLE roles are not initially assigned. // These can be assigned to other smart contracts to provide additional functionality for users. _setupRole(OWNER_ROLE, msg.sender); _setupRole(SLASHER_ROLE, msg.sender); _setupRole(EPOCH_PARAMETERS_ROLE, msg.sender); _setupRole(REWARDS_RATE_ROLE, msg.sender); // Set OWNER_ROLE as the admin of all roles. _setRoleAdmin(OWNER_ROLE, OWNER_ROLE); _setRoleAdmin(SLASHER_ROLE, OWNER_ROLE); _setRoleAdmin(EPOCH_PARAMETERS_ROLE, OWNER_ROLE); _setRoleAdmin(REWARDS_RATE_ROLE, OWNER_ROLE); _setRoleAdmin(CLAIM_OPERATOR_ROLE, OWNER_ROLE); _setRoleAdmin(STAKE_OPERATOR_ROLE, OWNER_ROLE); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Rewards } from './SM1Rewards.sol'; /** * @title SM1StakedBalances * @author dYdX * * @dev Accounting of staked balances. * * NOTE: Functions may revert if epoch zero has not started. * * NOTE: All amounts dealt with in this file are denominated in staked units, which because of the * exchange rate, may not correspond one-to-one with the underlying token. See SM1Staking.sol. * * STAKED BALANCE ACCOUNTING: * * A staked balance is in one of two states: * - active: Earning staking rewards; cannot be withdrawn by staker; may be slashed. * - inactive: Not earning rewards; can be withdrawn by the staker; may be slashed. * * A staker may have a combination of active and inactive balances. The following operations * affect staked balances as follows: * - deposit: Increase active balance. * - request withdrawal: At the end of the current epoch, move some active funds to inactive. * - withdraw: Decrease inactive balance. * - transfer: Move some active funds to another staker. * * To encode the fact that a balance may be scheduled to change at the end of a certain epoch, we * store each balance as a struct of three fields: currentEpoch, currentEpochBalance, and * nextEpochBalance. * * REWARDS ACCOUNTING: * * Active funds earn rewards for the period of time that they remain active. This means, after * requesting a withdrawal of some funds, those funds will continue to earn rewards until the end * of the epoch. For example: * * epoch: n n + 1 n + 2 n + 3 * | | | | * +----------+----------+----------+-----... * ^ t_0: User makes a deposit. * ^ t_1: User requests a withdrawal of all funds. * ^ t_2: The funds change state from active to inactive. * * In the above scenario, the user would earn rewards for the period from t_0 to t_2, varying * with the total staked balance in that period. If the user only request a withdrawal for a part * of their balance, then the remaining balance would continue earning rewards beyond t_2. * * User rewards must be settled via SM1Rewards any time a user's active balance changes. Special * attention is paid to the the epoch boundaries, where funds may have transitioned from active * to inactive. * * SETTLEMENT DETAILS: * * Internally, this module uses the following types of operations on stored balances: * - Load: Loads a balance, while applying settlement logic internally to get the * up-to-date result. Returns settlement results without updating state. * - Store: Stores a balance. * - Load-for-update: Performs a load and applies updates as needed to rewards accounting. * Since this is state-changing, it must be followed by a store operation. * - Settle: Performs load-for-update and store operations. * * This module is responsible for maintaining the following invariants to ensure rewards are * calculated correctly: * - When an active balance is loaded for update, if a rollover occurs from one epoch to the * next, the rewards index must be settled up to the boundary at which the rollover occurs. * - Because the global rewards index is needed to update the user rewards index, the total * active balance must be settled before any staker balances are settled or loaded for update. * - A staker's balance must be settled before their rewards are settled. */ abstract contract SM1StakedBalances is SM1Rewards { using SafeCast for uint256; using SafeMath for uint256; // ============ Constructor ============ constructor( IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) SM1Rewards(rewardsToken, rewardsTreasury, distributionStart, distributionEnd) {} // ============ Public Functions ============ /** * @notice Get the current active balance of a staker. */ function getActiveBalanceCurrentEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance( _ACTIVE_BALANCES_[staker] ); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch active balance of a staker. */ function getActiveBalanceNextEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance( _ACTIVE_BALANCES_[staker] ); return uint256(balance.nextEpochBalance); } /** * @notice Get the current total active balance. */ function getTotalActiveBalanceCurrentEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance( _TOTAL_ACTIVE_BALANCE_ ); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch total active balance. */ function getTotalActiveBalanceNextEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } (SM1Types.StoredBalance memory balance, , , ) = _loadActiveBalance( _TOTAL_ACTIVE_BALANCE_ ); return uint256(balance.nextEpochBalance); } /** * @notice Get the current inactive balance of a staker. * @dev The balance is converted via the index to token units. */ function getInactiveBalanceCurrentEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_INACTIVE_BALANCES_[staker]); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch inactive balance of a staker. * @dev The balance is converted via the index to token units. */ function getInactiveBalanceNextEpoch( address staker ) public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_INACTIVE_BALANCES_[staker]); return uint256(balance.nextEpochBalance); } /** * @notice Get the current total inactive balance. */ function getTotalInactiveBalanceCurrentEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_TOTAL_INACTIVE_BALANCE_); return uint256(balance.currentEpochBalance); } /** * @notice Get the next epoch total inactive balance. */ function getTotalInactiveBalanceNextEpoch() public view returns (uint256) { if (!hasEpochZeroStarted()) { return 0; } SM1Types.StoredBalance memory balance = _loadInactiveBalance(_TOTAL_INACTIVE_BALANCE_); return uint256(balance.nextEpochBalance); } /** * @notice Get the current transferable balance for a user. The user can * only transfer their balance that is not currently inactive or going to be * inactive in the next epoch. Note that this means the user's transferable funds * are their active balance of the next epoch. * * @param account The account to get the transferable balance of. * * @return The user's transferable balance. */ function getTransferableBalance( address account ) public view returns (uint256) { return getActiveBalanceNextEpoch(account); } // ============ Internal Functions ============ function _increaseCurrentAndNextActiveBalance( address staker, uint256 amount ) internal { // Always settle total active balance before settling a staker active balance. uint256 oldTotalBalance = _increaseCurrentAndNextBalances(address(0), true, amount); uint256 oldUserBalance = _increaseCurrentAndNextBalances(staker, true, amount); // When an active balance changes at current timestamp, settle rewards to the current timestamp. _settleUserRewardsUpToNow(staker, oldUserBalance, oldTotalBalance); } function _moveNextBalanceActiveToInactive( address staker, uint256 amount ) internal { // Decrease the active balance for the next epoch. // Always settle total active balance before settling a staker active balance. _decreaseNextBalance(address(0), true, amount); _decreaseNextBalance(staker, true, amount); // Increase the inactive balance for the next epoch. _increaseNextBalance(address(0), false, amount); _increaseNextBalance(staker, false, amount); // Note that we don't need to settle rewards since the current active balance did not change. } function _transferCurrentAndNextActiveBalance( address sender, address recipient, uint256 amount ) internal { // Always settle total active balance before settling a staker active balance. uint256 totalBalance = _settleTotalActiveBalance(); // Move current and next active balances from sender to recipient. uint256 oldSenderBalance = _decreaseCurrentAndNextBalances(sender, true, amount); uint256 oldRecipientBalance = _increaseCurrentAndNextBalances(recipient, true, amount); // When an active balance changes at current timestamp, settle rewards to the current timestamp. _settleUserRewardsUpToNow(sender, oldSenderBalance, totalBalance); _settleUserRewardsUpToNow(recipient, oldRecipientBalance, totalBalance); } function _decreaseCurrentAndNextInactiveBalance( address staker, uint256 amount ) internal { // Decrease the inactive balance for the next epoch. _decreaseCurrentAndNextBalances(address(0), false, amount); _decreaseCurrentAndNextBalances(staker, false, amount); // Note that we don't settle rewards since active balances are not affected. } function _settleTotalActiveBalance() internal returns (uint256) { return _settleBalance(address(0), true); } function _settleAndClaimRewards( address staker, address recipient ) internal returns (uint256) { // Always settle total active balance before settling a staker active balance. uint256 totalBalance = _settleTotalActiveBalance(); // Always settle staker active balance before settling staker rewards. uint256 userBalance = _settleBalance(staker, true); // Settle rewards balance since we want to claim the full accrued amount. _settleUserRewardsUpToNow(staker, userBalance, totalBalance); // Claim rewards balance. return _claimRewards(staker, recipient); } // ============ Private Functions ============ /** * @dev Load a balance for update and then store it. */ function _settleBalance( address maybeStaker, bool isActiveBalance ) private returns (uint256) { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 currentBalance = uint256(balance.currentEpochBalance); _storeBalance(balancePtr, balance); return currentBalance; } /** * @dev Settle a balance while applying an increase. */ function _increaseCurrentAndNextBalances( address maybeStaker, bool isActiveBalance, uint256 amount ) private returns (uint256) { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 originalCurrentBalance = uint256(balance.currentEpochBalance); balance.currentEpochBalance = originalCurrentBalance.add(amount).toUint240(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint240(); _storeBalance(balancePtr, balance); return originalCurrentBalance; } /** * @dev Settle a balance while applying a decrease. */ function _decreaseCurrentAndNextBalances( address maybeStaker, bool isActiveBalance, uint256 amount ) private returns (uint256) { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); uint256 originalCurrentBalance = uint256(balance.currentEpochBalance); balance.currentEpochBalance = originalCurrentBalance.sub(amount).toUint240(); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint240(); _storeBalance(balancePtr, balance); return originalCurrentBalance; } /** * @dev Settle a balance while applying an increase. */ function _increaseNextBalance( address maybeStaker, bool isActiveBalance, uint256 amount ) private { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); balance.nextEpochBalance = uint256(balance.nextEpochBalance).add(amount).toUint240(); _storeBalance(balancePtr, balance); } /** * @dev Settle a balance while applying a decrease. */ function _decreaseNextBalance( address maybeStaker, bool isActiveBalance, uint256 amount ) private { SM1Types.StoredBalance storage balancePtr = _getBalancePtr(maybeStaker, isActiveBalance); SM1Types.StoredBalance memory balance = _loadBalanceForUpdate(balancePtr, maybeStaker, isActiveBalance); balance.nextEpochBalance = uint256(balance.nextEpochBalance).sub(amount).toUint240(); _storeBalance(balancePtr, balance); } function _getBalancePtr( address maybeStaker, bool isActiveBalance ) private view returns (SM1Types.StoredBalance storage) { // Active. if (isActiveBalance) { if (maybeStaker != address(0)) { return _ACTIVE_BALANCES_[maybeStaker]; } return _TOTAL_ACTIVE_BALANCE_; } // Inactive. if (maybeStaker != address(0)) { return _INACTIVE_BALANCES_[maybeStaker]; } return _TOTAL_INACTIVE_BALANCE_; } /** * @dev Load a balance for updating. * * IMPORTANT: This function may modify state, and so the balance MUST be stored afterwards. * - For active balances: * - If a rollover occurs, rewards are settled up to the epoch boundary. * * @param balancePtr A storage pointer to the balance. * @param maybeStaker The user address, or address(0) to update total balance. * @param isActiveBalance Whether the balance is an active balance. */ function _loadBalanceForUpdate( SM1Types.StoredBalance storage balancePtr, address maybeStaker, bool isActiveBalance ) private returns (SM1Types.StoredBalance memory) { // Active balance. if (isActiveBalance) { ( SM1Types.StoredBalance memory balance, uint256 beforeRolloverEpoch, uint256 beforeRolloverBalance, bool didRolloverOccur ) = _loadActiveBalance(balancePtr); if (didRolloverOccur) { // Handle the effect of the balance rollover on rewards. We must partially settle the index // up to the epoch boundary where the change in balance occurred. We pass in the balance // from before the boundary. if (maybeStaker == address(0)) { // If it's the total active balance... _settleGlobalIndexUpToEpoch(beforeRolloverBalance, beforeRolloverEpoch); } else { // If it's a user active balance... _settleUserRewardsUpToEpoch(maybeStaker, beforeRolloverBalance, beforeRolloverEpoch); } } return balance; } // Inactive balance. return _loadInactiveBalance(balancePtr); } function _loadActiveBalance( SM1Types.StoredBalance storage balancePtr ) private view returns ( SM1Types.StoredBalance memory, uint256, uint256, bool ) { SM1Types.StoredBalance memory balance = balancePtr; // Return these as they may be needed for rewards settlement. uint256 beforeRolloverEpoch = uint256(balance.currentEpoch); uint256 beforeRolloverBalance = uint256(balance.currentEpochBalance); bool didRolloverOccur = false; // Roll the balance forward if needed. uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(balance.currentEpoch)) { didRolloverOccur = balance.currentEpochBalance != balance.nextEpochBalance; balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; } return (balance, beforeRolloverEpoch, beforeRolloverBalance, didRolloverOccur); } function _loadInactiveBalance( SM1Types.StoredBalance storage balancePtr ) private view returns (SM1Types.StoredBalance memory) { SM1Types.StoredBalance memory balance = balancePtr; // Roll the balance forward if needed. uint256 currentEpoch = getCurrentEpoch(); if (currentEpoch > uint256(balance.currentEpoch)) { balance.currentEpoch = currentEpoch.toUint16(); balance.currentEpochBalance = balance.nextEpochBalance; } return balance; } /** * @dev Store a balance. */ function _storeBalance( SM1Types.StoredBalance storage balancePtr, SM1Types.StoredBalance memory balance ) private { // Note: This should use a single `sstore` when compiler optimizations are enabled. balancePtr.currentEpoch = balance.currentEpoch; balancePtr.currentEpochBalance = balance.currentEpochBalance; balancePtr.nextEpochBalance = balance.nextEpochBalance; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { AccessControlUpgradeable } from '../../../dependencies/open-zeppelin/AccessControlUpgradeable.sol'; import { ReentrancyGuard } from '../../../utils/ReentrancyGuard.sol'; import { VersionedInitializable } from '../../../utils/VersionedInitializable.sol'; import { SM1Types } from '../lib/SM1Types.sol'; /** * @title SM1Storage * @author dYdX * * @dev Storage contract. Contains or inherits from all contract with storage. */ abstract contract SM1Storage is AccessControlUpgradeable, ReentrancyGuard, VersionedInitializable { // ============ Epoch Schedule ============ /// @dev The parameters specifying the function from timestamp to epoch number. SM1Types.EpochParameters internal _EPOCH_PARAMETERS_; /// @dev The period of time at the end of each epoch in which withdrawals cannot be requested. uint256 internal _BLACKOUT_WINDOW_; // ============ Staked Token ERC20 ============ /// @dev Allowances for ERC-20 transfers. mapping(address => mapping(address => uint256)) internal _ALLOWANCES_; // ============ Governance Power Delegation ============ /// @dev Domain separator for EIP-712 signatures. bytes32 internal _DOMAIN_SEPARATOR_; /// @dev Mapping from (owner) => (next valid nonce) for EIP-712 signatures. mapping(address => uint256) internal _NONCES_; /// @dev Snapshots and delegates for governance voting power. mapping(address => mapping(uint256 => SM1Types.Snapshot)) internal _VOTING_SNAPSHOTS_; mapping(address => uint256) internal _VOTING_SNAPSHOT_COUNTS_; mapping(address => address) internal _VOTING_DELEGATES_; /// @dev Snapshots and delegates for governance proposition power. mapping(address => mapping(uint256 => SM1Types.Snapshot)) internal _PROPOSITION_SNAPSHOTS_; mapping(address => uint256) internal _PROPOSITION_SNAPSHOT_COUNTS_; mapping(address => address) internal _PROPOSITION_DELEGATES_; // ============ Rewards Accounting ============ /// @dev The emission rate of rewards. uint256 internal _REWARDS_PER_SECOND_; /// @dev The cumulative rewards earned per staked token. (Shared storage slot.) uint224 internal _GLOBAL_INDEX_; /// @dev The timestamp at which the global index was last updated. (Shared storage slot.) uint32 internal _GLOBAL_INDEX_TIMESTAMP_; /// @dev The value of the global index when the user's staked balance was last updated. mapping(address => uint256) internal _USER_INDEXES_; /// @dev The user's accrued, unclaimed rewards (as of the last update to the user index). mapping(address => uint256) internal _USER_REWARDS_BALANCES_; /// @dev The value of the global index at the end of a given epoch. mapping(uint256 => uint256) internal _EPOCH_INDEXES_; // ============ Staker Accounting ============ /// @dev The active balance by staker. mapping(address => SM1Types.StoredBalance) internal _ACTIVE_BALANCES_; /// @dev The total active balance of stakers. SM1Types.StoredBalance internal _TOTAL_ACTIVE_BALANCE_; /// @dev The inactive balance by staker. mapping(address => SM1Types.StoredBalance) internal _INACTIVE_BALANCES_; /// @dev The total inactive balance of stakers. SM1Types.StoredBalance internal _TOTAL_INACTIVE_BALANCE_; // ============ Exchange Rate ============ /// @dev The value of one underlying token, in the units used for staked balances, denominated /// as a mutiple of EXCHANGE_RATE_BASE for additional precision. uint256 internal _EXCHANGE_RATE_; /// @dev Historical snapshots of the exchange rate, in each block that it has changed. mapping(uint256 => SM1Types.Snapshot) internal _EXCHANGE_RATE_SNAPSHOTS_; /// @dev Number of snapshots of the exchange rate. uint256 internal _EXCHANGE_RATE_SNAPSHOT_COUNT_; } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; import './Context.sol'; import './Strings.sol'; import './ERC165.sol'; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Context, IAccessControlUpgradeable, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged( bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole ); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( 'AccessControl: account ', Strings.toHexString(uint160(account), 20), ' is missing role ', Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), 'AccessControl: can only renounce roles for self'); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @title ReentrancyGuard * @author dYdX * * @dev Updated ReentrancyGuard library designed to be used with Proxy Contracts. */ abstract contract ReentrancyGuard { uint256 private constant NOT_ENTERED = 1; uint256 private constant ENTERED = uint256(int256(-1)); uint256 private _STATUS_; constructor() internal { _STATUS_ = NOT_ENTERED; } modifier nonReentrant() { require(_STATUS_ != ENTERED, 'ReentrancyGuard: reentrant call'); _STATUS_ = ENTERED; _; _STATUS_ = NOT_ENTERED; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; /** * @title VersionedInitializable * @author Aave, inspired by the OpenZeppelin Initializable contract * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. * */ abstract contract VersionedInitializable { /** * @dev Indicates that the contract has been initialized. */ uint256 internal lastInitializedRevision = 0; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { uint256 revision = getRevision(); require(revision > lastInitializedRevision, "Contract instance has already been initialized"); lastInitializedRevision = revision; _; } /// @dev returns the revision number of the contract. /// Needs to be defined in the inherited class as a constant. function getRevision() internal pure virtual returns(uint256); // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; /* * @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.7.5; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = '0123456789abcdef'; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return '0'; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return '0x00'; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = '0'; buffer[1] = 'x'; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, 'Strings: hex length insufficient'); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity 0.7.5; 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.7.5; /** * @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: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; /** * @dev Methods for downcasting unsigned integers, reverting on overflow. */ library SafeCast { /** * @dev Downcast to a uint16, reverting on overflow. */ function toUint16( uint256 a ) internal pure returns (uint16) { uint16 b = uint16(a); require( uint256(b) == a, 'SafeCast: toUint16 overflow' ); return b; } /** * @dev Downcast to a uint32, reverting on overflow. */ function toUint32( uint256 a ) internal pure returns (uint32) { uint32 b = uint32(a); require( uint256(b) == a, 'SafeCast: toUint32 overflow' ); return b; } /** * @dev Downcast to a uint128, reverting on overflow. */ function toUint128( uint256 a ) internal pure returns (uint128) { uint128 b = uint128(a); require( uint256(b) == a, 'SafeCast: toUint128 overflow' ); return b; } /** * @dev Downcast to a uint224, reverting on overflow. */ function toUint224( uint256 a ) internal pure returns (uint224) { uint224 b = uint224(a); require( uint256(b) == a, 'SafeCast: toUint224 overflow' ); return b; } /** * @dev Downcast to a uint240, reverting on overflow. */ function toUint240( uint256 a ) internal pure returns (uint240) { uint240 b = uint240(a); require( uint256(b) == a, 'SafeCast: toUint240 overflow' ); return b; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeERC20 } from '../../../dependencies/open-zeppelin/SafeERC20.sol'; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { Math } from '../../../utils/Math.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { SM1EpochSchedule } from './SM1EpochSchedule.sol'; /** * @title SM1Rewards * @author dYdX * * @dev Manages the distribution of token rewards. * * Rewards are distributed continuously. After each second, an account earns rewards `r` according * to the following formula: * * r = R * s / S * * Where: * - `R` is the rewards distributed globally each second, also called the “emission rate.” * - `s` is the account's staked balance in that second (technically, it is measured at the * end of the second) * - `S` is the sum total of all staked balances in that second (again, measured at the end of * the second) * * The parameter `R` can be configured by the contract owner. For every second that elapses, * exactly `R` tokens will accrue to users, save for rounding errors, and with the exception that * while the total staked balance is zero, no tokens will accrue to anyone. * * The accounting works as follows: A global index is stored which represents the cumulative * number of rewards tokens earned per staked token since the start of the distribution. * The value of this index increases over time, and there are two factors affecting the rate of * increase: * 1) The emission rate (in the numerator) * 2) The total number of staked tokens (in the denominator) * * Whenever either factor changes, in some timestamp T, we settle the global index up to T by * calculating the increase in the index since the last update using the OLD values of the factors: * * indexDelta = timeDelta * emissionPerSecond * INDEX_BASE / totalStaked * * Where `INDEX_BASE` is a scaling factor used to allow more precision in the storage of the index. * * For each user we store an accrued rewards balance, as well as a user index, which is a cache of * the global index at the time that the user's accrued rewards balance was last updated. Then at * any point in time, a user's claimable rewards are represented by the following: * * rewards = _USER_REWARDS_BALANCES_[user] + userStaked * ( * settledGlobalIndex - _USER_INDEXES_[user] * ) / INDEX_BASE */ abstract contract SM1Rewards is SM1EpochSchedule { using SafeCast for uint256; using SafeERC20 for IERC20; using SafeMath for uint256; // ============ Constants ============ /// @dev Additional precision used to represent the global and user index values. uint256 private constant INDEX_BASE = 10**18; /// @notice The rewards token. IERC20 public immutable REWARDS_TOKEN; /// @notice Address to pull rewards from. Must have provided an allowance to this contract. address public immutable REWARDS_TREASURY; /// @notice Start timestamp (inclusive) of the period in which rewards can be earned. uint256 public immutable DISTRIBUTION_START; /// @notice End timestamp (exclusive) of the period in which rewards can be earned. uint256 public immutable DISTRIBUTION_END; // ============ Events ============ event RewardsPerSecondUpdated( uint256 emissionPerSecond ); event GlobalIndexUpdated( uint256 index ); event UserIndexUpdated( address indexed user, uint256 index, uint256 unclaimedRewards ); event ClaimedRewards( address indexed user, address recipient, uint256 claimedRewards ); // ============ Constructor ============ constructor( IERC20 rewardsToken, address rewardsTreasury, uint256 distributionStart, uint256 distributionEnd ) { require( distributionEnd >= distributionStart, 'SM1Rewards: Invalid parameters' ); REWARDS_TOKEN = rewardsToken; REWARDS_TREASURY = rewardsTreasury; DISTRIBUTION_START = distributionStart; DISTRIBUTION_END = distributionEnd; } // ============ External Functions ============ /** * @notice The current emission rate of rewards. * * @return The number of rewards tokens issued globally each second. */ function getRewardsPerSecond() external view returns (uint256) { return _REWARDS_PER_SECOND_; } // ============ Internal Functions ============ /** * @dev Initialize the contract. */ function __SM1Rewards_init() internal { _GLOBAL_INDEX_TIMESTAMP_ = Math.max(block.timestamp, DISTRIBUTION_START).toUint32(); } /** * @dev Set the emission rate of rewards. * * IMPORTANT: Do not call this function without settling the total staked balance first, to * ensure that the index is settled up to the epoch boundaries. * * @param emissionPerSecond The new number of rewards tokens to give out each second. * @param totalStaked The total staked balance. */ function _setRewardsPerSecond( uint256 emissionPerSecond, uint256 totalStaked ) internal { _settleGlobalIndexUpToNow(totalStaked); _REWARDS_PER_SECOND_ = emissionPerSecond; emit RewardsPerSecondUpdated(emissionPerSecond); } /** * @dev Claim tokens, sending them to the specified recipient. * * Note: In order to claim all accrued rewards, the total and user staked balances must first be * settled before calling this function. * * @param user The user's address. * @param recipient The address to send rewards to. * * @return The number of rewards tokens claimed. */ function _claimRewards( address user, address recipient ) internal returns (uint256) { uint256 accruedRewards = _USER_REWARDS_BALANCES_[user]; _USER_REWARDS_BALANCES_[user] = 0; REWARDS_TOKEN.safeTransferFrom(REWARDS_TREASURY, recipient, accruedRewards); emit ClaimedRewards(user, recipient, accruedRewards); return accruedRewards; } /** * @dev Settle a user's rewards up to the latest global index as of `block.timestamp`. Triggers a * settlement of the global index up to `block.timestamp`. Should be called with the OLD user * and total balances. * * @param user The user's address. * @param userStaked Tokens staked by the user during the period since the last user index * update. * @param totalStaked Total tokens staked by all users during the period since the last global * index update. * * @return The user's accrued rewards, including past unclaimed rewards. */ function _settleUserRewardsUpToNow( address user, uint256 userStaked, uint256 totalStaked ) internal returns (uint256) { uint256 globalIndex = _settleGlobalIndexUpToNow(totalStaked); return _settleUserRewardsUpToIndex(user, userStaked, globalIndex); } /** * @dev Settle a user's rewards up to an epoch boundary. Should be used to partially settle a * user's rewards if their balance was known to have changed on that epoch boundary. * * @param user The user's address. * @param userStaked Tokens staked by the user. Should be accurate for the time period * since the last update to this user and up to the end of the * specified epoch. * @param epochNumber Settle the user's rewards up to the end of this epoch. * * @return The user's accrued rewards, including past unclaimed rewards, up to the end of the * specified epoch. */ function _settleUserRewardsUpToEpoch( address user, uint256 userStaked, uint256 epochNumber ) internal returns (uint256) { uint256 globalIndex = _EPOCH_INDEXES_[epochNumber]; return _settleUserRewardsUpToIndex(user, userStaked, globalIndex); } /** * @dev Settle the global index up to the end of the given epoch. * * IMPORTANT: This function should only be called under conditions which ensure the following: * - `epochNumber` < the current epoch number * - `_GLOBAL_INDEX_TIMESTAMP_ < settleUpToTimestamp` * - `_EPOCH_INDEXES_[epochNumber] = 0` */ function _settleGlobalIndexUpToEpoch( uint256 totalStaked, uint256 epochNumber ) internal returns (uint256) { uint256 settleUpToTimestamp = getStartOfEpoch(epochNumber.add(1)); uint256 globalIndex = _settleGlobalIndexUpToTimestamp(totalStaked, settleUpToTimestamp); _EPOCH_INDEXES_[epochNumber] = globalIndex; return globalIndex; } // ============ Private Functions ============ /** * @dev Updates the global index, reflecting cumulative rewards given out per staked token. * * @param totalStaked The total staked balance, which should be constant in the interval * since the last update to the global index. * * @return The new global index. */ function _settleGlobalIndexUpToNow( uint256 totalStaked ) private returns (uint256) { return _settleGlobalIndexUpToTimestamp(totalStaked, block.timestamp); } /** * @dev Helper function which settles a user's rewards up to a global index. Should be called * any time a user's staked balance changes, with the OLD user and total balances. * * @param user The user's address. * @param userStaked Tokens staked by the user during the period since the last user index * update. * @param newGlobalIndex The new index value to bring the user index up to. MUST NOT be less * than the user's index. * * @return The user's accrued rewards, including past unclaimed rewards. */ function _settleUserRewardsUpToIndex( address user, uint256 userStaked, uint256 newGlobalIndex ) private returns (uint256) { uint256 oldAccruedRewards = _USER_REWARDS_BALANCES_[user]; uint256 oldUserIndex = _USER_INDEXES_[user]; if (oldUserIndex == newGlobalIndex) { return oldAccruedRewards; } uint256 newAccruedRewards; if (userStaked == 0) { // Note: Even if the user's staked balance is zero, we still need to update the user index. newAccruedRewards = oldAccruedRewards; } else { // Calculate newly accrued rewards since the last update to the user's index. uint256 indexDelta = newGlobalIndex.sub(oldUserIndex); uint256 accruedRewardsDelta = userStaked.mul(indexDelta).div(INDEX_BASE); newAccruedRewards = oldAccruedRewards.add(accruedRewardsDelta); // Update the user's rewards. _USER_REWARDS_BALANCES_[user] = newAccruedRewards; } // Update the user's index. _USER_INDEXES_[user] = newGlobalIndex; emit UserIndexUpdated(user, newGlobalIndex, newAccruedRewards); return newAccruedRewards; } /** * @dev Updates the global index, reflecting cumulative rewards given out per staked token. * * @param totalStaked The total staked balance, which should be constant in the interval * (_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp). * @param settleUpToTimestamp The timestamp up to which to settle rewards. It MUST satisfy * `settleUpToTimestamp <= block.timestamp`. * * @return The new global index. */ function _settleGlobalIndexUpToTimestamp( uint256 totalStaked, uint256 settleUpToTimestamp ) private returns (uint256) { uint256 oldGlobalIndex = uint256(_GLOBAL_INDEX_); // The goal of this function is to calculate rewards earned since the last global index update. // These rewards are earned over the time interval which is the intersection of the intervals // [_GLOBAL_INDEX_TIMESTAMP_, settleUpToTimestamp] and [DISTRIBUTION_START, DISTRIBUTION_END]. // // We can simplify a bit based on the assumption: // `_GLOBAL_INDEX_TIMESTAMP_ >= DISTRIBUTION_START` // // Get the start and end of the time interval under consideration. uint256 intervalStart = uint256(_GLOBAL_INDEX_TIMESTAMP_); uint256 intervalEnd = Math.min(settleUpToTimestamp, DISTRIBUTION_END); // Return early if the interval has length zero (incl. case where intervalEnd < intervalStart). if (intervalEnd <= intervalStart) { return oldGlobalIndex; } // Note: If we reach this point, we must update _GLOBAL_INDEX_TIMESTAMP_. uint256 emissionPerSecond = _REWARDS_PER_SECOND_; if (emissionPerSecond == 0 || totalStaked == 0) { // Ensure a log is emitted if the timestamp changed, even if the index does not change. _GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32(); emit GlobalIndexUpdated(oldGlobalIndex); return oldGlobalIndex; } // Calculate the change in index over the interval. uint256 timeDelta = intervalEnd.sub(intervalStart); uint256 indexDelta = timeDelta.mul(emissionPerSecond).mul(INDEX_BASE).div(totalStaked); // Calculate, update, and return the new global index. uint256 newGlobalIndex = oldGlobalIndex.add(indexDelta); // Update storage. (Shared storage slot.) _GLOBAL_INDEX_TIMESTAMP_ = intervalEnd.toUint32(); _GLOBAL_INDEX_ = newGlobalIndex.toUint224(); emit GlobalIndexUpdated(newGlobalIndex); return newGlobalIndex; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../dependencies/open-zeppelin/SafeMath.sol'; /** * @title Math * @author dYdX * * @dev Library for non-standard Math functions. */ library Math { using SafeMath for uint256; // ============ Library Functions ============ /** * @dev Return `ceil(numerator / denominator)`. */ function divRoundUp( uint256 numerator, uint256 denominator ) internal pure returns (uint256) { if (numerator == 0) { // SafeMath will check for zero denominator return SafeMath.div(0, denominator); } return numerator.sub(1).div(denominator).add(1); } /** * @dev Returns the minimum between a and b. */ function min( uint256 a, uint256 b ) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the maximum between a and b. */ function max( uint256 a, uint256 b ) internal pure returns (uint256) { return a > b ? a : b; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SafeCast } from '../lib/SafeCast.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1EpochSchedule * @author dYdX * * @dev Defines a function from block timestamp to epoch number. * * The formula used is `n = floor((t - b) / a)` where: * - `n` is the epoch number * - `t` is the timestamp (in seconds) * - `b` is a non-negative offset, indicating the start of epoch zero (in seconds) * - `a` is the length of an epoch, a.k.a. the interval (in seconds) * * Note that by restricting `b` to be non-negative, we limit ourselves to functions in which epoch * zero starts at a non-negative timestamp. * * The recommended epoch length and blackout window are 28 and 7 days respectively; however, these * are modifiable by the admin, within the specified bounds. */ abstract contract SM1EpochSchedule is SM1Storage { using SafeCast for uint256; using SafeMath for uint256; // ============ Events ============ event EpochParametersChanged( SM1Types.EpochParameters epochParameters ); event BlackoutWindowChanged( uint256 blackoutWindow ); // ============ Initializer ============ function __SM1EpochSchedule_init( uint256 interval, uint256 offset, uint256 blackoutWindow ) internal { require( block.timestamp < offset, 'SM1EpochSchedule: Epoch zero must start after initialization' ); _setBlackoutWindow(blackoutWindow); _setEpochParameters(interval, offset); } // ============ Public Functions ============ /** * @notice Get the epoch at the current block timestamp. * * NOTE: Reverts if epoch zero has not started. * * @return The current epoch number. */ function getCurrentEpoch() public view returns (uint256) { (uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp(); return offsetTimestamp.div(interval); } /** * @notice Get the time remaining in the current epoch. * * NOTE: Reverts if epoch zero has not started. * * @return The number of seconds until the next epoch. */ function getTimeRemainingInCurrentEpoch() public view returns (uint256) { (uint256 interval, uint256 offsetTimestamp) = _getIntervalAndOffsetTimestamp(); uint256 timeElapsedInEpoch = offsetTimestamp.mod(interval); return interval.sub(timeElapsedInEpoch); } /** * @notice Given an epoch number, get the start of that epoch. Calculated as `t = (n * a) + b`. * * @return The timestamp in seconds representing the start of that epoch. */ function getStartOfEpoch( uint256 epochNumber ) public view returns (uint256) { SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 interval = uint256(epochParameters.interval); uint256 offset = uint256(epochParameters.offset); return epochNumber.mul(interval).add(offset); } /** * @notice Check whether we are at or past the start of epoch zero. * * @return Boolean `true` if the current timestamp is at least the start of epoch zero, * otherwise `false`. */ function hasEpochZeroStarted() public view returns (bool) { SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 offset = uint256(epochParameters.offset); return block.timestamp >= offset; } /** * @notice Check whether we are in a blackout window, where withdrawal requests are restricted. * Note that before epoch zero has started, there are no blackout windows. * * @return Boolean `true` if we are in a blackout window, otherwise `false`. */ function inBlackoutWindow() public view returns (bool) { return hasEpochZeroStarted() && getTimeRemainingInCurrentEpoch() <= _BLACKOUT_WINDOW_; } // ============ Internal Functions ============ function _setEpochParameters( uint256 interval, uint256 offset ) internal { SM1Types.EpochParameters memory epochParameters = SM1Types.EpochParameters({interval: interval.toUint128(), offset: offset.toUint128()}); _EPOCH_PARAMETERS_ = epochParameters; emit EpochParametersChanged(epochParameters); } function _setBlackoutWindow( uint256 blackoutWindow ) internal { _BLACKOUT_WINDOW_ = blackoutWindow; emit BlackoutWindowChanged(blackoutWindow); } // ============ Private Functions ============ /** * @dev Helper function to read params from storage and apply offset to the given timestamp. * Recall that the formula for epoch number is `n = (t - b) / a`. * * NOTE: Reverts if epoch zero has not started. * * @return The values `a` and `(t - b)`. */ function _getIntervalAndOffsetTimestamp() private view returns (uint256, uint256) { SM1Types.EpochParameters memory epochParameters = _EPOCH_PARAMETERS_; uint256 interval = uint256(epochParameters.interval); uint256 offset = uint256(epochParameters.offset); require( block.timestamp >= offset, 'SM1EpochSchedule: Epoch zero has not started' ); uint256 offsetTimestamp = block.timestamp.sub(offset); return (interval, offsetTimestamp); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IERC20 } from '../../../interfaces/IERC20.sol'; import { IERC20Detailed } from '../../../interfaces/IERC20Detailed.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1GovernancePowerDelegation } from './SM1GovernancePowerDelegation.sol'; import { SM1StakedBalances } from './SM1StakedBalances.sol'; /** * @title SM1ERC20 * @author dYdX * * @dev ERC20 interface for staked tokens. Implements governance functionality for the tokens. * * Also allows a user with an active stake to transfer their staked tokens to another user, * even if they would otherwise be restricted from withdrawing. */ abstract contract SM1ERC20 is SM1StakedBalances, SM1GovernancePowerDelegation, IERC20Detailed { using SafeMath for uint256; // ============ Constants ============ /// @notice EIP-712 typehash for token approval via EIP-2612 permit. bytes32 public constant PERMIT_TYPEHASH = keccak256( 'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)' ); // ============ External Functions ============ function name() external pure override returns (string memory) { return 'Staked DYDX'; } function symbol() external pure override returns (string memory) { return 'stkDYDX'; } function decimals() external pure override returns (uint8) { return 18; } /** * @notice Get the total supply of staked balances. * * Note that due to the exchange rate, this is different than querying the total balance of * underyling token staked to this contract. * * @return The sum of all staked balances. */ function totalSupply() external view override returns (uint256) { return getTotalActiveBalanceCurrentEpoch() + getTotalInactiveBalanceCurrentEpoch(); } /** * @notice Get a user's staked balance. * * Note that due to the exchange rate, one unit of staked balance may not be equivalent to one * unit of the underlying token. Also note that a user's staked balance is different from a * user's transferable balance. * * @param account The account to get the balance of. * * @return The user's staked balance. */ function balanceOf( address account ) public view override(SM1GovernancePowerDelegation, IERC20) returns (uint256) { return getActiveBalanceCurrentEpoch(account) + getInactiveBalanceCurrentEpoch(account); } function transfer( address recipient, uint256 amount ) external override nonReentrant returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance( address owner, address spender ) external view override returns (uint256) { return _ALLOWANCES_[owner][spender]; } function approve( address spender, uint256 amount ) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external override nonReentrant returns (bool) { _transfer(sender, recipient, amount); _approve( sender, msg.sender, _ALLOWANCES_[sender][msg.sender].sub(amount, 'SM1ERC20: transfer amount exceeds allowance') ); return true; } function increaseAllowance( address spender, uint256 addedValue ) external returns (bool) { _approve(msg.sender, spender, _ALLOWANCES_[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance( address spender, uint256 subtractedValue ) external returns (bool) { _approve( msg.sender, spender, _ALLOWANCES_[msg.sender][spender].sub( subtractedValue, 'SM1ERC20: Decreased allowance below zero' ) ); return true; } /** * @notice Implements the permit function as specified in EIP-2612. * * @param owner Address of the token owner. * @param spender Address of the spender. * @param value Amount of allowance. * @param deadline Expiration timestamp for the signature. * @param v Signature param. * @param r Signature param. * @param s Signature param. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require( owner != address(0), 'SM1ERC20: INVALID_OWNER' ); require( block.timestamp <= deadline, 'SM1ERC20: INVALID_EXPIRATION' ); uint256 currentValidNonce = _NONCES_[owner]; bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', _DOMAIN_SEPARATOR_, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline)) ) ); require( owner == ecrecover(digest, v, r, s), 'SM1ERC20: INVALID_SIGNATURE' ); _NONCES_[owner] = currentValidNonce.add(1); _approve(owner, spender, value); } // ============ Internal Functions ============ function _transfer( address sender, address recipient, uint256 amount ) internal { require( sender != address(0), 'SM1ERC20: Transfer from address(0)' ); require( recipient != address(0), 'SM1ERC20: Transfer to address(0)' ); require( getTransferableBalance(sender) >= amount, 'SM1ERC20: Transfer exceeds next epoch active balance' ); // Update staked balances and delegate snapshots. _transferCurrentAndNextActiveBalance(sender, recipient, amount); _moveDelegatesForTransfer(sender, recipient, amount); emit Transfer(sender, recipient, amount); } function _approve( address owner, address spender, uint256 amount ) internal { require( owner != address(0), 'SM1ERC20: Approve from address(0)' ); require( spender != address(0), 'SM1ERC20: Approve to address(0)' ); _ALLOWANCES_[owner][spender] = amount; emit Approval(owner, spender, amount); } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; import { IERC20 } from './IERC20.sol'; /** * @dev Interface for ERC20 including metadata **/ interface IERC20Detailed is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { IGovernancePowerDelegationERC20 } from '../../../interfaces/IGovernancePowerDelegationERC20.sol'; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1ExchangeRate } from './SM1ExchangeRate.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1GovernancePowerDelegation * @author dYdX * * @dev Provides support for two types of governance powers which are separately delegatable. * Provides functions for delegation and for querying a user's power at a certain block number. * * Internally, makes use of staked balances denoted in staked units, but returns underlying token * units from the getPowerAtBlock() and getPowerCurrent() functions. * * This is based on, and is designed to match, Aave's implementation, which is used in their * governance token and staked token contracts. */ abstract contract SM1GovernancePowerDelegation is SM1ExchangeRate, IGovernancePowerDelegationERC20 { using SafeMath for uint256; // ============ Constants ============ /// @notice EIP-712 typehash for delegation by signature of a specific governance power type. bytes32 public constant DELEGATE_BY_TYPE_TYPEHASH = keccak256( 'DelegateByType(address delegatee,uint256 type,uint256 nonce,uint256 expiry)' ); /// @notice EIP-712 typehash for delegation by signature of all governance powers. bytes32 public constant DELEGATE_TYPEHASH = keccak256( 'Delegate(address delegatee,uint256 nonce,uint256 expiry)' ); // ============ External Functions ============ /** * @notice Delegates a specific governance power of the sender to a delegatee. * * @param delegatee The address to delegate power to. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function delegateByType( address delegatee, DelegationType delegationType ) external override { _delegateByType(msg.sender, delegatee, delegationType); } /** * @notice Delegates all governance powers of the sender to a delegatee. * * @param delegatee The address to delegate power to. */ function delegate( address delegatee ) external override { _delegateByType(msg.sender, delegatee, DelegationType.VOTING_POWER); _delegateByType(msg.sender, delegatee, DelegationType.PROPOSITION_POWER); } /** * @dev Delegates specific governance power from signer to `delegatee` using an EIP-712 signature. * * @param delegatee The address to delegate votes to. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). * @param nonce The signer's nonce for EIP-712 signatures on this contract. * @param expiry Expiration timestamp for the signature. * @param v Signature param. * @param r Signature param. * @param s Signature param. */ function delegateByTypeBySig( address delegatee, DelegationType delegationType, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 structHash = keccak256( abi.encode(DELEGATE_BY_TYPE_TYPEHASH, delegatee, uint256(delegationType), nonce, expiry) ); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', _DOMAIN_SEPARATOR_, structHash)); address signer = ecrecover(digest, v, r, s); require( signer != address(0), 'SM1GovernancePowerDelegation: INVALID_SIGNATURE' ); require( nonce == _NONCES_[signer]++, 'SM1GovernancePowerDelegation: INVALID_NONCE' ); require( block.timestamp <= expiry, 'SM1GovernancePowerDelegation: INVALID_EXPIRATION' ); _delegateByType(signer, delegatee, delegationType); } /** * @dev Delegates both governance powers from signer to `delegatee` using an EIP-712 signature. * * @param delegatee The address to delegate votes to. * @param nonce The signer's nonce for EIP-712 signatures on this contract. * @param expiry Expiration timestamp for the signature. * @param v Signature param. * @param r Signature param. * @param s Signature param. */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 structHash = keccak256(abi.encode(DELEGATE_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', _DOMAIN_SEPARATOR_, structHash)); address signer = ecrecover(digest, v, r, s); require( signer != address(0), 'SM1GovernancePowerDelegation: INVALID_SIGNATURE' ); require( nonce == _NONCES_[signer]++, 'SM1GovernancePowerDelegation: INVALID_NONCE' ); require( block.timestamp <= expiry, 'SM1GovernancePowerDelegation: INVALID_EXPIRATION' ); _delegateByType(signer, delegatee, DelegationType.VOTING_POWER); _delegateByType(signer, delegatee, DelegationType.PROPOSITION_POWER); } /** * @notice Returns the delegatee of a user. * * @param delegator The address of the delegator. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function getDelegateeByType( address delegator, DelegationType delegationType ) external override view returns (address) { (, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType); return _getDelegatee(delegator, delegates); } /** * @notice Returns the current power of a user. The current power is the power delegated * at the time of the last snapshot. * * @param user The user whose power to query. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function getPowerCurrent( address user, DelegationType delegationType ) external override view returns (uint256) { return getPowerAtBlock(user, block.number, delegationType); } /** * @notice Get the next valid nonce for EIP-712 signatures. * * This nonce should be used when signing for any of the following functions: * - permit() * - delegateByTypeBySig() * - delegateBySig() */ function nonces( address owner ) external view returns (uint256) { return _NONCES_[owner]; } // ============ Public Functions ============ function balanceOf( address account ) public view virtual returns (uint256); /** * @notice Returns the power of a user at a certain block, denominated in underlying token units. * * @param user The user whose power to query. * @param blockNumber The block number at which to get the user's power. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). * * @return The user's governance power of the specified type, in underlying token units. */ function getPowerAtBlock( address user, uint256 blockNumber, DelegationType delegationType ) public override view returns (uint256) { ( mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotCounts, // unused: delegates ) = _getDelegationDataByType(delegationType); uint256 stakeAmount = _findValueAtBlock( snapshots[user], snapshotCounts[user], blockNumber, 0 ); uint256 exchangeRate = _findValueAtBlock( _EXCHANGE_RATE_SNAPSHOTS_, _EXCHANGE_RATE_SNAPSHOT_COUNT_, blockNumber, EXCHANGE_RATE_BASE ); return underlyingAmountFromStakeAmountWithExchangeRate(stakeAmount, exchangeRate); } // ============ Internal Functions ============ /** * @dev Delegates one specific power to a delegatee. * * @param delegator The user whose power to delegate. * @param delegatee The address to delegate power to. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function _delegateByType( address delegator, address delegatee, DelegationType delegationType ) internal { require( delegatee != address(0), 'SM1GovernancePowerDelegation: INVALID_DELEGATEE' ); (, , mapping(address => address) storage delegates) = _getDelegationDataByType(delegationType); uint256 delegatorBalance = balanceOf(delegator); address previousDelegatee = _getDelegatee(delegator, delegates); delegates[delegator] = delegatee; _moveDelegatesByType(previousDelegatee, delegatee, delegatorBalance, delegationType); emit DelegateChanged(delegator, delegatee, delegationType); } /** * @dev Update delegate snapshots whenever staked tokens are transfered, minted, or burned. * * @param from The sender. * @param to The recipient. * @param stakedAmount The amount being transfered, denominated in staked units. */ function _moveDelegatesForTransfer( address from, address to, uint256 stakedAmount ) internal { address votingPowerFromDelegatee = _getDelegatee(from, _VOTING_DELEGATES_); address votingPowerToDelegatee = _getDelegatee(to, _VOTING_DELEGATES_); _moveDelegatesByType( votingPowerFromDelegatee, votingPowerToDelegatee, stakedAmount, DelegationType.VOTING_POWER ); address propositionPowerFromDelegatee = _getDelegatee(from, _PROPOSITION_DELEGATES_); address propositionPowerToDelegatee = _getDelegatee(to, _PROPOSITION_DELEGATES_); _moveDelegatesByType( propositionPowerFromDelegatee, propositionPowerToDelegatee, stakedAmount, DelegationType.PROPOSITION_POWER ); } /** * @dev Moves power from one user to another. * * @param from The user from which delegated power is moved. * @param to The user that will receive the delegated power. * @param amount The amount of power to be moved. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function _moveDelegatesByType( address from, address to, uint256 amount, DelegationType delegationType ) internal { if (from == to) { return; } ( mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage snapshots, mapping(address => uint256) storage snapshotCounts, // unused: delegates ) = _getDelegationDataByType(delegationType); if (from != address(0)) { mapping(uint256 => SM1Types.Snapshot) storage fromSnapshots = snapshots[from]; uint256 fromSnapshotCount = snapshotCounts[from]; uint256 previousBalance = 0; if (fromSnapshotCount != 0) { previousBalance = fromSnapshots[fromSnapshotCount - 1].value; } uint256 newBalance = previousBalance.sub(amount); snapshotCounts[from] = _writeSnapshot( fromSnapshots, fromSnapshotCount, newBalance ); emit DelegatedPowerChanged(from, newBalance, delegationType); } if (to != address(0)) { mapping(uint256 => SM1Types.Snapshot) storage toSnapshots = snapshots[to]; uint256 toSnapshotCount = snapshotCounts[to]; uint256 previousBalance = 0; if (toSnapshotCount != 0) { previousBalance = toSnapshots[toSnapshotCount - 1].value; } uint256 newBalance = previousBalance.add(amount); snapshotCounts[to] = _writeSnapshot( toSnapshots, toSnapshotCount, newBalance ); emit DelegatedPowerChanged(to, newBalance, delegationType); } } /** * @dev Returns delegation data (snapshot, snapshotCount, delegates) by delegation type. * * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). * * @return The mapping of each user to a mapping of snapshots. * @return The mapping of each user to the total number of snapshots for that user. * @return The mapping of each user to the user's delegate. */ function _getDelegationDataByType( DelegationType delegationType ) internal view returns ( mapping(address => mapping(uint256 => SM1Types.Snapshot)) storage, mapping(address => uint256) storage, mapping(address => address) storage ) { if (delegationType == DelegationType.VOTING_POWER) { return ( _VOTING_SNAPSHOTS_, _VOTING_SNAPSHOT_COUNTS_, _VOTING_DELEGATES_ ); } else { return ( _PROPOSITION_SNAPSHOTS_, _PROPOSITION_SNAPSHOT_COUNTS_, _PROPOSITION_DELEGATES_ ); } } /** * @dev Returns the delegatee of a user. If a user never performed any delegation, their * delegated address will be 0x0, in which case we return the user's own address. * * @param delegator The address of the user for which return the delegatee. * @param delegates The mapping of delegates for a particular type of delegation. */ function _getDelegatee( address delegator, mapping(address => address) storage delegates ) internal view returns (address) { address previousDelegatee = delegates[delegator]; if (previousDelegatee == address(0)) { return delegator; } return previousDelegatee; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; interface IGovernancePowerDelegationERC20 { enum DelegationType { VOTING_POWER, PROPOSITION_POWER } /** * @dev Emitted when a user delegates governance power to another user. * * @param delegator The delegator. * @param delegatee The delegatee. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ event DelegateChanged( address indexed delegator, address indexed delegatee, DelegationType delegationType ); /** * @dev Emitted when an action changes the delegated power of a user. * * @param user The user whose delegated power has changed. * @param amount The new amount of delegated power for the user. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ event DelegatedPowerChanged(address indexed user, uint256 amount, DelegationType delegationType); /** * @dev Delegates a specific governance power to a delegatee. * * @param delegatee The address to delegate power to. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function delegateByType(address delegatee, DelegationType delegationType) external virtual; /** * @dev Delegates all governance powers to a delegatee. * * @param delegatee The user to which the power will be delegated. */ function delegate(address delegatee) external virtual; /** * @dev Returns the delegatee of an user. * * @param delegator The address of the delegator. * @param delegationType The type of delegation (VOTING_POWER, PROPOSITION_POWER). */ function getDelegateeByType(address delegator, DelegationType delegationType) external view virtual returns (address); /** * @dev Returns the current delegated power of a user. The current power is the power delegated * at the time of the last snapshot. * * @param user The user whose power to query. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function getPowerCurrent(address user, DelegationType delegationType) external view virtual returns (uint256); /** * @dev Returns the delegated power of a user at a certain block. * * @param user The user whose power to query. * @param blockNumber The block number at which to get the user's power. * @param delegationType The type of power (VOTING_POWER, PROPOSITION_POWER). */ function getPowerAtBlock( address user, uint256 blockNumber, DelegationType delegationType ) external view virtual returns (uint256); } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SafeMath } from '../../../dependencies/open-zeppelin/SafeMath.sol'; import { SM1Snapshots } from './SM1Snapshots.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1ExchangeRate * @author dYdX * * @dev Performs math using the exchange rate, which converts between underlying units of the token * that was staked (e.g. STAKED_TOKEN.balanceOf(account)), and staked units, used by this contract * for all staked balances (e.g. this.balanceOf(account)). * * OVERVIEW: * * The exchange rate is stored as a multiple of EXCHANGE_RATE_BASE, and represents the number of * staked balance units that each unit of underlying token is worth. Before any slashes have * occurred, the exchange rate is equal to one. The exchange rate can increase with each slash, * indicating that staked balances are becoming less and less valuable, per unit, relative to the * underlying token. * * AVOIDING OVERFLOW AND UNDERFLOW: * * Staked balances are represented internally as uint240, so the result of an operation returning * a staked balances must return a value less than 2^240. Intermediate values in calcuations are * represented as uint256, so all operations within a calculation must return values under 2^256. * * In the functions below operating on the exchange rate, we are strategic in our choice of the * order of multiplication and division operations, in order to avoid both overflow and underflow. * * We use the following assumptions and principles to implement this module: * - (ASSUMPTION) An amount denoted in underlying token units is never greater than 10^28. * - If the exchange rate is greater than 10^46, then we may perform division on the exchange * rate before performing multiplication, provided that the denominator is not greater * than 10^28 (to ensure a result with at least 18 decimals of precision). Specifically, * we use EXCHANGE_RATE_MAY_OVERFLOW as the cutoff, which is a number greater than 10^46. * - Since staked balances are stored as uint240, we cap the exchange rate to ensure that a * staked balance can never overflow (using the assumption above). */ abstract contract SM1ExchangeRate is SM1Snapshots, SM1Storage { using SafeMath for uint256; // ============ Constants ============ /// @notice The assumed upper bound on the total supply of the staked token. uint256 public constant MAX_UNDERLYING_BALANCE = 1e28; /// @notice Base unit used to represent the exchange rate, for additional precision. uint256 public constant EXCHANGE_RATE_BASE = 1e18; /// @notice Cutoff where an exchange rate may overflow after multiplying by an underlying balance. /// @dev Approximately 1.2e49 uint256 public constant EXCHANGE_RATE_MAY_OVERFLOW = (2 ** 256 - 1) / MAX_UNDERLYING_BALANCE; /// @notice Cutoff where a stake amount may overflow after multiplying by EXCHANGE_RATE_BASE. /// @dev Approximately 1.2e59 uint256 public constant STAKE_AMOUNT_MAY_OVERFLOW = (2 ** 256 - 1) / EXCHANGE_RATE_BASE; /// @notice Max exchange rate. /// @dev Approximately 1.8e62 uint256 public constant MAX_EXCHANGE_RATE = ( ((2 ** 240 - 1) / MAX_UNDERLYING_BALANCE) * EXCHANGE_RATE_BASE ); // ============ Initializer ============ function __SM1ExchangeRate_init() internal { _EXCHANGE_RATE_ = EXCHANGE_RATE_BASE; } function stakeAmountFromUnderlyingAmount( uint256 underlyingAmount ) internal view returns (uint256) { uint256 exchangeRate = _EXCHANGE_RATE_; if (exchangeRate > EXCHANGE_RATE_MAY_OVERFLOW) { uint256 exchangeRateUnbased = exchangeRate.div(EXCHANGE_RATE_BASE); return underlyingAmount.mul(exchangeRateUnbased); } else { return underlyingAmount.mul(exchangeRate).div(EXCHANGE_RATE_BASE); } } function underlyingAmountFromStakeAmount( uint256 stakeAmount ) internal view returns (uint256) { return underlyingAmountFromStakeAmountWithExchangeRate(stakeAmount, _EXCHANGE_RATE_); } function underlyingAmountFromStakeAmountWithExchangeRate( uint256 stakeAmount, uint256 exchangeRate ) internal pure returns (uint256) { if (stakeAmount > STAKE_AMOUNT_MAY_OVERFLOW) { // Note that this case implies that exchangeRate > EXCHANGE_RATE_MAY_OVERFLOW. uint256 exchangeRateUnbased = exchangeRate.div(EXCHANGE_RATE_BASE); return stakeAmount.div(exchangeRateUnbased); } else { return stakeAmount.mul(EXCHANGE_RATE_BASE).div(exchangeRate); } } function updateExchangeRate( uint256 numerator, uint256 denominator ) internal returns (uint256) { uint256 oldExchangeRate = _EXCHANGE_RATE_; // Avoid overflow. // Note that the numerator and denominator are both denominated in underlying token units. uint256 newExchangeRate; if (oldExchangeRate > EXCHANGE_RATE_MAY_OVERFLOW) { newExchangeRate = oldExchangeRate.div(denominator).mul(numerator); } else { newExchangeRate = oldExchangeRate.mul(numerator).div(denominator); } require( newExchangeRate <= MAX_EXCHANGE_RATE, 'SM1ExchangeRate: Max exchange rate exceeded' ); _EXCHANGE_RATE_SNAPSHOT_COUNT_ = _writeSnapshot( _EXCHANGE_RATE_SNAPSHOTS_, _EXCHANGE_RATE_SNAPSHOT_COUNT_, newExchangeRate ); _EXCHANGE_RATE_ = newExchangeRate; return newExchangeRate; } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.7.5; pragma abicoder v2; import { SM1Types } from '../lib/SM1Types.sol'; import { SM1Storage } from './SM1Storage.sol'; /** * @title SM1Snapshots * @author dYdX * * @dev Handles storage and retrieval of historical values by block number. * * Note that the snapshot stored at a given block number represents the value as of the end of * that block. */ abstract contract SM1Snapshots { /** * @dev Writes a snapshot of a value at the current block. * * @param snapshots Storage mapping from snapshot index to snapshot struct. * @param snapshotCount The total number of snapshots in the provided mapping. * @param newValue The new value to snapshot at the current block. * * @return The new snapshot count. */ function _writeSnapshot( mapping(uint256 => SM1Types.Snapshot) storage snapshots, uint256 snapshotCount, uint256 newValue ) internal returns (uint256) { uint256 currentBlock = block.number; if ( snapshotCount != 0 && snapshots[snapshotCount - 1].blockNumber == currentBlock ) { // If there was a previous snapshot for this block, overwrite it. snapshots[snapshotCount - 1].value = newValue; return snapshotCount; } else { snapshots[snapshotCount] = SM1Types.Snapshot(currentBlock, newValue); return snapshotCount + 1; } } /** * @dev Search for the snapshot value at a given block. Uses binary search. * * Reverts if `blockNumber` is greater than the current block number. * * @param snapshots Storage mapping from snapshot index to snapshot struct. * @param snapshotCount The total number of snapshots in the provided mapping. * @param blockNumber The block number to search for. * @param initialValue The value to return if `blockNumber` is before the earliest snapshot. * * @return The snapshot value at the specified block number. */ function _findValueAtBlock( mapping(uint256 => SM1Types.Snapshot) storage snapshots, uint256 snapshotCount, uint256 blockNumber, uint256 initialValue ) internal view returns (uint256) { require( blockNumber <= block.number, 'SM1Snapshots: INVALID_BLOCK_NUMBER' ); if (snapshotCount == 0) { return initialValue; } // Check earliest snapshot. if (blockNumber < snapshots[0].blockNumber) { return initialValue; } // Check latest snapshot. if (blockNumber >= snapshots[snapshotCount - 1].blockNumber) { return snapshots[snapshotCount - 1].value; } uint256 lower = 0; uint256 upper = snapshotCount - 1; while (upper > lower) { uint256 center = upper - (upper - lower) / 2; // Ceil, avoiding overflow. SM1Types.Snapshot memory snapshot = snapshots[center]; if (snapshot.blockNumber == blockNumber) { return snapshot.value; } else if (snapshot.blockNumber < blockNumber) { lower = center; } else { upper = center - 1; } } return snapshots[lower].value; } }
* @dev Store a balance./ Note: This should use a single `sstore` when compiler optimizations are enabled.
function _storeBalance( SM1Types.StoredBalance storage balancePtr, SM1Types.StoredBalance memory balance ) private { balancePtr.currentEpoch = balance.currentEpoch; balancePtr.currentEpochBalance = balance.currentEpochBalance; balancePtr.nextEpochBalance = balance.nextEpochBalance; }
203,930
[ 1, 2257, 279, 11013, 18, 19, 3609, 30, 1220, 1410, 999, 279, 2202, 1375, 87, 2233, 68, 1347, 5274, 5213, 7089, 854, 3696, 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 ]
[ 1, 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, 389, 2233, 13937, 12, 203, 565, 12014, 21, 2016, 18, 18005, 13937, 2502, 11013, 5263, 16, 203, 565, 12014, 21, 2016, 18, 18005, 13937, 3778, 11013, 203, 225, 262, 203, 565, 3238, 203, 225, 288, 203, 565, 11013, 5263, 18, 2972, 14638, 273, 11013, 18, 2972, 14638, 31, 203, 565, 11013, 5263, 18, 2972, 14638, 13937, 273, 11013, 18, 2972, 14638, 13937, 31, 203, 565, 11013, 5263, 18, 4285, 14638, 13937, 273, 11013, 18, 4285, 14638, 13937, 31, 203, 225, 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 ]
./partial_match/1/0xCEf916fa01C299810A481F22eb641150F4A4b923/sources/Pioneer.sol
infect case demolish barricades case
function _infect( uint256 tokenId, uint8 castleId, uint8 oldCastleId ) internal isAvailableZombie(tokenId, castleId) { if (castles[castleId].barricades == 0) { require( castles[castleId].zombies < MAX_ZOMBIES, "reached the maximum zombie limit" ); castles[castleId].zombies++; castles[castleId].lastAttackedBlock = block.number; if (oldCastleId != 0) { castles[oldCastleId].zombies--; } characters[tokenId].castleId = castleId; characters[tokenId].lastActionedBlock = block.number; if (oldCastleId != 0) { castles[oldCastleId].zombies--; characters[tokenId].castleId = 0; } castles[castleId].barricades--; characters[tokenId].lastActionedBlock = block.number; uint256 demolishReward = BARRICADE_PRICE * 10**18; emit AttackBarricade( _msgSender(), tokenId, castleId, demolishReward ); dopes.safeTransfer(_msgSender(), demolishReward); } }
16,107,896
[ 1, 10625, 386, 648, 9626, 355, 1468, 4653, 1512, 16601, 648, 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, 389, 10625, 386, 12, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 2254, 28, 4812, 298, 548, 16, 203, 3639, 2254, 28, 1592, 9735, 298, 548, 203, 565, 262, 2713, 28293, 62, 16659, 1385, 12, 2316, 548, 16, 4812, 298, 548, 13, 288, 203, 3639, 309, 261, 4155, 1040, 63, 4155, 298, 548, 8009, 3215, 1512, 16601, 422, 374, 13, 288, 203, 5411, 2583, 12, 203, 7734, 4812, 1040, 63, 4155, 298, 548, 8009, 94, 16659, 606, 411, 4552, 67, 62, 1872, 38, 8805, 16, 203, 7734, 315, 266, 2004, 326, 4207, 998, 16659, 1385, 1800, 6, 203, 5411, 11272, 203, 5411, 4812, 1040, 63, 4155, 298, 548, 8009, 94, 16659, 606, 9904, 31, 203, 5411, 4812, 1040, 63, 4155, 298, 548, 8009, 2722, 3075, 484, 329, 1768, 273, 1203, 18, 2696, 31, 203, 203, 5411, 309, 261, 1673, 9735, 298, 548, 480, 374, 13, 288, 203, 7734, 4812, 1040, 63, 1673, 9735, 298, 548, 8009, 94, 16659, 606, 413, 31, 203, 5411, 289, 203, 203, 5411, 3949, 63, 2316, 548, 8009, 4155, 298, 548, 273, 4812, 298, 548, 31, 203, 5411, 3949, 63, 2316, 548, 8009, 2722, 1803, 329, 1768, 273, 1203, 18, 2696, 31, 203, 5411, 309, 261, 1673, 9735, 298, 548, 480, 374, 13, 288, 203, 7734, 4812, 1040, 63, 1673, 9735, 298, 548, 8009, 94, 16659, 606, 413, 31, 203, 7734, 3949, 63, 2316, 548, 8009, 4155, 298, 548, 273, 374, 31, 203, 5411, 289, 203, 5411, 4812, 1040, 63, 4155, 298, 548, 8009, 3215, 1512, 16601, 2 ]
pragma solidity ^ 0.4.2; contract mortal { /* Define variable owner of the type address*/ address owner; /* this function is executed at initialization and sets the owner of the contract */ function mortal() { owner = msg.sender; } /* Function to recover the funds on the contract */ function kill() { if (msg.sender == owner) selfdestruct(owner); } } contract TheWinnerTakesItAll is mortal { address[] public participants; address public winner; uint public hashed = 1; bool public gameClosed = false; uint public pNum; event AddedAddressMessage(address changer, string message); /* * Init */ function TheWinnerTakesItAll(uint _pNum) { pNum =_pNum; } /* * Check whether an address already existed */ function addressExsist(address a) returns(bool) { for(uint i = 0; i < participants.length; i++) { if(participants[i] == a) { return true; } } return false; } /* * Get complete list of participants */ function getParticipants() returns (address[]) { return participants; } /* * Add new address */ function addAddress(address a) public { if (participants.length < 15) { if(now % 2 == 0) { if(!addressExsist(a)) { hashed = hashed * uint(sha3(a)); participants.push(a); AddedAddressMessage(a, "new address, hashed address"); } else { AddedAddressMessage(a, "address exists, nothing added"); } } else { if(!addressExsist(a)) { hashed = hashed * uint(sha3(now)); participants.push(a); AddedAddressMessage(a, "new address, hashed timestamp"); AddedAddressMessage(a, "new address"); } else { AddedAddressMessage(a, "address exists, nothing added"); } } } else { throw; } } /* * Get winner */ function getWinner() returns (address) { if ((participants.length < pNum) && (!gameClosed)) { throw; } else { winner = participants[hashed % pNum]; gameClosed = true; return winner; } } }
Get complete list of participants/
function getParticipants() returns (address[]) { return participants; }
5,422,068
[ 1, 967, 3912, 666, 434, 22346, 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 ]
[ 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, 13657, 27620, 1435, 1135, 261, 2867, 63, 5717, 288, 203, 3639, 327, 22346, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x82895fE2945A8B19c5E511E5AA90Da3Aa27331eA/sources/CCPCyborgs.sol
* @dev Owner or Project Leader can set the flag state of a token ID. Note: Flagged tokens are locked and untransferable./
function flagID(uint256 _id, bool _state) external { require(msg.sender == owner() || msg.sender == projectLeader, "NOoPL"); flagged[_id] = _state; }
2,700,858
[ 1, 5541, 578, 5420, 26048, 848, 444, 326, 2982, 919, 434, 279, 1147, 1599, 18, 3609, 30, 9960, 2423, 2430, 854, 8586, 471, 640, 13866, 429, 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 ]
[ 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 2982, 734, 12, 11890, 5034, 389, 350, 16, 1426, 389, 2019, 13, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 1435, 747, 1234, 18, 15330, 422, 1984, 15254, 16, 315, 3417, 83, 6253, 8863, 203, 3639, 2982, 2423, 63, 67, 350, 65, 273, 389, 2019, 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 ]
/** *Submitted for verification at Etherscan.io on 2020-08-20 */ pragma solidity 0.6.10; 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; } } //Note that assert() is now used because the try/catch mechanism in the DepoToken.sol contract does not revert on failure with require(); /** * @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; assert(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) { assert(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; assert(c / a == b/*, "SafeMath: multiplication overflow"*/); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { assert(b > 0/*, errorMessage*/); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { assert(b != 0/*, errorMessage*/); return a % b; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { assert(_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 { assert(newOwner != address(0)/*, "Ownable: new owner is the zero address"*/); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // Contract used to calculate stakes. Unused currently. abstract contract CalculatorInterface { function calculateNumTokens(uint256 balance, uint256 daysStaked, address stakerAddress, uint256 totalSupply) public virtual returns (uint256); function randomness() public view virtual returns (uint256); } // Parent token contract, see DepoToken.sol abstract contract DepoToken { function balanceOf(address account) public view virtual returns (uint256); function _burn(address account, uint256 amount) external virtual; } /** * @dev Implementation of Depo: * Depo is a price-reactive cryptocurrency. * That is, the inflation rate of the token is wholly dependent on its market activity. * Minting does not happen when the price is less than the day prior. * When the price is greater than the day prior, the inflation for that day is * a function of its price, percent increase, volume, any positive price streaks, * and the amount of time any given holder has been holding. * In the first iteration, the dev team acts as the price oracle, but in the future, we plan to integrate a Chainlink price oracle. * This contract is the staking contract for the project and is upgradeable by the owner. */ contract DepoStaking is Ownable { using SafeMath for uint256; // A 'staker' is an individual who holds the minimum staking amount in his address. struct staker { uint startTimestamp; // When the staking started in unix time (block.timesamp) uint lastTimestamp; // When the last staking reward was claimed in unix time (block.timestamp) } struct update { // Price updateState uint timestamp; // Last update timestamp, unix time uint numerator; // Numerator of percent change (1% increase = 1/100) uint denominator; // Denominator of percent change uint price; // In USD. 0001 is $0.001, 1000 is $1.000, 1001 is $1.001, etc uint volume; // In whole USD (100 = $100) } DepoToken public token; // ERC20 token contract that uses this upgradeable contract for staking and burning modifier onlyToken() { assert(_msgSender() == address(token)/*, "Caller must be DEPO token contract."*/); _; } modifier onlyNextStakingContract() { // Caller must be the next staking contract assert(_msgSender() == _nextStakingContract); _; } mapping (address => staker) private _stakers; // Mapping of all individuals staking/holding tokens greater than minStake mapping (address => string) private _whitelist; // Mapping of all addresses that do not burn tokens on receive and send (generally other smart contracts). Mapping of address to reason (string) mapping (address => uint256) private _blacklist; // Mapping of all addresses that receive a specific token burn when receiving. Mapping of address to percent burn (uint256) bool private _enableBurns; // Enable burning on transfer or fee on transfer bool private _priceTarget1Hit; // Price targets, defined in updateState() bool private _priceTarget2Hit; address public _uniswapV2Pair; // Uniswap pair address, done for fees on Uniswap sells uint8 private _uniswapSellerBurnPercent; // Uniswap sells pay a fee bool private _enableUniswapDirectBurns; // Enable seller fees on Uniswap uint256 private _minStake; // Minimum amount to stake uint8 private _minStakeDurationDays; // Minimum amount of time to claim staking rewards uint8 private _minPercentIncrease; // Minimum percent increase to enable rewards for the day. 10 = 1.0%, 100 = 10.0% uint256 private _inflationAdjustmentFactor; // Factor to adjust the amount of rewards (inflation) to be given out in a single day uint256 private _streak; // Number of days in a row that the price has increased update public _lastUpdate; // latest price update CalculatorInterface private _externalCalculator; // external calculator to calculate the number of tokens given several variables (defined above). Currently unused address private _nextStakingContract; // Next staking contract deployed. Used for migrating staker state. bool private _useExternalCalc; // self-explanatory bool private _freeze; // freeze all transfers in an emergency bool private _enableHoldersDay; // once a month, holders receive a nice bump event StakerRemoved(address StakerAddress); // Staker was removed due to balance dropping below _minStake event StakerAdded(address StakerAddress); // Staker was added due to balance increasing abolve _minStake event StakesUpdated(uint Amount); // Staking rewards were claimed event MassiveCelebration(); // Happens when price targets are hit event Transfer(address indexed from, address indexed to, uint256 value); // self-explanatory constructor (DepoToken Token) public { token = Token; _minStake = 500E18; _inflationAdjustmentFactor = 100; _streak = 0; _minStakeDurationDays = 0; _useExternalCalc = false; _uniswapSellerBurnPercent = 5; _enableBurns = false; _freeze = false; _minPercentIncrease = 10; // 1.0% min increase _enableUniswapDirectBurns = false; } // The owner (or price oracle) will call this function to update the price on days the coin is positive. On negative days, no update is made. function updateState(uint numerator, uint denominator, uint256 price, uint256 volume) public onlyOwner { // when chainlink is integrated a separate contract will call this function (onlyOwner state will be changed as well) //inject PUBLIC FUNC TO EXTERNAL require(numerator > 0 && denominator > 0 && price > 0 && volume > 0, "Parameters cannot be negative or zero"); if (numerator < 2 && denominator == 100 || numerator < 20 && denominator == 1000) { require(mulDiv(1000, numerator, denominator) >= _minPercentIncrease, "Increase must be at least _minPercentIncrease to count"); } uint8 daysSinceLastUpdate = uint8((block.timestamp - _lastUpdate.timestamp) / 86400); // We calculate time since last price update in days. Overflow is possible but incredibly unlikely. if (daysSinceLastUpdate == 0) { // We should only update once per day, but block timestamps can vary _streak++; } else if (daysSinceLastUpdate == 1) { _streak++; // If we updated yesterday and today, we are on a streak } else { _streak = 1; } if (price >= 1000 && _priceTarget1Hit == false) { // 1000 = $1.00 _priceTarget1Hit = true; _streak = 50; emit MassiveCelebration(); } else if (price >= 10000 && _priceTarget2Hit == false) { // It is written, so it shall be done _priceTarget2Hit = true; _streak = 100; _minStake = 100E18; // Need $1000 to stake emit MassiveCelebration(); } _lastUpdate = update(block.timestamp, numerator, denominator, price, volume); } function resetStakeTime() public { // This is only necessary if a new staking contract is deployed. Resets 0 timestamp to block.timestamp //inject PUBLIC FUNC TO EXTERNAL uint balance = token.balanceOf(msg.sender); assert(balance > 0); assert(balance >= _minStake); staker memory thisStaker = _stakers[msg.sender]; if (thisStaker.lastTimestamp == 0) { _stakers[msg.sender].lastTimestamp = block.timestamp; } if (thisStaker.startTimestamp == 0) { _stakers[msg.sender].startTimestamp = block.timestamp; } } // This is used by the next staking contract to migrate staker state function resetStakeTimeMigrateState(address addr) public onlyNextStakingContract returns (uint256 startTimestamp, uint256 lastTimestamp) { //inject PUBLIC FUNC TO EXTERNAL startTimestamp = _stakers[addr].startTimestamp; lastTimestamp = _stakers[addr].lastTimestamp; _stakers[addr].lastTimestamp = block.timestamp; _stakers[addr].startTimestamp = block.timestamp; } function updateMyStakes(address stakerAddress, uint256 balance, uint256 totalSupply) public onlyToken returns (uint256) { // This function is called by the token contract. Holders call the function on the token contract every day the price is positive to claim rewards. //inject PUBLIC FUNC TO EXTERNAL assert(balance > 0); staker memory thisStaker = _stakers[stakerAddress]; assert(thisStaker.lastTimestamp > 0/*,"Error: your last timestamp cannot be zero."*/); // We use asserts now so that we fail on errors due to try/catch in token contract. assert(thisStaker.startTimestamp > 0/*,"Error: your start timestamp cannot be zero."*/); assert((block.timestamp.sub(_lastUpdate.timestamp)) / 86400 == 0/*, "Stakes must be updated the same day of the latest update"*/); // We recognize that block.timestamp can be gamed by miners to some extent, but from what we undertand block timestamps *cannot be before the last block* by consensus rules, otherwise they will fork the chain assert(block.timestamp > thisStaker.lastTimestamp/*, "Error: block timestamp is not greater than your last timestamp!"*/); assert(_lastUpdate.timestamp > thisStaker.lastTimestamp/*, "Error: you can only update stakes once per day. You also cannot update stakes on the same day that you purchased them."*/); uint daysStaked = block.timestamp.sub(thisStaker.startTimestamp) / 86400; // Calculate time staked in days assert(daysStaked >= _minStakeDurationDays/*, "You must stake for at least minStakeDurationDays to claim rewards"*/); assert(balance >= _minStake/*, "You must have a balance of at least minStake to claim rewards"*/); uint numTokens = calculateNumTokens(balance, daysStaked, stakerAddress, totalSupply); // Calls token calculation function - this is either an external contract or the function in this contract if (_enableHoldersDay && daysStaked >= 30) { numTokens = mulDiv(balance, daysStaked, 600); // Once a month, holders get a nice bump } _stakers[stakerAddress].lastTimestamp = block.timestamp; // Again, this can be gamed to some extent, but *cannot be before the last block* emit StakesUpdated(numTokens); return numTokens; // Token contract will add these tokens to the balance of stakerAddress } function calculateNumTokens(uint256 balance, uint256 daysStaked, address stakerAddress, uint256 totalSupply) internal returns (uint256) { if (_useExternalCalc) { return _externalCalculator.calculateNumTokens(balance, daysStaked, stakerAddress, totalSupply); // Use external contract, if one is enabled (disabled by default, currently unused) } uint256 inflationAdjustmentFactor = _inflationAdjustmentFactor; if (_streak > 1) { inflationAdjustmentFactor /= _streak; // If there is a streak, we decrease the inflationAdjustmentFactor } if (daysStaked > 60) { // If you stake for more than 60 days, you have hit the upper limit of the multiplier daysStaked = 60; } else if (daysStaked == 0) { // If the minimum days staked is zero, we change the number to 1 so we don't return zero below daysStaked = 1; } uint marketCap = mulDiv(totalSupply, _lastUpdate.price, 1000E18); // Market cap (including locked team tokens) uint ratio = marketCap.div(_lastUpdate.volume); // Ratio of market cap to volume if (ratio > 50) { // Too little volume. Decrease rewards. inflationAdjustmentFactor = inflationAdjustmentFactor.mul(10); } else if (ratio > 25) { // Still not enough. Streak doesn't count. inflationAdjustmentFactor = _inflationAdjustmentFactor; } uint numTokens = mulDiv(balance, _lastUpdate.numerator * daysStaked, _lastUpdate.denominator * inflationAdjustmentFactor); // Function that calculates how many tokens are due. See muldiv below. uint tenPercent = mulDiv(balance, 1, 10); if (numTokens > tenPercent) { // We don't allow a daily rewards of greater than ten percent of a holder's balance. numTokens = tenPercent; } return numTokens; } // Self-explanatory functions to update several configuration variables function updateTokenAddress(DepoToken newToken) public onlyOwner { //inject PUBLIC FUNC TO EXTERNAL require(address(newToken) != address(0)); token = newToken; } function updateCalculator(CalculatorInterface calc) public onlyOwner { //inject PUBLIC FUNC TO EXTERNAL if(address(calc) == address(0)) { _externalCalculator = CalculatorInterface(address(0)); _useExternalCalc = false; } else { _externalCalculator = calc; _useExternalCalc = true; } } function updateInflationAdjustmentFactor(uint256 inflationAdjustmentFactor) public onlyOwner { //inject PUBLIC FUNC TO EXTERNAL _inflationAdjustmentFactor = inflationAdjustmentFactor; } function updateStreak(uint streak) public onlyOwner { //inject PUBLIC FUNC TO EXTERNAL _streak = streak; } function updateMinStakeDurationDays(uint8 minStakeDurationDays) public onlyOwner { //inject PUBLIC FUNC TO EXTERNAL _minStakeDurationDays = minStakeDurationDays; } function updateMinStakes(uint minStake) public onlyOwner { //inject PUBLIC FUNC TO EXTERNAL _minStake = minStake; } function updateMinPercentIncrease(uint8 minIncrease) public onlyOwner { //inject PUBLIC FUNC TO EXTERNAL _minPercentIncrease = minIncrease; } function enableBurns(bool enabledBurns) public onlyOwner { //inject PUBLIC FUNC TO EXTERNAL _enableBurns = enabledBurns; } function updateHoldersDay(bool enableHoldersDay) public onlyOwner { //inject PUBLIC FUNC TO EXTERNAL _enableHoldersDay = enableHoldersDay; } function updateWhitelist(address addr, string calldata reason, bool remove) external onlyOwner returns (bool) { if (remove) { delete _whitelist[addr]; return true; } else { _whitelist[addr] = reason; return true; } return false; } function updateBlacklist(address addr, uint256 fee, bool remove) public onlyOwner returns (bool) { //inject PUBLIC FUNC TO EXTERNAL if (remove) { delete _blacklist[addr]; return true; } else { _blacklist[addr] = fee; return true; } return false; } function updateUniswapPair(address addr) public onlyOwner returns (bool) { //inject PUBLIC FUNC TO EXTERNAL require(addr != address(0)); _uniswapV2Pair = addr; return true; } function updateDirectSellBurns(bool enableDirectSellBurns) public onlyOwner { //inject PUBLIC FUNC TO EXTERNAL _enableUniswapDirectBurns = enableDirectSellBurns; } function updateUniswapSellerBurnPercent(uint8 sellerBurnPercent) public onlyOwner { //inject PUBLIC FUNC TO EXTERNAL _uniswapSellerBurnPercent = sellerBurnPercent; } function freeze(bool enableFreeze) public onlyOwner { //inject PUBLIC FUNC TO EXTERNAL _freeze = enableFreeze; } function updateNextStakingContract(address nextContract) public onlyOwner { //inject PUBLIC FUNC TO EXTERNAL require(nextContract != address(0)); _nextStakingContract = nextContract; } function getStaker(address staker) public view returns (uint256, uint256) { //inject PUBLIC FUNC TO EXTERNAL return (_stakers[staker].startTimestamp, _stakers[staker].lastTimestamp); } function getWhitelist(address addr) public view returns (string memory) { //inject PUBLIC FUNC TO EXTERNAL return _whitelist[addr]; } function getBlacklist(address addr) public view returns (uint) { //inject PUBLIC FUNC TO EXTERNAL return _blacklist[addr]; } // This function was not written by us. It was taken from here: https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1 // We believe it works but do not have the understanding of math required to verify it 100%. // Takes in three numbers and calculates x * (y/z) // This is very useful for this contract as percentages are used constantly function mulDiv (uint x, uint y, uint z) public pure returns (uint) { (uint l, uint h) = fullMul (x, y); assert (h < z); uint mm = mulmod (x, y, z); if (mm > l) h -= 1; l -= mm; uint pow2 = z & -z; z /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint r = 1; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; r *= 2 - z * r; return l * r; } function fullMul (uint x, uint y) private pure returns (uint l, uint h) { uint mm = mulmod (x, y, uint (-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function streak() public view returns (uint) { return _streak; } // Hooks the transfer() function on DepoToken. All transfers call this function. Takes in sender, recipient address and balances and amount and returns sender balance, recipient balance, and burned amount function transferHook(address sender, address recipient, uint256 amount, uint256 senderBalance, uint256 recipientBalance) public onlyToken returns (uint256, uint256, uint256) { //inject PUBLIC FUNC TO EXTERNAL assert(_freeze == false); assert(sender != recipient); assert(amount > 0); assert(senderBalance >= amount); uint totalAmount = amount; bool shouldAddStaker = true; // We assume that the recipient is a potential staker (not a smart contract) uint burnedAmount = 0; if (_enableBurns && bytes(_whitelist[sender]).length == 0 && bytes(_whitelist[recipient]).length == 0) { // Burns are enabled and neither the recipient nor the sender are whitelisted burnedAmount = mulDiv(amount, _randomness(), 100); // Calculates the amount to be burned. Random integer between 1% and 4%. See _randomness() below if (_blacklist[recipient] > 0) { //Transferring to a blacklisted address incurs a specific fee burnedAmount = mulDiv(amount, _blacklist[recipient], 100); // Calculate the fee. The fee is burnt shouldAddStaker = false; // Blacklisted addresses will never be stakers. } if (burnedAmount > 0) { if (burnedAmount > amount) { totalAmount = 0; } else { totalAmount = amount.sub(burnedAmount); } senderBalance = senderBalance.sub(burnedAmount, "ERC20: burn amount exceeds balance"); // Remove the burned amount from the sender's balance } } else if (recipient == _uniswapV2Pair) { // Uniswap was used. This is a special case. Uniswap is burn on receive but whitelist on send, so sellers pay fee and buyers do not. shouldAddStaker = false; if (_enableUniswapDirectBurns) { burnedAmount = mulDiv(amount, _uniswapSellerBurnPercent, 100); // Seller fee if (burnedAmount > 0) { if (burnedAmount > amount) { totalAmount = 0; } else { totalAmount = amount.sub(burnedAmount); } senderBalance = senderBalance.sub(burnedAmount, "ERC20: burn amount exceeds balance"); } } } if (bytes(_whitelist[recipient]).length > 0) { shouldAddStaker = false; } // Here we calculate the percent of the balance an address is receiving. If the address receives too many tokens, the staking time and last time rewards were claimed is reset to block.timestamp // This is necessary because otherwise funds could move from address to address with no penality and thus an individual could claim multiple times with the same funds if (shouldAddStaker && _stakers[recipient].startTimestamp > 0 && recipientBalance > 0) { // If you are currently staking, these should all be true uint percent = mulDiv(1000000, totalAmount, recipientBalance); // This is not really 'percent' it is just a number that represents the totalAmount as a fraction of the recipientBalance assert(percent > 0); if(percent.add(_stakers[recipient].startTimestamp) > block.timestamp) { // We represent the 'percent' as seconds and add to the recipient's unix time _stakers[recipient].startTimestamp = block.timestamp; } else { _stakers[recipient].startTimestamp = _stakers[recipient].startTimestamp.add(percent); // Receiving too many tokens resets your holding time } if(percent.add(_stakers[recipient].lastTimestamp) > block.timestamp) { _stakers[recipient].lastTimestamp = block.timestamp; } else { _stakers[recipient].lastTimestamp = _stakers[recipient].lastTimestamp.add(percent); // Receiving too many tokens may make you ineligible to claim the next day } } else if (shouldAddStaker && recipientBalance == 0 && (_stakers[recipient].startTimestamp > 0 || _stakers[recipient].lastTimestamp > 0)) { // Invalid state, so we reset their data/remove them delete _stakers[recipient]; emit StakerRemoved(recipient); } senderBalance = senderBalance.sub(totalAmount, "ERC20: transfer amount exceeds balance"); // Normal ERC20 transfer recipientBalance = recipientBalance.add(totalAmount); if (shouldAddStaker && _stakers[recipient].startTimestamp == 0 && (totalAmount >= _minStake || recipientBalance >= _minStake)) { // If the recipient was not previously a staker and their balance is now greater than minStake, we add them automatically _stakers[recipient] = staker(block.timestamp, block.timestamp); emit StakerAdded(recipient); } if (senderBalance < _minStake) { // If the sender's balance is below the minimum stake, we remove them automatically // Remove staker delete _stakers[sender]; emit StakerRemoved(sender); } else { _stakers[sender].startTimestamp = block.timestamp; // Sending tokens automatically resets your 'holding time' if (_stakers[sender].lastTimestamp == 0) { _stakers[sender].lastTimestamp = block.timestamp; } } return (senderBalance, recipientBalance, burnedAmount); } function _randomness() internal view returns (uint256) { // Calculates token burn on transfer between 1% and 4% (integers) if(_useExternalCalc) { return _externalCalculator.randomness(); } return 1 + uint256(keccak256(abi.encodePacked(blockhash(block.number-1), _msgSender())))%4; // We use the previous block hash as entropy. Can be gamed by a miner to some extent, but we accept this. } function burn(address account, uint256 amount) public onlyOwner { // We allow ourselves to burn tokens in case they were minted due to a bug //inject PUBLIC FUNC TO EXTERNAL token._burn(account, amount); } function resetStakeTimeDebug(address account) public onlyOwner { // We allow ourselves to reset stake times in case they get changed incorrectly due to a bug //inject PUBLIC FUNC TO EXTERNAL _stakers[account].lastTimestamp = block.timestamp; _stakers[account].startTimestamp = block.timestamp; } }
This is used by the next staking contract to migrate staker state
startTimestamp = _stakers[addr].startTimestamp;
12,964,624
[ 1, 2503, 353, 1399, 635, 326, 1024, 384, 6159, 6835, 358, 13187, 384, 6388, 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 ]
[ 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, 0 ]
[ 1, 3639, 787, 4921, 273, 389, 334, 581, 414, 63, 4793, 8009, 1937, 4921, 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 ]